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,3603 @@
1
+ /**
2
+ * The plugin's page inside DSH's native Settings.
3
+ *
4
+ * A sidebar tab belongs to one conversation, so it deliberately shows **only**
5
+ * that session's project. This page is the other half of the picture: every
6
+ * project with a live session, one selected at a time, with two remembered
7
+ * views — `Table` (a dense overview) and `By files` (the plugin's own model:
8
+ * documents read in priority order, a later document overriding an earlier
9
+ * entry) — plus the split editor.
10
+ *
11
+ * The editor writes, and only within the frozen contract of
12
+ * `docs/design/contracts/write-path.md`: the form edits the parsed {@link EntrySnapshot}
13
+ * the row carries, the JSON pane shows that entry against the snapshot as a
14
+ * line diff, and a save goes through a confirmation that names the document,
15
+ * the `.bak` copy and the format normalization. A row whose
16
+ * {@link ServerRow.writeScope} is `readonly` keeps the old blocked rendering,
17
+ * with `writeBlockedReason` on every control. Secrets stay out of the editor's
18
+ * reach: a masked `env`/`headers` key submitted untouched carries `masked: true`
19
+ * and no value, so the document keeps the secret the form never saw.
20
+ *
21
+ * Registration contract (DSH `settings.section`, kind `list`, scope
22
+ * `root`, owner copy intentionally empty):
23
+ *
24
+ * ```ts
25
+ * ctx.slots.inject('settings.section', () => ctx.slots.register({
26
+ * name: 'settings.section', id, order, label: () => t('tab'), locale: NS,
27
+ * inject: () => ({}),
28
+ * }, SettingsTab))
29
+ * ```
30
+ *
31
+ * `slots.inject` is not decoration: the slot is declared by the Plugins
32
+ * settings section at runtime, and `slots.register` **throws** on an undeclared
33
+ * slot. Data comes from the host over `/project-mcp/snapshot` (see
34
+ * `src/ui.ts`), through the same poll path the sidebar tab uses.
35
+ *
36
+ * The DSH client packages (`@deepseek-ai/dsh-client-ui-slots`, `-locale`,
37
+ * `-ui-settings`) are provided by the web shell and are not dependencies of
38
+ * this package, so the contract is mirrored structurally here: the composed
39
+ * props type is `PropsRuntime<'settings.section'> & PropsLocale<NS> &
40
+ * InjectFace<SettingsTabInjected>`, which for this slot means "no owner props,
41
+ * the namespace-bound `t` seat, and the inject factory's members".
42
+ *
43
+ * @module dsh-project-mcp/client/settings
44
+ */
45
+
46
+ import { createElement as h, useCallback, useEffect, useRef, useState } from 'react'
47
+ import type { CSSProperties, ReactHTML, ReactNode } from 'react'
48
+ import { PACKAGE_NAME, ROUTE_ACTIONS, ROUTE_PREFIX } from '../shared.ts'
49
+ import type { SaveErrorCode, SaveRequest } from '../shared.ts'
50
+ import type {
51
+ ConflictChoice,
52
+ EntryField,
53
+ EntrySnapshot,
54
+ McpSnapshot,
55
+ ProjectSnapshot,
56
+ ServerRow,
57
+ ServerStatus,
58
+ ToolMode,
59
+ } from '../types.ts'
60
+ import {
61
+ DEFAULT_REFRESH_MS,
62
+ STATUS_COLOR,
63
+ STATUS_HINT,
64
+ STATUS_KEYS,
65
+ basename,
66
+ browserStorage,
67
+ emptyState,
68
+ idleNote,
69
+ rowDetail,
70
+ serverCount,
71
+ storeString,
72
+ storedString,
73
+ useSnapshot,
74
+ } from './view.ts'
75
+ import type { PanelStorage } from './view.ts'
76
+ import { DEFAULT_SETTINGS_PAGE, SettingsPageSwitch, ToolsPage, choiceKey } from './settings-tools.ts'
77
+ import type { SettingsPageKey } from './settings-tools.ts'
78
+ import {
79
+ conflictBody,
80
+ operatorBody,
81
+ pinBody,
82
+ policyBody,
83
+ postConflict,
84
+ requestMode,
85
+ requestPin,
86
+ } from './policy.ts'
87
+ import type { PolicyRefusal } from './policy.ts'
88
+ import { projectPolicyRows } from './settings-tools.ts'
89
+ import { uiTranslate } from './locales/ui.ts'
90
+ import { hostTranslate, resolveHost } from './locales/host.ts'
91
+
92
+ /** Locale namespace the page's copy is registered under. */
93
+ export const NS = 'settings.projectMcp'
94
+
95
+ /**
96
+ * The settings page's own English copy, half of the namespace's dictionary.
97
+ *
98
+ * Keys only; the language switch stays with the shell, which re-registers
99
+ * nothing here — a second language is one more dictionary, not a code change.
100
+ * `./locales/ui.ts` adds the panel's half for the one
101
+ * `ctx.locale.register(NS, { zh, en, ru })` call the plugin makes.
102
+ */
103
+ export const EN = {
104
+ project: 'Project',
105
+ projectsOne: '1 project with a live session',
106
+ projectsMany: '{count} projects with live sessions',
107
+ viewTable: 'Table',
108
+ viewFiles: 'By files',
109
+ sync: 'Sync',
110
+ syncHint: 'Re-read the host snapshot now',
111
+ server: 'Server',
112
+ transport: 'Transport',
113
+ status: 'Status',
114
+ source: 'Source',
115
+ on: 'On',
116
+ servers: 'Servers',
117
+ paneEntry: 'Entry',
118
+ name: 'Name',
119
+ detail: 'Detail',
120
+ loading: 'Reading the host snapshot…',
121
+ loadingHint: 'The page polls /project-mcp/snapshot as soon as it opens.',
122
+ hostUnavailable: 'The page did not get an answer from the plugin host.',
123
+ hostUnavailableHint:
124
+ 'The host half serves {route}; it picks up changes only after a dsh web restart — check the log.',
125
+ noSessions: 'No session is attached to a project yet.',
126
+ noSessionsHint:
127
+ 'Servers come up when a session starts working inside a project folder — nothing is mounted for a project without one.',
128
+ noSessionsPaths: 'read: {paths}',
129
+ noSessionsNoPaths:
130
+ 'this deployment reads no MCP document — list the documents to read in the plugin config (`localFiles`, `globalFiles`)',
131
+ noServers: 'This project declares no MCP servers.',
132
+ noServersHint: 'Nothing is declared, so nothing is mounted for its sessions.',
133
+ noServersNoPath: 'This deployment reads no project document, so there is nowhere to declare one.',
134
+ documentUnknown: 'declaration document unknown',
135
+ global: 'global',
136
+ priority: 'priority {tier}/{total}',
137
+ overrideFrom: '↳ overrides {name} from {from}',
138
+ overrideUnpinned: '↳ overrides {name} declared in a lower-priority document',
139
+ nameReason: 'Read-only: the server name is the declaration key the host reports.',
140
+ statusReason: 'Read-only: the status comes from the running host, not from a document.',
141
+ sourceReason: 'Read-only: the declaring document path comes from the host.',
142
+ detailReason: 'Read-only: the host redacts this text and never includes arguments.',
143
+ openToEdit: 'Read-only here: open the server to edit its entry.',
144
+ rowActionsMore: '…',
145
+ rowActionsHint: 'Open this entry in the editor',
146
+ retry: 'Retry',
147
+ retryHint: 'Retry this project’s failed mounts now',
148
+ showJson: 'Show JSON',
149
+ hideJson: 'Hide JSON',
150
+ jsonPreview: 'snapshot JSON',
151
+ jsonPreviewHint: 'Read from the host snapshot; the document on disk is not touched.',
152
+ back: 'Back to the list',
153
+ backHint: 'Return to the overview without changing anything',
154
+ // Editor: the fields of the parsed entry.
155
+ entryUnavailable: 'The host did not parse this entry, so there is nothing to edit.',
156
+ commandField: 'Command',
157
+ argsField: 'Args',
158
+ cwdField: 'CWD',
159
+ urlField: 'URL',
160
+ envField: 'Env',
161
+ headersField: 'Headers',
162
+ enabledField: 'Enabled',
163
+ timeoutField: 'Timeout',
164
+ keyField: 'Key',
165
+ valueField: 'Value',
166
+ argsHint: 'One argument per line; every line is written verbatim.',
167
+ envHint: 'One value per key; a key the form drops is removed from the entry.',
168
+ headersHint: 'One value per header; a key the form drops is removed from the entry.',
169
+ timeoutHint: 'Milliseconds; empty means the declaration sets no timeout.',
170
+ enabledValue: 'enabled: {value}',
171
+ absent: 'absent',
172
+ maskedValue: '•••• unchanged — type to replace',
173
+ valuePlaceholder: 'value',
174
+ keyPlaceholder: 'KEY',
175
+ credentialsNote:
176
+ 'Comes from an external source — the project .env or the credentials file — not from this document: it is shown and written back untouched.',
177
+ credentialValue: 'from the project .env or the credentials file',
178
+ addKey: 'Add key',
179
+ addKeyHint: 'Append an empty key; an unnamed key is not written.',
180
+ removeKey: '✕',
181
+ removeKeyHint: 'Drop this key; a dropped key is removed from the entry.',
182
+ // Writing.
183
+ editableNote:
184
+ 'Editing {document}: Save asks for confirmation, keeps {backup} and rewrites the entry wholesale.',
185
+ writeBlocked: 'Read-only: {reason}',
186
+ writeBlockedUnknown: 'the host did not report why this document may not be written.',
187
+ save: 'Save…',
188
+ saveHint: 'Open the confirmation for this write',
189
+ saveNoChange: 'No change to save yet.',
190
+ saveUnavailable: 'The snapshot carries no declaring document or revision to write back to.',
191
+ saveTimeoutInvalid: 'The timeout is not a whole number of milliseconds.',
192
+ saving: 'Writing…',
193
+ discard: 'Discard',
194
+ discardHint: 'Restore every field from the snapshot and write nothing',
195
+ discardReason: 'No change to restore yet.',
196
+ unsaved: 'unsaved',
197
+ jsonDiff: 'diff',
198
+ jsonClean: 'no change',
199
+ jsonUnavailable: 'no parsed entry',
200
+ jsonInvalid: 'The JSON does not parse into an entry: {reason}',
201
+ jsonEditHint: 'Edit the entry as the document declares it',
202
+ saveJsonInvalid: 'Fix the JSON pane first: it does not parse into an entry.',
203
+ footerWrite: '→ {document} · .bak copy · confirmation',
204
+ footerReadonly: '→ {document} · read-only',
205
+ confirmTitle: 'Write {document}?',
206
+ confirmBackup: 'The current document is copied to {backup} first.',
207
+ confirmFormat:
208
+ 'The entry replaces mcpServers[{server}] wholesale. The document is re-serialized with two-space indentation and a trailing newline, so the indentation and the key order of the rest of the document are normalized.',
209
+ confirmConsent:
210
+ 'This is a global document: every project reads it, so the write needs explicit consent.',
211
+ consentLabel: 'I understand this rewrites a global document shared by every project.',
212
+ confirmWrite: 'Write the document',
213
+ confirmWriteHint: 'Write the document after the checks above',
214
+ confirmBlocked: 'Tick the consent box first: a global write without it is refused.',
215
+ cancel: 'Cancel',
216
+ saveOk: 'Saved: the document was written and re-read.',
217
+ saveErrorInvalid:
218
+ 'The host refused the entry: it is not one this plugin would mount. Nothing was written.',
219
+ saveErrorBlocked:
220
+ 'The document may not be written on this tier, or the consent is missing. Nothing was written.',
221
+ saveErrorConflict: 'The document changed since this snapshot was taken. Nothing was written.',
222
+ saveErrorNotFound: 'The document or the server is no longer there. Nothing was written.',
223
+ saveErrorFailed: 'The write itself failed; the document is left as it was. Nothing was written.',
224
+ hostMessage: 'The host said: {message}',
225
+ reRead: 'Re-read',
226
+ reReadHint: 'Refetch the host snapshot and rebuild the form from it',
227
+ // Our own two pages, and the disclosure policy page next to `Servers`.
228
+ tabServers: 'Servers',
229
+ tabTools: 'Tools',
230
+ policyNote: 'the mode this project follows, and the tools pinned for it',
231
+ checkConflicts: 'Check conflicts',
232
+ checkConflictsHint:
233
+ 'the conflicting server names the host reports for this project, read from its snapshot; the button re-reads it now',
234
+ conflictsNone: 'no conflicting server name in this project',
235
+ conflictProfile: 'profile name',
236
+ conflictDuplicate: 'duplicate declaration',
237
+ conflictSources: 'declared in {sources}',
238
+ choiceLabel: 'show',
239
+ choiceLocal: 'this project\u2019s copy as {alias}',
240
+ choiceProfileHint: 'keep the profile instance\u2019s tools exactly as they are',
241
+ choiceLocalHint:
242
+ 'mount this project\u2019s own declaration beside the profile one, under the local name {alias}',
243
+ choiceNative: 'this project\u2019s declaration under its own name',
244
+ choiceNativeHint:
245
+ 'mount this project\u2019s own declaration under the name it declares: it is the nearer one in this project, so it shadows the profile instance\u2019s tools here while every other project keeps seeing them',
246
+ choiceRefused: 'The host refused the choice:',
247
+ toolsCount: 'tools',
248
+ pinned: 'Pinned',
249
+ mode: 'Mode',
250
+ modeDisclosure: 'disclosure',
251
+ modeDirect: 'all direct',
252
+ modeOff: 'off',
253
+ modeHint: 'written straight away, on the request the host assembles next',
254
+ modeRefused: 'The host refused the mode:',
255
+ pinRefused: 'The host refused the pin:',
256
+ pinList: 'pinned · written by hand, offered in every request',
257
+ pinListEmpty: 'no pins yet — switch one on in the tool list below',
258
+ serverAllOffered: 'all {count} of its tools are offered directly',
259
+ serverPartlyOffered: '{offered} of {total} tools offered directly',
260
+ // The server-level pin (F-44): one switch for the whole server row, above the
261
+ // per-name rows it stands for.
262
+ serverPin: 'pin this server’s tools',
263
+ serverPinHint: 'Pin every tool this server mounts — the hidden ones too — so every request carries them',
264
+ serverUnpin: 'unpin this server’s tools',
265
+ serverUnpinHint: 'Stop pinning the tools of this server',
266
+ prefixFact: 'mcp__<server>__<tool>; the registry applies the prefix, not this page',
267
+ pinTag: 'pin',
268
+ moreTools: '… {count} more',
269
+ requestPreview: 'request preview',
270
+ requestPreviewTools: 'tools[] = {count}',
271
+ requestPreviewTokens: '≈ {tokens} tokens',
272
+ requestPreviewHidden: 'hidden {count}',
273
+ requestPreviewSaved: 'hidden {count} · ≈ {tokens} tokens saved',
274
+ requestPreviewNoOffer: 'no offer published by this session yet',
275
+ // The host's own usage counters, the same six keys and the same words the
276
+ // panel's table holds: the settings page draws its server rows and its pin
277
+ // picker itself, and one namespace means one spelling of `never called`
278
+ // (merged with the panel's half in `./locales/ui.ts`, panel last).
279
+ callsOne: '1 call',
280
+ callsMany: '{count} calls',
281
+ callsNone: 'never called',
282
+ idleDay: 'idle {count}d',
283
+ idleHour: 'idle {count}h',
284
+ idleMinute: 'idle {count}m',
285
+ } satisfies Record<string, string>
286
+
287
+ /** A dictionary key of this namespace. */
288
+ export type LocaleKey = keyof typeof EN
289
+
290
+ /** Translate one key, with optional `{name}` template params (the DSH seat). */
291
+ export type Translate = (key: string, params?: Record<string, unknown>) => string
292
+
293
+ /**
294
+ * Bind the translate seat the framework injects, falling back to this module's
295
+ * own English dictionary when the page renders outside a DSH shell (tests, or a
296
+ * browser half newer than the host).
297
+ * @param t - the `t` seat of the composed props, when the framework passes one.
298
+ * @returns a translate function that always answers.
299
+ */
300
+ export function translateOf(t?: Translate): Translate {
301
+ return t ?? fallbackTranslate
302
+ }
303
+
304
+ function fallbackTranslate(key: string, params?: Record<string, unknown>): string {
305
+ const template = (EN as Record<string, string>)[key] ?? key
306
+ if (params === undefined) return template
307
+ return template.replace(/\{(\w+)\}/g, (match, name: string) =>
308
+ name in params ? String(params[name]) : match,
309
+ )
310
+ }
311
+
312
+ /**
313
+ * Slot key the page contributes to.
314
+ *
315
+ * `settings.section` is the settings navigation itself: one entry per settings
316
+ * page, rendered as the content column when it is selected. The plugin's page is
317
+ * a page in its own right — it has a project selector, its own view switch and a
318
+ * write path — not a detail tab of the plugin inventory, so it belongs here
319
+ * rather than inside the Plugins section.
320
+ */
321
+ export const SETTINGS_SLOT = 'settings.section'
322
+
323
+ /** Section id inside the navigation: the package name, so the row reads like the plugin. */
324
+ export const SETTINGS_TAB_ID = PACKAGE_NAME
325
+
326
+ /**
327
+ * Navigation position. The in-box sections run from `0` (General) to `25`
328
+ * (Archived sessions), and installed plugins fill the rows after them; a page
329
+ * about this plugin's own project data belongs at the end of that list.
330
+ */
331
+ export const SETTINGS_TAB_ORDER = 900
332
+
333
+ /** Options a `list` slot accepts for one registration. */
334
+ export interface SlotRegistration<Slot extends string = string> {
335
+ name: Slot
336
+ id: string
337
+ order: number
338
+ /** The shell re-reads this per render, so a language switch needs no re-register. */
339
+ label?: () => string
340
+ locale: string
341
+ /** The registrant's business face; empty while the page reads the host over HTTP. */
342
+ inject?: () => Record<string, never>
343
+ }
344
+
345
+ /** Options the settings page registers with; the slot it may claim is fixed. */
346
+ export type SettingsTabRegistration = SlotRegistration<typeof SETTINGS_SLOT>
347
+
348
+ /** Injected business face of the settings tab. Nothing yet: the page fetches. */
349
+ export type SettingsTabInjected = Record<never, never>
350
+
351
+ /**
352
+ * Composed component props, mirroring
353
+ * `PropsRuntime<'settings.section'> & PropsLocale<NS> & InjectFace<SettingsTabInjected>`:
354
+ * the slot's owner passes no props, the framework contributes the
355
+ * namespace-bound `t` seat, and the inject face's members arrive flattened.
356
+ *
357
+ * `t` is optional so the page still renders its own English copy outside a DSH
358
+ * shell, which is also what the no-DOM view tests rely on.
359
+ */
360
+ export interface SettingsTabProps {
361
+ t?: Translate
362
+ /**
363
+ * The `projectMcp.host` seat, injected by {@link registerSettingsTab} from
364
+ * the locale service the framework's own `t` cannot reach: `t` is bound to
365
+ * the UI namespace, while host messages resolve through their own. Absent in
366
+ * tests and outside a shell — the resolver then falls back to the payload's
367
+ * English message.
368
+ */
369
+ hostT?: Translate | undefined
370
+ }
371
+
372
+ /**
373
+ * The two client services the settings contribution needs. Both are optional in
374
+ * a composition, which is exactly why registration goes through `ctx.inject`
375
+ * rather than a module-level `inject` list: dropping either one must not take
376
+ * the `dsh-better-sidebar` tab down with it.
377
+ */
378
+ export interface SlotLocale {
379
+ register(namespace: string, dictionaries: Record<string, Record<string, string>>): () => void
380
+ bind(namespace: string): Translate
381
+ /**
382
+ * Add a language the shell does not ship, so dictionaries registered under
383
+ * its id resolve. Optional: a shell whose locale service predates the method
384
+ * must not break this plugin's boot — its keys then fall back to English.
385
+ */
386
+ addLanguage?(input: { id: string; label: string; fallback: string }): () => void
387
+ }
388
+
389
+ /**
390
+ * The slot service, as a registrant uses it.
391
+ *
392
+ * `register`'s component seat is the slots package's own generic (a component of
393
+ * the slot's composed props), which this package mirrors structurally: each
394
+ * registrant supplies the props type it reads, so the settings page keeps its
395
+ * `SettingsTabProps` and nothing else has to share it.
396
+ */
397
+ export interface SlotSlots<Slot extends string = string> {
398
+ inject(slot: string, callback: () => unknown): unknown
399
+ register<Props>(
400
+ options: SlotRegistration<Slot>,
401
+ component: (props: Props) => ReactNode,
402
+ ): unknown
403
+ }
404
+
405
+ /**
406
+ * The two client services a contribution needs. Both are optional in a
407
+ * composition, which is exactly why registration goes through `ctx.inject`
408
+ * rather than a module-level `inject` list: dropping either one must not take
409
+ * the `dsh-better-sidebar` tab down with it.
410
+ */
411
+ export interface SettingsSlotServices {
412
+ effect(execute: () => unknown, label?: string): unknown
413
+ locale: SlotLocale
414
+ slots: SlotSlots<typeof SETTINGS_SLOT>
415
+ }
416
+
417
+ /**
418
+ * Contribute the page to the Plugins settings section.
419
+ *
420
+ * Two steps, because the slot is declared by the section at runtime:
421
+ * `slots.inject` waits for the declaration (and re-registers after a collapse,
422
+ * so a settings-section reload does not leave the tab missing), and the callback
423
+ * calls `slots.register`, which would throw if the slot were not declared yet.
424
+ * @param services - the injected `slots` and `locale` services.
425
+ * @param component - the page to register; the real one by default. The
426
+ * design-only render mode passes its fixture-fed page (`./design.ts`) so the
427
+ * slot, the id and the order stay a single implementation.
428
+ */
429
+ export function registerSettingsTab(
430
+ services: SettingsSlotServices,
431
+ component: (props: SettingsTabProps) => ReactNode = SettingsTab,
432
+ ): void {
433
+ // The one translator both seats share: the bound namespace answers first,
434
+ // the merged English table answers a key the active language lacks, and the
435
+ // raw key shows only when even English has nothing for it. The slot keeps
436
+ // `locale: NS` so the framework's own seat stays consistent.
437
+ const t = uiTranslate(services.locale)
438
+ // The second namespace's seat: the framework binds `t` to `NS` only, so the
439
+ // host messages' translator is bound here and handed to the page as a prop.
440
+ const hostT = hostTranslate(services.locale)
441
+ services.slots.inject(SETTINGS_SLOT, () =>
442
+ services.slots.register(
443
+ {
444
+ name: SETTINGS_SLOT,
445
+ id: SETTINGS_TAB_ID,
446
+ order: SETTINGS_TAB_ORDER,
447
+ label: () => t('tab'),
448
+ locale: NS,
449
+ inject: () => ({}),
450
+ },
451
+ (props: SettingsTabProps) => component({ ...props, hostT }),
452
+ ),
453
+ )
454
+ }
455
+
456
+ /** Which overview the page shows; the choice is remembered. */
457
+ export type SettingsView = 'table' | 'files'
458
+
459
+ /** View shown when nothing valid is persisted. */
460
+ export const DEFAULT_SETTINGS_VIEW: SettingsView = 'table'
461
+
462
+ /**
463
+ * `localStorage` key the page persists its view under.
464
+ *
465
+ * The settings page has no `pluginSettings` blob of its own — that helper
466
+ * belongs to a sidebar tab descriptor — so the view is a browser-local
467
+ * preference rather than a synced one.
468
+ */
469
+ export const SETTINGS_VIEW_STORAGE_KEY = `${PACKAGE_NAME}:settings-view`
470
+
471
+ /**
472
+ * Read the persisted view.
473
+ * @param storage - storage to read; defaults to the browser's own.
474
+ * @returns the stored view, or {@link DEFAULT_SETTINGS_VIEW}.
475
+ */
476
+ export function settingsViewOf(storage: PanelStorage | undefined = browserStorage()): SettingsView {
477
+ return storedString(SETTINGS_VIEW_STORAGE_KEY, storage) === 'files'
478
+ ? 'files'
479
+ : DEFAULT_SETTINGS_VIEW
480
+ }
481
+
482
+ /**
483
+ * Persist the view; hostile storage only costs the choice at the next reload.
484
+ * @param view - view to store.
485
+ * @param storage - storage to write; defaults to the browser's own.
486
+ */
487
+ export function persistSettingsView(
488
+ view: SettingsView,
489
+ storage: PanelStorage | undefined = browserStorage(),
490
+ ): void {
491
+ storeString(SETTINGS_VIEW_STORAGE_KEY, view, storage)
492
+ }
493
+
494
+ /**
495
+ * The project the page shows.
496
+ *
497
+ * The page is the one surface that lists every project with a live session, but
498
+ * it renders exactly one project's rows at a time: an unknown or stale
499
+ * selection falls back to the first project, never to a mix.
500
+ * @param snapshot - host snapshot, or undefined before the first poll lands.
501
+ * @param projectRoot - the selected project root, when known.
502
+ * @returns the selected project, or undefined while there is none.
503
+ */
504
+ export function selectedProject(
505
+ snapshot: McpSnapshot | undefined,
506
+ projectRoot: string | undefined,
507
+ ): ProjectSnapshot | undefined {
508
+ if (snapshot === undefined || snapshot.projects.length === 0) return undefined
509
+ if (projectRoot !== undefined) {
510
+ const match = snapshot.projects.find((project) => project.projectRoot === projectRoot)
511
+ if (match !== undefined) return match
512
+ }
513
+ return snapshot.projects[0]
514
+ }
515
+
516
+ /**
517
+ * Display label of a declaring document: relative to the project root, or
518
+ * home-shortened when it is a global document.
519
+ * @param source - absolute document path.
520
+ * @param projectRoot - the project the document belongs to.
521
+ * @returns the label shown on a card or in the Source column.
522
+ */
523
+ export function documentLabel(source: string, projectRoot: string): string {
524
+ if (source.startsWith(`${projectRoot}/`)) return source.slice(projectRoot.length + 1)
525
+ return source.replace(/^(\/Users\/[^/]+|\/home\/[^/]+)/, '~')
526
+ }
527
+
528
+ /**
529
+ * Where one declaring document sits in the read order of its project.
530
+ *
531
+ * The order is the host's to publish (`ProjectSnapshot.files`): global documents
532
+ * first, then the project's own, so a tier is the 1-based place in that list and
533
+ * `total` is how many it holds — a deployment that reads one document prints
534
+ * `priority 1/1` instead of a `3` it cannot have. A host older than the field
535
+ * reports nothing, and then the shipped names answer: the global documents, then
536
+ * `<project>/.kimi-code/mcp.json`, then `<project>/.dsh/mcp.json`. A document
537
+ * outside either table has no priority, and the panel says nothing rather than
538
+ * inventing one.
539
+ */
540
+ export interface DocumentPriority {
541
+ /** 1-based place in the read order of this project. */
542
+ readonly tier: number
543
+ /** How many documents that read order holds. */
544
+ readonly total: number
545
+ /** True for a global document, read before the project's own. */
546
+ readonly global: boolean
547
+ }
548
+
549
+ /** Documents this version reads when the host reports none — the shipped names. */
550
+ const SHIPPED_LOCAL_FILES = ['.kimi-code/mcp.json', '.dsh/mcp.json'] as const
551
+
552
+ /** The one project document this version ships with, for a host that says none. */
553
+ const DEFAULT_LOCAL_SPECS = ['.dsh/mcp.json'] as const
554
+
555
+ /**
556
+ * Priority of a declaring document, per {@link DocumentPriority}.
557
+ * @param source - absolute document path, or `''` when the host reported none.
558
+ * @param project - the project the document belongs to.
559
+ * @returns the tier, or `undefined` when the document is not one this project reads.
560
+ */
561
+ export function documentPriority(source: string, project: ProjectSnapshot): DocumentPriority | undefined {
562
+ if (source === '') return undefined
563
+ const files = project.files
564
+ if (files !== undefined) {
565
+ const index = files.findIndex((file) => file.path === source)
566
+ const file = files[index]
567
+ if (file === undefined) return undefined
568
+ return { tier: index + 1, total: files.length, global: file.scope === 'global' }
569
+ }
570
+ const projectRoot = project.projectRoot
571
+ if (!source.startsWith(`${projectRoot}/`)) {
572
+ return /(\.dsh|\.kimi-code)\/mcp\.json$/.test(source)
573
+ ? { tier: 1, total: SHIPPED_LOCAL_FILES.length + 1, global: true }
574
+ : undefined
575
+ }
576
+ const index = SHIPPED_LOCAL_FILES.findIndex((relative) => source === `${projectRoot}/${relative}`)
577
+ return index < 0 ? undefined : { tier: index + 2, total: SHIPPED_LOCAL_FILES.length + 1, global: false }
578
+ }
579
+
580
+ /** A spec that already names where it lives, so the panel prints it as written. */
581
+ function isRootedSpec(spec: string): boolean {
582
+ return spec.startsWith('/') || spec.startsWith('~') || spec.startsWith('$') || /^[A-Za-z]:[\\/]/.test(spec)
583
+ }
584
+
585
+ /**
586
+ * Documents of the deployment itself, written the way a person would write them
587
+ * in the config: `<project>/…` for a local spec, `~/…` for a relative global one.
588
+ * A host older than `sources` reported nothing, and then this version's shipped
589
+ * names answer — the same ones its own default reads.
590
+ */
591
+ function deploymentDocuments(snapshot: McpSnapshot): string[] {
592
+ const sources = snapshot.sources
593
+ if (sources === undefined) return DEFAULT_LOCAL_SPECS.map((relative) => `<project>/${relative}`)
594
+ return [
595
+ ...sources.global.map((spec) => (isRootedSpec(spec) ? spec : `~/${spec}`)),
596
+ ...sources.local.map((spec) => (isRootedSpec(spec) ? spec : `<project>/${spec}`)),
597
+ ]
598
+ }
599
+
600
+ /**
601
+ * The `read: …` code line under an empty state, said from the config rather than
602
+ * from a file name baked into this bundle.
603
+ */
604
+ function readPaths(snapshot: McpSnapshot, t: Translate): string {
605
+ const documents = deploymentDocuments(snapshot)
606
+ return documents.length === 0 ? t('noSessionsNoPaths') : t('noSessionsPaths', { paths: documents.join(' · ') })
607
+ }
608
+
609
+ /** One overridden declaration, as the host's merge warning reports it. */
610
+ export interface OverrideNote {
611
+ /** `serverName` that was declared in more than one document. */
612
+ name: string
613
+ /**
614
+ * The overridden document, when the snapshot pins it; `undefined` when more
615
+ * than one lower-priority document could have carried the losing entry.
616
+ */
617
+ from: string | undefined
618
+ }
619
+
620
+ /** One card of the "By files" view: a document and the servers it declares. */
621
+ export interface DocumentGroup {
622
+ /** Absolute document path, or `''` when the host reported no source. */
623
+ source: string
624
+ /** Path relative to the project (or `~`-shortened); `''` when source is `''`. */
625
+ label: string
626
+ /** Where the document sits in the read order, per {@link documentPriority}. */
627
+ priority: DocumentPriority | undefined
628
+ /** The surviving rows that this document declares. */
629
+ rows: ServerRow[]
630
+ /** Declarations of this document's servers that a later document replaced. */
631
+ overrides: OverrideNote[]
632
+ }
633
+
634
+ /**
635
+ * Group a project's rows per declaring document, in priority order.
636
+ *
637
+ * The plugin's native model is the document, not the server: a document read
638
+ * later overrides an earlier entry with the same `serverName`, so the earlier
639
+ * declaration is a property of the file that won. The host reports the
640
+ * overridden *name* in a merge warning (`project.issues`) and the winner's
641
+ * document in the row's `source`; this function pairs the two. Which earlier
642
+ * document carried the losing entry is only knowable when a single
643
+ * lower-priority document is in the picture, so {@link OverrideNote.from} stays
644
+ * `undefined` otherwise and the view says so instead of guessing.
645
+ * @param project - one project from the host snapshot.
646
+ * @returns one group per declaring document, lowest priority first.
647
+ */
648
+ export function fileGroups(project: ProjectSnapshot): DocumentGroup[] {
649
+ const groups: DocumentGroup[] = []
650
+ for (const row of project.rows) {
651
+ const source = row.source ?? ''
652
+ let group = groups.find((candidate) => candidate.source === source)
653
+ if (group === undefined) {
654
+ group = {
655
+ source,
656
+ label: source === '' ? '' : documentLabel(source, project.projectRoot),
657
+ priority: source === '' ? undefined : documentPriority(source, project),
658
+ rows: [],
659
+ overrides: [],
660
+ }
661
+ groups.push(group)
662
+ }
663
+ group.rows.push(row)
664
+ }
665
+ // Stable in modern engines: documents keep their first-appearance order inside
666
+ // one tier, and documents the read order does not know come last.
667
+ groups.sort((left, right) => (left.priority?.tier ?? Number.MAX_SAFE_INTEGER) - (right.priority?.tier ?? Number.MAX_SAFE_INTEGER))
668
+ for (const issue of project.issues) {
669
+ // The merge warning is recognised by its wire code, never by its prose:
670
+ // the client translates the payload, so an English string-match would both
671
+ // miss under another language and misread a translated message.
672
+ if (issue.server === undefined || issue.code !== 'parse.server.multiDocument') continue
673
+ const winnerIndex = groups.findIndex((group) =>
674
+ group.rows.some((row) => row.name === issue.server),
675
+ )
676
+ if (winnerIndex < 0) continue
677
+ const winner = groups[winnerIndex]
678
+ if (winner === undefined) continue
679
+ const earlier = groups
680
+ .slice(0, winnerIndex)
681
+ .filter(
682
+ (group) =>
683
+ group.priority === undefined ||
684
+ winner.priority === undefined ||
685
+ group.priority.tier < winner.priority.tier,
686
+ )
687
+ winner.overrides.push({
688
+ name: issue.server,
689
+ from: earlier.length === 1 ? earlier[0]?.label : undefined,
690
+ })
691
+ }
692
+ return groups
693
+ }
694
+
695
+ /** The `1 project …` / `3 projects …` toolbar summary. */
696
+ function liveProjectCount(count: number, t: Translate): string {
697
+ return count === 1 ? t('projectsOne') : t('projectsMany', { count })
698
+ }
699
+
700
+ // ── styles ────────────────────────────────────────────────────────────────────
701
+ // Same vocabulary as `view.ts`: only the DSH alias layer's own custom
702
+ // properties, each with the fallback a non-DSH page needs.
703
+
704
+ const BORDER = '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))'
705
+ const BORDER_L2 = '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.4))'
706
+
707
+ /**
708
+ * The longest a line of copy is allowed to run before it wraps.
709
+ *
710
+ * The settings panel is a modal `min(800px, 100vw - 48px)` wide, so a hint laid
711
+ * out at full width runs to ~110 characters and the eye loses the line. The
712
+ * mockups cap their prose at 74–84ch for the same reason; this is the cap the
713
+ * page's own copy uses.
714
+ */
715
+ const COPY_COLUMN = '72ch'
716
+
717
+ export const STYLE = {
718
+ root: {
719
+ display: 'flex',
720
+ flexDirection: 'column',
721
+ height: '100%',
722
+ minHeight: 0,
723
+ color: 'inherit',
724
+ } satisfies CSSProperties,
725
+ bar: {
726
+ display: 'flex',
727
+ alignItems: 'center',
728
+ gap: 6,
729
+ padding: '6px 8px',
730
+ borderBottom: BORDER,
731
+ flexWrap: 'wrap',
732
+ } satisfies CSSProperties,
733
+ muted: { opacity: 0.9, fontSize: '0.9em' } satisfies CSSProperties,
734
+ title: {
735
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
736
+ marginRight: 4,
737
+ } satisfies CSSProperties,
738
+ body: { flex: 1, minHeight: 0, overflow: 'auto', padding: '2px 2px 18px' } satisfies CSSProperties,
739
+ segment: {
740
+ display: 'flex',
741
+ gap: 2,
742
+ border: BORDER,
743
+ borderRadius: 6,
744
+ padding: 1,
745
+ } satisfies CSSProperties,
746
+ segmentItem: {
747
+ padding: '1px 8px',
748
+ border: 'none',
749
+ borderRadius: 4,
750
+ background: 'transparent',
751
+ color: 'inherit',
752
+ opacity: 0.65,
753
+ cursor: 'pointer',
754
+ font: 'inherit',
755
+ fontSize: '0.9em',
756
+ } satisfies CSSProperties,
757
+ segmentItemActive: {
758
+ background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',
759
+ opacity: 1,
760
+ } satisfies CSSProperties,
761
+ button: {
762
+ padding: '2px 8px',
763
+ borderRadius: 4,
764
+ border: BORDER,
765
+ background: 'transparent',
766
+ color: 'inherit',
767
+ cursor: 'pointer',
768
+ font: 'inherit',
769
+ } satisfies CSSProperties,
770
+ buttonPrimary: {
771
+ padding: '2px 8px',
772
+ borderRadius: 4,
773
+ border: '1px solid transparent',
774
+ background: 'var(--dsw-alias-button-primary-fill, currentColor)',
775
+ color: 'var(--dsw-alias-label-primary-foreground, inherit)',
776
+ cursor: 'pointer',
777
+ font: 'inherit',
778
+ } satisfies CSSProperties,
779
+ select: {
780
+ border: BORDER,
781
+ borderRadius: 4,
782
+ padding: '2px 4px',
783
+ background: 'var(--dsw-alias-bg-layer-2, transparent)',
784
+ color: 'inherit',
785
+ font: 'inherit',
786
+ fontSize: '0.9em',
787
+ } satisfies CSSProperties,
788
+ card: {
789
+ border: BORDER,
790
+ borderRadius: 7,
791
+ marginBottom: 7,
792
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
793
+ overflow: 'hidden',
794
+ } satisfies CSSProperties,
795
+ cardHead: {
796
+ display: 'flex',
797
+ alignItems: 'center',
798
+ gap: 7,
799
+ padding: '6px 9px',
800
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
801
+ background: 'var(--dsw-alias-bg-layer-2, transparent)',
802
+ borderBottom: BORDER,
803
+ } satisfies CSSProperties,
804
+ cardPath: {
805
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
806
+ fontSize: '0.9em',
807
+ } satisfies CSSProperties,
808
+ tag: {
809
+ opacity: 0.75,
810
+ fontSize: '0.8em',
811
+ border: BORDER,
812
+ borderRadius: 4,
813
+ padding: '0 5px',
814
+ color: 'var(--dsw-alias-label-secondary, inherit)',
815
+ whiteSpace: 'nowrap',
816
+ } satisfies CSSProperties,
817
+ /** The `warn` chip of the mockups: the same rule, in the warning tone. */
818
+ tagWarn: {
819
+ opacity: 1,
820
+ borderColor: 'var(--dsw-alias-state-warn-label, #b45309)',
821
+ color: 'var(--dsw-alias-state-warn-label, #b45309)',
822
+ } satisfies CSSProperties,
823
+ /**
824
+ * The choice control of a conflict card: the label, then the two answers side
825
+ * by side. Four pixels apart like the mockups' own switch, and one row that
826
+ * wraps rather than a column, because a long local name widens its button.
827
+ */
828
+ choiceRow: {
829
+ display: 'flex',
830
+ alignItems: 'center',
831
+ gap: 6,
832
+ flexWrap: 'wrap',
833
+ marginTop: 6,
834
+ } satisfies CSSProperties,
835
+ /** One answer of that control, while it is the one in force. */
836
+ choiceOn: {
837
+ padding: '2px 8px',
838
+ borderRadius: 4,
839
+ border: '1px solid var(--dsw-alias-state-warn-label, #b45309)',
840
+ background: 'var(--dsw-alias-bg-layer-2, rgba(127, 127, 127, 0.08))',
841
+ color: 'inherit',
842
+ cursor: 'pointer',
843
+ font: 'inherit',
844
+ } satisfies CSSProperties,
845
+ /** One answer of that control, while the other one is in force. */
846
+ choiceOff: {
847
+ padding: '2px 8px',
848
+ borderRadius: 4,
849
+ border: BORDER,
850
+ background: 'transparent',
851
+ color: 'var(--dsw-alias-label-secondary, inherit)',
852
+ cursor: 'pointer',
853
+ font: 'inherit',
854
+ } satisfies CSSProperties,
855
+ /** The `error` chip of the mockups, for the conflicts the host reports. */
856
+ tagError: {
857
+ opacity: 1,
858
+ borderColor: 'var(--dsw-alias-state-error-primary, #ec1313)',
859
+ color: 'var(--dsw-alias-state-error-primary, #ec1313)',
860
+ } satisfies CSSProperties,
861
+ row: {
862
+ display: 'flex',
863
+ alignItems: 'center',
864
+ gap: 6,
865
+ padding: '5px 9px',
866
+ borderTop: BORDER,
867
+ } satisfies CSSProperties,
868
+ dot: {
869
+ width: 8,
870
+ height: 8,
871
+ borderRadius: '50%',
872
+ display: 'inline-block',
873
+ flex: 'none',
874
+ alignSelf: 'center',
875
+ } satisfies CSSProperties,
876
+ serverButton: {
877
+ padding: 0,
878
+ border: 'none',
879
+ background: 'transparent',
880
+ color: 'inherit',
881
+ cursor: 'pointer',
882
+ font: 'inherit',
883
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
884
+ textAlign: 'left',
885
+ } satisfies CSSProperties,
886
+ serverButtonActive: {
887
+ color: 'var(--dsw-alias-state-business-primary, inherit)',
888
+ } satisfies CSSProperties,
889
+ overrideNote: {
890
+ padding: '3px 8px 3px 22px',
891
+ borderTop: BORDER,
892
+ opacity: 0.75,
893
+ fontSize: '0.85em',
894
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
895
+ } satisfies CSSProperties,
896
+ note: {
897
+ marginTop: 8,
898
+ padding: '5px 7px',
899
+ borderLeft: '2px solid var(--dsw-alias-state-warn-primary, #f59e0b)',
900
+ background: 'var(--dsw-alias-state-warn-tertiary, transparent)',
901
+ fontSize: '0.85em',
902
+ overflowWrap: 'anywhere',
903
+ maxWidth: COPY_COLUMN,
904
+ // The failing-mount notes reuse this style and carry a multi-line detail.
905
+ whiteSpace: 'pre-wrap',
906
+ } satisfies CSSProperties,
907
+ table: { width: '100%', borderCollapse: 'collapse' } satisfies CSSProperties,
908
+ th: {
909
+ textAlign: 'left',
910
+ fontWeight: 500,
911
+ fontSize: '0.75em',
912
+ letterSpacing: '0.06em',
913
+ textTransform: 'uppercase',
914
+ // A header cell is a label, not prose: letting it wrap turns a column into a
915
+ // one-word sliver at the panel's width.
916
+ whiteSpace: 'nowrap',
917
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
918
+ padding: '0 8px 5px 0',
919
+ } satisfies CSSProperties,
920
+ td: {
921
+ padding: '6px 8px 6px 0',
922
+ borderTop: BORDER,
923
+ verticalAlign: 'baseline',
924
+ // A cell is a value, not a heading: without this the browser's own `th`/`td`
925
+ // default would render every name in the table bolder than the mockups do.
926
+ fontWeight: 400,
927
+ } satisfies CSSProperties,
928
+ /** The editor's own checkboxes: a real input, so it only needs the reset. */
929
+ switch: { margin: 0 } satisfies CSSProperties,
930
+ /** The On column: the mockups' switch, drawn from the tokens they name. */
931
+ switchOn: {
932
+ display: 'inline-flex',
933
+ alignItems: 'center',
934
+ width: 26,
935
+ height: 15,
936
+ borderRadius: 8,
937
+ padding: 0,
938
+ border: 'none',
939
+ background: 'var(--dsw-alias-state-business-primary, var(--dsw-alias-state-success-primary, #22c55e))',
940
+ cursor: 'pointer',
941
+ verticalAlign: '-2px',
942
+ } satisfies CSSProperties,
943
+ switchOff: { background: 'var(--dsw-alias-border-l3, #d0d3d8)' } satisfies CSSProperties,
944
+ /** The knob inside {@link STYLE.switchOn}, pushed right when the row is on. */
945
+ switchKnob: {
946
+ width: 11,
947
+ height: 11,
948
+ borderRadius: '50%',
949
+ background: 'var(--dsw-alias-label-primary-foreground, #ffffff)',
950
+ marginLeft: 2,
951
+ pointerEvents: 'none',
952
+ } satisfies CSSProperties,
953
+ switchKnobOn: { marginLeft: 13 } satisfies CSSProperties,
954
+ // The vertical setting rows the `Tools` page is built from — the shape DSH's
955
+ // own settings pages use (one row per setting: text column left, control
956
+ // right, rule under). The `split` / `pane*` styles below belong to the entry
957
+ // editor, whose three panes are deliberately not reused by a policy form:
958
+ // its panes are far too narrow for a sentence, so the copy has nowhere to go
959
+ // but a one-word-wide sliver.
960
+ /** One setting row: label and description left, control right, rule under. */
961
+ settingRow: {
962
+ display: 'flex',
963
+ alignItems: 'center',
964
+ gap: 16,
965
+ padding: '16px 0',
966
+ borderBottom: BORDER,
967
+ } satisfies CSSProperties,
968
+ /** The last row of a group or a block, which carries no trailing rule. */
969
+ lastRow: { borderBottom: 'none' } satisfies CSSProperties,
970
+ /** The row's text column: the wide one, and the one copy wraps in. */
971
+ settingRowText: {
972
+ flex: 1,
973
+ minWidth: 0,
974
+ display: 'flex',
975
+ flexDirection: 'column',
976
+ gap: 3,
977
+ } satisfies CSSProperties,
978
+ settingRowLabel: { fontWeight: 600 } satisfies CSSProperties,
979
+ settingRowDesc: {
980
+ fontSize: '0.85em',
981
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
982
+ overflowWrap: 'anywhere',
983
+ } satisfies CSSProperties,
984
+ /** The control column: sized to its content, never the column that wraps. */
985
+ settingRowControl: {
986
+ flex: 'none',
987
+ display: 'inline-flex',
988
+ alignItems: 'center',
989
+ gap: 6,
990
+ } satisfies CSSProperties,
991
+ /** A titled group of rows below the first one. */
992
+ settingGroup: { marginTop: 16 } satisfies CSSProperties,
993
+ settingGroupHead: {
994
+ fontSize: '0.75em',
995
+ letterSpacing: '0.06em',
996
+ textTransform: 'uppercase',
997
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
998
+ marginBottom: 6,
999
+ } satisfies CSSProperties,
1000
+ /** The pinned names: chips that wrap across the row, not a column of their own. */
1001
+ tagList: {
1002
+ display: 'flex',
1003
+ flexWrap: 'wrap',
1004
+ alignItems: 'center',
1005
+ gap: 4,
1006
+ } satisfies CSSProperties,
1007
+ /** A table too wide for the panel scrolls instead of colliding with it. */
1008
+ tableScroll: { maxWidth: '100%', overflowX: 'auto' } satisfies CSSProperties,
1009
+ split: {
1010
+ display: 'flex',
1011
+ alignItems: 'stretch',
1012
+ minHeight: 260,
1013
+ border: BORDER,
1014
+ borderRadius: 7,
1015
+ overflow: 'hidden',
1016
+ } satisfies CSSProperties,
1017
+ /** Laid on top of {@link STYLE.split} while the panes stack. */
1018
+ splitNarrow: { flexDirection: 'column' } satisfies CSSProperties,
1019
+ splitBar: {
1020
+ display: 'flex',
1021
+ alignItems: 'center',
1022
+ gap: 6,
1023
+ marginBottom: 6,
1024
+ flexWrap: 'wrap',
1025
+ } satisfies CSSProperties,
1026
+ splitFooter: {
1027
+ display: 'flex',
1028
+ alignItems: 'center',
1029
+ gap: 6,
1030
+ marginTop: 6,
1031
+ flexWrap: 'wrap',
1032
+ } satisfies CSSProperties,
1033
+ paneList: {
1034
+ flex: '1 1 168px',
1035
+ minWidth: 0,
1036
+ borderRight: BORDER,
1037
+ overflow: 'auto',
1038
+ } satisfies CSSProperties,
1039
+ /** The server list stacked: full width, its rule on the bottom edge. */
1040
+ paneListNarrow: {
1041
+ flex: 'none',
1042
+ width: '100%',
1043
+ maxHeight: 180,
1044
+ borderRight: 'none',
1045
+ borderBottom: BORDER,
1046
+ } satisfies CSSProperties,
1047
+ paneHead: {
1048
+ padding: '5px 8px',
1049
+ fontSize: '0.75em',
1050
+ letterSpacing: '0.06em',
1051
+ textTransform: 'uppercase',
1052
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
1053
+ borderBottom: BORDER,
1054
+ } satisfies CSSProperties,
1055
+ listItem: {
1056
+ display: 'flex',
1057
+ alignItems: 'center',
1058
+ gap: 6,
1059
+ padding: '4px 8px',
1060
+ borderBottom: BORDER,
1061
+ } satisfies CSSProperties,
1062
+ listItemActive: {
1063
+ background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',
1064
+ } satisfies CSSProperties,
1065
+ /**
1066
+ * The right column: the entry's form, and the JSON body under it.
1067
+ *
1068
+ * The JSON used to be a third column beside the form, which made both narrow
1069
+ * and put the entry in two places at once. Under the form it is the same entry
1070
+ * — the form's fields on top, the document body below — and the list keeps the
1071
+ * only fixed width.
1072
+ */
1073
+ paneColumn: {
1074
+ flex: '1 1 240px',
1075
+ minWidth: 0,
1076
+ display: 'flex',
1077
+ flexDirection: 'column',
1078
+ } satisfies CSSProperties,
1079
+ /** The form on top of the column: its own height, its rule on the bottom edge. */
1080
+ paneForm: {
1081
+ flex: 'none',
1082
+ minWidth: 0,
1083
+ padding: '8px 10px',
1084
+ borderBottom: BORDER,
1085
+ } satisfies CSSProperties,
1086
+ /** The column stacked: full width, no rules left over from the row. */
1087
+ paneColumnNarrow: {
1088
+ flex: 'none',
1089
+ width: '100%',
1090
+ } satisfies CSSProperties,
1091
+ paneFormNarrow: {
1092
+ width: '100%',
1093
+ } satisfies CSSProperties,
1094
+ paneJson: {
1095
+ flex: '1 1 auto',
1096
+ minWidth: 0,
1097
+ display: 'flex',
1098
+ flexDirection: 'column',
1099
+ background: 'var(--dsw-alias-markdown-code-block, transparent)',
1100
+ } satisfies CSSProperties,
1101
+ /** The JSON pane stacked: full width, its own height under the form. */
1102
+ paneJsonNarrow: {
1103
+ flex: 'none',
1104
+ width: '100%',
1105
+ minHeight: 200,
1106
+ } satisfies CSSProperties,
1107
+ json: {
1108
+ margin: 0,
1109
+ padding: '8px 10px',
1110
+ fontSize: '0.8em',
1111
+ whiteSpace: 'pre',
1112
+ overflowX: 'auto',
1113
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
1114
+ } satisfies CSSProperties,
1115
+ /**
1116
+ * The editable body: the pane's own `pre`, as a control.
1117
+ *
1118
+ * `pre-wrap` rather than `pre`: the pane is a column of the settings panel and
1119
+ * a long `args` line would otherwise scroll sideways inside it. `resize` is on
1120
+ * because the entry is read as a whole and a wrapped line is not always the
1121
+ * shape someone wants.
1122
+ */
1123
+ jsonArea: {
1124
+ flex: '1 1 auto',
1125
+ minHeight: 160,
1126
+ margin: 0,
1127
+ padding: '8px 10px',
1128
+ border: 'none',
1129
+ background: 'transparent',
1130
+ color: 'inherit',
1131
+ font: 'inherit',
1132
+ fontSize: '0.8em',
1133
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
1134
+ lineHeight: '1.5',
1135
+ whiteSpace: 'pre-wrap',
1136
+ overflowWrap: 'anywhere',
1137
+ overflowY: 'auto',
1138
+ resize: 'vertical',
1139
+ boxSizing: 'border-box',
1140
+ width: '100%',
1141
+ } satisfies CSSProperties,
1142
+ field: {
1143
+ display: 'grid',
1144
+ gridTemplateColumns: '90px 1fr',
1145
+ gap: '5px 9px',
1146
+ alignItems: 'center',
1147
+ marginBottom: 4,
1148
+ } satisfies CSSProperties,
1149
+ fieldLabel: {
1150
+ fontSize: '0.75em',
1151
+ letterSpacing: '0.05em',
1152
+ textTransform: 'uppercase',
1153
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
1154
+ } satisfies CSSProperties,
1155
+ input: {
1156
+ border: BORDER,
1157
+ borderRadius: 4,
1158
+ padding: '2px 6px',
1159
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
1160
+ color: 'inherit',
1161
+ font: 'inherit',
1162
+ fontSize: '0.85em',
1163
+ minWidth: 0,
1164
+ } satisfies CSSProperties,
1165
+ /**
1166
+ * The read-only Detail row. A mount detail is a multi-line diagnostic, and an
1167
+ * `<input>` collapses its line breaks — the operator would lose exactly the
1168
+ * structure that makes the message readable.
1169
+ */
1170
+ fieldText: {
1171
+ border: BORDER,
1172
+ borderRadius: 4,
1173
+ padding: '2px 6px',
1174
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
1175
+ color: 'inherit',
1176
+ font: 'inherit',
1177
+ fontSize: '0.85em',
1178
+ minWidth: 0,
1179
+ whiteSpace: 'pre-wrap',
1180
+ overflowWrap: 'anywhere',
1181
+ } satisfies CSSProperties,
1182
+ fieldHint: {
1183
+ margin: '-2px 0 6px 99px',
1184
+ fontSize: '0.8em',
1185
+ opacity: 0.6,
1186
+ overflowWrap: 'anywhere',
1187
+ } satisfies CSSProperties,
1188
+ fieldGroup: {
1189
+ display: 'grid',
1190
+ gridTemplateColumns: '90px 1fr',
1191
+ gap: '4px 9px',
1192
+ alignItems: 'start',
1193
+ marginBottom: 5,
1194
+ } satisfies CSSProperties,
1195
+ fieldRow: { display: 'flex', gap: 4, alignItems: 'center', marginBottom: 3 } satisfies CSSProperties,
1196
+ fieldKey: {
1197
+ flex: 'none',
1198
+ minWidth: 90,
1199
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
1200
+ fontSize: '0.8em',
1201
+ overflowWrap: 'anywhere',
1202
+ } satisfies CSSProperties,
1203
+ iconButton: {
1204
+ flex: 'none',
1205
+ padding: '1px 5px',
1206
+ borderRadius: 4,
1207
+ border: BORDER,
1208
+ background: 'transparent',
1209
+ color: 'inherit',
1210
+ cursor: 'pointer',
1211
+ font: 'inherit',
1212
+ fontSize: '0.8em',
1213
+ } satisfies CSSProperties,
1214
+ confirm: {
1215
+ marginTop: 6,
1216
+ padding: '7px 9px',
1217
+ border: BORDER,
1218
+ borderRadius: 6,
1219
+ background: 'var(--dsw-alias-bg-layer-2, transparent)',
1220
+ display: 'flex',
1221
+ flexDirection: 'column',
1222
+ gap: 4,
1223
+ } satisfies CSSProperties,
1224
+ noteOk: {
1225
+ marginTop: 8,
1226
+ padding: '5px 7px',
1227
+ borderLeft: '2px solid var(--dsw-alias-state-success-primary, #22c55e)',
1228
+ background: 'var(--dsw-alias-state-success-tertiary, transparent)',
1229
+ fontSize: '0.85em',
1230
+ overflowWrap: 'anywhere',
1231
+ } satisfies CSSProperties,
1232
+ noteError: {
1233
+ marginTop: 8,
1234
+ padding: '5px 7px',
1235
+ borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',
1236
+ background: 'var(--dsw-alias-interactive-bg-hover-danger, var(--dsw-alias-state-error-tertiary, transparent))',
1237
+ borderRadius: '0 5px 5px 0',
1238
+ fontSize: '0.85em',
1239
+ overflowWrap: 'anywhere',
1240
+ maxWidth: COPY_COLUMN,
1241
+ } satisfies CSSProperties,
1242
+ errorState: { padding: '10px 12px' } satisfies CSSProperties,
1243
+ stateTitle: { opacity: 0.9, marginBottom: 4 } satisfies CSSProperties,
1244
+ /** Muted one-liner under a row or a card: a short label, never a paragraph. */
1245
+ hint: {
1246
+ opacity: 0.6,
1247
+ fontSize: '0.85em',
1248
+ overflowWrap: 'anywhere',
1249
+ maxWidth: COPY_COLUMN,
1250
+ } satisfies CSSProperties,
1251
+ codeLine: {
1252
+ margin: '6px auto 0',
1253
+ maxWidth: 560,
1254
+ padding: '5px 8px',
1255
+ border: BORDER,
1256
+ borderRadius: 5,
1257
+ background: 'var(--dsw-alias-markdown-code-block, transparent)',
1258
+ color: 'var(--dsw-alias-link, inherit)',
1259
+ fontSize: '0.8em',
1260
+ fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',
1261
+ textAlign: 'left',
1262
+ } satisfies CSSProperties,
1263
+ } as const
1264
+
1265
+ // ── layout adaptivity ─────────────────────────────────────────────────────────
1266
+
1267
+ /**
1268
+ * The query the page stacks its split editor's panes on.
1269
+ *
1270
+ * The editor lives inside DSH's settings panel, not in the viewport: the panel
1271
+ * is `min(800px, 100vw - 48px)` wide, its navigation rail is 188px and its
1272
+ * options column pads 24px per side, so the page is given `min(564px, 100vw -
1273
+ * 284px)`. Three panes need all 564px of that, which is why they are flexible;
1274
+ * a viewport below 848px starts shrinking the panel itself, and three panes
1275
+ * there are slivers. The query sits at that break, so the panes stack whenever
1276
+ * the settings panel is not at its full 800px width.
1277
+ */
1278
+ export const NARROW_SETTINGS_QUERY = '(max-width: 850px)'
1279
+
1280
+ /** Just enough of `MediaQueryList` for the detector, so tests need no DOM. */
1281
+ export interface MediaQueryLike {
1282
+ /** `true` while the query matches the current viewport. */
1283
+ matches: boolean
1284
+ /** Optional, so a test double can drive the flag by hand. */
1285
+ addEventListener?(type: 'change', listener: () => void): void
1286
+ /** Optional, for the same reason. */
1287
+ removeEventListener?(type: 'change', listener: () => void): void
1288
+ }
1289
+
1290
+ /** One `matchMedia` query, as the detector asks for it. */
1291
+ export type MediaQueryMatcher = (query: string) => MediaQueryLike
1292
+
1293
+ /**
1294
+ * The browser's media-query matcher, or undefined when this half runs without
1295
+ * one — a non-browser host, or a policy that blocks the property.
1296
+ * @returns a matcher bound to the host, or undefined.
1297
+ */
1298
+ export function browserMatchMedia(): MediaQueryMatcher | undefined {
1299
+ try {
1300
+ const host = globalThis as { matchMedia?: MediaQueryMatcher }
1301
+ if (typeof host.matchMedia !== 'function') return undefined
1302
+ const match = host.matchMedia
1303
+ return (query) => match.call(host, query)
1304
+ } catch {
1305
+ // Reading the property itself throws when a policy blocks it.
1306
+ return undefined
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * Resolve the narrow layout against a media-query matcher.
1312
+ * @param match - the browser's matcher, or undefined outside a browser.
1313
+ * @returns `true` when the panes must stack; `false` without a matcher.
1314
+ */
1315
+ export function narrowSettingsLayout(match: MediaQueryMatcher | undefined): boolean {
1316
+ return match?.(NARROW_SETTINGS_QUERY).matches === true
1317
+ }
1318
+
1319
+ /**
1320
+ * The narrow flag the page renders with, tracked across viewport resizes.
1321
+ *
1322
+ * Only the shell reads the media query: everything below it takes the flag as a
1323
+ * prop, which is what lets the no-DOM tests render both layouts.
1324
+ * @returns `true` while the viewport is at or below {@link NARROW_SETTINGS_QUERY}.
1325
+ */
1326
+ export function useNarrowSettings(): boolean {
1327
+ const [narrow, setNarrow] = useState(() => narrowSettingsLayout(browserMatchMedia()))
1328
+ useEffect(() => {
1329
+ const match = browserMatchMedia()
1330
+ if (match === undefined) return undefined
1331
+ const list = match(NARROW_SETTINGS_QUERY)
1332
+ const sync = (): void => setNarrow(list.matches === true)
1333
+ sync()
1334
+ list.addEventListener?.('change', sync)
1335
+ return () => list.removeEventListener?.('change', sync)
1336
+ }, [])
1337
+ return narrow
1338
+ }
1339
+
1340
+ // ── entry draft ───────────────────────────────────────────────────────────────
1341
+
1342
+ /**
1343
+ * One `env`/`headers` row as the editor holds it.
1344
+ *
1345
+ * The row is the key plus what the input shows, never a copy of the declared
1346
+ * value: a masked key the user did not touch carries no value at all, which is
1347
+ * exactly what {@link draftEntry} has to submit for it.
1348
+ */
1349
+ export interface FieldDraft {
1350
+ /** Key exactly as the document declares it, or the key being typed. */
1351
+ key: string
1352
+ /** What the value input shows; empty for a masked key until it is replaced. */
1353
+ text: string
1354
+ /** `true` when the host withheld the declared value as a secret. */
1355
+ masked: boolean
1356
+ /** `true` when the key resolves through the credentials file, not the document. */
1357
+ fromCredentials: boolean
1358
+ /** `true` once the user typed into a masked input, even back to empty. */
1359
+ replaced: boolean
1360
+ /** `true` for a row the user added; only its key is still editable. */
1361
+ added: boolean
1362
+ }
1363
+
1364
+ /**
1365
+ * The form state of one open row.
1366
+ *
1367
+ * Optional entry fields hold exactly what the snapshot reported — `undefined`
1368
+ * means the document declares nothing — so an untouched draft rebuilds the
1369
+ * declared entry field for field and the editor opens clean instead of
1370
+ * announcing a change the user never made.
1371
+ */
1372
+ export interface EntryDraft {
1373
+ /** Server the draft belongs to; a draft built for another row is ignored. */
1374
+ server: string
1375
+ /** `documentRevision` the draft was built from. */
1376
+ revision: string | undefined
1377
+ transport: 'stdio' | 'streamable-http'
1378
+ command: string | undefined
1379
+ args: readonly string[] | undefined
1380
+ cwd: string | undefined
1381
+ url: string | undefined
1382
+ /** `stdio`: declared environment, with the masked keys among them. */
1383
+ env: FieldDraft[]
1384
+ /** `true` when the declaration carried an `env`, so an emptied list still writes one. */
1385
+ envDeclared: boolean
1386
+ /** `streamable-http`: declared headers, with the masked keys among them. */
1387
+ headers: FieldDraft[]
1388
+ /** `true` when the declaration carried `headers`. */
1389
+ headersDeclared: boolean
1390
+ /** `enabled` exactly as declared: `undefined` means the document sets nothing. */
1391
+ enabled: boolean | undefined
1392
+ /** Milliseconds as typed; `''` means the declaration sets no timeout. */
1393
+ connectTimeoutMs: string
1394
+ /** Declared keys the editor never presents, written back untouched. */
1395
+ extra: Readonly<Record<string, unknown>>
1396
+ }
1397
+
1398
+ /** Build the editable rows of one `env`/`headers` list. */
1399
+ export function fieldDrafts(fields: readonly EntryField[] | undefined): FieldDraft[] {
1400
+ return (fields ?? []).map((field) => ({
1401
+ key: field.key,
1402
+ text: field.value ?? '',
1403
+ masked: field.masked === true,
1404
+ fromCredentials: field.fromCredentials === true,
1405
+ replaced: false,
1406
+ added: false,
1407
+ }))
1408
+ }
1409
+
1410
+ /**
1411
+ * The draft the editor opens on: the snapshot's own entry, field for field.
1412
+ * @param row - the row being edited.
1413
+ * @returns the draft, or undefined when the host did not parse the entry.
1414
+ */
1415
+ export function draftOf(row: ServerRow): EntryDraft | undefined {
1416
+ const entry = row.entry
1417
+ if (entry === undefined) return undefined
1418
+ return {
1419
+ server: row.name,
1420
+ revision: row.documentRevision,
1421
+ transport: entry.transport,
1422
+ command: entry.command,
1423
+ args: entry.args,
1424
+ cwd: entry.cwd,
1425
+ url: entry.url,
1426
+ env: fieldDrafts(entry.env),
1427
+ envDeclared: entry.env !== undefined,
1428
+ headers: fieldDrafts(entry.headers),
1429
+ headersDeclared: entry.headers !== undefined,
1430
+ enabled: entry.enabled,
1431
+ connectTimeoutMs: entry.connectTimeoutMs === undefined ? '' : String(entry.connectTimeoutMs),
1432
+ extra: entry.extra ?? {},
1433
+ }
1434
+ }
1435
+
1436
+ /**
1437
+ * The draft actually shown: the stored one while it still belongs to this row
1438
+ * and this document revision, otherwise a fresh one.
1439
+ *
1440
+ * A background poll that re-reads a changed document therefore drops a stale
1441
+ * edit instead of writing it back on the snapshot's revision: the save would be
1442
+ * refused as `conflict` anyway.
1443
+ * @param row - the row being edited.
1444
+ * @param stored - the draft the shell still holds, if any.
1445
+ * @returns the draft to render, or undefined when there is nothing to edit.
1446
+ */
1447
+ export function activeDraft(row: ServerRow, stored: EntryDraft | undefined): EntryDraft | undefined {
1448
+ const fresh = draftOf(row)
1449
+ if (fresh === undefined) return undefined
1450
+ if (stored === undefined || stored.server !== row.name || stored.revision !== row.documentRevision) {
1451
+ return fresh
1452
+ }
1453
+ return stored
1454
+ }
1455
+
1456
+ /** One declared key as the save request carries it; undefined when it is not ours to write. */
1457
+ function fieldOf(row: FieldDraft): EntryField | undefined {
1458
+ if (row.key === '') return undefined
1459
+ // A key the credentials file answers is not editable, but it must still be
1460
+ // submitted: the host replaces the whole `env`/`headers` object with what this
1461
+ // request carries, so a dropped key is a key deleted from the document — the
1462
+ // reference to the credential would vanish on any unrelated edit. The host
1463
+ // writes the declared text back for a `fromCredentials` field and never a value
1464
+ // from here.
1465
+ if (row.fromCredentials) return { key: row.key, masked: true, fromCredentials: true }
1466
+ // Untouched and masked: no value at all, so the document keeps its secret.
1467
+ if (row.masked && !row.replaced) return { key: row.key, masked: true }
1468
+ return { key: row.key, value: row.text }
1469
+ }
1470
+
1471
+ function fieldsOf(rows: readonly FieldDraft[]): EntryField[] {
1472
+ const fields: EntryField[] = []
1473
+ for (const row of rows) {
1474
+ const field = fieldOf(row)
1475
+ if (field !== undefined) fields.push(field)
1476
+ }
1477
+ return fields
1478
+ }
1479
+
1480
+ /** The timeout as typed, or undefined when the field is empty or not a duration. */
1481
+ export function timeoutOf(text: string): number | undefined {
1482
+ if (text.trim() === '') return undefined
1483
+ const value = Number(text)
1484
+ return Number.isInteger(value) && value >= 0 ? value : undefined
1485
+ }
1486
+
1487
+ /** `true` when the timeout field holds something that is not a duration. */
1488
+ export function timeoutInvalid(text: string): boolean {
1489
+ return text.trim() !== '' && timeoutOf(text) === undefined
1490
+ }
1491
+
1492
+ /**
1493
+ * The entry a save writes: the whole declaration, rebuilt from the draft.
1494
+ *
1495
+ * Everything the editor presents is taken from the draft; `extra` rides along
1496
+ * untouched, because a save replaces `mcpServers[server]` wholesale and dropping
1497
+ * the keys the form never showed would delete configuration.
1498
+ * @param draft - the open row's form state.
1499
+ * @returns the entry body of a {@link SaveRequest}.
1500
+ */
1501
+ export function draftEntry(draft: EntryDraft): EntrySnapshot {
1502
+ const env = fieldsOf(draft.env)
1503
+ const headers = fieldsOf(draft.headers)
1504
+ const timeout = timeoutOf(draft.connectTimeoutMs)
1505
+ const body: EntrySnapshot =
1506
+ draft.transport === 'stdio'
1507
+ ? {
1508
+ transport: 'stdio',
1509
+ ...(draft.command === undefined ? {} : { command: draft.command }),
1510
+ ...(draft.args === undefined ? {} : { args: draft.args }),
1511
+ ...(draft.cwd === undefined ? {} : { cwd: draft.cwd }),
1512
+ ...(env.length === 0 && !draft.envDeclared ? {} : { env }),
1513
+ }
1514
+ : {
1515
+ transport: 'streamable-http',
1516
+ ...(draft.url === undefined ? {} : { url: draft.url }),
1517
+ ...(headers.length === 0 && !draft.headersDeclared ? {} : { headers }),
1518
+ }
1519
+ return {
1520
+ ...body,
1521
+ ...(draft.enabled === undefined ? {} : { enabled: draft.enabled }),
1522
+ ...(timeout === undefined ? {} : { connectTimeoutMs: timeout }),
1523
+ ...(Object.keys(draft.extra).length === 0 ? {} : { extra: draft.extra }),
1524
+ }
1525
+ }
1526
+
1527
+ /**
1528
+ * The save request for one row, or undefined when the snapshot does not carry
1529
+ * what a write needs (the row has no declaring document or no revision).
1530
+ */
1531
+ export function saveRequestOf(
1532
+ project: ProjectSnapshot,
1533
+ row: ServerRow,
1534
+ entry: EntrySnapshot,
1535
+ consent: boolean,
1536
+ ): SaveRequest | undefined {
1537
+ if (row.source === undefined || row.documentRevision === undefined) return undefined
1538
+ return {
1539
+ projectRoot: project.projectRoot,
1540
+ server: row.name,
1541
+ document: row.source,
1542
+ revision: row.documentRevision,
1543
+ ...(row.writeScope === 'global' ? { consent } : {}),
1544
+ entry,
1545
+ }
1546
+ }
1547
+
1548
+ // ── the JSON pane's diff ──────────────────────────────────────────────────────
1549
+
1550
+ /** One line of the JSON pane: shared context, or one side of a change. */
1551
+ export interface DiffLine {
1552
+ kind: 'context' | 'removed' | 'added'
1553
+ text: string
1554
+ }
1555
+
1556
+ /**
1557
+ * Line diff between two pretty-printed entries.
1558
+ *
1559
+ * A plain longest-common-subsequence walk: entries are small, and a faithful
1560
+ * diff is what makes the pane show the edit instead of a copy of the snapshot.
1561
+ * @param before - the declared entry, line by line.
1562
+ * @param after - the entry the draft would write.
1563
+ * @returns every line of both sides, in reading order.
1564
+ */
1565
+ export function diffLines(before: readonly string[], after: readonly string[]): DiffLine[] {
1566
+ const table: number[][] = Array.from({ length: before.length + 1 }, () =>
1567
+ new Array<number>(after.length + 1).fill(0),
1568
+ )
1569
+ for (let i = before.length - 1; i >= 0; i -= 1) {
1570
+ for (let j = after.length - 1; j >= 0; j -= 1) {
1571
+ const row = table[i]
1572
+ const next = table[i + 1]
1573
+ if (row === undefined || next === undefined) continue
1574
+ row[j] =
1575
+ before[i] === after[j]
1576
+ ? (next[j + 1] ?? 0) + 1
1577
+ : Math.max(next[j] ?? 0, row[j + 1] ?? 0)
1578
+ }
1579
+ }
1580
+ const lines: DiffLine[] = []
1581
+ let i = 0
1582
+ let j = 0
1583
+ while (i < before.length && j < after.length) {
1584
+ const left = before[i] ?? ''
1585
+ const right = after[j] ?? ''
1586
+ if (left === right) {
1587
+ lines.push({ kind: 'context', text: left })
1588
+ i += 1
1589
+ j += 1
1590
+ } else if ((table[i + 1]?.[j] ?? 0) >= (table[i]?.[j + 1] ?? 0)) {
1591
+ lines.push({ kind: 'removed', text: left })
1592
+ i += 1
1593
+ } else {
1594
+ lines.push({ kind: 'added', text: right })
1595
+ j += 1
1596
+ }
1597
+ }
1598
+ for (; i < before.length; i += 1) lines.push({ kind: 'removed', text: before[i] ?? '' })
1599
+ for (; j < after.length; j += 1) lines.push({ kind: 'added', text: after[j] ?? '' })
1600
+ return lines
1601
+ }
1602
+
1603
+ /**
1604
+ * The entry in the shape the document holds it: the keys the form never showed
1605
+ * sit beside the parsed ones instead of under `extra`, and the keys that resolve
1606
+ * through the credentials file are gone, because the document does not declare
1607
+ * them at all.
1608
+ *
1609
+ * Both sides of the diff go through this, so an untouched draft compares equal
1610
+ * to the snapshot however the host bucketed the unparsed and credential keys.
1611
+ */
1612
+ export function entryBody(entry: EntrySnapshot): Record<string, unknown> {
1613
+ const body: Record<string, unknown> = { transport: entry.transport }
1614
+ if (entry.command !== undefined) body.command = entry.command
1615
+ if (entry.args !== undefined) body.args = entry.args
1616
+ if (entry.cwd !== undefined) body.cwd = entry.cwd
1617
+ const env = documentFields(entry.env)
1618
+ if (env !== undefined) body.env = env
1619
+ if (entry.url !== undefined) body.url = entry.url
1620
+ const headers = documentFields(entry.headers)
1621
+ if (headers !== undefined) body.headers = headers
1622
+ if (entry.enabled !== undefined) body.enabled = entry.enabled
1623
+ if (entry.connectTimeoutMs !== undefined) body.connectTimeoutMs = entry.connectTimeoutMs
1624
+ for (const [key, value] of Object.entries(entry.extra ?? {})) body[key] = value
1625
+ return body
1626
+ }
1627
+
1628
+ /** A declared list without the keys that only exist in the credentials file. */
1629
+ function documentFields(fields: readonly EntryField[] | undefined): EntryField[] | undefined {
1630
+ return fields?.filter((field) => field.fromCredentials !== true)
1631
+ }
1632
+
1633
+ /** The declared entry against the entry the draft would write, line by line. */
1634
+ export function entryDiff(declared: EntrySnapshot | undefined, edited: EntrySnapshot): DiffLine[] {
1635
+ const before = declared === undefined ? [] : JSON.stringify(entryBody(declared), null, 2).split('\n')
1636
+ return diffLines(before, JSON.stringify(entryBody(edited), null, 2).split('\n'))
1637
+ }
1638
+
1639
+ /** `true` when the draft would write something other than the declared entry. */
1640
+ export function entryDirty(declared: EntrySnapshot | undefined, edited: EntrySnapshot): boolean {
1641
+ return entryDiff(declared, edited).some((line) => line.kind !== 'context')
1642
+ }
1643
+
1644
+ /**
1645
+ * One `env`/`headers` list as the document holds it: a flat object of strings.
1646
+ *
1647
+ * The snapshot's own shape is a list of `{ key, value }` — that is what a diff
1648
+ * compares and what the JSON preview prints — while a document declares an
1649
+ * object. The pane edits the document, so this is the shape it shows.
1650
+ * @param fields - the draft's rows.
1651
+ * @returns the object; a key with no value (a secret the panel is not shown) and
1652
+ * a key answered outside the document are both left out, because neither has a
1653
+ * value the pane could print.
1654
+ */
1655
+ function recordFields(fields: readonly FieldDraft[]): Record<string, string> {
1656
+ const record: Record<string, string> = {}
1657
+ for (const field of fields) {
1658
+ if (field.key === '' || field.text === '' || field.fromCredentials === true) continue
1659
+ record[field.key] = field.text
1660
+ }
1661
+ return record
1662
+ }
1663
+
1664
+ /**
1665
+ * One draft as its document declares it: the shape a person writes in `mcp.json`.
1666
+ *
1667
+ * The keys a document cannot carry are the same ones {@link entryBody} drops: a
1668
+ * secret the panel is not shown has no value to print, and a key answered by the
1669
+ * project's `.env` or the credentials file is not in the document at all. Both
1670
+ * are kept by {@link draftFromJson} when the pane's text omits them, so editing
1671
+ * the body never erases one by accident.
1672
+ * @param draft - the entry the form and the pane edit.
1673
+ * @returns the declaration object the host would write.
1674
+ */
1675
+ export function documentBody(draft: EntryDraft): Record<string, unknown> {
1676
+ const body: Record<string, unknown> = { transport: draft.transport }
1677
+ if (draft.command !== undefined) body.command = draft.command
1678
+ if (draft.args !== undefined) body.args = draft.args
1679
+ if (draft.cwd !== undefined) body.cwd = draft.cwd
1680
+ if (draft.envDeclared) body.env = recordFields(draft.env)
1681
+ if (draft.url !== undefined) body.url = draft.url
1682
+ if (draft.headersDeclared) body.headers = recordFields(draft.headers)
1683
+ if (draft.enabled !== undefined) body.enabled = draft.enabled
1684
+ if (draft.connectTimeoutMs !== '') body.connectTimeoutMs = Number(draft.connectTimeoutMs)
1685
+ for (const [key, value] of Object.entries(draft.extra)) body[key] = value
1686
+ return body
1687
+ }
1688
+
1689
+ /** The entry as the JSON pane shows and writes it: the document's own body. */
1690
+ export function jsonBodyOf(draft: EntryDraft): string {
1691
+ return `${JSON.stringify(documentBody(draft), null, 2)}\n`
1692
+ }
1693
+
1694
+ /** One edit of the JSON pane: the draft it parses into, or why it does not. */
1695
+ export type JsonDraftAnswer = { draft: EntryDraft } | { error: string }
1696
+
1697
+ /** A string field, or `undefined` when the document sets nothing. */
1698
+ function jsonString(body: Record<string, unknown>, key: string): string | undefined | false {
1699
+ const value = body[key]
1700
+ if (value === undefined) return undefined
1701
+ return typeof value === 'string' ? value : false
1702
+ }
1703
+
1704
+ /** One `env`/`headers` pair of the parsed body, or `false` for a value that is not text. */
1705
+ function jsonFields(value: unknown, path: string): EntryField[] | undefined | false {
1706
+ if (value === undefined) return undefined
1707
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
1708
+ const fields: EntryField[] = []
1709
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
1710
+ if (typeof entry !== 'string') return false
1711
+ void path
1712
+ fields.push({ key, value: entry })
1713
+ }
1714
+ return fields
1715
+ }
1716
+
1717
+ /**
1718
+ * Read one JSON edit back into a draft.
1719
+ *
1720
+ * This is the inverse of {@link entryBody}, and it is deliberately the same
1721
+ * shape the form edits: whatever the pane parses becomes the draft the form
1722
+ * renders and the confirmation compares, so both entries edit one value.
1723
+ *
1724
+ * Two things the document cannot express are preserved rather than dropped:
1725
+ * keys answered outside it (the project's `.env` or the credentials file) are
1726
+ * not part of the body the pane shows, so a hand edit that omits them keeps the
1727
+ * ones the draft already had. Unknown keys travel in `extra` exactly as written,
1728
+ * because a save replaces the entry wholesale.
1729
+ * @param text - the pane's text.
1730
+ * @param base - the draft the pane opened on: its server, revision and the keys
1731
+ * the document does not carry.
1732
+ * @returns the parsed draft, or the first field that does not parse.
1733
+ */
1734
+ export function draftFromJson(text: string, base: EntryDraft): JsonDraftAnswer {
1735
+ let value: unknown
1736
+ try {
1737
+ value = JSON.parse(text)
1738
+ } catch (error) {
1739
+ return { error: error instanceof Error ? error.message : String(error) }
1740
+ }
1741
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
1742
+ return { error: 'not an object' }
1743
+ }
1744
+ const body = value as Record<string, unknown>
1745
+ const transport = body.transport
1746
+ if (transport !== 'stdio' && transport !== 'streamable-http') return { error: 'transport' }
1747
+
1748
+ const command = jsonString(body, 'command')
1749
+ if (command === false) return { error: 'command' }
1750
+ const cwd = jsonString(body, 'cwd')
1751
+ if (cwd === false) return { error: 'cwd' }
1752
+ const url = jsonString(body, 'url')
1753
+ if (url === false) return { error: 'url' }
1754
+
1755
+ let args: readonly string[] | undefined
1756
+ if (body.args !== undefined) {
1757
+ if (!Array.isArray(body.args)) return { error: 'args' }
1758
+ const lines: string[] = []
1759
+ for (const [index, entry] of body.args.entries()) {
1760
+ if (typeof entry !== 'string') return { error: `args[${index}]` }
1761
+ lines.push(entry)
1762
+ }
1763
+ args = lines
1764
+ }
1765
+
1766
+ const env = jsonFields(body.env, 'env')
1767
+ if (env === false) return { error: 'env' }
1768
+ const headers = jsonFields(body.headers, 'headers')
1769
+ if (headers === false) return { error: 'headers' }
1770
+
1771
+ const enabled = body.enabled
1772
+ if (enabled !== undefined && typeof enabled !== 'boolean') return { error: 'enabled' }
1773
+ const timeout = body.connectTimeoutMs
1774
+ if (timeout !== undefined && (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout < 0)) {
1775
+ return { error: 'connectTimeoutMs' }
1776
+ }
1777
+
1778
+ const known = new Set([
1779
+ 'transport',
1780
+ 'command',
1781
+ 'args',
1782
+ 'cwd',
1783
+ 'env',
1784
+ 'headers',
1785
+ 'url',
1786
+ 'enabled',
1787
+ 'connectTimeoutMs',
1788
+ ])
1789
+ const extra: Record<string, unknown> = {}
1790
+ for (const [key, entry] of Object.entries(body)) {
1791
+ if (!known.has(key)) extra[key] = entry
1792
+ }
1793
+
1794
+ /**
1795
+ * The parsed list, plus the keys the pane cannot show a value for.
1796
+ *
1797
+ * Both are keys the document holds and the pane's body does not print: a key
1798
+ * answered outside the document, and a secret whose value the host withholds.
1799
+ * The pane's text omitting them is "unchanged", not "deleted" — a save removes
1800
+ * a key when the draft drops it, and only the form's own row can do that.
1801
+ */
1802
+ const carryUnshown = (
1803
+ parsed: EntryField[] | undefined,
1804
+ was: readonly FieldDraft[],
1805
+ ): FieldDraft[] => {
1806
+ const text1 = (parsed ?? []).map((field) => ({
1807
+ key: field.key,
1808
+ text: field.value ?? '',
1809
+ masked: false,
1810
+ fromCredentials: false,
1811
+ replaced: false,
1812
+ added: false,
1813
+ }))
1814
+ const carried = new Set(text1.map((field) => field.key))
1815
+ for (const field of was) {
1816
+ const unshown = field.fromCredentials === true || (field.masked === true && field.text === '')
1817
+ if (unshown && !carried.has(field.key)) text1.push(field)
1818
+ }
1819
+ return text1
1820
+ }
1821
+
1822
+ return {
1823
+ draft: {
1824
+ server: base.server,
1825
+ revision: base.revision,
1826
+ // Every field above is narrowed to its real type by its own `false` check.
1827
+ transport,
1828
+ command,
1829
+ args,
1830
+ cwd,
1831
+ url,
1832
+ env: carryUnshown(env, base.env),
1833
+ envDeclared: env !== undefined,
1834
+ headers: carryUnshown(headers, base.headers),
1835
+ headersDeclared: headers !== undefined,
1836
+ enabled: enabled as boolean | undefined,
1837
+ connectTimeoutMs: timeout === undefined ? '' : String(timeout),
1838
+ extra,
1839
+ },
1840
+ }
1841
+ }
1842
+
1843
+ // ── saving ────────────────────────────────────────────────────────────────────
1844
+
1845
+ /** What the host answered to a save: written, or one of the frozen error codes. */
1846
+ export type SaveAnswer =
1847
+ | { readonly ok: true }
1848
+ | {
1849
+ readonly ok: false
1850
+ readonly code: SaveErrorCode
1851
+ readonly message: string
1852
+ /**
1853
+ * Wire code of `message` (`projectMcp.host` namespace), when the host
1854
+ * coded the refusal (F-48); `saveNotice` resolves it through the host
1855
+ * seat and an answer without it keeps the `hostMessage` wrapper.
1856
+ */
1857
+ readonly messageCode?: string | undefined
1858
+ /** Flat params of {@link SaveAnswer}'s messageCode, when it has any. */
1859
+ readonly messageParams?: Record<string, string> | undefined
1860
+ }
1861
+
1862
+ /** The sentence each frozen {@link SaveErrorCode} gets; the keys live in {@link EN}. */
1863
+ const SAVE_ERROR_KEYS: Record<SaveErrorCode, LocaleKey> = {
1864
+ invalid: 'saveErrorInvalid',
1865
+ blocked: 'saveErrorBlocked',
1866
+ conflict: 'saveErrorConflict',
1867
+ 'not-found': 'saveErrorNotFound',
1868
+ failed: 'saveErrorFailed',
1869
+ }
1870
+
1871
+ const SAVE_ERROR_CODES = Object.keys(SAVE_ERROR_KEYS) as SaveErrorCode[]
1872
+
1873
+ function codeOf(code: string | undefined): SaveErrorCode {
1874
+ return SAVE_ERROR_CODES.find((known) => known === code) ?? 'failed'
1875
+ }
1876
+
1877
+ /** The shape of the `{ ok, value | error }` envelope every host route answers with. */
1878
+ interface SaveEnvelope {
1879
+ ok?: boolean
1880
+ error?: { code?: string; message?: string; messageCode?: string; messageParams?: Record<string, string> }
1881
+ }
1882
+
1883
+ /**
1884
+ * `POST` one save and unwrap the envelope.
1885
+ *
1886
+ * Unlike the snapshot poll this never throws: every failure is one of the five
1887
+ * frozen codes, and `invalid` keeps the host's own text — the only place the
1888
+ * parser's reason reaches the user.
1889
+ * @param request - the entry, the document and the revision it was built from.
1890
+ * @returns the host's answer, normalized to {@link SaveAnswer}.
1891
+ */
1892
+ export async function postSave(request: SaveRequest): Promise<SaveAnswer> {
1893
+ try {
1894
+ const response = await fetch(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.save}`, {
1895
+ method: 'POST',
1896
+ headers: { 'content-type': 'application/json' },
1897
+ body: JSON.stringify(request),
1898
+ })
1899
+ const payload = (await response.json()) as SaveEnvelope
1900
+ if (payload.ok === true) return { ok: true }
1901
+ return {
1902
+ ok: false,
1903
+ code: codeOf(payload.error?.code),
1904
+ message: payload.error?.message ?? `request failed (${response.status})`,
1905
+ // The coded companions are optional on the wire: an old host's refusal
1906
+ // has none, and the notice falls back to the message.
1907
+ ...(typeof payload.error?.messageCode === 'string'
1908
+ ? { messageCode: payload.error.messageCode, messageParams: payload.error.messageParams }
1909
+ : {}),
1910
+ }
1911
+ } catch (error) {
1912
+ return { ok: false, code: 'failed', message: error instanceof Error ? error.message : String(error) }
1913
+ }
1914
+ }
1915
+
1916
+ /** One save answer, as a sentence, plus what the notice has to offer. */
1917
+ export interface SaveNotice {
1918
+ /** The sentence to show, one locale key per code. */
1919
+ text: string
1920
+ /** `true` when the document was written. */
1921
+ written: boolean
1922
+ /**
1923
+ * The host's own sentence, ready to render; only `invalid` shows it. A
1924
+ * coded refusal is resolved through the host seat and stands alone (F-48);
1925
+ * an uncoded one keeps the `hostMessage` wrapper it always had.
1926
+ */
1927
+ detail: string | undefined
1928
+ /** `true` when the page offers the re-read action that `conflict` asks for. */
1929
+ reRead: boolean
1930
+ }
1931
+
1932
+ /**
1933
+ * Turn a save answer into the sentence the page shows.
1934
+ * @param answer - the host's answer, normalized by {@link postSave}.
1935
+ * @param t - the UI-namespace seat.
1936
+ * @param hostT - the `projectMcp.host` seat for a coded refusal's message;
1937
+ * absent — or a seat that does not know the code — the payload's English
1938
+ * message answers, never the raw code.
1939
+ */
1940
+ export function saveNotice(answer: SaveAnswer, t: Translate, hostT?: Translate | undefined): SaveNotice {
1941
+ if (answer.ok) return { text: t('saveOk'), written: true, detail: undefined, reRead: false }
1942
+ return {
1943
+ text: t(SAVE_ERROR_KEYS[answer.code]),
1944
+ written: false,
1945
+ detail:
1946
+ answer.code !== 'invalid'
1947
+ ? undefined
1948
+ : answer.messageCode === undefined
1949
+ ? t('hostMessage', { message: answer.message })
1950
+ : resolveHost(hostT ?? hostTranslate(undefined), answer.messageCode, answer.messageParams, answer.message),
1951
+ reRead: answer.code === 'conflict',
1952
+ }
1953
+ }
1954
+
1955
+ // ── form controls ─────────────────────────────────────────────────────────────
1956
+
1957
+ /**
1958
+ * One control that feeds the save request.
1959
+ *
1960
+ * Enabled while the row may be written; when the tier is `readonly` it renders
1961
+ * disabled with the row's own `writeBlockedReason`. The internal `data-write`
1962
+ * marker lets the no-DOM tests find every such control without a rendered
1963
+ * document.
1964
+ */
1965
+ function formControl<T extends keyof ReactHTML>(
1966
+ kind: T,
1967
+ props: Record<string, unknown>,
1968
+ editable: boolean,
1969
+ reason: string,
1970
+ children?: ReactNode,
1971
+ ): ReactNode {
1972
+ const marked: Record<string, unknown> = {
1973
+ ...props,
1974
+ title: reason,
1975
+ 'data-write': true,
1976
+ ...(editable ? {} : { disabled: true }),
1977
+ }
1978
+ return h(kind, marked as never, children)
1979
+ }
1980
+
1981
+ /** A field the host owns: shown, never editable, with the reason why. */
1982
+ function hostField(label: string, value: string, reason: string): ReactNode {
1983
+ return h(
1984
+ 'div',
1985
+ { style: STYLE.field, key: label },
1986
+ h('span', { style: STYLE.fieldLabel }, label),
1987
+ h('input', {
1988
+ style: STYLE.input,
1989
+ value,
1990
+ readOnly: true,
1991
+ disabled: true,
1992
+ title: reason,
1993
+ 'aria-label': label,
1994
+ 'data-read': true,
1995
+ }),
1996
+ )
1997
+ }
1998
+
1999
+ /**
2000
+ * The same host-owned row for a value that carries line breaks — the mount
2001
+ * detail. It keeps the label, the read-only marker and the reason tooltip, but
2002
+ * renders pre-wrapped text so the diagnostic's structure survives.
2003
+ */
2004
+ function hostDetailField(label: string, value: string, reason: string): ReactNode {
2005
+ return h(
2006
+ 'div',
2007
+ { style: STYLE.field, key: label },
2008
+ h('span', { style: STYLE.fieldLabel }, label),
2009
+ h(
2010
+ 'div',
2011
+ {
2012
+ style: STYLE.fieldText,
2013
+ title: reason,
2014
+ 'aria-label': label,
2015
+ 'data-read': true,
2016
+ },
2017
+ value,
2018
+ ),
2019
+ )
2020
+ }
2021
+
2022
+ /** One editable text field of the parsed entry. */
2023
+ function textField(
2024
+ label: string,
2025
+ value: string,
2026
+ editable: boolean,
2027
+ reason: string,
2028
+ onChange: (value: string) => void,
2029
+ hint?: string,
2030
+ ): ReactNode {
2031
+ return h(
2032
+ 'div',
2033
+ { key: label },
2034
+ h(
2035
+ 'div',
2036
+ { style: STYLE.field },
2037
+ h('span', { style: STYLE.fieldLabel }, label),
2038
+ formControl(
2039
+ 'input',
2040
+ {
2041
+ style: STYLE.input,
2042
+ value,
2043
+ readOnly: !editable,
2044
+ 'aria-label': label,
2045
+ ...(editable
2046
+ ? { onChange: (event: { target: { value: string } }) => onChange(event.target.value) }
2047
+ : {}),
2048
+ },
2049
+ editable,
2050
+ reason,
2051
+ ),
2052
+ ),
2053
+ hint === undefined ? null : h('div', { style: STYLE.fieldHint }, hint),
2054
+ )
2055
+ }
2056
+
2057
+ /** Reproduce one `env`/`headers` list as key/value rows plus an add button. */
2058
+ function fieldList(
2059
+ label: string,
2060
+ rows: readonly FieldDraft[],
2061
+ editable: boolean,
2062
+ reason: string,
2063
+ t: Translate,
2064
+ hint: string,
2065
+ onChange: (rows: FieldDraft[]) => void,
2066
+ ): ReactNode {
2067
+ return h(
2068
+ 'div',
2069
+ { style: STYLE.fieldGroup, key: label },
2070
+ h('span', { style: STYLE.fieldLabel }, label),
2071
+ h(
2072
+ 'div',
2073
+ null,
2074
+ rows.length === 0 ? h('div', { style: STYLE.hint }, hint) : null,
2075
+ rows.map((row, index) =>
2076
+ h(
2077
+ 'div',
2078
+ { key: `${row.key}#${index}` },
2079
+ h(
2080
+ 'div',
2081
+ { style: STYLE.fieldRow },
2082
+ row.added
2083
+ ? formControl(
2084
+ 'input',
2085
+ {
2086
+ style: STYLE.input,
2087
+ value: row.key,
2088
+ placeholder: t('keyPlaceholder'),
2089
+ 'aria-label': t('keyField'),
2090
+ ...(editable
2091
+ ? {
2092
+ onChange: (event: { target: { value: string } }) =>
2093
+ onChange(replaceRow(rows, index, { key: event.target.value })),
2094
+ }
2095
+ : {}),
2096
+ },
2097
+ editable,
2098
+ reason,
2099
+ )
2100
+ : h('span', { style: STYLE.fieldKey, title: row.key }, row.key),
2101
+ row.fromCredentials
2102
+ ? h('input', {
2103
+ style: STYLE.input,
2104
+ value: row.text,
2105
+ readOnly: true,
2106
+ disabled: true,
2107
+ title: t('credentialsNote'),
2108
+ placeholder: t('credentialValue'),
2109
+ 'aria-label': `${row.key} — ${t('credentialsNote')}`,
2110
+ 'data-read': true,
2111
+ })
2112
+ : formControl(
2113
+ 'input',
2114
+ {
2115
+ style: STYLE.input,
2116
+ value: row.text,
2117
+ placeholder:
2118
+ row.masked && !row.replaced ? t('maskedValue') : t('valuePlaceholder'),
2119
+ 'aria-label': `${row.key} ${t('valueField')}`,
2120
+ ...(editable
2121
+ ? {
2122
+ onChange: (event: { target: { value: string } }) =>
2123
+ onChange(
2124
+ replaceRow(rows, index, {
2125
+ // A masked input becomes a replacement on the first
2126
+ // keystroke, even when the user clears it back to empty.
2127
+ text: event.target.value,
2128
+ replaced: row.masked ? true : row.replaced,
2129
+ }),
2130
+ ),
2131
+ }
2132
+ : {}),
2133
+ },
2134
+ editable,
2135
+ reason,
2136
+ ),
2137
+ row.fromCredentials || !editable
2138
+ ? null
2139
+ : h(
2140
+ 'button',
2141
+ {
2142
+ style: STYLE.iconButton,
2143
+ title: t('removeKeyHint'),
2144
+ 'aria-label': `${t('removeKey')} ${row.key}`,
2145
+ onClick: () => onChange(rows.filter((_entry, at) => at !== index)),
2146
+ },
2147
+ t('removeKey'),
2148
+ ),
2149
+ ),
2150
+ row.fromCredentials ? h('div', { style: STYLE.fieldHint }, t('credentialsNote')) : null,
2151
+ ),
2152
+ ),
2153
+ h(
2154
+ 'button',
2155
+ {
2156
+ style: { ...STYLE.button, fontSize: '0.8em' },
2157
+ disabled: !editable,
2158
+ title: editable ? t('addKeyHint') : reason,
2159
+ onClick: () =>
2160
+ onChange([
2161
+ ...rows,
2162
+ {
2163
+ key: '',
2164
+ text: '',
2165
+ masked: false,
2166
+ fromCredentials: false,
2167
+ replaced: false,
2168
+ added: true,
2169
+ },
2170
+ ]),
2171
+ },
2172
+ t('addKey'),
2173
+ ),
2174
+ ),
2175
+ )
2176
+ }
2177
+
2178
+ /** One row of a key/value list, replaced by key change or a typed value. */
2179
+ function replaceRow(
2180
+ rows: readonly FieldDraft[],
2181
+ index: number,
2182
+ patch: Partial<FieldDraft>,
2183
+ ): FieldDraft[] {
2184
+ return rows.map((row, at) => (at === index ? { ...row, ...patch } : row))
2185
+ }
2186
+
2187
+ /** The JSON pane's lines, coloured by side of the change. */
2188
+ /**
2189
+ * The reason a disabled control carries: the host's payload resolved through
2190
+ * the host namespace (a known code translates; an unknown one falls back to
2191
+ * the payload's own English, never the raw code), or the page's fallback when
2192
+ * the host reported no reason at all.
2193
+ */
2194
+ function blockedReason(row: ServerRow, t: Translate, hostT?: Translate | undefined): string {
2195
+ if (row.writeBlockedReason === undefined) return t('writeBlockedUnknown')
2196
+ return resolveHost(hostT ?? hostTranslate(undefined), row.blockedCode, row.blockedParams, row.writeBlockedReason)
2197
+ }
2198
+
2199
+ /** `true` when the row's declaring document may be rewritten at all. */
2200
+ function writable(row: ServerRow): boolean {
2201
+ return row.writeScope !== undefined && row.writeScope !== 'readonly'
2202
+ }
2203
+
2204
+ // ── the page ──────────────────────────────────────────────────────────────────
2205
+
2206
+ /**
2207
+ * Everything the page renders, as plain props — the tests drive this directly.
2208
+ *
2209
+ * The editor props ride along from {@link EditorProps}: the shell owns the draft
2210
+ * and the confirmation state, the page is a function of them.
2211
+ */
2212
+ export interface SettingsPageProps extends Omit<EditorProps, 'project' | 'row'> {
2213
+ /** Host snapshot, or undefined before the first poll lands. */
2214
+ snapshot: McpSnapshot | undefined
2215
+ /** Last fetch failure, when the host did not answer. */
2216
+ error: string | undefined
2217
+ /** True while a host action is in flight. */
2218
+ busy: boolean
2219
+ view: SettingsView
2220
+ onView: (view: SettingsView) => void
2221
+ /** Which page of this plugin's own settings page is open. */
2222
+ page: SettingsPageKey
2223
+ onPage: (page: SettingsPageKey) => void
2224
+ /** Selected project root; a stale value falls back to the first project. */
2225
+ selectedRoot: string | undefined
2226
+ onSelectProject: (projectRoot: string) => void
2227
+ /** Selected server name; opens the split editor. */
2228
+ selectedServer: string | undefined
2229
+ onSync: () => void
2230
+ /** Retry every failed mount of the selected project. */
2231
+ onRetry: () => void
2232
+ /** `true` while the table view also shows the snapshot's own JSON. */
2233
+ json: boolean
2234
+ onJson: (next: boolean) => void
2235
+ /** Switch one project's mode; written straight through to the host. */
2236
+ onMode: (projectRoot: string, mode: ToolMode) => void
2237
+ /** Roots with a mode write in flight. */
2238
+ modePending: ReadonlySet<string>
2239
+ /** Last refusal of a mode write, when the host did not take it. */
2240
+ modeError: string | undefined
2241
+ /** Wire companions of `modeError`, when the host coded the refusal (F-48). */
2242
+ modeErrorCode?: string | undefined
2243
+ /** Flat params of `modeErrorCode`. */
2244
+ modeErrorParams?: Record<string, string> | undefined
2245
+ /** Pin or unpin one tool of one project; the host stores it at once. */
2246
+ onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined
2247
+ /** Tool names with a pin write in flight. */
2248
+ pinPending?: ReadonlySet<string> | undefined
2249
+ /** Last refusal of a pin write, when the host did not take it. */
2250
+ pinError?: string | undefined
2251
+ /** Wire companions of `pinError`, when the host coded the refusal (F-48). */
2252
+ pinErrorCode?: string | undefined
2253
+ /** Flat params of `pinErrorCode`. */
2254
+ pinErrorParams?: Record<string, string> | undefined
2255
+ /** Choose which declaration of one contested name the project shows. */
2256
+ onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined
2257
+ /** Contested names with a choice write in flight, per `projectRoot` + name. */
2258
+ choicePending?: ReadonlySet<string> | undefined
2259
+ /** Last refusal of a choice write, when the host did not take it. */
2260
+ choiceError?: string | undefined
2261
+ /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */
2262
+ choiceErrorCode?: string | undefined
2263
+ /** Flat params of `choiceErrorCode`. */
2264
+ choiceErrorParams?: Record<string, string> | undefined
2265
+ }
2266
+
2267
+ /**
2268
+ * The registered component: wire the host poll, the remembered view and the
2269
+ * editor's own state into the pure page. Kept thin on purpose — everything below
2270
+ * this line is a plain function of its props, which is what the no-DOM tests
2271
+ * exercise.
2272
+ */
2273
+ export function SettingsTab(props: SettingsTabProps): ReactNode {
2274
+ const t = translateOf(props.t)
2275
+ const { snapshot, error, busy, run, reload } = useSnapshot(true, DEFAULT_REFRESH_MS)
2276
+ const [view, setView] = useState<SettingsView>(() => settingsViewOf())
2277
+ const [page, setPage] = useState<SettingsPageKey>(DEFAULT_SETTINGS_PAGE)
2278
+ const [selectedRoot, setSelectedRoot] = useState<string | undefined>(undefined)
2279
+ const [selectedServer, setSelectedServer] = useState<string | undefined>(undefined)
2280
+ const [modePending, setModePending] = useState<ReadonlySet<string>>(() => new Set())
2281
+ // Each refusal is the host's whole answer — prose plus the F-48 wire code
2282
+ // and its params — so the render site resolves the coded message through
2283
+ // the host seat and an old host's prose renders exactly as before.
2284
+ const [modeRefusal, setModeRefusal] = useState<PolicyRefusal | undefined>(undefined)
2285
+ // The other half of the policy: one row of the tool list disables while its own
2286
+ // pin is in flight, and the host's refusal is shown rather than reverted.
2287
+ const [pinPending, setPinPending] = useState<ReadonlySet<string>>(() => new Set())
2288
+ const [pinRefusal, setPinRefusal] = useState<PolicyRefusal | undefined>(undefined)
2289
+ // The durable answer to a name two declarations fight over: which of them the
2290
+ // project shows. One card disables while its own write is in flight.
2291
+ const [choicePending, setChoicePending] = useState<ReadonlySet<string>>(() => new Set())
2292
+ const [choiceRefusal, setChoiceRefusal] = useState<PolicyRefusal | undefined>(undefined)
2293
+ // The editor's own state: the draft the user is building, the confirmation
2294
+ // step, the consent a global write needs, and the last answer from the host.
2295
+ const [stored, setStored] = useState<EntryDraft | undefined>(undefined)
2296
+ /**
2297
+ * The JSON pane's parse error, held here rather than in the pane.
2298
+ *
2299
+ * The pane owns the text, but Save is decided here: a document must never be
2300
+ * written from text the pane could not read, so a failed parse blocks the
2301
+ * confirmation until the text parses again.
2302
+ */
2303
+ const [jsonError, setJsonError] = useState<string | undefined>(undefined)
2304
+ const [confirming, setConfirming] = useState(false)
2305
+ const [consent, setConsent] = useState(false)
2306
+ const [saveState, setSaveState] = useState<SaveAnswer | undefined>(undefined)
2307
+ const [saving, setSaving] = useState(false)
2308
+ // The one place the media query is read; the page below takes the flag as a prop.
2309
+ const narrow = useNarrowSettings()
2310
+ const resetEditor = useCallback((): void => {
2311
+ setStored(undefined)
2312
+ setConfirming(false)
2313
+ setConsent(false)
2314
+ setSaveState(undefined)
2315
+ setSaving(false)
2316
+ setJsonError(undefined)
2317
+ }, [])
2318
+ const chooseView = useCallback((next: SettingsView): void => {
2319
+ setView(next)
2320
+ persistSettingsView(next)
2321
+ }, [])
2322
+ const chooseProject = useCallback(
2323
+ (projectRoot: string): void => {
2324
+ setSelectedRoot(projectRoot)
2325
+ setSelectedServer(undefined)
2326
+ resetEditor()
2327
+ },
2328
+ [resetEditor],
2329
+ )
2330
+ const chooseServer = useCallback(
2331
+ (name: string | undefined): void => {
2332
+ setSelectedServer(name)
2333
+ resetEditor()
2334
+ },
2335
+ [resetEditor],
2336
+ )
2337
+ // Both operator actions act on the selected project and ask for the whole
2338
+ // snapshot back: this page lists every project, so a narrowed answer would
2339
+ // empty it, while the action itself must not start a server for a project the
2340
+ // user is not looking at. The toolbar's button and every broken row's own
2341
+ // `Retry` send exactly the same request.
2342
+ const sync = useCallback((): void => {
2343
+ void run(
2344
+ ROUTE_ACTIONS.sync,
2345
+ operatorBody(selectedProject(snapshot, selectedRoot)?.projectRoot, true),
2346
+ )
2347
+ }, [snapshot, selectedRoot, run])
2348
+ const retry = useCallback((): void => {
2349
+ void run(
2350
+ ROUTE_ACTIONS.retry,
2351
+ operatorBody(selectedProject(snapshot, selectedRoot)?.projectRoot, true),
2352
+ )
2353
+ }, [snapshot, selectedRoot, run])
2354
+ const [json, setJson] = useState(false)
2355
+ const chooseJson = useCallback((next: boolean): void => setJson(next), [])
2356
+ /**
2357
+ * Write one project's mode. The switch is not a draft: the host reads the mode
2358
+ * on each request assembly, so the answer of this call is the only source of
2359
+ * truth and a refusal is shown rather than silently reverted.
2360
+ */
2361
+ const onMode = useCallback(
2362
+ (projectRoot: string, mode: ToolMode): void => {
2363
+ setModeRefusal(undefined)
2364
+ void requestMode(policyBody(projectRoot, mode), {
2365
+ onStart: (root) => setModePending((previous) => new Set(previous).add(root)),
2366
+ onSettled: (root) =>
2367
+ setModePending((previous) => {
2368
+ const next = new Set(previous)
2369
+ next.delete(root)
2370
+ return next
2371
+ }),
2372
+ onRefused: (message, messageCode, messageParams) => setModeRefusal({ message, messageCode, messageParams }),
2373
+ })
2374
+ },
2375
+ [],
2376
+ )
2377
+ const onPin = useCallback((projectRoot: string, tool: string, pinned: boolean): void => {
2378
+ setPinRefusal(undefined)
2379
+ void requestPin(pinBody(projectRoot, tool, pinned), {
2380
+ onStart: (name) => setPinPending((previous) => new Set(previous).add(name)),
2381
+ onSettled: (name) =>
2382
+ setPinPending((previous) => {
2383
+ const next = new Set(previous)
2384
+ next.delete(name)
2385
+ return next
2386
+ }),
2387
+ onRefused: (message, messageCode, messageParams) => setPinRefusal({ message, messageCode, messageParams }),
2388
+ })
2389
+ }, [])
2390
+ const onChoice = useCallback(
2391
+ (projectRoot: string, server: string, choice: ConflictChoice): void => {
2392
+ setChoiceRefusal(undefined)
2393
+ const key = choiceKey(projectRoot, server)
2394
+ const settle = (): void =>
2395
+ setChoicePending((previous) => {
2396
+ const next = new Set(previous)
2397
+ next.delete(key)
2398
+ return next
2399
+ })
2400
+ setChoicePending((previous) => new Set(previous).add(key))
2401
+ void postConflict(conflictBody(projectRoot, server, choice))
2402
+ .then((answer) => {
2403
+ if (!answer.ok) {
2404
+ setChoiceRefusal({
2405
+ message: answer.message,
2406
+ messageCode: answer.messageCode,
2407
+ messageParams: answer.messageParams,
2408
+ })
2409
+ }
2410
+ })
2411
+ .finally(settle)
2412
+ },
2413
+ [],
2414
+ )
2415
+ const project = selectedProject(snapshot, selectedRoot)
2416
+ const row = project?.rows.find((entry) => entry.name === selectedServer)
2417
+ const draft = row === undefined ? undefined : activeDraft(row, stored)
2418
+ const onDraft = useCallback((next: EntryDraft): void => {
2419
+ setStored(next)
2420
+ // The form re-derives the pane's text from this draft, so whatever the pane
2421
+ // failed to parse is no longer what is on screen.
2422
+ setJsonError(undefined)
2423
+ }, [])
2424
+ const onJsonEdit = useCallback(
2425
+ (next: EntryDraft | undefined, error: string | undefined): void => {
2426
+ setJsonError(error)
2427
+ if (next !== undefined) setStored(next)
2428
+ },
2429
+ [],
2430
+ )
2431
+ const onDiscard = useCallback((): void => {
2432
+ setStored(undefined)
2433
+ setConfirming(false)
2434
+ setSaveState(undefined)
2435
+ }, [])
2436
+ const onAskSave = useCallback((): void => {
2437
+ setSaveState(undefined)
2438
+ setConfirming(true)
2439
+ }, [])
2440
+ const onCancelSave = useCallback((): void => setConfirming(false), [])
2441
+ const onConsent = useCallback((next: boolean): void => setConsent(next), [])
2442
+ const onReRead = useCallback((): void => {
2443
+ setStored(undefined)
2444
+ setConfirming(false)
2445
+ setSaveState(undefined)
2446
+ void reload()
2447
+ }, [reload])
2448
+ const onConfirmSave = useCallback((): void => {
2449
+ if (project === undefined || row === undefined || draft === undefined) return
2450
+ // Belt and braces with the disabled confirm button: a global write without
2451
+ // the explicit consent is never sent.
2452
+ if (row.writeScope === 'global' && !consent) return
2453
+ const request = saveRequestOf(project, row, draftEntry(draft), consent)
2454
+ if (request === undefined) return
2455
+ setSaving(true)
2456
+ void postSave(request).then((answer) => {
2457
+ setSaving(false)
2458
+ setConfirming(false)
2459
+ setSaveState(answer)
2460
+ if (!answer.ok) return
2461
+ // The write landed: drop the draft and pull the fresh snapshot the host
2462
+ // re-read after the save.
2463
+ setStored(undefined)
2464
+ setConsent(false)
2465
+ void reload()
2466
+ })
2467
+ }, [project, row, draft, consent, run, reload])
2468
+ return h(SettingsPage, {
2469
+ snapshot,
2470
+ error,
2471
+ busy,
2472
+ view,
2473
+ onView: chooseView,
2474
+ page,
2475
+ onPage: setPage,
2476
+ onMode,
2477
+ modePending,
2478
+ modeError: modeRefusal?.message,
2479
+ modeErrorCode: modeRefusal?.messageCode,
2480
+ modeErrorParams: modeRefusal?.messageParams,
2481
+ onPin,
2482
+ pinPending,
2483
+ pinError: pinRefusal?.message,
2484
+ pinErrorCode: pinRefusal?.messageCode,
2485
+ pinErrorParams: pinRefusal?.messageParams,
2486
+ onChoice,
2487
+ choicePending,
2488
+ choiceError: choiceRefusal?.message,
2489
+ choiceErrorCode: choiceRefusal?.messageCode,
2490
+ choiceErrorParams: choiceRefusal?.messageParams,
2491
+ selectedRoot,
2492
+ onSelectProject: chooseProject,
2493
+ selectedServer,
2494
+ onSelectServer: chooseServer,
2495
+ onSync: sync,
2496
+ onRetry: retry,
2497
+ json,
2498
+ onJson: chooseJson,
2499
+ draft,
2500
+ confirming,
2501
+ consent,
2502
+ saveState,
2503
+ saving,
2504
+ onDraft,
2505
+ onJsonEdit,
2506
+ jsonError,
2507
+ onDiscard,
2508
+ onAskSave,
2509
+ onCancelSave,
2510
+ onConsent,
2511
+ onConfirmSave,
2512
+ onReRead,
2513
+ narrow,
2514
+ t,
2515
+ hostT: props.hostT,
2516
+ })
2517
+ }
2518
+
2519
+ /**
2520
+ * The page: toolbar, then one state body. Exported so every state — before the
2521
+ * first poll, no live project, no declared server, a failed fetch — is asserted
2522
+ * without a DOM.
2523
+ * @param props - see {@link SettingsPageProps}.
2524
+ * @returns the page element tree.
2525
+ */
2526
+ export function SettingsPage(props: SettingsPageProps): ReactNode {
2527
+ const t = props.t
2528
+ const projects = props.snapshot?.projects ?? []
2529
+ return h(
2530
+ 'div',
2531
+ { style: STYLE.root },
2532
+ h(
2533
+ 'div',
2534
+ { style: STYLE.bar },
2535
+ projects.length === 0
2536
+ ? null
2537
+ : h(ProjectSelector, {
2538
+ projects,
2539
+ selected: props.selectedRoot,
2540
+ onSelect: props.onSelectProject,
2541
+ t,
2542
+ }),
2543
+ projects.length === 0
2544
+ ? null
2545
+ : h('span', { style: STYLE.muted }, liveProjectCount(projects.length, t)),
2546
+ h('span', { style: { flex: 1 } }),
2547
+ h(SettingsPageSwitch, { page: props.page, onChange: props.onPage, t }),
2548
+ // The view switch, the JSON reading and the way out of it belong to the
2549
+ // server page: `Tools` is one policy form, not a second way to read the
2550
+ // same documents, so it keeps the toolbar it shares and drops the rest.
2551
+ props.page === 'tools' ? null : h(ViewSwitch, { view: props.view, onChange: props.onView, t }),
2552
+ props.page === 'tools' || props.view !== 'table'
2553
+ ? null
2554
+ : h(
2555
+ 'button',
2556
+ {
2557
+ style: STYLE.button,
2558
+ 'aria-pressed': props.json,
2559
+ title: props.json ? t('hideJson') : t('showJson'),
2560
+ onClick: () => props.onJson(!props.json),
2561
+ },
2562
+ props.json ? t('hideJson') : t('showJson'),
2563
+ ),
2564
+ h(
2565
+ 'button',
2566
+ {
2567
+ style: STYLE.button,
2568
+ disabled: props.busy,
2569
+ title: t('syncHint'),
2570
+ onClick: props.onSync,
2571
+ },
2572
+ t('sync'),
2573
+ ),
2574
+ ),
2575
+ // A poll that fails after data has landed keeps the page: the rows stay, and
2576
+ // the failure is reported above them instead of replacing them.
2577
+ props.error === undefined || props.snapshot === undefined
2578
+ ? null
2579
+ : h(
2580
+ 'div',
2581
+ { style: STYLE.note },
2582
+ `${t('hostUnavailable')} `,
2583
+ h('span', { style: STYLE.hint }, props.error),
2584
+ ),
2585
+ h('div', { style: STYLE.body }, settingsBody(props)),
2586
+ )
2587
+ }
2588
+
2589
+ /**
2590
+ * The body below the toolbar: exactly one branch per situation, and every empty
2591
+ * branch names what is missing instead of showing an empty box.
2592
+ * @param props - see {@link SettingsPageProps}.
2593
+ * @returns the element tree below the toolbar.
2594
+ */
2595
+ export function settingsBody(props: SettingsPageProps): ReactNode {
2596
+ const t = props.t
2597
+ // The error state only when there is nothing to show; a later failure is
2598
+ // reported by the page above the rows it kept.
2599
+ if (props.error !== undefined && props.snapshot === undefined) {
2600
+ return h(
2601
+ 'div',
2602
+ { style: STYLE.errorState },
2603
+ h('div', { style: STYLE.stateTitle }, t('hostUnavailable')),
2604
+ h('div', { style: STYLE.hint }, t('hostUnavailableHint', { route: `${ROUTE_PREFIX}/snapshot` })),
2605
+ h('div', { style: STYLE.hint }, props.error),
2606
+ )
2607
+ }
2608
+ if (props.snapshot === undefined) {
2609
+ return h(
2610
+ 'div',
2611
+ { style: STYLE.errorState },
2612
+ emptyState(t('loading'), t('loadingHint')),
2613
+ )
2614
+ }
2615
+ const projects = props.snapshot.projects
2616
+ if (projects.length === 0) {
2617
+ return withCodeLine(t('noSessions'), t('noSessionsHint'), readPaths(props.snapshot, t))
2618
+ }
2619
+ const project = selectedProject(props.snapshot, props.selectedRoot)
2620
+ if (project === undefined) return null
2621
+ if (props.page === 'tools') {
2622
+ return h(ToolsPage, {
2623
+ project,
2624
+ rows: projectPolicyRows(projects),
2625
+ onMode: props.onMode,
2626
+ pending: props.modePending,
2627
+ modeError: props.modeError,
2628
+ modeErrorCode: props.modeErrorCode,
2629
+ modeErrorParams: props.modeErrorParams,
2630
+ onSync: props.onSync,
2631
+ onPin: props.onPin,
2632
+ pinPending: props.pinPending,
2633
+ pinError: props.pinError,
2634
+ pinErrorCode: props.pinErrorCode,
2635
+ pinErrorParams: props.pinErrorParams,
2636
+ onChoice: props.onChoice,
2637
+ choicePending: props.choicePending,
2638
+ choiceError: props.choiceError,
2639
+ choiceErrorCode: props.choiceErrorCode,
2640
+ choiceErrorParams: props.choiceErrorParams,
2641
+ t,
2642
+ hostT: props.hostT,
2643
+ })
2644
+ }
2645
+ const row = project.rows.find((entry) => entry.name === props.selectedServer)
2646
+ if (row !== undefined) {
2647
+ return h(EditorSplit, {
2648
+ project,
2649
+ row,
2650
+ onSelectServer: props.onSelectServer,
2651
+ draft: props.draft,
2652
+ confirming: props.confirming,
2653
+ consent: props.consent,
2654
+ saveState: props.saveState,
2655
+ saving: props.saving,
2656
+ onDraft: props.onDraft,
2657
+ onJsonEdit: props.onJsonEdit,
2658
+ jsonError: props.jsonError,
2659
+ onDiscard: props.onDiscard,
2660
+ onAskSave: props.onAskSave,
2661
+ onCancelSave: props.onCancelSave,
2662
+ onConsent: props.onConsent,
2663
+ onConfirmSave: props.onConfirmSave,
2664
+ onReRead: props.onReRead,
2665
+ narrow: props.narrow,
2666
+ t,
2667
+ hostT: props.hostT,
2668
+ })
2669
+ }
2670
+ if (project.rows.length === 0) {
2671
+ // Where to declare one: this project's own documents, as configured. An
2672
+ // empty list is the honest answer "nowhere", not a file name this bundle
2673
+ // would otherwise invent.
2674
+ const documents = (project.files ?? [])
2675
+ .filter((file) => file.scope === 'project')
2676
+ .map((file) => file.path)
2677
+ return documents.length === 0
2678
+ ? emptyState(t('noServers'), t('noServersNoPath'))
2679
+ : withCodeLine(t('noServers'), t('noServersHint'), documents.join(' · '))
2680
+ }
2681
+ return props.view === 'files'
2682
+ ? h(FileCards, {
2683
+ project,
2684
+ selectedServer: props.selectedServer,
2685
+ onSelectServer: props.onSelectServer,
2686
+ t,
2687
+ hostT: props.hostT,
2688
+ })
2689
+ : h(
2690
+ 'div',
2691
+ null,
2692
+ h(ServerTable, {
2693
+ project,
2694
+ selectedServer: props.selectedServer,
2695
+ onSelectServer: props.onSelectServer,
2696
+ onRetry: props.onRetry,
2697
+ busy: props.busy,
2698
+ t,
2699
+ hostT: props.hostT,
2700
+ }),
2701
+ // The table keeps the failure banners it renders; the JSON reading is an
2702
+ // extra, below them, and only while the toolbar's toggle is on.
2703
+ props.json ? h(JsonPreview, { project, t }) : null,
2704
+ )
2705
+ }
2706
+
2707
+ /** A centred empty state followed by the path or command that fixes it. */
2708
+ function withCodeLine(title: string, hint: string, code: string): ReactNode {
2709
+ return h('div', null, emptyState(title, hint), h('div', { style: STYLE.codeLine }, code))
2710
+ }
2711
+
2712
+ /** The `Table` / `By files` switch. Not a write: it only changes this page. */
2713
+ export function ViewSwitch(props: {
2714
+ view: SettingsView
2715
+ onChange: (view: SettingsView) => void
2716
+ t: Translate
2717
+ }): ReactNode {
2718
+ const item = (value: SettingsView, label: string): ReactNode =>
2719
+ h(
2720
+ 'button',
2721
+ {
2722
+ key: value,
2723
+ style:
2724
+ value === props.view
2725
+ ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }
2726
+ : STYLE.segmentItem,
2727
+ 'aria-pressed': value === props.view,
2728
+ onClick: () => props.onChange(value),
2729
+ },
2730
+ label,
2731
+ )
2732
+ return h(
2733
+ 'div',
2734
+ { style: STYLE.segment },
2735
+ item('table', props.t('viewTable')),
2736
+ item('files', props.t('viewFiles')),
2737
+ )
2738
+ }
2739
+
2740
+ /**
2741
+ * Project picker. The only seat on this page where another project is visible,
2742
+ * and it only ever selects which single project's rows the body renders.
2743
+ */
2744
+ export function ProjectSelector(props: {
2745
+ projects: readonly ProjectSnapshot[]
2746
+ selected: string | undefined
2747
+ onSelect: (projectRoot: string) => void
2748
+ t: Translate
2749
+ }): ReactNode {
2750
+ const value =
2751
+ props.selected !== undefined &&
2752
+ props.projects.some((project) => project.projectRoot === props.selected)
2753
+ ? props.selected
2754
+ : (props.projects[0]?.projectRoot ?? '')
2755
+ return h(
2756
+ 'label',
2757
+ { style: STYLE.muted },
2758
+ `${props.t('project')}: `,
2759
+ h(
2760
+ 'select',
2761
+ {
2762
+ style: STYLE.select,
2763
+ value,
2764
+ title: value,
2765
+ onChange: (event: { target: { value: string } }) => props.onSelect(event.target.value),
2766
+ },
2767
+ props.projects.map((project) =>
2768
+ h(
2769
+ 'option',
2770
+ { key: project.projectRoot, value: project.projectRoot },
2771
+ basename(project.projectRoot),
2772
+ ),
2773
+ ),
2774
+ ),
2775
+ )
2776
+ }
2777
+
2778
+ /** The dense overview: one row per declared server of the selected project. */
2779
+ /**
2780
+ * The table's status cell: the host's word for the row, in the colour of that
2781
+ * status, and — for a quiet row the host counted — how long it has been unused.
2782
+ *
2783
+ * The figure comes from the host's own `usage[server].lastUsedAt`; a row the
2784
+ * counters never recorded has nothing to print, and the cell stays the word it
2785
+ * has always been rather than saying `idle 0m`.
2786
+ */
2787
+ function statusCell(row: ServerRow, project: ProjectSnapshot, t: Translate): ReactNode {
2788
+ const idle = idleNote(row.status, project.usage?.[row.name]?.lastUsedAt, t)
2789
+ return h(
2790
+ 'td',
2791
+ { style: { ...STYLE.td, color: STATUS_COLOR[row.status] } },
2792
+ t(STATUS_KEYS[row.status]),
2793
+ idle === undefined ? null : h('span', { style: STYLE.hint }, ` ${idle}`),
2794
+ )
2795
+ }
2796
+
2797
+ export function ServerTable(props: {
2798
+ project: ProjectSnapshot
2799
+ selectedServer?: string | undefined
2800
+ onSelectServer: (name: string | undefined) => void
2801
+ /** Retry the project's failed mounts; absent while nothing can be written. */
2802
+ onRetry?: (() => void) | undefined
2803
+ /** `true` while a host action is in flight, so the row buttons stay still. */
2804
+ busy?: boolean | undefined
2805
+ t: Translate
2806
+ /** The host namespace's seat, for the rows' coded blocked reasons. */
2807
+ hostT?: Translate | undefined
2808
+ }): ReactNode {
2809
+ const t = props.t
2810
+ return h(
2811
+ 'div',
2812
+ { style: STYLE.tableScroll },
2813
+ h(
2814
+ 'table',
2815
+ { style: STYLE.table },
2816
+ h(
2817
+ 'thead',
2818
+ null,
2819
+ h(
2820
+ 'tr',
2821
+ null,
2822
+ h('th', { style: STYLE.th }, t('server')),
2823
+ h('th', { style: STYLE.th }, t('transport')),
2824
+ h('th', { style: STYLE.th }, t('status')),
2825
+ h('th', { style: STYLE.th }, t('source')),
2826
+ h('th', { style: STYLE.th }, t('on')),
2827
+ h('th', { style: STYLE.th }, ''),
2828
+ ),
2829
+ ),
2830
+ h(
2831
+ 'tbody',
2832
+ null,
2833
+ props.project.rows.map((row) =>
2834
+ h(
2835
+ 'tr',
2836
+ { key: row.name },
2837
+ h(
2838
+ 'td',
2839
+ { style: STYLE.td },
2840
+ statusDot(row.status, t),
2841
+ ' ',
2842
+ serverButton(row, row.name === props.selectedServer, props.onSelectServer, t, props.hostT),
2843
+ ),
2844
+ h('td', { style: STYLE.td }, h('span', { style: STYLE.muted }, row.transport ?? '—')),
2845
+ statusCell(row, props.project, t),
2846
+ h('td', { style: STYLE.td }, sourceLabel(row, props.project, t)),
2847
+ h('td', { style: STYLE.td }, enabledSwitch(row, t, props.hostT)),
2848
+ h('td', { style: STYLE.td }, rowAction(row, props, t)),
2849
+ ),
2850
+ ),
2851
+ ),
2852
+ ),
2853
+ ...props.project.rows
2854
+ .filter((row) => row.status === 'error' && row.detail !== undefined)
2855
+ .map((row) =>
2856
+ h(
2857
+ 'div',
2858
+ { style: STYLE.note, key: `detail-${row.name}` },
2859
+ h('strong', null, row.name),
2860
+ // The row passed the filter, so its detail is present; the seat
2861
+ // translates it when the host sent the wire code (F-48).
2862
+ ` — ${rowDetail(row, props.hostT) ?? ''}`,
2863
+ ),
2864
+ ),
2865
+ )
2866
+ }
2867
+
2868
+ /**
2869
+ * The table's last cell: the one action the row has.
2870
+ *
2871
+ * A broken row offers a real `Retry` — the host route is project-scoped, so it
2872
+ * sends the request the toolbar's own button sends. Every other row offers `…`,
2873
+ * which opens the entry in the split editor: on this surface a row is read-only,
2874
+ * so the only thing left to do with it is go and edit it. Both labels are keys;
2875
+ * neither control writes anything itself.
2876
+ * @param row - the server row.
2877
+ * @param props - the table's own props, for the action and the busy flag.
2878
+ * @param t - translate seat.
2879
+ * @returns the cell's content.
2880
+ */
2881
+ function rowAction(
2882
+ row: ServerRow,
2883
+ props: {
2884
+ onSelectServer: (name: string | undefined) => void
2885
+ onRetry?: (() => void) | undefined
2886
+ busy?: boolean | undefined
2887
+ },
2888
+ t: Translate,
2889
+ ): ReactNode {
2890
+ if (row.status === 'error' && props.onRetry !== undefined) {
2891
+ return h(
2892
+ 'button',
2893
+ {
2894
+ style: STYLE.button,
2895
+ title: t('retryHint'),
2896
+ disabled: props.busy === true,
2897
+ onClick: props.onRetry,
2898
+ },
2899
+ t('retry'),
2900
+ )
2901
+ }
2902
+ return h(
2903
+ 'button',
2904
+ {
2905
+ style: STYLE.button,
2906
+ title: t('rowActionsHint'),
2907
+ onClick: () => props.onSelectServer(row.name),
2908
+ },
2909
+ t('rowActionsMore'),
2910
+ )
2911
+ }
2912
+
2913
+ /**
2914
+ * The snapshot's own reading of a project's entries, as JSON.
2915
+ *
2916
+ * Built from the parsed entries the host published, not from the document on
2917
+ * disk: the page never reads a file, and this preview must not imply it does. A
2918
+ * row the host did not parse has no entry and is left out rather than invented.
2919
+ * @param project - the selected project.
2920
+ * @returns the two-space JSON body the preview prints.
2921
+ */
2922
+ export function projectJson(project: ProjectSnapshot): string {
2923
+ const servers: Record<string, unknown> = {}
2924
+ for (const row of project.rows) {
2925
+ if (row.entry === undefined) continue
2926
+ servers[row.name] = entryBody(row.entry)
2927
+ }
2928
+ return JSON.stringify({ mcpServers: servers }, null, 2)
2929
+ }
2930
+
2931
+ /**
2932
+ * The table view's optional JSON pane: the snapshot's entries, read-only.
2933
+ *
2934
+ * @param props - the project and the translate seat.
2935
+ * @returns the titled code block.
2936
+ */
2937
+ export function JsonPreview(props: { project: ProjectSnapshot; t: Translate }): ReactNode {
2938
+ return h(
2939
+ 'div',
2940
+ null,
2941
+ h('div', { style: STYLE.paneHead }, props.t('jsonPreview')),
2942
+ h('div', { style: STYLE.hint }, props.t('jsonPreviewHint')),
2943
+ h('pre', { style: STYLE.json }, projectJson(props.project)),
2944
+ )
2945
+ }
2946
+
2947
+ /** The "By files" overview: one card per declaring document, in priority order. */
2948
+ export function FileCards(props: {
2949
+ project: ProjectSnapshot
2950
+ selectedServer?: string | undefined
2951
+ onSelectServer: (name: string | undefined) => void
2952
+ t: Translate
2953
+ /** The host namespace's seat, for the rows' coded blocked reasons. */
2954
+ hostT?: Translate | undefined
2955
+ }): ReactNode {
2956
+ const t = props.t
2957
+ return h(
2958
+ 'div',
2959
+ null,
2960
+ fileGroups(props.project).map((group) =>
2961
+ h(
2962
+ 'div',
2963
+ { key: group.source, style: STYLE.card },
2964
+ h(
2965
+ 'div',
2966
+ { style: STYLE.cardHead },
2967
+ h(
2968
+ 'span',
2969
+ { style: STYLE.cardPath },
2970
+ group.source === '' ? t('documentUnknown') : group.label,
2971
+ ),
2972
+ group.priority?.global === true ? h('span', { style: STYLE.tag }, t('global')) : null,
2973
+ group.priority === undefined
2974
+ ? null
2975
+ : h('span', { style: STYLE.tag }, t('priority', { tier: group.priority.tier, total: group.priority.total })),
2976
+ h('span', { style: { flex: 1 } }),
2977
+ h('span', { style: STYLE.muted }, serverCount(group.rows.length, t)),
2978
+ ),
2979
+ group.rows.map((row) =>
2980
+ h(
2981
+ 'div',
2982
+ { key: row.name, style: STYLE.row },
2983
+ statusDot(row.status, t),
2984
+ serverButton(row, row.name === props.selectedServer, props.onSelectServer, t, props.hostT),
2985
+ row.transport === undefined
2986
+ ? null
2987
+ : h('span', { style: STYLE.tag }, row.transport),
2988
+ // The status carries the row's tone here too: the document view is
2989
+ // the same rows as the table, read by document instead of by column.
2990
+ h('span', { style: { ...STYLE.muted, color: STATUS_COLOR[row.status] } }, t(STATUS_KEYS[row.status])),
2991
+ h('span', { style: { flex: 1 } }),
2992
+ enabledSwitch(row, t, props.hostT),
2993
+ ),
2994
+ ),
2995
+ group.overrides.map((note, index) =>
2996
+ h(
2997
+ 'div',
2998
+ { key: `${note.name}#${index}`, style: STYLE.overrideNote },
2999
+ note.from === undefined
3000
+ ? t('overrideUnpinned', { name: note.name })
3001
+ : t('overrideFrom', { name: note.name, from: note.from }),
3002
+ ),
3003
+ ),
3004
+ ),
3005
+ ),
3006
+ )
3007
+ }
3008
+
3009
+ /** Everything the split editor renders, as plain props. */
3010
+ export interface EditorProps {
3011
+ /** Project the row belongs to; its root rides in the save request. */
3012
+ project: ProjectSnapshot
3013
+ /** The row being edited. */
3014
+ row: ServerRow
3015
+ /** Called with the server to open, or undefined to go back to the overview. */
3016
+ onSelectServer: (name: string | undefined) => void
3017
+ /**
3018
+ * The open row's form state, already resolved through {@link activeDraft} by
3019
+ * the shell: the stored draft while it still matches the row's revision, a
3020
+ * fresh one otherwise. Undefined when the host did not parse the entry.
3021
+ */
3022
+ draft: EntryDraft | undefined
3023
+ /** True while the confirmation step is open. */
3024
+ confirming: boolean
3025
+ /** Consent checkbox state; only `global` rows read it. */
3026
+ consent: boolean
3027
+ /** Last save answer, when one has landed. */
3028
+ saveState: SaveAnswer | undefined
3029
+ /** True while the save request is in flight. */
3030
+ saving: boolean
3031
+ /** The JSON pane's parse error, when the last edit did not parse. */
3032
+ jsonError?: string | undefined
3033
+ /** Report one JSON edit: a parsed draft, or the reason it did not parse. */
3034
+ onJsonEdit?: ((draft: EntryDraft | undefined, error: string | undefined) => void) | undefined
3035
+ onDraft: (draft: EntryDraft) => void
3036
+ onDiscard: () => void
3037
+ /** Open the confirmation step; writes nothing on its own. */
3038
+ onAskSave: () => void
3039
+ onCancelSave: () => void
3040
+ onConsent: (consent: boolean) => void
3041
+ /** Write the document: the only control that reaches the host. */
3042
+ onConfirmSave: () => void
3043
+ /** Refetch the snapshot after a `conflict`. */
3044
+ onReRead: () => void
3045
+ /**
3046
+ * Stack the three panes instead of laying them in a row. The shell passes
3047
+ * {@link useNarrowSettings}'s flag; the tests pass it by hand, which is why
3048
+ * the editor itself never reads the media query. Defaults to `false`.
3049
+ */
3050
+ narrow?: boolean | undefined
3051
+ t: Translate
3052
+ /**
3053
+ * The `projectMcp.host` seat for the host's coded messages (the blocked
3054
+ * reason is the first channel). Optional: absent outside a shell and in
3055
+ * tests, where the payload's English message renders exactly as before.
3056
+ */
3057
+ hostT?: Translate | undefined
3058
+ }
3059
+
3060
+ /**
3061
+ * One pane's rule for the current layout.
3062
+ * @param base - the pane's side-by-side rule.
3063
+ * @param stacked - the overrides for the stacked layout.
3064
+ * @param narrow - `true` while the panes render stacked.
3065
+ * @returns the style object the pane renders with.
3066
+ */
3067
+ function paneStyle(
3068
+ base: CSSProperties,
3069
+ stacked: CSSProperties,
3070
+ narrow: boolean,
3071
+ ): CSSProperties {
3072
+ return narrow ? { ...base, ...stacked } : base
3073
+ }
3074
+
3075
+ /**
3076
+ * The entry as JSON, editable: the pane under the form.
3077
+ *
3078
+ * One value, two views: the text is what the pane last showed or the user typed,
3079
+ * and every keystroke is parsed back into the shell's draft through
3080
+ * {@link draftFromJson}. A parse that fails leaves the draft alone and reports
3081
+ * the reason upward — the shell blocks Save on it, so a document can never be
3082
+ * written from text the pane could not read. The text re-syncs only when the
3083
+ * draft changes from somewhere else (the form above, another server): the draft
3084
+ * the pane itself produced is the one it already shows.
3085
+ * @param props - the draft, the write scope, the pane's own label and the
3086
+ * shell's error line.
3087
+ * @returns the editable body; its head belongs to the editor, which reads
3088
+ * whether the body differs from the snapshot.
3089
+ */
3090
+ export function JsonPane(props: {
3091
+ /** The draft the form and the pane both edit. */
3092
+ draft: EntryDraft
3093
+ /** `true` while the declaring document may be written. */
3094
+ editable: boolean
3095
+ /** Why it may not be written, when it may not. */
3096
+ reason: string
3097
+ /** The pane head's label: the document, and whether it differs from the snapshot. */
3098
+ label: string
3099
+ /** The parse error the shell holds, when the last edit did not parse. */
3100
+ error: string | undefined
3101
+ /** Report one edit: a parsed draft, or the reason it did not parse. */
3102
+ onJson?: ((draft: EntryDraft | undefined, error: string | undefined) => void) | undefined
3103
+ t: Translate
3104
+ }): ReactNode {
3105
+ const t = props.t
3106
+ const [text, setText] = useState(() => jsonBodyOf(props.draft))
3107
+ /** The draft this pane produced last, so its own echo does not overwrite the text. */
3108
+ const adopted = useRef<EntryDraft | undefined>(props.draft)
3109
+ useEffect(() => {
3110
+ if (props.draft === adopted.current) return
3111
+ adopted.current = props.draft
3112
+ setText(jsonBodyOf(props.draft))
3113
+ }, [props.draft])
3114
+ const change = (next: string): void => {
3115
+ setText(next)
3116
+ const answer = draftFromJson(next, props.draft)
3117
+ if ('error' in answer) {
3118
+ props.onJson?.(undefined, answer.error)
3119
+ return
3120
+ }
3121
+ adopted.current = answer.draft
3122
+ props.onJson?.(answer.draft, undefined)
3123
+ }
3124
+ return h(
3125
+ 'div',
3126
+ null,
3127
+ h('textarea', {
3128
+ style: props.editable ? STYLE.jsonArea : { ...STYLE.jsonArea, opacity: 0.75 },
3129
+ value: text,
3130
+ readOnly: !props.editable,
3131
+ spellCheck: false,
3132
+ 'aria-label': props.label,
3133
+ // The same marking the form's controls carry: this is a write control of
3134
+ // the document, and on a tier that may not be written it is disabled with
3135
+ // the host's own reason as its title.
3136
+ 'data-write': true,
3137
+ title: props.editable ? t('jsonEditHint') : props.reason,
3138
+ ...(props.editable ? {} : { disabled: true }),
3139
+ onChange: (event: { target: { value: string } }) => change(event.target.value),
3140
+ }),
3141
+ props.error === undefined
3142
+ ? null
3143
+ : h('div', { style: STYLE.noteError }, t('jsonInvalid', { reason: props.error })),
3144
+ )
3145
+ }
3146
+
3147
+ /**
3148
+ * The split editor: the project's servers on the left, and the entry on the
3149
+ * right — its fields, and the document body under them.
3150
+ *
3151
+ * One entry, two editors: the form's fields and the JSON pane both write the same
3152
+ * draft, and the pane parses every keystroke back into it. That is the one thing
3153
+ * the pane cannot delegate: text the pane cannot read leaves the draft alone and
3154
+ * blocks the write (the shell holds the reason), so a document is never saved
3155
+ * from something nobody parsed. A `readonly` tier keeps every control disabled
3156
+ * with `writeBlockedReason`. Nothing reaches the host before the confirmation
3157
+ * step: Save only opens it, and the confirm button inside it is the write. The
3158
+ * list and the entry column share the width they are given until `narrow` says
3159
+ * there is too little of it, and then everything stacks.
3160
+ */
3161
+ export function EditorSplit(props: EditorProps): ReactNode {
3162
+ const t = props.t
3163
+ const narrow = props.narrow === true
3164
+ const { project, row } = props
3165
+ const { draft } = props
3166
+ const declared = row.entry
3167
+ const edited = draft === undefined ? undefined : draftEntry(draft)
3168
+ const dirty = declared !== undefined && edited !== undefined && entryDirty(declared, edited)
3169
+ const parsed = draft !== undefined && edited !== undefined
3170
+ const editable = parsed && writable(row)
3171
+ const reason = blockedReason(row, t, props.hostT)
3172
+ const timeoutBad = draft !== undefined && timeoutInvalid(draft.connectTimeoutMs)
3173
+ const request = edited === undefined ? undefined : saveRequestOf(project, row, edited, props.consent)
3174
+ const jsonBad = props.jsonError !== undefined
3175
+ const saveEnabled =
3176
+ !props.saving && editable && dirty && !timeoutBad && !jsonBad && request !== undefined
3177
+ // The Save control is never silently dead: whatever disables it is its title.
3178
+ const saveReason = ((): string => {
3179
+ if (!parsed) return t('entryUnavailable')
3180
+ if (jsonBad) return t('saveJsonInvalid')
3181
+ if (!writable(row)) return reason
3182
+ if (timeoutBad) return t('saveTimeoutInvalid')
3183
+ if (request === undefined) return t('saveUnavailable')
3184
+ if (props.saving) return t('saving')
3185
+ if (!dirty) return t('saveNoChange')
3186
+ return t('saveHint')
3187
+ })()
3188
+ const global = row.writeScope === 'global'
3189
+ const confirmReady = !props.saving && (!global || props.consent)
3190
+ const source = row.source
3191
+ const label = source === undefined ? t('documentUnknown') : documentLabel(source, project.projectRoot)
3192
+ const backup = source === undefined ? undefined : `${source}.bak`
3193
+ const backupLabel =
3194
+ backup === undefined ? t('documentUnknown') : documentLabel(backup, project.projectRoot)
3195
+ const state = !parsed
3196
+ ? t('entryUnavailable')
3197
+ : writable(row)
3198
+ ? t('editableNote', { document: label, backup: backupLabel })
3199
+ : t('writeBlocked', { reason })
3200
+ return h(
3201
+ 'div',
3202
+ null,
3203
+ h(
3204
+ 'div',
3205
+ { style: STYLE.splitBar },
3206
+ h(
3207
+ 'button',
3208
+ {
3209
+ style: STYLE.button,
3210
+ title: t('backHint'),
3211
+ onClick: () => props.onSelectServer(undefined),
3212
+ },
3213
+ `‹ ${t('back')}`,
3214
+ ),
3215
+ h('span', { style: STYLE.hint, title: source ?? project.projectRoot }, state),
3216
+ ),
3217
+ h(
3218
+ 'div',
3219
+ { style: paneStyle(STYLE.split, STYLE.splitNarrow, narrow) },
3220
+ h(
3221
+ 'div',
3222
+ {
3223
+ style: paneStyle(STYLE.paneList, STYLE.paneListNarrow, narrow),
3224
+ 'data-pane': 'list',
3225
+ },
3226
+ h('div', { style: STYLE.paneHead }, t('servers')),
3227
+ project.rows.map((entry) =>
3228
+ h(
3229
+ 'div',
3230
+ {
3231
+ key: entry.name,
3232
+ style:
3233
+ entry.name === row.name
3234
+ ? { ...STYLE.listItem, ...STYLE.listItemActive }
3235
+ : STYLE.listItem,
3236
+ },
3237
+ statusDot(entry.status, t),
3238
+ serverButton(entry, entry.name === row.name, props.onSelectServer, t, props.hostT),
3239
+ ),
3240
+ ),
3241
+ ),
3242
+ h(
3243
+ 'div',
3244
+ { style: paneStyle(STYLE.paneColumn, STYLE.paneColumnNarrow, narrow) },
3245
+ h(
3246
+ 'div',
3247
+ {
3248
+ style: paneStyle(STYLE.paneForm, STYLE.paneFormNarrow, narrow),
3249
+ 'data-pane': 'form',
3250
+ },
3251
+ // The form's own head: the pane below it holds the same entry in the
3252
+ // shape the document keeps, and the list is every declared server.
3253
+ h('div', { style: STYLE.paneHead }, t('paneEntry')),
3254
+ hostField(t('name'), row.name, t('nameReason')),
3255
+ ...(draft === undefined
3256
+ ? []
3257
+ : draftFields(draft, declared, editable, reason, t, props.onDraft)),
3258
+ hostField(t('status'), t(STATUS_KEYS[row.status]), t('statusReason')),
3259
+ hostField(t('source'), source ?? t('documentUnknown'), t('sourceReason')),
3260
+ hostDetailField(t('detail'), rowDetail(row, props.hostT) ?? '—', t('detailReason')),
3261
+ ),
3262
+ h(
3263
+ 'div',
3264
+ {
3265
+ style: paneStyle(STYLE.paneJson, STYLE.paneJsonNarrow, narrow),
3266
+ 'data-pane': 'json',
3267
+ },
3268
+ h(
3269
+ 'div',
3270
+ { style: STYLE.paneHead },
3271
+ draft === undefined || edited === undefined
3272
+ ? label
3273
+ : `${label} · ${dirty ? t('jsonDiff') : t('jsonClean')}`,
3274
+ ),
3275
+ draft === undefined || declared === undefined || edited === undefined
3276
+ ? h('div', { style: STYLE.json }, t('jsonUnavailable'))
3277
+ : h(JsonPane, {
3278
+ draft,
3279
+ editable,
3280
+ reason,
3281
+ label,
3282
+ error: props.jsonError,
3283
+ onJson: props.onJsonEdit,
3284
+ t,
3285
+ }),
3286
+ ),
3287
+ ),
3288
+ ),
3289
+ h(
3290
+ 'div',
3291
+ null,
3292
+ h(
3293
+ 'div',
3294
+ { style: STYLE.splitFooter },
3295
+ formControl(
3296
+ 'button',
3297
+ { style: STYLE.buttonPrimary, onClick: props.onAskSave },
3298
+ saveEnabled,
3299
+ saveReason,
3300
+ t('save'),
3301
+ ),
3302
+ h(
3303
+ 'button',
3304
+ {
3305
+ style: STYLE.button,
3306
+ disabled: !dirty,
3307
+ title: dirty ? t('discardHint') : t('discardReason'),
3308
+ onClick: props.onDiscard,
3309
+ },
3310
+ t('discard'),
3311
+ ),
3312
+ dirty ? h('span', { style: STYLE.tag }, t('unsaved')) : null,
3313
+ h('span', { style: { flex: 1 } }),
3314
+ h(
3315
+ 'span',
3316
+ {
3317
+ style: STYLE.hint,
3318
+ title: source ?? project.projectRoot,
3319
+ },
3320
+ t(writable(row) ? 'footerWrite' : 'footerReadonly', { document: label }),
3321
+ ),
3322
+ ),
3323
+ props.confirming
3324
+ ? confirmation({
3325
+ label,
3326
+ backupLabel,
3327
+ server: row.name,
3328
+ global,
3329
+ consent: props.consent,
3330
+ ready: confirmReady,
3331
+ saving: props.saving,
3332
+ t,
3333
+ onConsent: props.onConsent,
3334
+ onConfirm: props.onConfirmSave,
3335
+ onCancel: props.onCancelSave,
3336
+ })
3337
+ : null,
3338
+ props.saveState === undefined ? null : noticeBlock(props.saveState, t, props.onReRead, props.hostT),
3339
+ ),
3340
+ )
3341
+ }
3342
+
3343
+ /** The entry's own fields, for the transport the draft currently declares. */
3344
+ function draftFields(
3345
+ draft: EntryDraft,
3346
+ declared: EntrySnapshot | undefined,
3347
+ editable: boolean,
3348
+ reason: string,
3349
+ t: Translate,
3350
+ onDraft: (draft: EntryDraft) => void,
3351
+ ): ReactNode[] {
3352
+ const clearable = (value: string): string | undefined => (value === '' ? undefined : value)
3353
+ const transport = transportField(draft, editable, reason, t, onDraft)
3354
+ if (draft.transport === 'streamable-http') {
3355
+ return [
3356
+ transport,
3357
+ textField(t('urlField'), draft.url ?? '', editable, reason, (value) =>
3358
+ onDraft({ ...draft, url: clearable(value) }),
3359
+ ),
3360
+ fieldList(t('headersField'), draft.headers, editable, reason, t, t('headersHint'), (headers) =>
3361
+ onDraft({ ...draft, headers }),
3362
+ ),
3363
+ ...commonFields(draft, declared, editable, reason, t, onDraft),
3364
+ ]
3365
+ }
3366
+ return [
3367
+ transport,
3368
+ textField(t('commandField'), draft.command ?? '', editable, reason, (value) =>
3369
+ onDraft({ ...draft, command: clearable(value) }),
3370
+ ),
3371
+ textField(
3372
+ t('argsField'),
3373
+ (draft.args ?? []).join('\n'),
3374
+ editable,
3375
+ reason,
3376
+ (value) => onDraft({ ...draft, args: value === '' ? undefined : value.split('\n') }),
3377
+ t('argsHint'),
3378
+ ),
3379
+ textField(t('cwdField'), draft.cwd ?? '', editable, reason, (value) =>
3380
+ onDraft({ ...draft, cwd: clearable(value) }),
3381
+ ),
3382
+ fieldList(t('envField'), draft.env, editable, reason, t, t('envHint'), (env) =>
3383
+ onDraft({ ...draft, env }),
3384
+ ),
3385
+ ...commonFields(draft, declared, editable, reason, t, onDraft),
3386
+ ]
3387
+ }
3388
+
3389
+ /** Fields both transports carry: `enabled` and the connect timeout. */
3390
+ function commonFields(
3391
+ draft: EntryDraft,
3392
+ declared: EntrySnapshot | undefined,
3393
+ editable: boolean,
3394
+ reason: string,
3395
+ t: Translate,
3396
+ onDraft: (draft: EntryDraft) => void,
3397
+ ): ReactNode[] {
3398
+ const value = draft.enabled === undefined ? t('absent') : String(draft.enabled)
3399
+ return [
3400
+ h(
3401
+ 'div',
3402
+ { style: STYLE.field, key: 'enabled' },
3403
+ h('span', { style: STYLE.fieldLabel }, t('enabledField')),
3404
+ h(
3405
+ 'label',
3406
+ { style: { display: 'flex', alignItems: 'center', gap: 6 } },
3407
+ formControl(
3408
+ 'input',
3409
+ {
3410
+ type: 'checkbox',
3411
+ checked: draft.enabled !== false,
3412
+ style: STYLE.switch,
3413
+ 'aria-label': t('enabledField'),
3414
+ ...(editable
3415
+ ? {
3416
+ onChange: (event: { target: { checked: boolean } }) =>
3417
+ onDraft({
3418
+ ...draft,
3419
+ enabled: event.target.checked ? (declared?.enabled === true ? true : undefined) : false,
3420
+ }),
3421
+ }
3422
+ : {}),
3423
+ },
3424
+ editable,
3425
+ reason,
3426
+ ),
3427
+ h('span', { style: STYLE.hint }, t('enabledValue', { value })),
3428
+ ),
3429
+ ),
3430
+ textField(
3431
+ t('timeoutField'),
3432
+ draft.connectTimeoutMs,
3433
+ editable,
3434
+ reason,
3435
+ (value) => onDraft({ ...draft, connectTimeoutMs: value }),
3436
+ timeoutInvalid(draft.connectTimeoutMs) ? t('saveTimeoutInvalid') : t('timeoutHint'),
3437
+ ),
3438
+ ]
3439
+ }
3440
+
3441
+ /** The confirmation step: what is written where, and the consent it may need. */
3442
+ function confirmation(props: {
3443
+ label: string
3444
+ backupLabel: string
3445
+ server: string
3446
+ global: boolean
3447
+ consent: boolean
3448
+ ready: boolean
3449
+ saving: boolean
3450
+ t: Translate
3451
+ onConsent: (consent: boolean) => void
3452
+ onConfirm: () => void
3453
+ onCancel: () => void
3454
+ }): ReactNode {
3455
+ const { t } = props
3456
+ return h(
3457
+ 'div',
3458
+ { style: STYLE.confirm },
3459
+ h('div', { style: STYLE.stateTitle }, t('confirmTitle', { document: props.label })),
3460
+ h('div', { style: STYLE.hint }, t('confirmBackup', { backup: props.backupLabel })),
3461
+ h('div', { style: STYLE.hint }, t('confirmFormat', { server: props.server })),
3462
+ props.global ? h('div', { style: STYLE.hint }, t('confirmConsent')) : null,
3463
+ props.global
3464
+ ? h(
3465
+ 'label',
3466
+ { style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: '0.85em' } },
3467
+ h('input', {
3468
+ type: 'checkbox',
3469
+ checked: props.consent,
3470
+ style: STYLE.switch,
3471
+ 'aria-label': t('consentLabel'),
3472
+ onChange: (event: { target: { checked: boolean } }) =>
3473
+ props.onConsent(event.target.checked),
3474
+ }),
3475
+ t('consentLabel'),
3476
+ )
3477
+ : null,
3478
+ h(
3479
+ 'div',
3480
+ { style: STYLE.splitFooter },
3481
+ formControl(
3482
+ 'button',
3483
+ { style: STYLE.buttonPrimary, onClick: props.onConfirm },
3484
+ props.ready,
3485
+ props.ready ? t('confirmWriteHint') : props.saving ? t('saving') : t('confirmBlocked'),
3486
+ t('confirmWrite'),
3487
+ ),
3488
+ h('button', { style: STYLE.button, onClick: props.onCancel }, t('cancel')),
3489
+ ),
3490
+ )
3491
+ }
3492
+
3493
+ /** The sentence the last save answer gets, plus the actions it offers. */
3494
+ function noticeBlock(answer: SaveAnswer, t: Translate, onReRead: () => void, hostT?: Translate | undefined): ReactNode {
3495
+ const notice = saveNotice(answer, t, hostT)
3496
+ return h(
3497
+ 'div',
3498
+ { style: notice.written ? STYLE.noteOk : STYLE.noteError },
3499
+ notice.text,
3500
+ // The detail arrives ready to render: saveNotice applied the hostMessage
3501
+ // wrapper to an uncoded answer and the host seat to a coded one.
3502
+ notice.detail === undefined ? null : h('div', { style: STYLE.hint }, notice.detail),
3503
+ notice.reRead
3504
+ ? h('button', { style: STYLE.button, title: t('reReadHint'), onClick: onReRead }, t('reRead'))
3505
+ : null,
3506
+ )
3507
+ }
3508
+
3509
+ /** The transport field: the two transports the host maps. */
3510
+ function transportField(
3511
+ draft: EntryDraft,
3512
+ editable: boolean,
3513
+ reason: string,
3514
+ t: Translate,
3515
+ onDraft: (draft: EntryDraft) => void,
3516
+ ): ReactNode {
3517
+ return h(
3518
+ 'div',
3519
+ { style: STYLE.field, key: 'transport' },
3520
+ h('span', { style: STYLE.fieldLabel }, t('transport')),
3521
+ formControl(
3522
+ 'select',
3523
+ {
3524
+ style: STYLE.input,
3525
+ value: draft.transport,
3526
+ 'aria-label': t('transport'),
3527
+ ...(editable
3528
+ ? {
3529
+ onChange: (event: { target: { value: string } }) =>
3530
+ onDraft({
3531
+ ...draft,
3532
+ transport: event.target.value === 'streamable-http' ? 'streamable-http' : 'stdio',
3533
+ }),
3534
+ }
3535
+ : {}),
3536
+ },
3537
+ editable,
3538
+ reason,
3539
+ ['stdio', 'streamable-http'].map((option) => h('option', { key: option, value: option }, option)),
3540
+ ),
3541
+ )
3542
+ }
3543
+
3544
+ /** The Source column: the declaring document, or the project root fallback. */
3545
+ function sourceLabel(row: ServerRow, project: ProjectSnapshot, t: Translate): ReactNode {
3546
+ const label =
3547
+ row.source === undefined ? t('documentUnknown') : documentLabel(row.source, project.projectRoot)
3548
+ return h('span', { style: { ...STYLE.muted, fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)' }, title: row.source ?? project.projectRoot }, label)
3549
+ }
3550
+
3551
+ /** The row's `enabled` switch: the table edits nothing, so it opens the editor. */
3552
+ function enabledSwitch(row: ServerRow, t: Translate, hostT?: Translate | undefined): ReactNode {
3553
+ // The mockups draw the On column as their switch, not as a checkbox: the two
3554
+ // live states are the same fact (`enabled: false` is what `disabled` means),
3555
+ // and the switch is the shape the rest of the page's controls use. It is not
3556
+ // an editor either way — the click that opens the entry is the row's own.
3557
+ const on = row.status !== 'disabled'
3558
+ return formControl(
3559
+ 'button',
3560
+ {
3561
+ type: 'button',
3562
+ style: on ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },
3563
+ 'aria-checked': on,
3564
+ 'aria-label': t('on'),
3565
+ },
3566
+ false,
3567
+ writable(row) ? t('openToEdit') : blockedReason(row, t, hostT),
3568
+ h('span', {
3569
+ style: on ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob,
3570
+ 'aria-hidden': true,
3571
+ }),
3572
+ )
3573
+ }
3574
+
3575
+ /** A status dot; the colour and the wording both come from the shared vocabulary. */
3576
+ function statusDot(status: ServerStatus, t: Translate): ReactNode {
3577
+ return h('span', {
3578
+ style: { ...STYLE.dot, background: STATUS_COLOR[status] },
3579
+ title: t(STATUS_HINT[status]),
3580
+ 'aria-hidden': true,
3581
+ })
3582
+ }
3583
+
3584
+ /** A server name that selects it; selection is not a write. */
3585
+ function serverButton(
3586
+ row: ServerRow,
3587
+ selected: boolean,
3588
+ onSelect: (name: string | undefined) => void,
3589
+ t: Translate,
3590
+ hostT?: Translate | undefined,
3591
+ ): ReactNode {
3592
+ return h(
3593
+ 'button',
3594
+ {
3595
+ style: selected
3596
+ ? { ...STYLE.serverButton, ...STYLE.serverButtonActive }
3597
+ : STYLE.serverButton,
3598
+ title: rowDetail(row, hostT) ?? t(STATUS_HINT[row.status]),
3599
+ onClick: () => onSelect(selected ? undefined : row.name),
3600
+ },
3601
+ row.name,
3602
+ )
3603
+ }