local-mcp-manager 0.5.4 → 0.9.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,2887 @@
1
+ // Generated by npm run build:web; do not edit.
2
+ window.__ModuleLoader__.load({
3
+ id: "local-mcp-manager",
4
+ factory(require) {
5
+ const manifest = {"version":"0.9.0"};
6
+
7
+ /* lib/path-format.js */
8
+ // Workbench clients can be on a different OS than the DSH host. Validate the
9
+ // portable syntax here, then check the host's own format before any spawn.
10
+ function isWindowsAbsoluteCwd(path) {
11
+ return /^[A-Za-z]:[\\/]/.test(path)
12
+ || /^(?:\\\\|\/\/)[^\\/]+[\\/][^\\/]+(?:[\\/]|$)/.test(path)
13
+ }
14
+
15
+ function isPortableAbsoluteCwd(path) {
16
+ return path.startsWith('/') || isWindowsAbsoluteCwd(path)
17
+ }
18
+
19
+ /* src/workbench/contract.js */
20
+ // One strict contract for the bundled Host and browser. Do not include native
21
+ // forms, stored credential references, or unbounded runtime snapshots here.
22
+ const PACKAGE = 'local-mcp-manager'
23
+ const NAMESPACE = 'mcpManagerWorkbench'
24
+ const PANEL_ID = 'mcp-manager-workbench'
25
+ const METHODS = Object.freeze([
26
+ 'overview', 'getServer', 'getToolSchema', 'saveServer', 'removeServer', 'setServerEnabled', 'setToolPolicy', 'connect', 'refresh',
27
+ 'aggregate', 'invokeTool', 'testServer', 'exportConfig', 'importConfig', 'setServerTags', 'healthStatus', 'healthConfig',
28
+ 'registrySearch', 'readResource', 'getPrompt', 'statsOverview', 'logTail', 'logConfig', 'reviewTool', 'resourceWatches', 'setResourceWatch',
29
+ ])
30
+
31
+ function createContract(z) {
32
+ const id = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,31}$/)
33
+ const revision = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
34
+ const transport = z.enum(['streamable-http', 'sse', 'stdio'])
35
+ const section = z.enum(['connection', 'tools', 'activity', 'config'])
36
+ const count = z.number().int().nonnegative()
37
+ const stamp = z.number().nonnegative()
38
+ const pairName = z.string().trim().min(1).max(128)
39
+ const pairs = z.array(z.union([
40
+ z.strictObject({ name: pairName, keep: z.literal(true) }),
41
+ z.strictObject({ name: pairName, value: z.string().max(2000) }),
42
+ ])).max(16)
43
+ const configInput = {
44
+ url: z.string().max(2000), command: z.string().max(300),
45
+ args: z.array(z.string().max(2000)).max(64), cwd: z.string().max(1000),
46
+ timeoutMs: z.number().int().min(1000).max(180000),
47
+ }
48
+ const serverInput = z.strictObject({ id, transport, name: z.string().max(80),
49
+ url: configInput.url.optional(), command: configInput.command.optional(),
50
+ args: configInput.args.optional(), cwd: configInput.cwd.optional(), timeoutMs: configInput.timeoutMs,
51
+ enabled: z.boolean(), requireApproval: z.boolean(), headers: pairs, env: pairs,
52
+ tags: z.array(z.string().trim().min(1).max(24)).max(8).optional() })
53
+ const endpoint = z.strictObject({ id, revision })
54
+ const toolStamp = z.string().min(1).max(80)
55
+ const failure = z.strictObject({ ok: z.literal(false), code: z.string().min(1).max(64), message: z.string().min(1).max(512) })
56
+ const mutation = z.strictObject({ revision })
57
+ const accepted = z.strictObject({ revision, accepted: z.literal(true) })
58
+ const lastCheck = z.strictObject({ at: stamp, durationMs: stamp, ok: z.boolean() })
59
+ const faultCode = z.string().max(128).optional()
60
+ const faultMessage = z.string().max(512).optional()
61
+ const directoryRow = {
62
+ id, name: z.string().max(80), transport, enabled: z.boolean(),
63
+ status: z.enum(['connected', 'connecting', 'disconnected', 'reconnecting', 'disabled', 'error']),
64
+ error: z.strictObject({ code: faultCode, message: faultMessage }).nullable(),
65
+ lastCheck: lastCheck.nullable(), counts: z.strictObject({ tools: count, enabledTools: count }), refreshing: z.boolean(),
66
+ tags: z.array(z.string().max(24)).max(8),
67
+ }
68
+ const directory = z.strictObject({ revision, active: z.boolean(), autoConnect: z.boolean(), servers: z.array(z.strictObject(directoryRow)).max(32) })
69
+ const pairView = z.strictObject({ name: pairName, hasValue: z.boolean() })
70
+ const details = {
71
+ connection: z.strictObject({
72
+ target: z.string().max(512), serverInfo: z.strictObject({ name: z.string().max(512).optional(), version: z.string().max(128).optional() }).nullable(),
73
+ retries: count, nextRetryAt: stamp.nullable(), resources: count, prompts: count, logging: z.boolean().optional(),
74
+ canWatchResources: z.boolean().optional(),
75
+ resourceTemplates: z.array(z.strictObject({ uriTemplate: z.string().max(4096), name: z.string().max(200),
76
+ description: z.string().max(720), variables: z.array(z.string().min(1).max(128)).max(32) })).max(32).optional(),
77
+ resourceRows: z.array(z.strictObject({ uri: z.string().max(4096), name: z.string().max(200),
78
+ description: z.string().max(720), mimeType: z.string().max(120) })).max(200).optional(),
79
+ promptRows: z.array(z.strictObject({ name: z.string().max(256), description: z.string().max(720),
80
+ arguments: z.array(z.strictObject({ name: z.string().max(64), description: z.string().max(300), required: z.boolean() })).max(16) })).max(100).optional(),
81
+ }),
82
+ tools: z.strictObject({ rows: z.array(z.strictObject({ name: z.string().max(1024), description: z.string().max(720),
83
+ enabled: z.boolean(), requireApproval: z.boolean(), writable: z.boolean(), stamp: toolStamp.nullable(),
84
+ pending: z.boolean().optional(), hint: z.enum(['read-only', 'destructive']).optional() })).max(500), total: count }),
85
+ activity: z.strictObject({ stats: z.strictObject({ calls: count, failures: count, active: count }),
86
+ history: z.array(z.strictObject({ tool: z.string().max(1024), at: stamp, durationMs: stamp,
87
+ ok: z.boolean(), code: faultCode, message: faultMessage })).max(20) }),
88
+ config: z.strictObject({ ...configInput, headers: z.array(pairView).max(16), env: z.array(pairView).max(16) }),
89
+ }
90
+ const readRow = z.strictObject({ ...directoryRow, requireApproval: z.boolean() })
91
+ const serverDetail = z.discriminatedUnion('section', Object.entries(details).map(([key, detail]) =>
92
+ z.strictObject({ revision, server: readRow, section: z.literal(key), detail })))
93
+ const toolSchema = z.strictObject({ name: z.string().max(1024), schemaJson: z.string().max(16000), truncated: z.boolean(),
94
+ outputSchemaJson: z.string().max(16000).optional(), outputTruncated: z.boolean().optional() })
95
+ const aggregateRow = z.strictObject({ id, calls: count, failures: count, active: count, tools: count })
96
+ const aggregateData = z.strictObject({
97
+ runtimeReady: z.boolean(), generatedAt: stamp, configPath: z.string().max(512),
98
+ servers: z.array(aggregateRow).max(32),
99
+ byTool: z.array(z.strictObject({ tool: z.string().max(1024), calls: count, failures: count,
100
+ lastAt: stamp, lastDurationMs: stamp.nullable() })).max(24),
101
+ conflicts: z.array(z.strictObject({ tool: z.string().max(1024), servers: z.array(id).max(32) })).max(16),
102
+ })
103
+ const invokeResult = z.strictObject({ approvalRequired: z.literal(false), durationMs: stamp, isError: z.boolean(),
104
+ text: z.string().max(8000), truncated: z.boolean(), structured: z.boolean().optional(), code: faultCode })
105
+ const invokeData = z.discriminatedUnion('approvalRequired', [
106
+ z.strictObject({ approvalRequired: z.literal(true), confirmToken: z.string().min(8).max(80) }), invokeResult,
107
+ ])
108
+ const testResult = z.strictObject({ revision, id, status: z.enum(['connected', 'connecting', 'disconnected', 'reconnecting', 'disabled', 'error']),
109
+ error: z.strictObject({ code: faultCode, message: faultMessage }).nullable(), lastCheck: lastCheck.nullable(), durationMs: stamp })
110
+ const exportData = z.strictObject({ filename: z.string().max(80), contentJson: z.string().max(160000),
111
+ servers: count, redacted: z.boolean() })
112
+ const importData = z.strictObject({ revision, added: count, updated: count, replaced: z.boolean(), servers: count })
113
+ const healthData = z.strictObject({
114
+ enabled: z.boolean(), intervalMinutes: z.number().int().min(1).max(360),
115
+ autoDisableAfterFaults: z.number().int().min(0).max(10), lastTickAt: stamp.nullable(),
116
+ log: z.array(z.strictObject({at: stamp, serverId: id, kind: z.string().max(24), code: z.string().max(128).optional()})).max(20),
117
+ servers: z.array(z.strictObject({id, faults: count, lastFaultAt: stamp.nullable(), lastOkAt: stamp.nullable(),
118
+ lastKind: z.string().max(24)})).max(32),
119
+ })
120
+ const registryData = z.strictObject({servers: z.array(z.strictObject({name: z.string().max(160),
121
+ description: z.string().max(200), version: z.string().max(40), websiteUrl: z.string().max(300).nullable(),
122
+ status: z.string().max(16), transport, url: z.string().max(600).nullable(), command: z.string().max(80).nullable(),
123
+ args: z.array(z.string().max(300)).max(32), registryType: z.enum(['npm', 'pypi', 'oci']).optional(),
124
+ packageRef: z.string().min(1).max(300).optional(), headerNames: z.array(z.string().max(64)).max(8), envNames: z.array(z.string().max(64)).max(8)})).max(20),
125
+ source: z.string().max(80), unreachable: z.boolean(), reason: z.string().max(24).optional()})
126
+ const resourceUri = z.string().min(1).max(4096)
127
+ const watchData = z.strictObject({supported: z.boolean(), rows: z.array(z.strictObject({
128
+ uri: resourceUri, token: z.string().min(1).max(80), changedAt: stamp.nullable(),
129
+ })).max(16)})
130
+ const resourceData = z.strictObject({uri: z.string().max(4096), mimeType: z.string().max(120).nullable(),
131
+ text: z.string().max(16000).nullable(), blob: z.string().max(160000).nullable(), truncated: z.boolean(), size: count})
132
+ const promptData = z.strictObject({description: z.string().max(512).nullable(),
133
+ messages: z.array(z.strictObject({role: z.enum(['user', 'assistant']), text: z.string().max(16000)})).max(10)})
134
+ const statsData = z.strictObject({days: z.array(z.strictObject({date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), calls: count, failures: count})).max(30),
135
+ totals: z.strictObject({calls: count, failures: count, durationMs: count}), failureRate: z.number().min(0).max(1),
136
+ top: z.array(z.strictObject({tool: z.string().max(1024), calls: count, failures: count, avgMs: count, maxMs: count})).max(12),
137
+ slow: z.array(z.strictObject({tool: z.string().max(1024), serverId: id, at: stamp, durationMs: stamp, ok: z.boolean()})).max(8),
138
+ servers: z.array(z.strictObject({id, recent: z.array(z.strictObject({at: stamp, ok: z.boolean()})).max(12)})).max(32)})
139
+ const logData = z.strictObject({level: z.string().max(16).nullable(),
140
+ lines: z.array(z.strictObject({at: stamp, level: z.string().max(16), logger: z.string().max(64).nullable(), data: z.string().max(4000)})).max(300)})
141
+ const definitions = {
142
+ overview: ['List connection summaries for the workbench.', null, directory],
143
+ getServer: ['Read one panel of a configured server.', z.strictObject({ id, section }), serverDetail],
144
+ getToolSchema: ['Read one redacted tool input definition preview.', z.strictObject({ id, name: z.string().min(1).max(1024), stamp: toolStamp }), toolSchema],
145
+ reviewTool: ['Accept one exact discovered tool definition at a known configuration revision.',
146
+ z.strictObject({ id, revision, name: z.string().min(1).max(1024), stamp: toolStamp }), mutation],
147
+ saveServer: ['Save one new or existing server at a known revision.', z.strictObject({ revision, mode: z.enum(['create', 'edit']), server: serverInput }), mutation],
148
+ removeServer: ['Remove one configured server at a known revision.', z.strictObject({ id, revision }), mutation],
149
+ setServerEnabled: ['Set the desired connection state of one configured server.', z.strictObject({ id, revision, enabled: z.boolean() }), mutation],
150
+ setToolPolicy: ['Update a policy for the reviewed tool definition.', z.strictObject({ id, revision, name: z.string().min(1).max(256), enabled: z.boolean(), requireApproval: z.boolean(), stamp: toolStamp }), mutation],
151
+ connect: ['Request reconnection of an enabled server.', endpoint, accepted],
152
+ refresh: ['Request a refresh of its tool catalog.', endpoint, accepted],
153
+ aggregate: ['Aggregate fleet-wide dashboard numbers from live runtime slots.', null, aggregateData],
154
+ invokeTool: ['Invoke one live discovered tool with explicit approval handling.',
155
+ z.strictObject({ id, name: z.string().min(1).max(1024), stamp: toolStamp,
156
+ argsJson: z.string().max(16000), confirmToken: z.string().min(8).max(80).optional() }), invokeData],
157
+ testServer: ['Save one server, connect and report the observed result.',
158
+ z.strictObject({ revision, mode: z.enum(['create', 'edit']), server: serverInput }), testResult],
159
+ exportConfig: ['Export all configured servers as JSON.', z.strictObject({ mode: z.enum(['redacted', 'full']) }), exportData],
160
+ importConfig: ['Import a plugin backup or supported third-party MCP JSON at a known revision.',
161
+ z.strictObject({ revision, contentJson: z.string().max(160000), mode: z.enum(['merge', 'replace']) }), importData],
162
+ setServerTags: ['Update the organizational tags of one server.', z.strictObject({ id, revision, tags: z.array(z.string().trim().min(1).max(24)).max(8) }), mutation],
163
+ healthStatus: ['Read the background health watcher state and recent transitions.', null, healthData],
164
+ healthConfig: ['Configure the background health watcher.', z.strictObject({
165
+ enabled: z.boolean(), intervalMinutes: z.number().int().min(1).max(360),
166
+ autoDisableAfterFaults: z.number().int().min(0).max(10),
167
+ }), healthData],
168
+ registrySearch: ['Search the public MCP registry for connectable servers.',
169
+ z.strictObject({query: z.string().trim().min(1).max(100)}), registryData],
170
+ readResource: ['Read a resource on a connected server, optionally by expanding an advertised template.',
171
+ z.union([z.strictObject({id, uri: resourceUri}), z.strictObject({id, uriTemplate: resourceUri,
172
+ args: z.array(z.strictObject({name: z.string().min(1).max(128), value: z.string().max(1024)})).max(32).optional()})]), resourceData],
173
+ resourceWatches: ['Read the current connection’s resource subscription metadata.', z.strictObject({id}), watchData],
174
+ setResourceWatch: ['Start or stop watching a previously read resource on this connection.',
175
+ z.strictObject({id, uri: resourceUri, enabled: z.boolean()}), watchData],
176
+ getPrompt: ['Render one server prompt template with arguments.',
177
+ z.strictObject({id, name: z.string().min(1).max(256),
178
+ args: z.array(z.strictObject({name: z.string().min(1).max(64), value: z.string().max(2000)})).max(16).optional()}), promptData],
179
+ statsOverview: ['Aggregate persisted call statistics for trend views.',
180
+ z.strictObject({days: z.number().int().min(1).max(30)}), statsData],
181
+ logTail: ['Read recent log notifications of one server.', z.strictObject({id}), logData],
182
+ logConfig: ['Set the minimum log level of one connected server.',
183
+ z.strictObject({id, level: z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'])}), logData],
184
+ }
185
+ const makeCodec = (name, schema) => ({
186
+ mode: 'strict', typeSymbol: `${PACKAGE}#Workbench${name}`, create: () => schema,
187
+ get jsonSchema() { return z.toJSONSchema(schema) },
188
+ })
189
+ const schemas = []
190
+ const descriptors = METHODS.map(method => {
191
+ const [description, input, data] = definitions[method]
192
+ const reply = z.discriminatedUnion('ok', [failure, z.strictObject({ ok: z.literal(true), data })])
193
+ const parameters = []
194
+ if (input) {
195
+ const name = `${method}Input`, codec = makeCodec(name, input)
196
+ schemas.push({ name: `Workbench${name}`, create: codec.create })
197
+ parameters.push({ name: 'input', wire: 'input', source: 'json', codec, strictCodec: codec })
198
+ }
199
+ const name = `${method}Reply`, codec = makeCodec(name, reply)
200
+ schemas.push({ name: `Workbench${name}`, create: codec.create })
201
+ return {
202
+ id: `${PACKAGE}#${NAMESPACE}/${method}`, service: NAMESPACE, namespace: NAMESPACE, method, description,
203
+ invocation: { kind: 'direct' }, parameters,
204
+ result: { ...codec, encode: value => reply.parse(value), decode: value => reply.parse(value) },
205
+ }
206
+ })
207
+ return {
208
+ host: {
209
+ package: PACKAGE, face: 'host', schemas, invocations: descriptors,
210
+ model: { services: [{ key: NAMESPACE, exportName: NAMESPACE, tags: [], types: [],
211
+ members: descriptors.map(({ method, description, parameters }) => ({ name: method, kind: 'method',
212
+ signature: `${method}(${parameters.length ? 'input' : ''})`, description })),
213
+ }], events: [], objects: [] },
214
+ },
215
+ client: { package: PACKAGE, descriptors },
216
+ }
217
+ }
218
+
219
+ /* src/workbench/styles.js */
220
+ const styles = `
221
+ .mwb{container:mwb / inline-size;inline-size:100%;min-inline-size:0;color:var(--dsw-alias-label-primary,CanvasText);font:inherit;font-size:14px;line-height:1.45}
222
+ .mwb,.mwb *,.mwb *::before,.mwb *::after{box-sizing:border-box}
223
+ .mwb[data-scroll=y]{display:flex;flex-direction:column;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:var(--dsw-alias-scrollbar-thumb,var(--wb-line)) transparent}
224
+ .mwb[data-scroll=y]::-webkit-scrollbar{inline-size:10px}
225
+ .mwb[data-scroll=y]::-webkit-scrollbar-thumb{border:2px solid transparent;border-radius:100vw;background:var(--dsw-alias-scrollbar-thumb,var(--wb-line));background-clip:content-box}
226
+ .mwb[data-scroll=y] .mwb-shell{flex:1;display:flex;flex-direction:column;min-block-size:0}
227
+ .mwb[data-scroll=y] .mwb-console-top{position:sticky;inset-block-start:0;z-index:4;background:var(--wb-surface)}
228
+ .mwb[data-scroll=y] .mwb-grid{flex:1;min-block-size:0;overflow:hidden;align-items:stretch;grid-template-rows:minmax(0,1fr)}
229
+ .mwb[data-scroll=y] .mwb-grid>.mwb-directory,.mwb[data-scroll=y] .mwb-grid>.mwb-detail,.mwb[data-scroll=y] .mwb-grid>.mwb-dashboard{overflow-y:auto;min-block-size:0}
230
+ .mwb[data-scroll=y] .mwb-statusbar{position:sticky;inset-block-end:0;z-index:4;background:var(--wb-surface)}
231
+ .mwb-shell{--wb-ink:var(--dsw-alias-label-primary,CanvasText);--wb-sub:var(--dsw-alias-label-secondary,CanvasText);--wb-line:var(--dsw-alias-border-l2,GrayText);--wb-line-soft:color-mix(in srgb,var(--wb-line) 55%,transparent);--wb-surface:var(--dsw-alias-bg-layer-1,Canvas);--wb-surface-2:var(--dsw-alias-bg-layer-2,color-mix(in srgb,var(--wb-ink) 3%,var(--wb-surface)));--wb-hover:var(--dsw-alias-interactive-bg-hover,var(--dsw-alias-bg-layer-2,Canvas));--wb-blue:var(--dsw-alias-state-business-primary,Highlight);--wb-on-blue:var(--dsw-alias-label-primary-foreground,HighlightText);--wb-good:var(--dsw-alias-state-success-primary,var(--wb-ink));--wb-warn:var(--dsw-alias-state-warn-primary,var(--wb-ink));--wb-warn-text:var(--dsw-alias-state-warn-label,var(--wb-ink));--wb-bad:var(--dsw-alias-label-error,var(--wb-ink));--wb-bad-mark:var(--dsw-alias-state-error-primary,var(--wb-bad));--wb-idle:var(--dsw-alias-state-idle-primary,var(--wb-sub));--wb-cat-1:oklch(62% .14 25);--wb-cat-2:oklch(62% .14 70);--wb-cat-3:oklch(62% .14 145);--wb-cat-4:oklch(62% .14 185);--wb-cat-5:oklch(62% .14 230);--wb-cat-6:oklch(62% .14 280);--wb-cat-7:oklch(62% .14 320);--wb-cat-8:oklch(62% .14 30);max-inline-size:100rem;margin-inline:auto;padding:clamp(12px,2.2%,28px) clamp(12px,2.4%,32px);overflow-wrap:anywhere}
232
+ @media (prefers-color-scheme:dark){.mwb-shell{--wb-cat-1:oklch(76% .11 25);--wb-cat-2:oklch(76% .11 70);--wb-cat-3:oklch(76% .11 145);--wb-cat-4:oklch(76% .11 185);--wb-cat-5:oklch(76% .11 230);--wb-cat-6:oklch(76% .11 280);--wb-cat-7:oklch(76% .11 320);--wb-cat-8:oklch(76% .11 30)}}
233
+ .mwb .mwb-vh{position:absolute;inline-size:1px;block-size:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}
234
+ .mwb :where(h1,h2,h3,p,ul,ol,dl,dd,pre){margin:0}
235
+ .mwb :where(h1,h2,h3){line-height:1.25}
236
+ .mwb :where(button,input,select,textarea){font:inherit;color:inherit;min-inline-size:0}
237
+ .mwb :where(button,input,select,textarea,[tabindex]):focus-visible{outline:2px solid var(--wb-blue);outline-offset:2px}
238
+ .mwb :where(h2[tabindex],h3[tabindex]):focus{outline:2px solid var(--wb-blue);outline-offset:3px}
239
+ .mwb .mwb-header,.mwb .mwb-pane-head,.mwb .mwb-section-head{display:flex;align-items:center;justify-content:space-between;gap:8px 14px;flex-wrap:wrap;min-inline-size:0}
240
+ .mwb .mwb-console-top{min-inline-size:0;border-block-end:1px solid var(--wb-line-soft);margin-block-end:12px}
241
+ .mwb .mwb-header{padding-block:2px 10px}
242
+ .mwb .mwb-title-block{display:grid;gap:3px;min-inline-size:0}
243
+ .mwb .mwb-header-meta{color:var(--wb-sub);font-size:12px}
244
+ .mwb .mwb-meta-count{display:inline-flex;align-items:center;gap:5px;min-inline-size:0}
245
+ .mwb .mwb-title{display:flex;align-items:center;gap:9px;font-size:21px;font-size:clamp(20px,2.4cqi,26px);font-weight:700;letter-spacing:-.022em}
246
+ .mwb .mwb-title svg{flex:none}
247
+ .mwb .mwb-heading{font-size:19px;font-weight:660;letter-spacing:-.012em;max-inline-size:100%;min-inline-size:0}
248
+ .mwb .mwb-subhead{font-size:15px;font-weight:660;letter-spacing:-.008em;max-inline-size:100%;min-inline-size:0}
249
+ .mwb .mwb-muted,.mwb .mwb-hint{color:var(--wb-sub)}
250
+ .mwb .mwb-hint{display:block;font-size:12px;font-weight:400}
251
+ .mwb .mwb-num{font-variant-numeric:tabular-nums}
252
+ .mwb :where(.mwb-tech,pre,code){font-family:ui-monospace,SFMono-Regular,Consolas,monospace}
253
+ .mwb .mwb-actions{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px;min-inline-size:0}
254
+ .mwb .mwb-button{display:inline-flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--wb-line-soft);border-radius:8px;padding:5px 11px;min-block-size:34px;max-inline-size:100%;background:var(--wb-surface);text-align:center;cursor:pointer;overflow-wrap:anywhere;transition:background-color 140ms ease,border-color 140ms ease}
255
+ .mwb .mwb-button svg{flex:none}
256
+ .mwb .mwb-button[data-kind=primary]{color:var(--wb-on-blue);background:var(--wb-blue);border-color:transparent;font-weight:640}
257
+ .mwb .mwb-button[data-kind=quiet]{border-color:transparent;background:transparent;color:var(--wb-sub)}
258
+ .mwb .mwb-button[data-kind=danger]{color:var(--wb-bad);border-color:color-mix(in srgb,var(--wb-bad-mark) 32%,transparent)}
259
+ .mwb :where(button:disabled){opacity:.53;cursor:default}
260
+ @media (hover:hover){.mwb .mwb-button:not(:disabled):not([data-kind=primary]):hover,.mwb .mwb-tab:not([aria-selected=true]):hover,.mwb .mwb-switch:not(:disabled):hover{background:var(--wb-hover)}.mwb .mwb-button[data-kind=primary]:not(:disabled):hover{filter:brightness(.94)}}
261
+ .mwb .mwb-messages{display:grid;gap:8px}
262
+ .mwb .mwb-messages:not(:empty){margin-block:2px 12px}
263
+ .mwb .mwb-notice{border:1px solid var(--wb-line-soft);border-inline-start:3px solid var(--wb-line);border-radius:10px;padding:9px 12px;background:var(--wb-surface-2);overflow-wrap:anywhere}
264
+ .mwb .mwb-notice[data-tone=error]{border-inline-start-color:var(--wb-bad-mark);background:color-mix(in srgb,var(--wb-bad-mark) 8%,var(--wb-surface))}
265
+ .mwb .mwb-notice[data-tone=warn]{border-inline-start-color:var(--wb-warn);background:color-mix(in srgb,var(--wb-warn) 8%,var(--wb-surface))}
266
+ .mwb .mwb-distribution{display:inline-flex;align-items:stretch;gap:3px;border:1px solid var(--wb-line-soft);border-radius:10px;padding:3px;margin-block:0 2px;background:var(--wb-surface-2);max-inline-size:100%;min-inline-size:0}
267
+ .mwb .mwb-segment{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:6px;min-block-size:32px;min-inline-size:4.6rem;padding:0 11px;border:0;border-radius:7px;color:var(--wb-sub);background:transparent;cursor:pointer;white-space:nowrap;overflow:hidden;container:seg / inline-size;transition:background-color 140ms ease,color 140ms ease}
268
+ .mwb .mwb-segment[data-group=all]{--seg-tone:var(--wb-blue)}
269
+ .mwb .mwb-segment[data-group=online]{--seg-tone:var(--wb-good)}
270
+ .mwb .mwb-segment[data-group=fault]{--seg-tone:var(--wb-bad-mark)}
271
+ .mwb .mwb-segment[data-group=progress]{--seg-tone:var(--wb-warn)}
272
+ .mwb .mwb-segment[data-group=offline]{--seg-tone:var(--wb-idle)}
273
+ .mwb .mwb-segment[data-group=disabled]{--seg-tone:var(--wb-line)}
274
+ .mwb .mwb-segment[aria-pressed=true]{color:var(--wb-ink);font-weight:650;background:var(--wb-surface);box-shadow:inset 0 0 0 1px var(--wb-line-soft),inset 0 -2px 0 var(--seg-tone)}
275
+ .mwb .mwb-segment[data-zero=true]{opacity:.55}
276
+ .mwb .mwb-segment[data-zero=true][aria-pressed=true]{opacity:1}
277
+ .mwb .mwb-segment .mwb-num{min-inline-size:1ch;color:var(--wb-ink);font-size:13px;font-weight:650}
278
+ @media (hover:hover){.mwb .mwb-segment:not([aria-pressed=true]):hover{background:var(--wb-hover);opacity:1}}
279
+ @container seg (max-width:4.4rem){.mwb .mwb-seg-label{display:none}}
280
+ @media (prefers-reduced-motion:reduce){.mwb .mwb-skeleton-bar{animation:none;opacity:.4}.mwb .mwb-button,.mwb .mwb-segment,.mwb .mwb-server,.mwb .mwb-overlay,.mwb .mwb-drawer{transition:none;animation:none}}
281
+ .mwb .mwb-dot{display:inline-block;inline-size:7px;block-size:7px;flex:none;border-radius:100%;background:currentColor;color:var(--dsw-alias-state-idle-primary,var(--wb-sub))}
282
+ .mwb .mwb-dot[data-tone=online]{color:var(--wb-good)}
283
+ .mwb .mwb-dot[data-tone=fault]{color:var(--wb-bad-mark)}
284
+ .mwb .mwb-dot[data-tone=progress]{color:var(--wb-warn)}
285
+ .mwb .mwb-dot[data-tone=disabled]{border:1px solid currentColor;background:transparent}
286
+ .mwb .mwb-badge{display:inline-flex;align-items:center;gap:6px;padding:2px 9px;border-radius:999px;background:color-mix(in srgb,var(--wb-idle) 12%,transparent);font-size:12px;font-weight:600;white-space:nowrap;min-inline-size:0}
287
+ .mwb .mwb-badge[data-tone=online]{color:var(--wb-good);background:color-mix(in srgb,var(--wb-good) 14%,transparent)}
288
+ .mwb .mwb-badge[data-tone=fault]{color:var(--wb-bad);background:color-mix(in srgb,var(--wb-bad-mark) 14%,transparent)}
289
+ .mwb .mwb-badge[data-tone=progress]{color:var(--wb-warn-text);background:color-mix(in srgb,var(--wb-warn) 16%,transparent)}
290
+ .mwb .mwb-badge[data-tone=disabled]{color:var(--wb-sub);background:color-mix(in srgb,var(--wb-line) 16%,transparent)}
291
+ .mwb .mwb-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;align-items:start;min-inline-size:0}
292
+ .mwb .mwb-directory,.mwb .mwb-detail{min-inline-size:0}
293
+ .mwb .mwb-compare-tools{display:flex;align-items:flex-end;flex-wrap:wrap;gap:8px 10px;margin-block:10px 12px}
294
+ .mwb .mwb-compare-tools>:first-child{flex:1 1 11rem}
295
+ .mwb .mwb-compare-tools>:not(:first-child){flex:0 1 10rem}
296
+ .mwb .mwb-field{min-inline-size:0;display:grid;align-content:start;gap:4px;font-size:13px;font-weight:560}
297
+ .mwb .mwb-field :where(input,select,textarea){inline-size:100%;max-inline-size:100%;min-block-size:34px;padding:5px 10px;border:1px solid var(--wb-line-soft);border-radius:8px;background:var(--wb-surface);font-weight:400;transition:border-color 140ms ease}
298
+ .mwb .mwb-field :where(input,textarea)::placeholder{color:var(--wb-sub)}
299
+ .mwb .mwb-field :where(input[readonly],input:disabled,select:disabled,textarea:disabled){background:var(--wb-hover);color:var(--wb-sub)}
300
+ .mwb .mwb-field textarea{resize:vertical}
301
+ .mwb .mwb-list-tools{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:end;gap:8px;margin-block:6px 10px}
302
+ .mwb .mwb-list-tools .mwb-field{font-size:12px}
303
+ .mwb .mwb-list-tools .mwb-field :where(input,select){min-block-size:32px;padding-block:3px}
304
+ .mwb .mwb-list-tools .mwb-button{min-block-size:32px}
305
+ .mwb .mwb-server-list{list-style:none;margin:0;padding:0;display:grid;gap:2px}
306
+ .mwb .mwb-server{position:relative;display:grid;grid-template-columns:auto minmax(0,1fr);align-items:start;gap:0 8px;padding:9px 10px 9px 12px;border-radius:9px;border:0;cursor:pointer;transition:background-color 120ms ease}
307
+ .mwb .mwb-server[data-locked=true]{cursor:default}
308
+ .mwb .mwb-server[data-selected=true]{background:color-mix(in srgb,var(--wb-blue) 9%,var(--wb-surface));box-shadow:inset 2px 0 var(--wb-blue)}
309
+ .mwb .mwb-server[data-selected=true] .mwb-row-open{color:var(--wb-blue)}
310
+ @media (hover:hover){.mwb .mwb-server:not([data-selected=true]):not([data-locked=true]):hover{background:var(--wb-hover)}}
311
+ .mwb .mwb-server-body{display:grid;gap:3px;min-inline-size:0}
312
+ .mwb .mwb-server-head{display:flex;align-items:center;gap:4px 10px;flex-wrap:wrap;min-inline-size:0}
313
+ .mwb .mwb-row-open{display:block;border:0;background:transparent;padding:0;color:var(--wb-ink);font-weight:640;font-size:14px;text-align:start;cursor:pointer;max-inline-size:100%;min-block-size:20px;overflow-wrap:anywhere}
314
+ .mwb .mwb-transport{font-size:11px;white-space:nowrap}
315
+ .mwb .mwb-server-spacer{flex:1 1 0}
316
+ .mwb .mwb-heartbeat{display:inline-flex;align-items:flex-end;gap:2px;flex:none;inline-size:calc(12 * 6px - 2px)}
317
+ .mwb .mwb-beat{display:block;inline-size:4px;block-size:14px;border-radius:1px;background:var(--wb-line-soft)}
318
+ .mwb .mwb-beat[data-tone=ok]{background:var(--wb-good)}
319
+ .mwb .mwb-beat[data-tone=fault]{background:var(--wb-bad-mark)}
320
+ .mwb .mwb-server-meta{display:flex;align-items:baseline;gap:3px 12px;flex-wrap:wrap;min-inline-size:0;font-size:12px;color:var(--wb-sub);padding-inline-end:5rem}
321
+ .mwb .mwb-server-meta .mwb-num{color:var(--wb-ink);font-weight:620}
322
+ .mwb .mwb-last-error{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;font-size:12px;color:var(--wb-bad)}
323
+ .mwb .mwb-server-actions{position:absolute;inset-inline-end:8px;inset-block-end:7px}
324
+ .mwb .mwb-row-clone{opacity:0;min-block-size:28px;padding:2px 8px}
325
+ .mwb .mwb-server:hover .mwb-row-clone,.mwb .mwb-server:focus-within .mwb-row-clone,.mwb .mwb-server[data-selected=true] .mwb-row-clone{opacity:1}
326
+ @media (hover:none){.mwb .mwb-row-clone{opacity:1}}
327
+ .mwb .mwb-empty{display:grid;gap:6px;justify-items:start;border:1px dashed var(--wb-line-soft);border-radius:10px;padding:18px 16px}
328
+ .mwb .mwb-skeleton{display:grid;gap:9px;margin-block:10px;min-inline-size:0}
329
+ .mwb .mwb-skeleton-row{display:flex;gap:10px;align-items:center;min-inline-size:0}
330
+ .mwb .mwb-skeleton-bar{display:block;inline-size:40%;block-size:10px;border-radius:6px;background:var(--dsw-alias-bg-skeleton,var(--wb-hover));animation:mwb-shimmer 1.2s ease-in-out infinite}
331
+ .mwb .mwb-skeleton-row .mwb-skeleton-bar:last-child{inline-size:55%}
332
+ @keyframes mwb-shimmer{50%{opacity:.4}}
333
+ .mwb .mwb-dashboard{display:grid;grid-template-rows:max-content max-content;gap:14px;align-content:start;min-inline-size:0}
334
+ .mwb .mwb-metrics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));border:1px solid var(--wb-line-soft);border-radius:12px;overflow:hidden;background:var(--wb-surface)}
335
+ .mwb .mwb-brick{display:grid;gap:2px;padding:12px 14px;border:0;border-inline-start:1px solid var(--wb-line-soft);border-block-start:1px solid var(--wb-line-soft);background:transparent;min-inline-size:0}
336
+ .mwb .mwb-brick:nth-child(3n+1){border-inline-start:0}
337
+ .mwb .mwb-brick:nth-child(-n+3){border-block-start:0}
338
+ .mwb .mwb-brick .mwb-dot{color:var(--cat)}
339
+ .mwb .mwb-brick-value{display:flex;align-items:center;gap:8px;font-size:22px;font-weight:700;letter-spacing:-.02em;line-height:1.2}
340
+ .mwb .mwb-bento{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;min-inline-size:0}
341
+ .mwb .mwb-card{display:grid;gap:8px;align-content:start;padding:14px 16px;border:1px solid var(--wb-line-soft);border-radius:12px;background:var(--wb-surface);min-inline-size:0}
342
+ .mwb .mwb-stats-card{grid-column:span 2}
343
+ .mwb .mwb-health{grid-column:span 2}
344
+ .mwb .mwb-conflicts{border-inline-start:3px solid var(--wb-warn)}
345
+ .mwb .mwb-rank{list-style:none;padding:0;display:grid;gap:10px}
346
+ .mwb .mwb-rank>li{display:grid;gap:5px;min-inline-size:0}
347
+ .mwb .mwb-rank-row{display:flex;align-items:baseline;gap:4px 9px;flex-wrap:wrap;min-inline-size:0}
348
+ .mwb .mwb-rank .mwb-dot{color:var(--cat)}
349
+ .mwb .mwb-rank-row .mwb-num{color:var(--wb-ink);font-weight:640}
350
+ .mwb .mwb-rank-bar{display:block;block-size:4px;border-radius:999px;background:var(--cat);min-inline-size:0}
351
+ .mwb .mwb-conflict-list{list-style:none;padding:0;display:grid;gap:6px}
352
+ .mwb .mwb-conflict-list>li{display:flex;align-items:baseline;gap:4px 9px;flex-wrap:wrap;min-inline-size:0}
353
+ .mwb .mwb-chips{display:flex;flex-wrap:wrap;gap:5px;min-inline-size:0}
354
+ .mwb .mwb-chip{display:inline-flex;align-items:center;border:1px solid color-mix(in srgb,var(--cat) 34%,transparent);border-radius:999px;padding:1px 9px;background:color-mix(in srgb,var(--cat) 12%,var(--wb-surface));font-size:12px;min-block-size:22px;cursor:pointer;color:var(--wb-ink)}
355
+ .mwb .mwb-chip[aria-pressed=true]{border-color:var(--cat);background:color-mix(in srgb,var(--cat) 24%,var(--wb-surface));font-weight:640}
356
+ .mwb .mwb-statusbar{display:flex;align-items:center;flex-wrap:wrap;gap:2px 14px;min-block-size:32px;margin-block-start:14px;padding-block:8px 0;border-block-start:1px solid var(--wb-line-soft);font-size:12px;color:var(--wb-sub);min-inline-size:0}
357
+ .mwb .mwb-status-item{display:inline-flex;align-items:center;gap:5px;min-inline-size:0}
358
+ .mwb .mwb-status-path{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-inline-size:40cqi;flex:0 1 auto}
359
+ .mwb .mwb-playground{margin-block:8px 2px;padding:10px 12px;border:1px solid var(--wb-line-soft);border-radius:10px;background:var(--wb-surface-2);display:grid;gap:8px;min-inline-size:0}
360
+ .mwb .mwb-play-fields{display:grid;gap:8px;min-inline-size:0}
361
+ .mwb .mwb-play-result{display:grid;gap:6px;min-inline-size:0}
362
+ .mwb .mwb-play-meta{display:flex;align-items:baseline;gap:4px 9px;flex-wrap:wrap;min-inline-size:0}
363
+ .mwb .mwb-play-result pre{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;font-size:12px;border-block-start:1px solid var(--wb-line-soft);padding-block-start:8px}
364
+ .mwb .mwb-test-line{display:flex;align-items:baseline;gap:4px 10px;flex-wrap:wrap;padding:8px 0;border-block-start:1px solid var(--wb-line-soft);margin-block-start:8px;min-inline-size:0}
365
+ .mwb .mwb-io{display:grid;gap:10px;margin-block:0;padding:0;border:0;min-inline-size:0}
366
+ .mwb .mwb-io-row{display:flex;align-items:center;justify-content:flex-end;gap:6px 10px;flex-wrap:wrap;min-inline-size:0}
367
+ .mwb .mwb-io-result{display:flex;align-items:baseline;gap:4px 9px;flex-wrap:wrap;min-inline-size:0}
368
+ .mwb .mwb-io textarea{inline-size:100%;max-inline-size:100%;min-block-size:64px;padding:6px 10px;border:1px solid var(--wb-line-soft);border-radius:8px;background:var(--wb-surface);font-weight:400;resize:vertical}
369
+ .mwb .mwb-io-modes{display:flex;gap:4px 14px;flex-wrap:wrap}
370
+ .mwb .mwb-templates{display:grid;gap:8px;margin-block:0;padding:0;border:0;min-inline-size:0}
371
+ .mwb .mwb-template-list{list-style:none;padding:0;display:grid;gap:8px}
372
+ .mwb .mwb-template-list>li{display:grid;gap:2px;border:1px solid var(--wb-line-soft);border-radius:10px;padding:10px 12px;min-inline-size:0}
373
+ .mwb .mwb-tpl-label{font-weight:640}
374
+ .mwb .mwb-health{gap:10px}
375
+ .mwb .mwb-health-head{display:flex;align-items:center;justify-content:space-between;gap:6px 10px;flex-wrap:wrap;min-inline-size:0}
376
+ .mwb .mwb-health-settings{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 10px}
377
+ .mwb .mwb-health-log{list-style:none;padding:0;display:grid;gap:6px}
378
+ .mwb .mwb-health-log>li{display:flex;align-items:baseline;gap:4px 9px;flex-wrap:wrap;min-inline-size:0}
379
+ .mwb .mwb-health-log .mwb-dot{flex:none;inline-size:7px;block-size:7px;align-self:center}
380
+ .mwb .mwb-health-servers{list-style:none;padding:0;display:flex;gap:4px 14px;flex-wrap:wrap}
381
+ .mwb .mwb-tag-editor{display:grid;gap:8px;padding-block-start:10px;border-block-start:1px solid var(--wb-line-soft);margin-block-start:12px;min-inline-size:0}
382
+ .mwb .mwb-bulk-bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:9px 12px;border:1px dashed color-mix(in srgb,var(--wb-blue) 45%,var(--wb-line));border-radius:10px;background:color-mix(in srgb,var(--wb-blue) 5%,var(--wb-surface));margin-block-end:8px}
383
+ .mwb .mwb-detail{border:1px solid var(--wb-line-soft);border-radius:12px;background:var(--wb-surface);min-block-size:100%}
384
+ .mwb .mwb-pane-head{padding:14px 16px 10px}
385
+ .mwb .mwb-pane-head>div:first-child{min-inline-size:0}
386
+ .mwb .mwb-pane-body{padding:14px 16px 18px;min-inline-size:0}
387
+ .mwb .mwb-lineup{display:flex;gap:6px 10px;align-items:center;flex-wrap:wrap;margin-block-start:6px}
388
+ .mwb .mwb-tabs{display:flex;flex-wrap:wrap;gap:0 2px;padding-inline:10px;border-block:1px solid var(--wb-line-soft);background:var(--wb-surface-2)}
389
+ .mwb .mwb-tab{min-block-size:36px;padding:6px 10px;border:0;border-block-end:2px solid transparent;background:transparent;color:var(--wb-sub);cursor:pointer;text-align:start;font-weight:560;transition:color 140ms ease,background-color 140ms ease}
390
+ .mwb .mwb-tab[aria-selected=true]{color:var(--wb-ink);border-block-end-color:var(--wb-blue);font-weight:660}
391
+ .mwb .mwb-tab:focus-visible{outline-offset:-2px}
392
+ .mwb .mwb-data,.mwb .mwb-meta-line{margin-block:10px;min-inline-size:0}
393
+ .mwb .mwb-data>div{display:grid;grid-template-columns:minmax(6rem, .44fr) minmax(0,1fr);padding:7px 0;gap:3px 10px;border-block-end:1px solid var(--wb-line-soft);min-inline-size:0}
394
+ .mwb .mwb-data dt,.mwb .mwb-meta-line dt{color:var(--wb-sub);font-size:13px}
395
+ .mwb .mwb-data dd{min-inline-size:0;font-weight:620;font-variant-numeric:tabular-nums}
396
+ .mwb .mwb-meta-line{display:flex;gap:5px 16px;flex-wrap:wrap}
397
+ .mwb .mwb-meta-line>div{display:flex;gap:4px 6px;align-items:baseline;flex-wrap:wrap}
398
+ .mwb .mwb-meta-line dd{font-weight:640}
399
+ .mwb .mwb-tool-list{list-style:none;padding:0;margin-block-start:10px;border-block-start:1px solid var(--wb-line-soft)}
400
+ .mwb .mwb-tool-list>li{border-block-end:1px solid var(--wb-line-soft);min-inline-size:0;padding:9px 0}
401
+ .mwb .mwb-history{list-style:none;padding:0;margin-block-start:9px;min-inline-size:0}
402
+ .mwb .mwb-history>li{position:relative;min-inline-size:0;padding:8px 0 8px 17px}
403
+ .mwb .mwb-history>li::before{content:'';position:absolute;inset-inline-start:5px;inset-block:0;inline-size:2px;background:var(--wb-line-soft)}
404
+ .mwb .mwb-history>li:last-child::before{inset-block-end:auto;block-size:16px}
405
+ .mwb .mwb-history>li::after{content:'';position:absolute;inset-inline-start:2px;inset-block-start:12px;inline-size:8px;block-size:8px;border-radius:100%;background:var(--wb-idle)}
406
+ .mwb .mwb-history>li[data-tone=online]::after{background:var(--wb-good)}
407
+ .mwb .mwb-history>li[data-tone=fault]::after{background:var(--wb-bad-mark)}
408
+ .mwb .mwb-tool-main{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:4px 8px}
409
+ .mwb .mwb-tool-name{font-size:13px;font-weight:620}
410
+ .mwb .mwb-tool-notes{margin-block-start:3px}
411
+ .mwb .mwb-tool-controls{display:flex;flex-wrap:wrap;gap:4px 9px;align-items:center;margin-block-start:5px}
412
+ .mwb .mwb-switch{inline-size:auto;display:inline-flex;align-items:center;gap:6px;min-block-size:32px;border:0;border-radius:8px;padding:3px 6px;background:transparent;font-size:12px;cursor:pointer;text-align:start}
413
+ .mwb .mwb-track{display:flex;align-items:center;flex:none;inline-size:29px;block-size:16px;border:1px solid var(--wb-line-soft);border-radius:100vw;padding:2px;background:var(--wb-hover)}
414
+ .mwb .mwb-track::before{content:'';inline-size:10px;block-size:10px;border-radius:100%;background:var(--wb-sub)}
415
+ .mwb .mwb-switch[aria-checked=true] .mwb-track{justify-content:flex-end;border-color:var(--wb-blue);background:var(--wb-blue)}
416
+ .mwb .mwb-switch[aria-checked=true] .mwb-track::before{background:var(--wb-on-blue)}
417
+ .mwb .mwb-schema,.mwb .mwb-confirm{margin-block:8px 2px;padding:10px 12px;border:1px solid var(--wb-line-soft);border-radius:10px;background:var(--wb-surface-2);display:grid;gap:6px;min-inline-size:0}
418
+ .mwb .mwb-confirm{border-inline-start:3px solid var(--wb-warn)}
419
+ .mwb .mwb-schema pre,.mwb .mwb-config-data pre{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;font-size:12px}
420
+ .mwb .mwb-schema pre{border-block-start:1px solid var(--wb-line-soft);padding-block-start:8px}
421
+ .mwb .mwb-history-head{display:flex;align-items:baseline;gap:4px 9px;flex-wrap:wrap}
422
+ .mwb .mwb-history-head strong{min-inline-size:0}
423
+ .mwb .mwb-cred-summary{display:flex;gap:4px 9px;flex-wrap:wrap;list-style:none;padding:0}
424
+ .mwb .mwb-cred-summary>li{min-inline-size:0;overflow-wrap:anywhere}
425
+ .mwb .mwb-cred-summary code{font-size:12px}
426
+ .mwb .mwb-danger-zone{padding-block-start:10px;border-block-start:1px solid var(--wb-line-soft);margin-block-start:12px}
427
+ .mwb .mwb-form{display:grid;gap:12px;margin-block-start:8px;min-inline-size:0}
428
+ .mwb .mwb-form fieldset{padding:10px 0 0;margin:0;border:0;border-block-start:1px solid var(--wb-line-soft);min-inline-size:0}
429
+ .mwb .mwb-form legend{padding-inline-end:8px;font-weight:650}
430
+ .mwb .mwb-fields,.mwb .mwb-pair-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 10px;align-items:start}
431
+ .mwb .mwb-wide{grid-column:1/-1}
432
+ .mwb .mwb-check-field{display:flex;align-items:center;min-block-size:32px;gap:7px}
433
+ .mwb .mwb-check-field input{flex:none;inline-size:16px;block-size:16px;accent-color:var(--wb-blue);margin:0}
434
+ .mwb .mwb-pairs{list-style:none;padding:0;margin-block:5px 8px}
435
+ .mwb .mwb-pair-row{padding:7px 0;border-block-end:1px solid var(--wb-line-soft)}
436
+ .mwb .mwb-pair-state{font-size:13px;min-inline-size:0}
437
+ .mwb .mwb-form-actions{margin-block-start:2px;padding-block-start:10px;border-block-start:1px solid var(--wb-line-soft)}
438
+ .mwb .mwb-panel{display:grid;gap:10px}
439
+ .mwb .mwb-res-list,.mwb .mwb-reg-list{list-style:none;margin:0;padding:0;display:grid;gap:8px}
440
+ .mwb .mwb-res-list>li,.mwb .mwb-reg-list>li{border:1px solid var(--wb-line-soft);border-radius:10px;padding:8px 10px;background:var(--wb-surface-2);display:grid;gap:4px;min-inline-size:0}
441
+ .mwb .mwb-res-row{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:baseline;inline-size:100%;text-align:start;background:none;border:0;padding:4px 2px;border-radius:7px;cursor:pointer;color:inherit;font:inherit}
442
+ @media (hover:hover){.mwb .mwb-res-row:hover{background:var(--wb-hover)}}
443
+ .mwb .mwb-res-preview{border:1px solid var(--wb-line-soft);border-radius:9px;padding:10px 12px;margin-block-start:4px;background:var(--wb-surface);display:grid;gap:8px}
444
+ .mwb .mwb-res-preview fieldset{border:1px solid var(--wb-line-soft);border-radius:8px;padding:8px 10px;display:grid;gap:6px}
445
+ .mwb .mwb-res-preview pre{margin:0;white-space:pre-wrap;word-break:break-word;max-block-size:22rem;overflow-y:auto;font-size:12px}
446
+ .mwb .mwb-res-image{max-inline-size:100%;block-size:auto;border-radius:8px}
447
+ .mwb .mwb-prompt-message{display:grid;gap:3px;border-inline-start:2px solid var(--wb-line-soft);padding-inline-start:10px}
448
+ .mwb .mwb-log-console{list-style:none;margin:6px 0 0;padding:10px 12px;background:var(--wb-surface-2);border:1px solid var(--wb-line-soft);border-radius:10px;max-block-size:26rem;overflow-y:auto;display:grid;gap:4px;font-size:12px}
449
+ .mwb .mwb-log-console li{display:flex;flex-wrap:wrap;gap:2px 8px;align-items:baseline}
450
+ .mwb .mwb-log-console li[data-tone=fault]{color:var(--dsw-alias-danger-fg,#c44)}
451
+ .mwb .mwb-log-console li[data-tone=warn]{color:var(--dsw-alias-warning-fg,#c92)}
452
+ .mwb .mwb-log-data{word-break:break-all;white-space:pre-wrap;flex:1 1 auto}
453
+ .mwb .mwb-chart{display:flex;align-items:flex-end;justify-content:flex-start;gap:6px;block-size:7.5rem;padding:8px 6px 20px;border-block-end:1px solid var(--wb-line-soft)}
454
+ .mwb .mwb-chart-col{flex:1 1 0;max-inline-size:2.6rem;display:flex;flex-direction:column;justify-content:flex-end;gap:2px;block-size:100%;position:relative;min-inline-size:0}
455
+ .mwb .mwb-chart-bar{display:block;inline-size:100%;border-radius:3px 3px 0 0;background:var(--wb-blue)}
456
+ .mwb .mwb-chart-fail{background:var(--wb-bad-mark);margin-block-start:1px}
457
+ .mwb .mwb-chart-day{position:absolute;inset-block-end:-16px;inset-inline:0;text-align:center;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
458
+ .mwb .mwb-stats-card ul{list-style:none;margin:4px 0 0;padding:0;display:grid;gap:4px}
459
+ .mwb .mwb-stats-card li{display:flex;justify-content:space-between;gap:8px;font-size:12px;min-inline-size:0}
460
+ .mwb .mwb-stats-card li span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
461
+ .mwb .mwb-reg-main{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:baseline;min-inline-size:0}
462
+ .mwb .mwb-reg-main strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-inline-size:100%}
463
+ .mwb .mwb-overlay{position:fixed;inset:0;z-index:60;display:flex;justify-content:flex-end;background:color-mix(in srgb,var(--wb-ink) 28%,transparent);animation:mwb-fade 160ms ease-out}
464
+ .mwb .mwb-drawer{display:grid;grid-template-rows:auto minmax(0,1fr);inline-size:min(30rem,94vw);block-size:100%;background:var(--wb-surface);border-inline-start:1px solid var(--wb-line-soft);box-shadow:-12px 0 32px color-mix(in srgb,var(--wb-ink) 14%,transparent);animation:mwb-slide 220ms ease-out}
465
+ .mwb .mwb-drawer:focus-visible{outline-offset:-2px}
466
+ .mwb .mwb-drawer-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px 10px 12px 16px;border-block-end:1px solid var(--wb-line-soft)}
467
+ .mwb .mwb-drawer-body{padding:16px;overflow-y:auto;display:grid;gap:12px;align-content:start;min-inline-size:0}
468
+ @keyframes mwb-fade{from{opacity:0}}
469
+ @keyframes mwb-slide{from{transform:translateX(24px);opacity:0}}
470
+ @container mwb (min-width:66rem){
471
+ .mwb .mwb-grid[data-open=true]{grid-template-columns:minmax(0,.84fr) minmax(0,1.16fr);gap:20px}
472
+ .mwb .mwb-grid[data-editing=true]{grid-template-columns:minmax(0,.8fr) minmax(0,1fr)}
473
+ .mwb .mwb-grid[data-dash=true]{grid-template-columns:minmax(0,.78fr) minmax(0,1.22fr);gap:20px}
474
+ }
475
+ @container mwb (max-width:66rem){
476
+ .mwb .mwb-bento{grid-template-columns:repeat(2,minmax(0,1fr))}
477
+ .mwb .mwb-stats-card{grid-column:1/-1}
478
+ .mwb .mwb-health{grid-column:span 1}
479
+ }
480
+ @container mwb (max-width:48rem){
481
+ .mwb .mwb-shell[data-pane=directory] .mwb-detail,.mwb .mwb-shell[data-pane=detail] :is(.mwb-directory,.mwb-dashboard,.mwb-distribution,.mwb-header-add){display:none}
482
+ .mwb .mwb-shell[data-pane=directory] .mwb-dashboard{order:-1}
483
+ .mwb .mwb-shell[data-pane=directory] .mwb-bento{display:none}
484
+ .mwb[data-scroll=y] .mwb-grid{display:flex;flex-direction:column;overflow-y:auto}
485
+ .mwb[data-scroll=y] .mwb-grid>.mwb-directory,.mwb[data-scroll=y] .mwb-grid>.mwb-detail,.mwb[data-scroll=y] .mwb-grid>.mwb-dashboard{flex:none;overflow:visible;min-block-size:0}
486
+ .mwb .mwb-grid{gap:0}
487
+ .mwb .mwb-distribution{display:flex}
488
+ .mwb .mwb-segment{flex:1 1 0%;min-inline-size:0}
489
+ .mwb .mwb-list-tools{grid-template-columns:minmax(0,1fr) auto auto}
490
+ }
491
+ @container mwb (max-width:31rem){
492
+ .mwb .mwb-fields,.mwb .mwb-pair-row{grid-template-columns:minmax(0,1fr)}
493
+ .mwb .mwb-detail{border-inline:0;border-radius:0}
494
+ .mwb .mwb-pane-head,.mwb .mwb-pane-body{padding-inline:4px}
495
+ .mwb .mwb-compare-tools>:not(:first-child){flex:1 1 8rem}
496
+ .mwb .mwb-data>div{grid-template-columns:minmax(0,1fr);gap:2px}
497
+ .mwb .mwb-button{min-block-size:37px}
498
+ .mwb .mwb-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}
499
+ .mwb .mwb-brick:nth-child(3n+1){border-inline-start:1px solid var(--wb-line-soft)}
500
+ .mwb .mwb-brick:nth-child(2n+1){border-inline-start:0}
501
+ .mwb .mwb-brick:nth-child(-n+3){border-block-start:1px solid var(--wb-line-soft)}
502
+ .mwb .mwb-brick:nth-child(-n+2){border-block-start:0}
503
+ .mwb .mwb-bento{grid-template-columns:minmax(0,1fr)}
504
+ .mwb .mwb-server-meta{padding-inline-end:0}
505
+ .mwb .mwb-server-actions{position:static;margin-block-start:4px}
506
+ }
507
+ @supports not (container-type:inline-size){
508
+ @media (min-width:66rem){.mwb .mwb-grid[data-open=true]{grid-template-columns:minmax(0,.84fr) minmax(0,1.16fr)}.mwb .mwb-grid[data-dash=true]{grid-template-columns:minmax(0,.78fr) minmax(0,1.22fr)}}
509
+ @media (max-width:48rem){
510
+ .mwb .mwb-shell[data-pane=directory] .mwb-detail,.mwb .mwb-shell[data-pane=detail] :is(.mwb-directory,.mwb-dashboard,.mwb-distribution,.mwb-header-add){display:none}
511
+ .mwb .mwb-shell[data-pane=directory] .mwb-dashboard{order:-1}
512
+ .mwb .mwb-shell[data-pane=directory] .mwb-bento{display:none}
513
+ .mwb .mwb-distribution{display:flex}.mwb .mwb-segment{flex:1 1 0%;min-inline-size:0}
514
+ }
515
+ @media (max-width:31rem){.mwb .mwb-fields,.mwb .mwb-pair-row,.mwb .mwb-data>div{grid-template-columns:minmax(0,1fr)}}
516
+ }`;
517
+
518
+ /* src/workbench/ui-locale.js */
519
+ const zh = {
520
+ resTemplates: '资源模板', resParams: '填写模板参数', resParamsHint: '留空的参数会被省略。', resRefresh: '刷新预览',
521
+ resWatch: '订阅变更', resUnwatch: '停止订阅', resWatchList: '当前连接的订阅', resChanged: '资源有变更,刷新预览可查看最新内容。',
522
+ resWatchHint: '离开页面后订阅仍生效;重连后需要重新订阅。', resNoPreview: '该内容不支持在此预览。',
523
+ resTemplateFailed: '请核对模板参数;订阅前先预览资源。', resWatchFailed: '订阅操作未确认。请核对当前连接。',
524
+ resWatchLimit: '每个连接最多订阅 16 个资源。',
525
+ toolPending: '待复核', toolReview: '复核此定义', toolReviewOkay: '工具定义已复核。',
526
+ toolReviewFailed: '复核未保存。请刷新,并检查宿主存储。',
527
+ toolReviewNeeded: '工具定义新增或变化,复核前不会交给模型调用。',
528
+ confirmReview: '接受这份工具定义?', reviewHint: '只批准当前版本的定义,调用时仍执行审批策略。',
529
+ toolReadOnlyHint: '服务声明:只读', toolDestructiveHint: '服务声明:破坏性操作,逐次审批',
530
+ outputDefinition: '返回定义', structuredResult: '结构化结果', registryPackage: '包 / 镜像',
531
+ registryDockerHint: '需要 DSH 主机安装并启动 Docker。标签可能变化;摘要可锁定镜像内容。',
532
+ nav: 'MCP 服务器', panel: 'MCP 操作台', title: 'MCP 操作台', localeTag: 'zh-CN',
533
+ intro: '管理此引擎的 MCP 连接、服务器配置和工具调用策略。',
534
+ add: '新增服务器', reload: '刷新工作台', loading: '正在读取服务器…',
535
+ directory: '服务器目录', search: '搜索服务器', searchHint: '按名称、ID 或连接方式搜索',
536
+ filter: '连接状态', all: '全部状态', noMatches: '没有匹配的服务器。', reset: '清除筛选',
537
+ empty: '还没有服务器', emptyHint: '新增服务器后,可在这里查看连接状态与配置。',
538
+ noSelection: '未选中服务器', noSelectionHint: '从目录中选择服务器查看详情。', outOfFilter: '当前查看的服务器不在筛选结果中。',
539
+ runtime: '运行时', ready: '就绪', notReady: '未就绪', master: '连接总开关', on: '开启', off: '关闭',
540
+ runtimeOff: '运行时未就绪。配置仍可查看,连接操作暂不可用。',
541
+ masterOff: '连接总开关已关闭。请在宿主的插件设置中开启后再发起连接。',
542
+ 'transport.streamable-http': 'Streamable HTTP', 'transport.sse': 'SSE', 'transport.stdio': '本地进程(stdio)',
543
+ 'status.connected': '已连接', 'status.connecting': '连接中', 'status.reconnecting': '重连中',
544
+ 'status.disconnected': '未连接', 'status.disabled': '已停用', 'status.error': '连接异常', 'status.degraded': '已连接,有异常',
545
+ connect: '请求连接', refresh: '请求刷新目录', refreshing: '正在刷新服务目录…',
546
+ edit: '编辑配置', remove: '删除服务器', enableServer: '启用服务器', disableServer: '停用服务器',
547
+ serverDisabled: '服务器已停用。先启用,再发起连接。',
548
+ lastCheck: '最近检查', never: '尚未检查', checkOk: '通过', checkFailed: '未通过', ms: '毫秒',
549
+ tools: '工具总数', enabledTools: '已启用工具', resources: '资源', prompts: '提示模板',
550
+ toolTitle: '工具与调用策略', toolName: '工具', toolEnabled: '启用', toolApproval: '需审批',
551
+ toolEmpty: '服务器没有上报工具。可以请求刷新目录。',
552
+ toolOffline: '连接后可查看和调整服务器上报的工具。已保存的策略会保留。',
553
+ toolHint: '只列出当前连接上报的工具。宿主的权限规则仍然生效。',
554
+ confirmRemove: '确认删除这台服务器?', removeHint: '服务器配置与工具策略将从工作台移除。',
555
+ confirmApproval: '确认取消此工具的审批要求?',
556
+ approvalHint: '此设置不再额外要求审批;宿主的权限规则仍然生效。',
557
+ confirmServerApproval: '确认取消新工具的默认审批要求?',
558
+ serverApprovalHint: '未单独配置的工具会使用此默认值;宿主的权限规则仍然生效。',
559
+ confirm: '确认', confirmDelete: '确认删除', cancel: '取消',
560
+ createTitle: '新增服务器', editTitle: '编辑服务器',
561
+ formIntro: '尚未保存的配置只留在当前表单。凭据值由宿主保管。',
562
+ draftOpen: '请先保存或退出编辑,再切换服务器。',
563
+ identity: '标识与连接', policy: '启用与审批', id: '服务器 ID', name: '显示名称',
564
+ idHint: '以字母开头,最多 32 个字符,可用字母、数字、下划线和短横线。保存后不可改。',
565
+ nameHint: '留空时使用服务器 ID。', transport: '连接方式', url: '服务器 URL', command: '启动程序',
566
+ args: '启动参数(JSON 字符串数组)', argsHint: '每个参数是一个字符串;没有参数时填写 []。',
567
+ cwd: '工作目录(可选)', cwdHint: '使用 DSH 引擎所在主机的绝对路径。',
568
+ headers: '自定义请求头', env: '环境变量',
569
+ headersHint: '用于 HTTP 连接。已保存行的名称不可改;改名请移除后新增。',
570
+ envHint: '用于本地进程。已保存行的名称不可改;改名请移除后新增。',
571
+ pairName: '名称', pairValue: '值', addPair: '添加一项', removePair: '移除项',
572
+ pairEmpty: '暂无条目。', pairStored: '已保存,值不显示', pairStoredEmpty: '已保存,值为空',
573
+ pairChange: '修改值', pairKeep: '保留原值', pairClear: '留空并保存会清空原值。',
574
+ formEnabled: '保存后启用', formApproval: '工具默认需审批', timeout: '调用超时(毫秒)',
575
+ timeoutHint: '1000 到 180000 毫秒。', save: '保存配置', saving: '保存中…',
576
+ exit: '退出编辑', reopen: '丢弃草稿并重开',
577
+ staleDraft: '配置已在别处更新。草稿仍在;请核对改动,重开后再保存。',
578
+ goneDraft: '该服务器已被删除。草稿仍在;请复制需要的内容,再退出编辑。',
579
+ invalidId: '请检查服务器 ID。', invalidTransport: '请选择支持的连接方式。',
580
+ duplicateId: '服务器 ID 已被使用。', serverLimit: '已达到 32 台服务器的上限。',
581
+ invalidUrl: '请输入不含账号、密码或片段的完整 HTTP(S) URL。', urlCredential: '请在自定义请求头中填写密钥,不要放在 URL 参数里。',
582
+ invalidCommand: '请填写单个启动程序名或绝对路径。', invalidArgs: '请填写有效的 JSON 字符串数组,最多 64 个参数。',
583
+ invalidCwd: '工作目录须使用绝对路径。', invalidTimeout: '调用超时须为 1000 到 180000 之间的整数。',
584
+ invalidHeaders: '请检查请求头名称、重复项和长度。某些请求头由连接器管理。',
585
+ invalidEnv: '请检查环境变量名称、重复项和长度。某些变量由宿主管理。',
586
+ invalidPairValue: '值最多 2000 个字符,不可含换行或首尾空白。',
587
+ targetChanged: '连接目标已变更。请移除、清空或重新填写原有请求头和环境变量的值。',
588
+ vaultUnavailable: '当前宿主尚未提供凭据存储。原配置未修改。',
589
+ vaultWriteFailed: '宿主未能保存凭据。原配置未修改。',
590
+ busy: '正在处理请求并读取最新状态…', requestedConnect: '已请求连接。连接结果以服务器状态为准。',
591
+ requestedRefresh: '已请求刷新目录。请以最近检查与工具列表为准。',
592
+ saved: '服务器配置已保存。', removed: '服务器已删除。', enabled: '服务器已启用。',
593
+ disabled: '服务器已停用。', toolSaved: '工具策略已保存。',
594
+ unavailable: 'MCP 管理服务暂不可用。请确认宿主已加载插件后刷新工作台。',
595
+ forbidden: '当前访问方式没有管理权限。', missing: '服务器或工具已不在最新目录中。',
596
+ conflict: '配置已更新。请核对最新状态后重新操作。',
597
+ invalidInput: '配置未通过宿主校验。请检查填写内容。', failed: '请求失败。请核对最新状态后再操作。',
598
+ oldSnapshot: '下方保留上次读取的状态,刷新成功后可继续操作。',
599
+ viewError: '连接报告了异常。请检查配置或尝试重新连接。',
600
+ 'fault.connection-failed': '连接失败。请检查服务器地址与凭据。',
601
+ 'fault.discovery-failed': '目录刷新失败。请检查连接后再操作。',
602
+ 'fault.tool-failed': '工具调用失败。', 'fault.tool-disabled': '工具已禁用或连接配置已变更。',
603
+ 'fault.credential-missing': '连接凭据不可用。请编辑服务器并重新填写对应的值。',
604
+ 'fault.auth-rejected': '服务器验签失败(401)。请检查请求头名称和值。',
605
+ 'fault.access-denied': '服务器拒绝访问(403)。请检查凭据权限或服务商网络限制。',
606
+ 'fault.rate-limited': '请求次数或额度超限(429)。请检查额度或稍后重试。',
607
+ 'fault.invalid-transport': '连接配置无效。请检查连接方式和地址。',
608
+ 'fault.stdio-cwd-platform': '工作目录与 DSH 主机的路径格式不匹配。',
609
+ 'fault.stdio-start-not-found': 'DSH 主机找不到启动程序或工作目录。',
610
+ 'fault.stdio-start-denied': 'DSH 主机没有权限启动此程序或进入工作目录。',
611
+ 'fault.unsafe-request': '宿主已拦截跨来源请求或重定向。',
612
+ 'fault.registration-failed': '工具名称冲突,目录注册失败。',
613
+ 'fault.schema-secret': '工具定义包含连接凭据,宿主未加载该目录。',
614
+ 'fault.timeout': '连接或目录检查超时。', 'fault.cancelled': '连接操作已取消。',
615
+ 'fault.close-failed': '宿主未确认旧连接已关闭。请重启引擎后再试。',
616
+ 'fault.retry-exhausted': '多次重连失败。请检查配置后手动请求连接。',
617
+ distribution: '连接状态分布', 'group.all': '全部', 'group.online': '在线', 'group.fault': '有异常',
618
+ 'group.progress': '连接中', 'group.offline': '未连接', 'group.disabled': '已停用',
619
+ sort: '排序', 'sort.attention': '异常优先', 'sort.name': '名称', 'sort.checked': '最近检查', 'sort.tools': '可用工具',
620
+ results: '匹配 / 总数', availableTools: '可用工具', toolsRatio: '已启用 / 上报', serverColumn: '服务器',
621
+ back: '返回服务器列表', closeDetails: '关闭详情', selectedGone: '此服务器已从目录移除。',
622
+ detailLoading: '正在读取所选分区…', detailFailed: '分区读取失败。请重新读取。',
623
+ detailStale: '目录与服务器详情版本不同。请刷新工作台后再操作。', retry: '重新读取',
624
+ 'tab.connection': '连接', 'tab.tools': '工具', 'tab.activity': '活动', 'tab.config': '配置', detailTabs: '服务器分区',
625
+ target: '连接目标', reportedName: '服务器报告', retryCount: '已重试次数', nextRetry: '下次重试',
626
+ tryConnect: '请求重连', refreshingTable: '目录刷新中', connectionReadout: '连接诊断',
627
+ findTool: '搜索工具', findToolHint: '按工具名称或说明搜索', toolCount: '显示 / 上报',
628
+ toolNoMatches: '没有匹配的工具。', catalogReadOnly: '当前策略只读。', toolChanged: '工具定义已更新,请重新查看。',
629
+ schemaOpen: '参数定义', schemaClose: '关闭定义', schemaLoading: '正在读取参数定义…',
630
+ schemaFailed: '未读到此工具的参数定义。可以关闭后再打开。', schemaTruncated: '仅展示前一部分;不是完整定义。',
631
+ activityTitle: '本次运行活动', activityHint: '最多显示最近 20 条调用,只记录时间、耗时和结果。',
632
+ activityNoRuntime: '运行时未就绪,暂时没有活动可读。', activityEmpty: '本次引擎运行尚无调用记录。',
633
+ calls: '调用', failures: '失败', inFlight: '进行中', ok: '成功', notOk: '失败',
634
+ configTitle: '已保存的配置', configEnabled: '已启用', configApproval: '默认需审批', configEndpoint: 'HTTP 地址',
635
+ configPairsSet: '有保存值', configPairsEmpty: '值为空', targetReset: '更换连接目标会清除已有工具策略,并恢复默认审批。',
636
+ errConnectionShort: '连接失败', errRefreshShort: '目录刷新失败', errCredentialShort: '凭据缺失',
637
+ errAuthShort: '鉴权失败', errAccessShort: '访问受限', errQuotaShort: '频率或额度受限', errTimeShort: '操作超时',
638
+ 'meta.online': '在线 {n}', 'meta.fault': '有异常 {n}', 'meta.progress': '连接中 {n}', 'meta.offline': '未连接 {n}', 'meta.disabled': '已停用 {n}',
639
+ heartbeatNone: '还没有调用记录', heartbeatLabel: '最近 {n} 次调用:{ok} 次成功,{fail} 次失败', drawerClose: '关闭',
640
+ updatedJustNow: '刚刚更新', updatedMin: '{n} 分钟前更新', updatedHour: '{n} 小时前更新', updatedDay: '{n} 天前更新',
641
+ relJustNow: '刚刚', relSec: '{n} 秒前', relMin: '{n} 分钟前', relHour: '{n} 小时前', relDay: '{n} 天前',
642
+ dashTitle: '总览', metricServers: '服务器', rankTitle: '工具调用排行', rankMore: '另有 {n} 个工具未列出',
643
+ conflictTitle: '工具冲突', conflictHint: '以下工具由多台服务器同时上报。', tags: '标签',
644
+ statusEngineOn: '引擎运行中', statusEngineOff: '引擎未运行', lockFree: '写入锁空闲', lockBusy: '写入锁占用',
645
+ playground: '试运行', playgroundHint: '按参数定义填写后直接调用该工具,试运行同样受审批策略约束。',
646
+ playgroundRun: '运行', playgroundRaw: '参数定义不可解析,请直接填写 JSON 参数。',
647
+ argUnset: '未设置', argJsonHint: '填写 JSON 值。', argInvalid: '请检查 JSON 格式。', invoking: '正在运行工具…',
648
+ confirmInvoke: '确认试运行此工具?', invokeHint: '试运行同样受审批策略约束,将由宿主执行。',
649
+ resultTruncated: '结果过长,已截断展示。',
650
+ saveAndTest: '保存并测试', testing: '保存并测试中…', testTitle: '连接测试',
651
+ io: '导入 / 导出', exportRedacted: '导出(脱敏)', exportFull: '导出(含凭据)',
652
+ confirmExport: '导出包含明文凭据的配置?', exportHint: '导出文件包含全部服务器与明文凭据,请妥善保管。',
653
+ exported: '已下载 {n} 台服务器的配置。', copyButton: '复制到剪贴板', copied: '已复制。',
654
+ importField: '或粘贴 JSON', importFile: '选择 JSON 文件', importFileReading: '正在读取文件…',
655
+ importFileLarge: '文件超过 160 KB。', importFileFailed: '读取文件失败。请重新选择。',
656
+ importFileHint: '支持本插件备份和常见第三方 MCP JSON。第三方服务导入后默认停用。', importMerge: '合并', importReplace: '替换', importRun: '开始导入',
657
+ confirmImport: '替换将删除现有全部服务器,继续?', importReplaceHint: '替换模式会先移除现有全部服务器,再导入文件中的服务器。',
658
+ importAdded: '新增 {n}', importUpdated: '更新 {n}', importReplaced: '已替换现有目录。', importJson: '请粘贴有效的 JSON 配置。',
659
+ clone: '克隆', cloneSuffix: ' 副本',
660
+ templateOpen: '从模板新增', templates: '模板', templateHint: '选择模板进入预填编辑器,ID 与凭据仍需自填。',
661
+ tplExa: '云托管 Exa 搜索,凭据写入 x-api-key 请求头。', tplContext7: '云托管 Context7 文档检索,凭据写入 CONTEXT7_API_KEY 请求头。',
662
+ tplGithub: '云托管 GitHub MCP,凭据写入 Authorization 请求头(Bearer 令牌)。', tplPlaywright: '本地 Playwright 控制进程,无需凭据。',
663
+ tplNotion: '云托管 Notion,凭据写入 Authorization 请求头(Bearer 令牌)。', tplFetch: '本地 Fetch 进程,无需凭据。',
664
+ healthTitle: '健康巡检', healthOff: '健康巡检未开启。开启后按固定间隔自动检查每台服务器,连续异常可自动停用。',
665
+ healthEnable: '开启巡检', healthInterval: '巡检间隔(分钟)', healthAutoDisable: '连续异常自动停用(0 为关闭)',
666
+ healthLog: '最近转移', healthFaults: '异常 {n} 次', healthEmpty: '暂无巡检记录。',
667
+ 'healthKind.fault': '异常', 'healthKind.recovered': '恢复', 'healthKind.auto-disabled': '已自动停用',
668
+ healthSaved: '巡检设置已保存。', tagsField: '逗号分隔,最多 8 个', tagsSave: '保存标签',
669
+ tagsSaved: '标签已保存。', tagsInvalid: '请检查标签:最多 8 个,每个不超过 24 字符。',
670
+ registryOpen: '从目录添加', registryHint: '搜索 MCP 官方注册表,选中后进入预填编辑器,ID 与凭据仍需自填。',
671
+ registrySearchBtn: '搜索', registrySearching: '正在搜索注册表…', registryEmpty: '没有匹配的服务器。',
672
+ registryUnreachable: '注册表暂时不可用,请稍后再试。', registryFailed: '搜索失败,请稍后重试。',
673
+ registryTimeout: '连接注册表超时,请稍后重试。', registryDns: '域名解析失败,请检查网络后重试。',
674
+ registryTls: '与注册表的安全连接失败,请稍后重试。', registryHttp: '注册表返回异常状态',
675
+ registryInstall: '填入编辑器', registryFrom: '来自目录:{n}',
676
+ bulkSelect: '批量选择', bulkExit: '退出批量', bulkEnable: '批量启用', bulkDisable: '批量停用',
677
+ bulkConnect: '批量重连', bulkDone: '已处理 {n} 台服务器。', bulkPartial: '部分服务器处理失败,已停止。',
678
+ bulkBusy: '正在批量处理…', bulkColumn: '选择',
679
+ 'tab.resources': '资源', 'tab.prompts': '提示词', 'tab.logs': '日志',
680
+ resourcesTitle: '资源目录', resourcesHint: '服务器提供的资源,点开预览内容;需要服务器在线。',
681
+ resourcesEmpty: '该服务器未提供资源。', resOpen: '预览', resClose: '收起', resLoading: '正在读取资源…',
682
+ resTruncated: '内容过长,已截断显示。', resCopy: '复制内容', resCopied: '已复制。',
683
+ promptsTitle: '提示词库', promptsHint: '服务器预置的任务模板,填参数渲染后复制使用;需要服务器在线。',
684
+ promptsEmpty: '该服务器未提供提示词。', promptArgs: '参数', promptRender: '渲染提示词', promptRendering: '正在渲染…',
685
+ promptResult: '渲染结果', promptCopy: '复制全部', promptCopied: '已复制。', promptRequired: '必填',
686
+ logsTitle: '日志控制台', logsStdioHint: '显示本地进程最近的标准错误(stderr);连接失败后仍可查看。', logsHint: '服务器运行日志(若服务器支持 logging 能力),自动刷新。',
687
+ logsEmpty: '暂无日志。', logsLevel: '级别', logsPaused: '服务器离线,暂停刷新。',
688
+ logsUnsupported: '该服务器未提供日志能力(logging),无法采集日志。',
689
+ logsAuto: '自动刷新', logsApplied: '日志级别已更新。',
690
+ statsTitle: '调用趋势', statsHint: '最近 14 天的持久化调用统计(独立 stats.json,重启不清零)。',
691
+ statsCalls: '调用', statsFailRate: '失败率', statsSlow: '最慢调用', statsTop: '高频工具',
692
+ statsNoData: '暂无持久化统计。',
693
+ faultUnsupported: '该服务器未提供此能力或当前未连接。',
694
+ faultReadFailed: '读取资源失败,请稍后重试。', faultPromptFailed: '渲染提示词失败,请检查参数。',
695
+ needsLive: '需要服务器在线才能使用。',
696
+ };
697
+ const en = {
698
+ resTemplates: 'Resource templates', resParams: 'Template parameters', resParamsHint: 'Blank parameters are omitted.', resRefresh: 'Refresh preview',
699
+ resWatch: 'Watch for changes', resUnwatch: 'Stop watching', resWatchList: 'Subscriptions on this connection', resChanged: 'The resource changed. Refresh the preview to see the latest content.',
700
+ resWatchHint: 'Subscriptions remain active when you leave this page and end when the connection closes.', resNoPreview: 'This content is not available for preview.',
701
+ resTemplateFailed: 'Check the template and values. Open a preview before subscribing.', resWatchFailed: 'The subscription operation was not confirmed. Check the connection.',
702
+ resWatchLimit: 'Watch up to 16 resources on each connection.',
703
+ toolPending: 'Review required', toolReview: 'Review this definition', toolReviewOkay: 'Tool definition accepted.',
704
+ toolReviewFailed: 'The review was not saved. Reload and check storage on the host.',
705
+ toolReviewNeeded: 'This definition is new or changed. It stays unavailable to the model until reviewed.',
706
+ confirmReview: 'Accept this tool definition?', reviewHint: 'This accepts the current definition only. Call approval rules still apply.',
707
+ toolReadOnlyHint: 'Server hint: read-only', toolDestructiveHint: 'Server hint: destructive, approve every call',
708
+ outputDefinition: 'Output definition', structuredResult: 'Structured result', registryPackage: 'Package / image',
709
+ registryDockerHint: 'Docker must be running on the DSH host. Tags can change; a digest pins the image content.',
710
+ nav: 'MCP servers', panel: 'MCP workbench', title: 'MCP workbench', localeTag: 'en',
711
+ intro: 'Manage MCP connections, server configuration, and tool policies for this engine.',
712
+ add: 'Add server', reload: 'Reload workspace', loading: 'Reading servers…',
713
+ directory: 'Servers', search: 'Search servers', searchHint: 'Search by name, ID, or transport',
714
+ filter: 'Connection status', all: 'All statuses', noMatches: 'No servers match your filters.', reset: 'Clear filters',
715
+ empty: 'No servers yet', emptyHint: 'Add a server to manage its connection and configuration here.',
716
+ noSelection: 'No server selected', noSelectionHint: 'Select a server from the list to inspect it.', outOfFilter: 'The server you are viewing is outside the current filter.',
717
+ runtime: 'Runtime', ready: 'Ready', notReady: 'Not ready', master: 'Connections', on: 'On', off: 'Off',
718
+ runtimeOff: 'The runtime is not ready. You can view configuration, but connection actions are unavailable.',
719
+ masterOff: 'Connections are off. Turn them on in the host plugin settings to request a connection.',
720
+ 'transport.streamable-http': 'Streamable HTTP', 'transport.sse': 'SSE', 'transport.stdio': 'Local process (stdio)',
721
+ 'status.connected': 'Connected', 'status.connecting': 'Connecting', 'status.reconnecting': 'Reconnecting',
722
+ 'status.disconnected': 'Disconnected', 'status.disabled': 'Disabled', 'status.error': 'Connection error', 'status.degraded': 'Connected with errors',
723
+ connect: 'Request connection', refresh: 'Request catalog refresh', refreshing: 'Refreshing server catalog…',
724
+ edit: 'Edit configuration', remove: 'Delete server', enableServer: 'Enable server', disableServer: 'Disable server',
725
+ serverDisabled: 'This server is disabled. Enable it to request a connection.',
726
+ lastCheck: 'Last check', never: 'Not checked yet', checkOk: 'Passed', checkFailed: 'Failed', ms: 'ms',
727
+ tools: 'Total tools', enabledTools: 'Enabled tools', resources: 'Resources', prompts: 'Prompts',
728
+ toolTitle: 'Tools and call policies', toolName: 'Tool', toolEnabled: 'Enabled', toolApproval: 'Require approval',
729
+ toolEmpty: 'The server reported no tools. You can request a catalog refresh.',
730
+ toolOffline: 'Connect to view and manage tools reported by the server. Saved policies are kept.',
731
+ toolHint: 'Only tools reported by the current connection appear here. Host permissions still apply.',
732
+ confirmRemove: 'Delete this server?', removeHint: 'Its configuration and tool policies will be removed from the workspace.',
733
+ confirmApproval: 'Remove the approval requirement for this tool?',
734
+ approvalHint: 'This policy will no longer add an approval requirement. Host permissions still apply.',
735
+ confirmServerApproval: 'Remove the default approval requirement for new tools?',
736
+ serverApprovalHint: 'Tools without an individual policy use this default. Host permissions still apply.',
737
+ confirm: 'Confirm', confirmDelete: 'Confirm deletion', cancel: 'Cancel',
738
+ createTitle: 'Add server', editTitle: 'Edit server',
739
+ formIntro: 'Unsaved changes stay in this form. The host stores credential values.',
740
+ draftOpen: 'Save or exit the editor before switching servers.',
741
+ identity: 'Identity and connection', policy: 'Availability and approval', id: 'Server ID', name: 'Display name',
742
+ idHint: 'Start with a letter. Use up to 32 letters, digits, underscores or hyphens. The ID cannot change after saving.',
743
+ nameHint: 'Leave blank to use the server ID.', transport: 'Transport', url: 'Server URL', command: 'Launch program',
744
+ args: 'Launch arguments (JSON array of strings)', argsHint: 'Write each argument as a string. Use [] for no arguments.',
745
+ cwd: 'Working directory (optional)', cwdHint: 'Use an absolute path on the host running DSH.',
746
+ headers: 'Custom request headers', env: 'Environment variables',
747
+ headersHint: 'Used by HTTP connections. To rename a saved row, remove it and add a new one.',
748
+ envHint: 'Used by local processes. To rename a saved row, remove it and add a new one.',
749
+ pairName: 'Name', pairValue: 'Value', addPair: 'Add entry', removePair: 'Remove entry',
750
+ pairEmpty: 'No entries.', pairStored: 'Saved; value hidden', pairStoredEmpty: 'Saved; empty value',
751
+ pairChange: 'Change value', pairKeep: 'Keep saved value', pairClear: 'Save with an empty field to clear the saved value.',
752
+ formEnabled: 'Enable after saving', formApproval: 'Require approval by default', timeout: 'Call timeout (ms)',
753
+ timeoutHint: '1,000 to 180,000 milliseconds.', save: 'Save configuration', saving: 'Saving…',
754
+ exit: 'Exit editor', reopen: 'Discard draft and reopen',
755
+ staleDraft: 'Configuration changed elsewhere. Your draft is intact. Review it and reopen the editor to save again.',
756
+ goneDraft: 'This server was deleted. Your draft is intact; copy what you need before exiting the editor.',
757
+ invalidId: 'Check the server ID.', invalidTransport: 'Select a supported transport.',
758
+ duplicateId: 'This server ID is already in use.', serverLimit: 'The workspace supports up to 32 servers.',
759
+ invalidUrl: 'Enter a full HTTP(S) URL without user information or a fragment.', urlCredential: 'Put keys in custom request headers, not in URL parameters.',
760
+ invalidCommand: 'Enter a single program name or absolute path.', invalidArgs: 'Enter a JSON array of up to 64 strings.',
761
+ invalidCwd: 'Use an absolute path for the working directory.', invalidTimeout: 'Use an integer between 1,000 and 180,000 for the call timeout.',
762
+ invalidHeaders: 'Check header names, duplicates, and lengths. Some headers are managed by the connector.',
763
+ invalidEnv: 'Check variable names, duplicates, and lengths. Some variables are managed by the host.',
764
+ invalidPairValue: 'Use up to 2,000 characters with no line breaks or leading or trailing spaces.',
765
+ targetChanged: 'The connection target changed. Remove, clear, or re-enter the saved request header and environment values.',
766
+ vaultUnavailable: 'The host has not made credential storage available. Your configuration was not changed.',
767
+ vaultWriteFailed: 'The host did not save the credentials. Your configuration was not changed.',
768
+ busy: 'Processing the request and reading the latest status…', requestedConnect: 'Connection requested. Check the server status for the result.',
769
+ requestedRefresh: 'Catalog refresh requested. Check the last check and tool list for the result.',
770
+ saved: 'Server configuration saved.', removed: 'Server deleted.', enabled: 'Server enabled.',
771
+ disabled: 'Server disabled.', toolSaved: 'Tool policy saved.',
772
+ unavailable: 'The MCP management service is unavailable. Check that the host loaded the plugin, then reload the workspace.',
773
+ forbidden: 'This connection does not have management access.', missing: 'The server or tool is no longer in the current list.',
774
+ conflict: 'Configuration changed. Check the latest state before making another change.',
775
+ invalidInput: 'The host rejected the configuration. Check the fields and try again.', failed: 'The request failed. Check the latest state before trying again.',
776
+ oldSnapshot: 'Showing the last snapshot. Actions are available after a successful reload.',
777
+ viewError: 'The connection reported a problem. Check the configuration or request a new connection.',
778
+ 'fault.connection-failed': 'Connection failed. Check the server address and credentials.',
779
+ 'fault.discovery-failed': 'Catalog refresh failed. Check the connection before trying again.',
780
+ 'fault.tool-failed': 'The tool call failed.', 'fault.tool-disabled': 'The tool was disabled or its connection configuration changed.',
781
+ 'fault.credential-missing': 'A connection credential is unavailable. Edit the server and re-enter its value.',
782
+ 'fault.auth-rejected': 'Authentication failed (401). Check the request header names and values.',
783
+ 'fault.access-denied': 'The server denied access (403). Check key permissions or provider network limits.',
784
+ 'fault.rate-limited': 'Request or quota limit reached (429). Check the quota or try again later.',
785
+ 'fault.invalid-transport': 'The connection configuration is invalid. Check its transport and address.',
786
+ 'fault.stdio-cwd-platform': 'The working directory does not match the DSH host’s path format.',
787
+ 'fault.stdio-start-not-found': 'The DSH host could not find the executable or working directory.',
788
+ 'fault.stdio-start-denied': 'The DSH host lacks permission to start the program or enter its directory.',
789
+ 'fault.unsafe-request': 'The host blocked a cross-origin request or redirect.',
790
+ 'fault.registration-failed': 'Conflicting tool names prevented catalog registration.',
791
+ 'fault.schema-secret': 'The tool definition contained credentials, so the host did not load the catalog.',
792
+ 'fault.timeout': 'The connection or catalog check timed out.', 'fault.cancelled': 'The connection action was cancelled.',
793
+ 'fault.close-failed': 'The host could not confirm that the previous connection closed. Restart the engine before trying again.',
794
+ 'fault.retry-exhausted': 'Reconnection attempts failed. Check the configuration and request a new connection.',
795
+ distribution: 'Connection distribution', 'group.all': 'All', 'group.online': 'Online', 'group.fault': 'Needs attention',
796
+ 'group.progress': 'In progress', 'group.offline': 'Disconnected', 'group.disabled': 'Disabled',
797
+ sort: 'Sort', 'sort.attention': 'Attention first', 'sort.name': 'Name', 'sort.checked': 'Last checked', 'sort.tools': 'Available tools',
798
+ results: 'Matching / Total', availableTools: 'Available tools', toolsRatio: 'Enabled / Reported', serverColumn: 'Server',
799
+ back: 'Back to servers', closeDetails: 'Close details', selectedGone: 'This server is no longer in the directory.',
800
+ detailLoading: 'Reading this section…', detailFailed: 'This section could not be read. Try reading it again.',
801
+ detailStale: 'The directory and server details are from different revisions. Reload the workspace before making changes.', retry: 'Read again',
802
+ 'tab.connection': 'Connection', 'tab.tools': 'Tools', 'tab.activity': 'Activity', 'tab.config': 'Configuration', detailTabs: 'Server sections',
803
+ target: 'Connection target', reportedName: 'Server reports', retryCount: 'Retry attempts', nextRetry: 'Next retry',
804
+ tryConnect: 'Request reconnection', refreshingTable: 'Catalog refreshing', connectionReadout: 'Connection diagnostics',
805
+ findTool: 'Search tools', findToolHint: 'Search tool names or descriptions', toolCount: 'Shown / Reported',
806
+ toolNoMatches: 'No tools match your search.', catalogReadOnly: 'This policy is read-only.', toolChanged: 'The tool definition changed. Review it again before making changes.',
807
+ schemaOpen: 'Input definition', schemaClose: 'Close definition', schemaLoading: 'Reading input definition…',
808
+ schemaFailed: 'The input definition could not be read. Close it and open it again.', schemaTruncated: 'Partial preview; the definition is not complete.',
809
+ activityTitle: 'Activity in this engine run', activityHint: 'Shows up to 20 recent calls with timing and results only.',
810
+ activityNoRuntime: 'The runtime is not ready. Activity is unavailable.', activityEmpty: 'No calls recorded in this engine run.',
811
+ calls: 'Calls', failures: 'Failures', inFlight: 'In progress', ok: 'Succeeded', notOk: 'Failed',
812
+ configTitle: 'Saved configuration', configEnabled: 'Enabled', configApproval: 'Require approval by default', configEndpoint: 'HTTP address',
813
+ configPairsSet: 'Has saved value', configPairsEmpty: 'Empty value', targetReset: 'Changing the connection target clears saved tool policies and restores the approval requirement.',
814
+ errConnectionShort: 'Connection failed', errRefreshShort: 'Catalog refresh failed', errCredentialShort: 'Missing credential',
815
+ errAuthShort: 'Authentication failed', errAccessShort: 'Access denied', errQuotaShort: 'Rate or quota limit', errTimeShort: 'Timed out',
816
+ 'meta.online': '{n} online', 'meta.fault': '{n} needs attention', 'meta.progress': '{n} in progress', 'meta.offline': '{n} disconnected', 'meta.disabled': '{n} disabled',
817
+ heartbeatNone: 'No calls recorded yet', heartbeatLabel: 'Last {n} calls: {ok} succeeded, {fail} failed', drawerClose: 'Close',
818
+ updatedJustNow: 'Updated just now', updatedMin: 'Updated {n} min ago', updatedHour: 'Updated {n} h ago', updatedDay: 'Updated {n} d ago',
819
+ relJustNow: 'just now', relSec: '{n}s ago', relMin: '{n}m ago', relHour: '{n}h ago', relDay: '{n}d ago',
820
+ dashTitle: 'Overview', metricServers: 'Servers', rankTitle: 'Tool call ranking', rankMore: '{n} more tools not listed',
821
+ conflictTitle: 'Tool conflicts', conflictHint: 'These tools are reported by multiple servers.', tags: 'Tags',
822
+ statusEngineOn: 'Engine running', statusEngineOff: 'Engine stopped', lockFree: 'Write lock free', lockBusy: 'Write lock held',
823
+ playground: 'Try it', playgroundHint: 'Fill the arguments from the input definition and call the tool directly; the run follows the same approval policy.',
824
+ playgroundRun: 'Run', playgroundRaw: 'The definition is unreadable; write the arguments as JSON.',
825
+ argUnset: 'Not set', argJsonHint: 'Write a JSON value.', argInvalid: 'Check the JSON formatting.', invoking: 'Running the tool…',
826
+ confirmInvoke: 'Run this tool once?', invokeHint: 'The run follows the same approval policy and executes on the host.',
827
+ resultTruncated: 'The result was too long and was truncated.',
828
+ saveAndTest: 'Save and test', testing: 'Saving and testing…', testTitle: 'Connection test',
829
+ io: 'Import / export', exportRedacted: 'Export redacted', exportFull: 'Export with credentials',
830
+ confirmExport: 'Export the configuration with credentials?', exportHint: 'The export file contains every server with credentials in plain text. Store it carefully.',
831
+ exported: 'Downloaded the configuration of {n} servers.', copyButton: 'Copy to clipboard', copied: 'Copied.',
832
+ importField: 'Or paste JSON', importFile: 'Choose JSON file', importFileReading: 'Reading file…',
833
+ importFileLarge: 'The file exceeds 160 KB.', importFileFailed: 'Could not read the file. Select it again.',
834
+ importFileHint: 'Accepts this plugin’s backups and common third-party MCP JSON. Imported third-party servers start disabled.', importMerge: 'Merge', importReplace: 'Replace', importRun: 'Start import',
835
+ confirmImport: 'Replace deletes every existing server. Continue?', importReplaceHint: 'Replace removes every existing server before importing the file.',
836
+ importAdded: '{n} added', importUpdated: '{n} updated', importReplaced: 'The directory was replaced.', importJson: 'Paste a valid JSON configuration.',
837
+ clone: 'Clone', cloneSuffix: ' copy',
838
+ templateOpen: 'Add from template', templates: 'Templates', templateHint: 'Pick a template to open a pre-filled editor; you still choose the ID and credentials.',
839
+ tplExa: 'Hosted Exa search; put the key in the x-api-key header.', tplContext7: 'Hosted Context7 docs; put the key in the CONTEXT7_API_KEY header.',
840
+ tplGithub: 'Hosted GitHub MCP; put a Bearer token in the Authorization header.', tplPlaywright: 'Local Playwright process; no credentials needed.',
841
+ tplNotion: 'Hosted Notion; put a Bearer token in the Authorization header.', tplFetch: 'Local Fetch process; no credentials needed.',
842
+ healthTitle: 'Health checks', healthOff: 'Health checks are off. When on, every server is checked on a fixed interval, and repeated faults can auto-disable it.',
843
+ healthEnable: 'Turn on checks', healthInterval: 'Interval (minutes)', healthAutoDisable: 'Auto-disable after faults (0 is off)',
844
+ healthLog: 'Recent transitions', healthFaults: '{n} faults', healthEmpty: 'No checks recorded yet.',
845
+ 'healthKind.fault': 'Fault', 'healthKind.recovered': 'Recovered', 'healthKind.auto-disabled': 'Auto-disabled',
846
+ healthSaved: 'Health settings saved.', tagsField: 'Comma separated, up to 8', tagsSave: 'Save tags',
847
+ tagsSaved: 'Tags saved.', tagsInvalid: 'Check the tags: up to 8, each up to 24 characters.',
848
+ registryOpen: 'From registry', registryHint: 'Search the public MCP registry; pick one to open a prefilled editor. ID and credentials stay yours to enter.',
849
+ registrySearchBtn: 'Search', registrySearching: 'Searching the registry…', registryEmpty: 'No matching servers.',
850
+ registryUnreachable: 'Registry temporarily unreachable. Try again later.', registryFailed: 'Search failed. Try again later.',
851
+ registryTimeout: 'Registry connection timed out. Try again later.', registryDns: 'Name resolution failed. Check the network and retry.',
852
+ registryTls: 'Secure connection to the registry failed. Try again later.', registryHttp: 'Registry returned an unexpected status',
853
+ registryInstall: 'Fill editor', registryFrom: 'From registry: {n}',
854
+ bulkSelect: 'Bulk select', bulkExit: 'Exit bulk', bulkEnable: 'Enable selected', bulkDisable: 'Disable selected',
855
+ bulkConnect: 'Reconnect selected', bulkDone: 'Processed {n} servers.', bulkPartial: 'Some servers failed; stopped.',
856
+ bulkBusy: 'Working in bulk…', bulkColumn: 'Pick',
857
+ 'tab.resources': 'Resources', 'tab.prompts': 'Prompts', 'tab.logs': 'Logs',
858
+ resourcesTitle: 'Resources', resourcesHint: 'Resources offered by the server; open one to preview. Requires a live connection.',
859
+ resourcesEmpty: 'This server offers no resources.', resOpen: 'Preview', resClose: 'Collapse', resLoading: 'Reading resource…',
860
+ resTruncated: 'Content truncated for display.', resCopy: 'Copy content', resCopied: 'Copied.',
861
+ promptsTitle: 'Prompt library', promptsHint: 'Server-provided task templates; fill arguments, render, then copy. Requires a live connection.',
862
+ promptsEmpty: 'This server offers no prompts.', promptArgs: 'Arguments', promptRender: 'Render prompt', promptRendering: 'Rendering…',
863
+ promptResult: 'Rendered result', promptCopy: 'Copy all', promptCopied: 'Copied.', promptRequired: 'required',
864
+ logsTitle: 'Log console', logsStdioHint: 'Recent standard error (stderr) from the local process, including failed launches.', logsHint: 'Server runtime logs (when the server supports logging), auto-refreshing.',
865
+ logsEmpty: 'No log lines yet.', logsLevel: 'Level', logsPaused: 'Server offline; auto-refresh paused.',
866
+ logsUnsupported: 'This server does not offer the logging capability, so no log lines can be collected.',
867
+ logsAuto: 'Auto refresh', logsApplied: 'Log level updated.',
868
+ statsTitle: 'Call trends', statsHint: 'Persisted call statistics over the last 14 days (side-car stats.json, survives restarts).',
869
+ statsCalls: 'Calls', statsFailRate: 'Failure rate', statsSlow: 'Slowest calls', statsTop: 'Top tools',
870
+ statsNoData: 'No persisted statistics yet.',
871
+ faultUnsupported: 'This server does not provide this capability, or it is not connected.',
872
+ faultReadFailed: 'Resource read failed. Try again later.', faultPromptFailed: 'Prompt render failed. Check the arguments.',
873
+ needsLive: 'Requires a live server connection.',
874
+ };
875
+
876
+ /* src/workbench/ui-helpers.js */
877
+ const statuses = ['connected', 'connecting', 'reconnecting', 'disconnected', 'disabled', 'error'];
878
+ const transports = ['streamable-http', 'sse', 'stdio'];
879
+ const conflictCodes = new Set(['CONFLICT', 'REVISION_CONFLICT', 'PAIR_NOT_FOUND']);
880
+ const rpcErrors = {
881
+ FORBIDDEN: 'forbidden', UNAVAILABLE: 'unavailable', INTERNAL: 'failed',
882
+ NOT_READY: 'runtimeOff', RUNTIME_NOT_READY: 'runtimeOff', AUTO_CONNECT_DISABLED: 'masterOff', SERVER_DISABLED: 'serverDisabled',
883
+ NOT_FOUND: 'missing', SERVER_NOT_FOUND: 'missing', TOOL_NOT_FOUND: 'missing', TOOL_CHANGED: 'toolChanged',
884
+ SERVER_EXISTS: 'duplicateId', SERVER_LIMIT: 'serverLimit', INVALID_INPUT: 'invalidInput', VALIDATION: 'invalidInput',
885
+ TARGET_CHANGED_WITH_CREDENTIALS: 'targetChanged', VAULT_UNAVAILABLE: 'vaultUnavailable', CREDENTIAL_WRITE_FAILED: 'vaultWriteFailed',
886
+ TOOL_REVIEW_REQUIRED: 'toolReviewNeeded', TOOL_REVIEW_FAILED: 'toolReviewFailed', UNSUPPORTED: 'faultUnsupported', READ_FAILED: 'faultReadFailed', RESOURCE_TEMPLATE_INVALID: 'resTemplateFailed', RESOURCE_WATCH_FAILED: 'resWatchFailed',
887
+ RESOURCE_WATCH_LIMIT: 'resWatchLimit', PROMPT_FAILED: 'faultPromptFailed',
888
+ };
889
+ const localeOf = t => t('localeTag') === 'zh-CN' ? 'zh-CN' : 'en';
890
+ const displayName = server => server.name || server.id;
891
+ const statusOf = server => server.enabled === false ? 'disabled'
892
+ : statuses.includes(server.status) ? server.status : 'disconnected';
893
+ const transportLabel = (t, server) => transports.includes(server.transport) ? t('transport.' + server.transport) : server.transport;
894
+ const errorCode = error => typeof error?.code === 'string' ? error.code.toUpperCase().replaceAll('-', '_') : '';
895
+ const rpcErrorKey = (error, fallback = 'failed') => {
896
+ const code = errorCode(error);
897
+ return conflictCodes.has(code) ? 'conflict' : Object.hasOwn(rpcErrors, code) ? rpcErrors[code] : fallback;
898
+ };
899
+ const viewErrorText = (t, error) => {
900
+ const key = 'fault.' + (typeof error === 'string' ? error : error?.code?.toLowerCase().replaceAll('_', '-'));
901
+ if (Object.hasOwn(en, key)) return t(key);
902
+ const message = typeof error === 'string' ? error : error?.message;
903
+ return typeof message === 'string' && message.trim() ? message.slice(0, 320) : t('viewError');
904
+ };
905
+ const sections = ['connection', 'tools', 'activity', 'resources', 'prompts', 'logs', 'config'];
906
+ const groups = ['all', 'online', 'fault', 'progress', 'offline', 'disabled'];
907
+ const attentionRank = { fault: 0, progress: 1, offline: 2, online: 3, disabled: 4 };
908
+ const sortKeys = ['attention', 'name', 'checked', 'tools'];
909
+ const shortFaults = {
910
+ 'connection-failed': 'errConnectionShort', 'discovery-failed': 'errRefreshShort', 'credential-missing': 'errCredentialShort',
911
+ 'auth-rejected': 'errAuthShort', 'access-denied': 'errAccessShort', 'rate-limited': 'errQuotaShort', timeout: 'errTimeShort',
912
+ };
913
+ const shortFault = (t, error) => {
914
+ const code = error?.code;
915
+ return Object.hasOwn(shortFaults, code) ? t(shortFaults[code]) : viewErrorText(t, error);
916
+ };
917
+ const groupOf = server => {
918
+ const status = statusOf(server);
919
+ if (status === 'disabled') return 'disabled';
920
+ if (status === 'connecting' || status === 'reconnecting') return 'progress';
921
+ if (status === 'error' || server.error) return 'fault';
922
+ return status === 'connected' ? 'online' : 'offline';
923
+ };
924
+ const stamped = tool => typeof tool?.stamp === 'string' && tool.stamp.length > 0;
925
+ const online = (overview, server) => overview?.active === true && overview.autoConnect === true && server?.enabled === true && statusOf(server) === 'connected';
926
+ const number = (t, value) => Number.isFinite(value) ? value.toLocaleString(localeOf(t)) : '—';
927
+ const duration = (t, value) => Number.isFinite(value) ? number(t, value) + ' ' + t('ms') : '—';
928
+ const agoText = (t, key, value) => t(key).replace('{n}', number(t, value));
929
+ const relative = (t, at) => {
930
+ const seconds = Math.max(0, Math.floor((Date.now() - at) / 1000));
931
+ if (seconds < 10) return t('relJustNow');
932
+ if (seconds < 60) return agoText(t, 'relSec', seconds);
933
+ if (seconds < 3600) return agoText(t, 'relMin', Math.max(1, Math.floor(seconds / 60)));
934
+ if (seconds < 86400) return agoText(t, 'relHour', Math.floor(seconds / 3600));
935
+ return agoText(t, 'relDay', Math.floor(seconds / 86400));
936
+ };
937
+ const updated = (t, at) => {
938
+ const seconds = Math.max(0, Math.floor((Date.now() - at) / 1000));
939
+ if (seconds < 60) return t('updatedJustNow');
940
+ if (seconds < 3600) return agoText(t, 'updatedMin', Math.max(1, Math.floor(seconds / 60)));
941
+ if (seconds < 86400) return agoText(t, 'updatedHour', Math.floor(seconds / 3600));
942
+ return agoText(t, 'updatedDay', Math.floor(seconds / 86400));
943
+ };
944
+ const VERSION = 'v' + manifest.version;
945
+ // One stable categorical color index per tag name, so the same tag keeps the
946
+ // same data color everywhere (table chips, dashboard cards).
947
+ const tagTone = tag => { let sum = 7; for (const ch of tag) sum = (sum * 31 + ch.charCodeAt(0)) % 100003; return sum % 8 + 1; };
948
+ const middlePath = (value, max = 44) => value.length <= max ? value
949
+ : value.slice(0, Math.ceil((max - 1) / 2)) + '…' + value.slice(-Math.floor((max - 1) / 2));
950
+ const statusTone = status => status === 'connected' ? 'online' : status === 'error' ? 'fault'
951
+ : status === 'connecting' || status === 'reconnecting' ? 'progress' : status === 'disabled' ? 'disabled' : 'offline';
952
+ const cloneId = (id, taken) => {
953
+ for (let n = 1; ; n++) {
954
+ const suffix = n === 1 ? '-copy' : '-copy-' + n;
955
+ const candidate = id.slice(0, 32 - suffix.length) + suffix;
956
+ if (!taken.includes(candidate)) return candidate;
957
+ }
958
+ };
959
+ const playgroundInfo = schemaJson => {
960
+ try {
961
+ const parsed = JSON.parse(schemaJson);
962
+ if (parsed?.type === 'object' && parsed.properties && typeof parsed.properties === 'object' && !Array.isArray(parsed.properties)) return parsed;
963
+ } catch { /* Truncated or unreadable definitions fall back to raw JSON. */ }
964
+ return null;
965
+ };
966
+ const downloadText = (filename, text) => {
967
+ if (typeof document === 'undefined' || typeof URL?.createObjectURL !== 'function') return false;
968
+ try {
969
+ const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
970
+ const link = document.createElement('a');
971
+ link.href = url; link.download = filename; link.rel = 'noopener';
972
+ document.body.append(link); link.click(); link.remove();
973
+ URL.revokeObjectURL(url);
974
+ return true;
975
+ } catch { return false; }
976
+ };
977
+ // Built-in connection presets; credentials stay out of the source and are
978
+ // entered by the user after the editor opens.
979
+ const TEMPLATES = [
980
+ { key: 'exa', label: 'Exa', transport: 'streamable-http', url: 'https://mcp.exa.ai/mcp', hint: 'tplExa' },
981
+ { key: 'context7', label: 'Context7', transport: 'streamable-http', url: 'https://mcp.context7.com/mcp', hint: 'tplContext7' },
982
+ { key: 'github', label: 'GitHub MCP', transport: 'streamable-http', url: 'https://api.githubcopilot.com/mcp/', hint: 'tplGithub' },
983
+ { key: 'playwright', label: 'Playwright', transport: 'stdio', command: 'npx @playwright/mcp@latest', hint: 'tplPlaywright' },
984
+ { key: 'notion', label: 'Notion', transport: 'streamable-http', url: 'https://mcp.notion.com/mcp', hint: 'tplNotion' },
985
+ { key: 'fetch', label: 'Fetch', transport: 'stdio', command: 'uvx mcp-server-fetch', hint: 'tplFetch' },
986
+ ];
987
+ const blankRead = () => ({ data: null, error: null, reading: false });
988
+ const startModel = () => ({ overview: { ...blankRead(), reading: true }, view: blankRead(), schema: blankRead(),
989
+ aggregate: blankRead(), health: blankRead(), stats: blankRead(), route: null, schemaName: null, pending: null });
990
+
991
+ function makeDraft(server, config, revision, serial) {
992
+ const savedPairs = rows => (rows ?? []).map(({ name, hasValue }, index) => ({
993
+ key: 'saved-' + index, name, saved: true, hasValue: hasValue === true, keep: true, value: '',
994
+ }));
995
+ return {
996
+ mode: server ? 'edit' : 'create', baseRevision: revision, serial, conflicted: false, error: null,
997
+ beforeApproval: server?.requireApproval !== false,
998
+ draft: {
999
+ id: server?.id ?? '', name: server?.name ?? '', transport: server?.transport ?? 'streamable-http',
1000
+ url: config?.url ?? '', command: config?.command ?? '', argsText: JSON.stringify(config?.args ?? []), cwd: config?.cwd ?? '',
1001
+ enabled: server?.enabled === true, requireApproval: server?.requireApproval !== false,
1002
+ timeoutMs: String(config?.timeoutMs ?? 60000), headers: savedPairs(config?.headers), env: savedPairs(config?.env),
1003
+ },
1004
+ };
1005
+ }
1006
+
1007
+ const reserved = new Set(['constructor', 'prototype', '__proto__']);
1008
+ function saveInput(editor, servers) {
1009
+ const draft = editor.draft;
1010
+ const id = draft.id.trim();
1011
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,31}$/.test(id) || reserved.has(id)) return { error: 'invalidId' };
1012
+ if (editor.mode === 'create') {
1013
+ if (servers.some(server => server.id === id)) return { error: 'duplicateId' };
1014
+ if (servers.length >= 32) return { error: 'serverLimit' };
1015
+ }
1016
+ const { transport, enabled, requireApproval } = draft;
1017
+ if (!transports.includes(transport)) return { error: 'invalidTransport' };
1018
+ let url = '', command = '', args = [], cwd = '';
1019
+ if (transport === 'stdio') {
1020
+ command = draft.command.trim();
1021
+ if (!command || command.length > 300 || /[\r\n\0]/.test(command)) return { error: 'invalidCommand' };
1022
+ try { args = JSON.parse(draft.argsText.trim() || '[]'); } catch { return { error: 'invalidArgs' }; }
1023
+ if (!Array.isArray(args) || args.length > 64 || args.some(arg => typeof arg !== 'string' || arg.length > 2000 || arg.includes('\0'))) return { error: 'invalidArgs' };
1024
+ cwd = draft.cwd.trim();
1025
+ if (cwd && (!isPortableAbsoluteCwd(cwd) || cwd.includes('\0') || cwd.length > 1000)) return { error: 'invalidCwd' };
1026
+ } else {
1027
+ url = draft.url.trim();
1028
+ try {
1029
+ const parsed = new URL(url);
1030
+ if (url.length > 2000 || !/^https?:\/\//i.test(url) || /[\r\n\0]/.test(url)
1031
+ || parsed.username || parsed.password || parsed.hash) return { error: 'invalidUrl' };
1032
+ for (const key of parsed.searchParams.keys()) if (/key|token|secret|password|authorization/i.test(key)) return { error: 'urlCredential' };
1033
+ } catch { return { error: 'invalidUrl' }; }
1034
+ }
1035
+ const timeoutMs = Number(draft.timeoutMs);
1036
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 180000) return { error: 'invalidTimeout' };
1037
+ if ([...draft.headers, ...draft.env].some(row => !(row.saved && row.keep)
1038
+ && (row.value.length > 2000 || row.value !== row.value.trim() || /[\r\n\0]/.test(row.value)))) return { error: 'invalidPairValue' };
1039
+ function serializePairs(kind) {
1040
+ const rows = draft[kind];
1041
+ const seen = new Set();
1042
+ if (rows.length > 16) return null;
1043
+ const pairs = [];
1044
+ for (const row of rows) {
1045
+ const name = row.name.trim();
1046
+ const key = name.toLowerCase();
1047
+ const valid = kind === 'headers'
1048
+ ? /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name) && !/^(host|connection|content-length|transfer-encoding|cookie|set-cookie)$/i.test(name)
1049
+ : /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) && !/^(NODE_OPTIONS|NODE_PATH|LD_PRELOAD|LD_LIBRARY_PATH|DSH_.*)$/i.test(name);
1050
+ if (!valid || name.length > 128 || reserved.has(name) || seen.has(key)) return null;
1051
+ seen.add(key);
1052
+ pairs.push(row.saved && row.keep ? { name, keep: true } : { name, value: row.value });
1053
+ }
1054
+ return pairs;
1055
+ }
1056
+ const headers = serializePairs('headers');
1057
+ const env = serializePairs('env');
1058
+ if (!headers) return { error: 'invalidHeaders' };
1059
+ if (!env) return { error: 'invalidEnv' };
1060
+ return { input: { revision: editor.baseRevision, mode: editor.mode, server: {
1061
+ id, name: draft.name.trim() || id, transport, url, command, args, cwd, enabled, requireApproval, timeoutMs, headers, env,
1062
+ } } };
1063
+ }
1064
+
1065
+ /* src/workbench/ui-requests.js */
1066
+ // A scope is local to this Page and its API. Each read has its own serial; a
1067
+ // route change invalidates both section and schema, and reloading invalidates all reads.
1068
+ function createRequests(api, publish) {
1069
+ let state = startModel(), disposed = false, lock = null, follow = null;
1070
+ let overviewSeq = 0, viewSeq = 0, schemaSeq = 0, aggregateSeq = 0, healthSeq = 0, statsSeq = 0;
1071
+ const update = patch => { state = { ...state, ...patch }; publish(state); };
1072
+ const stopFollowing = () => { if (follow) clearTimeout(follow.timer); follow = null; };
1073
+ const validOverview = data => Number.isSafeInteger(data?.revision) && data.revision >= 0 && Array.isArray(data.servers)
1074
+ && typeof data.active === 'boolean' && typeof data.autoConnect === 'boolean';
1075
+ const rowAt = (data, id) => data?.servers.find(row => row.id === id);
1076
+ const inProgress = row => row?.refreshing || ['connecting', 'reconnecting'].includes(row?.status);
1077
+ const checkChanged = (from, to) => from?.at !== to?.at || from?.durationMs !== to?.durationMs || from?.ok !== to?.ok;
1078
+ const clearSection = (reading = false) => {
1079
+ ++viewSeq; ++schemaSeq;
1080
+ return { view: { ...blankRead(), reading }, schema: blankRead(), schemaName: null };
1081
+ };
1082
+ const hasServer = () => state.route && state.overview.data?.servers.some(row => row.id === state.route.id);
1083
+ async function readView() {
1084
+ if (disposed || !hasServer() || state.overview.reading || state.overview.error) return;
1085
+ const { id, section } = state.route;
1086
+ const { revision } = state.overview.data;
1087
+ if (section === 'logs') {
1088
+ const wireSection = 'connection';
1089
+ update(clearSection(true));
1090
+ const ticket = viewSeq;
1091
+ try {
1092
+ const data = await api.call('getServer', { id, section: wireSection });
1093
+ if (disposed || ticket !== viewSeq) return;
1094
+ if (data?.server?.id !== id || data.section !== wireSection || !data.detail) {
1095
+ update({ view: { ...blankRead(), error: 'detailFailed' } });
1096
+ } else if (data.revision !== revision) {
1097
+ update({ view: { ...blankRead(), error: 'detailStale' } });
1098
+ } else update({ view: { ...blankRead(), data: { ...data, section } } });
1099
+ } catch (error) {
1100
+ if (!disposed && ticket === viewSeq) update({ view: { ...blankRead(), error: rpcErrorKey(error, 'detailFailed') } });
1101
+ }
1102
+ return;
1103
+ }
1104
+ const wireSection = section === 'resources' || section === 'prompts' ? 'connection' : section;
1105
+ update(clearSection(true));
1106
+ const ticket = viewSeq;
1107
+ try {
1108
+ const data = await api.call('getServer', { id, section: wireSection });
1109
+ if (disposed || ticket !== viewSeq) return;
1110
+ if (data?.server?.id !== id || data.section !== wireSection || !data.detail) {
1111
+ update({ view: { ...blankRead(), error: 'detailFailed' } });
1112
+ } else if (data.revision !== revision) {
1113
+ update({ view: { ...blankRead(), error: 'detailStale' } });
1114
+ } else update({ view: { ...blankRead(), data: { ...data, section } } });
1115
+ } catch (error) {
1116
+ if (!disposed && ticket === viewSeq) update({ view: { ...blankRead(), error: rpcErrorKey(error, 'detailFailed') } });
1117
+ }
1118
+ }
1119
+ async function readOverview(owner = null) {
1120
+ if (disposed || owner !== lock) return;
1121
+ stopFollowing();
1122
+ const ticket = ++overviewSeq;
1123
+ update({ overview: { ...state.overview, reading: true, error: null }, ...clearSection(!!state.route) });
1124
+ try {
1125
+ const data = await api.call('overview');
1126
+ if (disposed || ticket !== overviewSeq) return;
1127
+ if (!validOverview(data)) throw new Error('Invalid overview');
1128
+ if (state.overview.data && data.revision < state.overview.data.revision) {
1129
+ update({ overview: { ...state.overview, reading: false, error: 'detailStale' }, ...clearSection() });
1130
+ return;
1131
+ }
1132
+ update({ overview: { ...blankRead(), data } });
1133
+ void readAggregate();
1134
+ void readHealth();
1135
+ void readStats();
1136
+ if (hasServer()) void readView();
1137
+ else if (state.view.reading) update(clearSection());
1138
+ } catch (error) {
1139
+ if (!disposed && ticket === overviewSeq) {
1140
+ update({ overview: { ...state.overview, reading: false, error: rpcErrorKey(error, 'unavailable') }, ...clearSection() });
1141
+ }
1142
+ }
1143
+ }
1144
+ // One fleet-wide dashboard read per overview cycle. A failing or not-ready
1145
+ // aggregate only hides the dashboard; it never blocks the directory.
1146
+ async function readAggregate() {
1147
+ if (disposed) return;
1148
+ const ticket = ++aggregateSeq;
1149
+ update({ aggregate: { ...state.aggregate, reading: true, error: null } });
1150
+ try {
1151
+ const reply = await api.call('aggregate');
1152
+ if (disposed || ticket !== aggregateSeq) return;
1153
+ if (reply?.runtimeReady !== true || typeof reply.generatedAt !== 'number'
1154
+ || !Array.isArray(reply.servers) || !Array.isArray(reply.byTool) || !Array.isArray(reply.conflicts)) throw new Error('Invalid aggregate');
1155
+ update({ aggregate: { ...blankRead(), data: reply } });
1156
+ } catch {
1157
+ if (!disposed && ticket === aggregateSeq) update({ aggregate: { ...blankRead(), error: 'unavailable' } });
1158
+ }
1159
+ }
1160
+ async function readHealth() {
1161
+ if (disposed) return;
1162
+ const ticket = ++healthSeq;
1163
+ update({ health: { ...state.health, reading: true, error: null } });
1164
+ try {
1165
+ const reply = await api.call('healthStatus');
1166
+ if (disposed || ticket !== healthSeq) return;
1167
+ if (typeof reply?.enabled !== 'boolean' || !Array.isArray(reply.log) || !Array.isArray(reply.servers)
1168
+ || !Number.isSafeInteger(reply.intervalMinutes)) throw new Error('Invalid health status');
1169
+ update({ health: { ...blankRead(), data: reply } });
1170
+ } catch {
1171
+ if (!disposed && ticket === healthSeq) update({ health: { ...blankRead(), error: 'unavailable' } });
1172
+ }
1173
+ }
1174
+ // Fleet trend read; a failure hides the trend card without touching the rest.
1175
+ async function readStats() {
1176
+ if (disposed) return;
1177
+ const ticket = ++statsSeq;
1178
+ update({ stats: { ...state.stats, reading: true, error: null } });
1179
+ try {
1180
+ const reply = await api.call('statsOverview', { days: 14 });
1181
+ if (disposed || ticket !== statsSeq) return;
1182
+ if (!reply || !Array.isArray(reply.days) || !Array.isArray(reply.top) || !Array.isArray(reply.slow)
1183
+ || !reply.totals || typeof reply.failureRate !== 'number') throw new Error('Invalid stats');
1184
+ update({ stats: { ...blankRead(), data: reply } });
1185
+ } catch {
1186
+ if (!disposed && ticket === statsSeq) update({ stats: { ...blankRead(), error: 'unavailable' } });
1187
+ }
1188
+ }
1189
+ function move(id, section = 'connection') {
1190
+ if (disposed || (state.route?.id === id && state.route?.section === section) || (!id && !state.route)) return;
1191
+ if (state.route?.id !== id) stopFollowing();
1192
+ const route = id ? { id, section } : null;
1193
+ update({ route, ...clearSection(!!route && !state.overview.error) });
1194
+ if (route) void readView();
1195
+ }
1196
+ // An accepted connect/refresh is scheduled asynchronously by the host. Read a
1197
+ // handful of times, without replacing the current panel just to show loading.
1198
+ // Manual reads, another mutation, leaving the server, editing, and teardown
1199
+ // cancel both the timer and permission for any pending reply to publish.
1200
+ function followStatus(id, before) {
1201
+ if (disposed || lock !== null || state.route?.id !== id || state.overview.error) return;
1202
+ let current = rowAt(state.overview.data, id);
1203
+ const delays = [900, 1700, 3300, 6500, 12000];
1204
+ let observedPending = inProgress(current);
1205
+ const settled = row => !row?.enabled || (!inProgress(row) && (observedPending
1206
+ || before?.status !== row.status || checkChanged(before?.lastCheck, row.lastCheck)));
1207
+ const enabled = data => data?.active && data.autoConnect;
1208
+ if (!enabled(state.overview.data) || settled(current)) return;
1209
+ const key = { timer: null };
1210
+ follow = key;
1211
+ let attempt = 0;
1212
+ const live = () => follow === key && !disposed && lock === null && state.route?.id === id && !state.overview.reading;
1213
+ const schedule = () => {
1214
+ if (!live()) return;
1215
+ if (attempt >= delays.length) { stopFollowing(); return; }
1216
+ key.timer = setTimeout(async () => {
1217
+ if (!live()) return;
1218
+ try {
1219
+ const data = await api.call('overview');
1220
+ if (!live()) return;
1221
+ const previous = state.overview.data;
1222
+ if (validOverview(data) && data.revision >= previous.revision) {
1223
+ current = rowAt(data, id);
1224
+ const last = rowAt(previous, id);
1225
+ const changed = last?.status !== current?.status || last?.refreshing !== current?.refreshing
1226
+ || checkChanged(last?.lastCheck, current?.lastCheck) || last?.error?.code !== current?.error?.code
1227
+ || last?.error?.message !== current?.error?.message;
1228
+ const refreshPane = previous.revision !== data.revision || (changed && state.route.section !== 'config');
1229
+ update({ overview: { ...blankRead(), data } });
1230
+ if (refreshPane) {
1231
+ if (hasServer()) void readView();
1232
+ else update(clearSection());
1233
+ }
1234
+ observedPending ||= inProgress(current);
1235
+ if (!enabled(data) || settled(current)) { stopFollowing(); return; }
1236
+ }
1237
+ } catch { /* A read failure never replays the accepted operation. */ }
1238
+ schedule();
1239
+ }, delays[attempt++]);
1240
+ };
1241
+ schedule();
1242
+ }
1243
+ const ready = (overview, section) => !disposed && lock === null && !state.overview.reading && !state.overview.error
1244
+ && !!overview && state.overview.data === overview && (section === undefined || state.view.data === section);
1245
+ async function run(overview, section, method, input, settle) {
1246
+ if (!ready(overview, section)) return false;
1247
+ stopFollowing();
1248
+ const owner = lock = {};
1249
+ update({ pending: method });
1250
+ let outcome;
1251
+ try { outcome = { ok: true, data: await api.call(method, input) }; }
1252
+ catch (error) { outcome = { ok: false, error }; }
1253
+ if (disposed) return false;
1254
+ try { settle(outcome); }
1255
+ finally {
1256
+ await readOverview(owner);
1257
+ if (!disposed) {
1258
+ lock = null; update({ pending: null });
1259
+ if (outcome.ok && (method === 'connect' || method === 'refresh')) followStatus(input.id, section?.server ?? rowAt(overview, input.id));
1260
+ }
1261
+ }
1262
+ return outcome.ok;
1263
+ }
1264
+ async function toggleSchema(overview, section, tool) {
1265
+ if (!stamped(tool) || !ready(overview, section) || state.route?.section !== 'tools' || !section?.detail.rows.includes(tool)) return;
1266
+ const { name, stamp } = tool;
1267
+ const ticket = ++schemaSeq;
1268
+ if (state.schemaName === name) { update({ schemaName: null, schema: blankRead() }); return; }
1269
+ const { id } = state.route;
1270
+ update({ schemaName: name, schema: { ...blankRead(), reading: true } });
1271
+ try {
1272
+ const data = await api.call('getToolSchema', { id, name, stamp });
1273
+ if (disposed || ticket !== schemaSeq) return;
1274
+ if (data?.name !== name || typeof data.schemaJson !== 'string') throw new Error('Invalid schema preview');
1275
+ update({ schema: { ...blankRead(), data } });
1276
+ } catch (error) {
1277
+ if (!disposed && ticket === schemaSeq) update({ schema: { ...blankRead(), error: rpcErrorKey(error, 'schemaFailed') } });
1278
+ }
1279
+ }
1280
+ return { move, readOverview, readView, ready, run, toggleSchema, stopFollowing,
1281
+ dispose() { disposed = true; stopFollowing(); ++overviewSeq; ++viewSeq; ++schemaSeq; } };
1282
+ }
1283
+
1284
+ /* src/workbench/ui-directory.js */
1285
+
1286
+ function createDirectoryUi(React) {
1287
+ const h = React.createElement;
1288
+ const { useEffect, useId, useRef, useState } = React;
1289
+
1290
+ function Icon({ name }) {
1291
+ const paths = {
1292
+ panel: 'M4.2 4.5h15.6a1.7 1.7 0 0 1 1.7 1.7v11.6a1.7 1.7 0 0 1-1.7 1.7H4.2a1.7 1.7 0 0 1-1.7-1.7V6.2a1.7 1.7 0 0 1 1.7-1.7ZM9 4.5v15m3.5-10h5m-5 5h5m-11.7-5h.2m-.2 5h.2',
1293
+ reload: 'M20 5v5h-5M4 19v-5h5m-4.3-4A7.5 7.5 0 0 1 17 6l3 4M4 14l3 4a7.5 7.5 0 0 0 12.3-4',
1294
+ add: 'M12 5v14M5 12h14', back: 'm14 6-6 6 6 6M8 12h11',
1295
+ };
1296
+ return h('svg', { viewBox: '0 0 24 24', width: name === 'panel' ? 21 : 16, height: name === 'panel' ? 21 : 16,
1297
+ 'aria-hidden': true, focusable: false, fill: 'none', stroke: 'currentColor', strokeWidth: 1.65,
1298
+ strokeLinecap: 'round', strokeLinejoin: 'round' }, h('path', { d: paths[name] }));
1299
+ }
1300
+ function PanelIcon() { return h(Icon, { name: 'panel' }); }
1301
+ function Button({ children, kind, icon, className, ...props }) {
1302
+ return h('button', { type: 'button', ...props, className: 'mwb-button' + (className ? ' ' + className : ''), 'data-kind': kind },
1303
+ icon && h(Icon, { name: icon }), children);
1304
+ }
1305
+ function Notice({ children, tone, alert = false }) {
1306
+ return h('div', { className: 'mwb-notice', 'data-tone': tone, role: alert ? 'alert' : 'status' }, children);
1307
+ }
1308
+ function Field({ label, hint, wide, children }) {
1309
+ const id = useId();
1310
+ return h('div', { className: 'mwb-field' + (wide ? ' mwb-wide' : '') }, h('label', { htmlFor: id }, label),
1311
+ React.cloneElement(children, { id, 'aria-describedby': hint ? id + '-help' : undefined }),
1312
+ hint && h('span', { id: id + '-help', className: 'mwb-hint' }, hint));
1313
+ }
1314
+ function Badge({ tone, children }) {
1315
+ return h('span', { className: 'mwb-badge', 'data-tone': tone }, h('i', { className: 'mwb-dot', 'data-tone': tone, 'aria-hidden': true }), children);
1316
+ }
1317
+ function Skeleton({ rows = 5 }) {
1318
+ return h('div', { className: 'mwb-skeleton', 'aria-busy': true }, Array.from({ length: rows }, (_, index) =>
1319
+ h('div', { className: 'mwb-skeleton-row', key: index },
1320
+ h('span', { className: 'mwb-skeleton-bar', 'aria-hidden': true }),
1321
+ h('span', { className: 'mwb-skeleton-bar', 'aria-hidden': true }))));
1322
+ }
1323
+ function StatusBar({ t, data, aggregate, locked, refreshed }) {
1324
+ const configPath = aggregate?.data?.configPath;
1325
+ return h('div', { className: 'mwb-statusbar' },
1326
+ data && h('span', { className: 'mwb-status-item' },
1327
+ h('i', { className: 'mwb-dot', 'data-tone': data.active ? 'online' : undefined, 'aria-hidden': true }),
1328
+ t(data.active ? 'statusEngineOn' : 'statusEngineOff')),
1329
+ refreshed && h('span', { className: 'mwb-status-item' }, refreshed),
1330
+ h('span', { className: 'mwb-status-item' }, t(locked ? 'lockBusy' : 'lockFree')),
1331
+ typeof configPath === 'string' && configPath && h('code', { className: 'mwb-status-path', title: configPath }, middlePath(configPath)),
1332
+ h('span', { className: 'mwb-status-item mwb-num' }, VERSION));
1333
+ }
1334
+ function Status({ t, server }) {
1335
+ const tone = groupOf(server), status = statusOf(server);
1336
+ return h(Badge, { tone }, t('status.' + (tone === 'fault' && status === 'connected' ? 'degraded' : status)));
1337
+ }
1338
+ function Clock({ at, t, short = false, rel = false }) {
1339
+ const date = at == null ? null : new Date(at);
1340
+ if (!date || !Number.isFinite(date.getTime())) return h('span', { className: 'mwb-hint' }, t('never'));
1341
+ const lang = localeOf(t);
1342
+ const full = date.toLocaleString(lang, { dateStyle: 'medium', timeStyle: 'short' });
1343
+ return h('time', { className: 'mwb-num', dateTime: date.toISOString(), title: full }, rel ? relative(t, at)
1344
+ : short ? date.toLocaleString(lang, { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : full);
1345
+ }
1346
+ function Confirm({ t, type, subject, disabled, stale, changedTool, onAccept, onCancel }) {
1347
+ const id = useId(), cancel = useRef(null);
1348
+ useEffect(() => { cancel.current?.focus(); }, []);
1349
+ const copy = type === 'remove' ? ['confirmRemove', 'removeHint']
1350
+ : type === 'tool' ? ['confirmApproval', 'approvalHint']
1351
+ : type === 'review' ? ['confirmReview', 'reviewHint']
1352
+ : type === 'invoke' ? ['confirmInvoke', 'invokeHint']
1353
+ : type === 'export' ? ['confirmExport', 'exportHint']
1354
+ : type === 'import' ? ['confirmImport', 'importReplaceHint']
1355
+ : ['confirmServerApproval', 'serverApprovalHint'];
1356
+ return h('div', { className: 'mwb-confirm', role: 'group', 'aria-labelledby': id, onKeyDown: event => {
1357
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onCancel(); }
1358
+ } }, h('strong', { id }, t(copy[0])), subject && h('p', null, subject),
1359
+ h('p', { className: 'mwb-hint' }, t(changedTool ? 'toolChanged' : stale ? 'conflict' : copy[1])),
1360
+ h('div', { className: 'mwb-actions' }, h(Button, { ref: cancel, onClick: onCancel }, t('cancel')),
1361
+ h(Button, { kind: type === 'remove' ? 'danger' : 'primary', disabled: disabled || stale, onClick: onAccept },
1362
+ t(type === 'remove' ? 'confirmDelete' : 'confirm'))));
1363
+ }
1364
+ function Switch({ label, checked, name, disabled, onChange }) {
1365
+ return h('button', { type: 'button', className: 'mwb-switch', role: 'switch', 'aria-label': label + ': ' + name,
1366
+ 'aria-checked': checked, disabled, onClick: event => onChange(!checked, event) },
1367
+ h('span', { className: 'mwb-track', 'aria-hidden': true }), label);
1368
+ }
1369
+ function Distribution({ t, servers, group, setGroup }) {
1370
+ const counts = { all: servers.length, online: 0, fault: 0, progress: 0, offline: 0, disabled: 0 };
1371
+ for (const server of servers) counts[groupOf(server)]++;
1372
+ // A compact, evenly sized filter row. Width no longer encodes the counts;
1373
+ // the numbers do, and an empty group stays readable instead of collapsing.
1374
+ return h('div', { className: 'mwb-distribution', role: 'group', 'aria-label': t('distribution') }, groups.map(item =>
1375
+ h('button', { type: 'button', className: 'mwb-segment', key: item, 'aria-pressed': group === item, 'data-group': item,
1376
+ 'data-zero': counts[item] === 0 || undefined,
1377
+ title: t('group.' + item) + ': ' + number(t, counts[item]),
1378
+ 'aria-label': t('group.' + item) + ': ' + number(t, counts[item]),
1379
+ onClick: () => setGroup(item) }, item !== 'all' && h('i', { className: 'mwb-dot', 'data-tone': item, 'aria-hidden': true }),
1380
+ h('span', { className: 'mwb-seg-label' }, t('group.' + item)), h('span', { className: 'mwb-num' }, number(t, counts[item])))));
1381
+ }
1382
+ function Chip({ tag, active, onTag }) {
1383
+ return h('button', { type: 'button', className: 'mwb-chip', 'aria-pressed': active,
1384
+ style: { '--cat': 'var(--wb-cat-' + tagTone(tag) + ')' },
1385
+ onClick: event => { event.stopPropagation(); onTag(tag); } }, tag);
1386
+ }
1387
+ function Metrics({ t, data, aggregate }) {
1388
+ const tally = { online: 0, fault: 0, progress: 0, offline: 0, disabled: 0 };
1389
+ for (const server of data.servers) tally[groupOf(server)]++;
1390
+ const sum = (rows, pick) => rows.reduce((total, row) => total + (pick(row) ?? 0), 0);
1391
+ const fleet = aggregate.servers ?? [];
1392
+ const bricks = [
1393
+ ['servers', data.servers.length, 'metricServers', 'var(--wb-blue)'],
1394
+ ['online', tally.online, 'group.online', 'var(--wb-good)'],
1395
+ ['fault', tally.fault, 'group.fault', tally.fault ? 'var(--wb-bad-mark)' : 'var(--wb-idle)'],
1396
+ ['tools', sum(data.servers, server => server.counts?.enabledTools), 'enabledTools', 'var(--wb-cat-5)'],
1397
+ ['calls', sum(fleet, row => row.calls), 'calls', 'var(--wb-cat-6)'],
1398
+ ['failures', sum(fleet, row => row.failures), 'failures', sum(fleet, row => row.failures) ? 'var(--wb-bad-mark)' : 'var(--wb-idle)'],
1399
+ ];
1400
+ return h('div', { className: 'mwb-metrics' }, bricks.map(([key, value, label, tone]) =>
1401
+ h('div', { className: 'mwb-brick', key, 'data-metric': key, style: { '--cat': tone } },
1402
+ h('div', { className: 'mwb-brick-value' }, h('i', { className: 'mwb-dot', 'aria-hidden': true }),
1403
+ h('strong', { className: 'mwb-num' }, number(t, value))),
1404
+ h('span', { className: 'mwb-hint' }, t(label)))));
1405
+ }
1406
+ function Ranking({ t, aggregate }) {
1407
+ const reported = aggregate.byTool ?? [];
1408
+ const rows = reported.slice(0, 8);
1409
+ const max = rows.reduce((max, row) => Math.max(max, row.calls), 1);
1410
+ const more = reported.length - rows.length;
1411
+ return h('div', { className: 'mwb-card mwb-rank-card' },
1412
+ h('h3', { className: 'mwb-subhead' }, t('rankTitle')),
1413
+ rows.length ? h('ol', { className: 'mwb-rank', role: 'list' }, rows.map((row, index) =>
1414
+ h('li', { key: row.tool, style: { '--cat': 'var(--wb-cat-' + (index % 8 + 1) + ')' } },
1415
+ h('div', { className: 'mwb-rank-row' }, h('i', { className: 'mwb-dot', 'aria-hidden': true }),
1416
+ h('code', { className: 'mwb-tech mwb-tool-name' }, row.tool),
1417
+ h('span', { className: 'mwb-num' }, '× ' + number(t, row.calls)),
1418
+ h(Clock, { at: row.lastAt, t, rel: true })),
1419
+ h('i', { className: 'mwb-rank-bar', 'aria-hidden': true,
1420
+ style: { inlineSize: Math.max(2, Math.round(row.calls / max * 100)) + '%' } }))))
1421
+ : h('p', { className: 'mwb-hint' }, t('activityEmpty')),
1422
+ more > 0 && h('p', { className: 'mwb-hint' }, t('rankMore').replace('{n}', number(t, more))));
1423
+ }
1424
+ function Conflicts({ t, aggregate }) {
1425
+ const rows = aggregate.conflicts ?? [];
1426
+ if (!rows.length) return null;
1427
+ return h('div', { className: 'mwb-card mwb-conflicts' },
1428
+ h('h3', { className: 'mwb-subhead' }, t('conflictTitle')),
1429
+ h('p', { className: 'mwb-hint' }, t('conflictHint')),
1430
+ h('ul', { className: 'mwb-conflict-list', role: 'list' }, rows.map(row => h('li', { key: row.tool },
1431
+ h('code', { className: 'mwb-tech' }, row.tool), h('span', { className: 'mwb-hint' }, row.servers.join(', '))))));
1432
+ }
1433
+ function Playground({ t, pg, reading, info, onField, onRaw, onRun, onAccept, onCancel }) {
1434
+ return h('div', { className: 'mwb-playground' },
1435
+ h('p', { className: 'mwb-hint' }, t('playgroundHint')),
1436
+ reading ? h('p', { className: 'mwb-hint', role: 'status' }, t('schemaLoading'))
1437
+ : info ? h('div', { className: 'mwb-play-fields' }, Object.entries(info.properties).map(([key, spec]) => {
1438
+ const type = spec?.type;
1439
+ const wide = type === 'object' || type === 'array';
1440
+ return h(Field, { key, label: key, hint: type ? String(type) : null, wide },
1441
+ type === 'boolean' ? h('select', { value: String(pg.fields[key] ?? ''), onChange: event => onField(key, event.target.value) },
1442
+ ['', 'true', 'false'].map(option => h('option', { key: option || 'unset', value: option }, option === '' ? t('argUnset') : option)))
1443
+ : wide ? h('textarea', { className: 'mwb-tech', rows: 2, value: String(pg.fields[key] ?? ''),
1444
+ placeholder: t('argJsonHint'), spellCheck: false, onChange: event => onField(key, event.target.value) })
1445
+ : h('input', { type: type === 'number' ? 'number' : 'text', value: String(pg.fields[key] ?? ''), spellCheck: false,
1446
+ onChange: event => onField(key, event.target.value) }));
1447
+ }))
1448
+ : h('div', { className: 'mwb-play-fields' },
1449
+ h('p', { className: 'mwb-hint' }, t('playgroundRaw')),
1450
+ h(Field, { label: 'JSON', wide: true }, h('textarea', { className: 'mwb-tech', rows: 3, value: pg.raw,
1451
+ spellCheck: false, onChange: event => onRaw(event.target.value) }))),
1452
+ pg.phase === 'confirm' ? h(Confirm, { t, type: 'invoke', onAccept: onAccept, onCancel: onCancel })
1453
+ : h('div', { className: 'mwb-actions' },
1454
+ h(Button, { kind: 'primary', disabled: pg.phase === 'running', onClick: onRun }, t(pg.phase === 'running' ? 'invoking' : 'playgroundRun'))),
1455
+ pg.error && h(Notice, { tone: 'error', alert: true }, t(pg.error)),
1456
+ pg.phase === 'result' && pg.result && h('div', { className: 'mwb-play-result', role: 'status' },
1457
+ h('div', { className: 'mwb-play-meta' },
1458
+ h(Badge, { tone: pg.result.isError ? 'fault' : 'online' }, t(pg.result.isError ? 'notOk' : 'ok')),
1459
+ pg.result.code && h('code', { className: 'mwb-hint mwb-tech' }, pg.result.code),
1460
+ h('span', { className: 'mwb-num' }, duration(t, pg.result.durationMs))),
1461
+ pg.result.structured && h('span', { className: 'mwb-hint' }, t('structuredResult')),
1462
+ h('pre', null, pg.result.text),
1463
+ pg.result.truncated && h('p', { className: 'mwb-hint' }, t('resultTruncated'))));
1464
+ }
1465
+ function IoPanel({ t, io, busy, onText, onFile, onMode, onExport, onExportFull, onImport, onAcceptExport, onAcceptImport, onCancel, onCopy }) {
1466
+ return h('div', { className: 'mwb-io' },
1467
+ io.phase === 'confirm-export' ? h(Confirm, { t, type: 'export', onAccept: onAcceptExport, onCancel: onCancel })
1468
+ : io.phase === 'confirm-import' ? h(Confirm, { t, type: 'import', onAccept: onAcceptImport, onCancel: onCancel })
1469
+ : h(React.Fragment, null,
1470
+ h('div', { className: 'mwb-io-row' },
1471
+ h('div', { className: 'mwb-actions' },
1472
+ h(Button, { disabled: busy, onClick: onExport }, t('exportRedacted')),
1473
+ h(Button, { disabled: busy, onClick: onExportFull }, t('exportFull')))),
1474
+ io.error && h(Notice, { tone: 'error', alert: true }, t(io.error)),
1475
+ io.result && h('div', { className: 'mwb-io-result', role: 'status' },
1476
+ h('code', { className: 'mwb-tech' }, io.result.filename),
1477
+ h('span', { className: 'mwb-hint' }, t(io.result.redacted ? 'exportRedacted' : 'exportFull')),
1478
+ h(Button, { kind: 'quiet', onClick: onCopy }, t(io.copied ? 'copied' : 'copyButton'))),
1479
+ h(Field, { label: t('importFile'), hint: t('importFileHint'), wide: true }, h('input', { type: 'file',
1480
+ accept: '.json,application/json', disabled: busy, onChange: event => {
1481
+ const file = event.target.files?.[0];
1482
+ if (file) onFile(file);
1483
+ event.target.value = '';
1484
+ } })),
1485
+ (io.fileReading || io.filename) && h('p', { className: 'mwb-hint', role: 'status' },
1486
+ io.fileReading ? t('importFileReading') : io.filename),
1487
+ h(Field, { label: t('importField'), wide: true }, h('textarea', { className: 'mwb-tech', rows: 4, value: io.filename ? '' : io.text,
1488
+ maxLength: 160000, spellCheck: false, onChange: event => onText(event.target.value) })),
1489
+ h('div', { className: 'mwb-io-modes', role: 'radiogroup', 'aria-label': t('io') },
1490
+ h('label', { className: 'mwb-check-field' }, h('input', { type: 'radio', name: 'mwb-import-mode',
1491
+ checked: io.mode === 'merge', onChange: () => onMode('merge') }), t('importMerge')),
1492
+ h('label', { className: 'mwb-check-field' }, h('input', { type: 'radio', name: 'mwb-import-mode',
1493
+ checked: io.mode === 'replace', onChange: () => onMode('replace') }), t('importReplace'))),
1494
+ io.importResult && h('div', { className: 'mwb-io-result', role: 'status' },
1495
+ h('span', { className: 'mwb-num' }, t('importAdded').replace('{n}', number(t, io.importResult.added))),
1496
+ h('span', { className: 'mwb-num' }, t('importUpdated').replace('{n}', number(t, io.importResult.updated))),
1497
+ io.importResult.replaced && h('span', { className: 'mwb-hint' }, t('importReplaced'))),
1498
+ h('div', { className: 'mwb-actions' },
1499
+ h(Button, { kind: 'primary', disabled: busy || io.fileReading || !io.text.trim(), onClick: onImport }, t('importRun')))));
1500
+ }
1501
+ function HealthCard({ t, health, busy, onConfig }) {
1502
+ const data = health?.data;
1503
+ if (!data) return null;
1504
+ return h('div', { className: 'mwb-card mwb-health' },
1505
+ h('div', { className: 'mwb-health-head' },
1506
+ h('h3', { className: 'mwb-subhead' }, t('healthTitle')),
1507
+ h(Switch, { label: t('healthTitle'), name: '', checked: data.enabled, disabled: busy,
1508
+ onChange: enabled => onConfig({ enabled, intervalMinutes: data.intervalMinutes, autoDisableAfterFaults: data.autoDisableAfterFaults }) })),
1509
+ data.enabled ? h(React.Fragment, null,
1510
+ h('div', { className: 'mwb-health-settings' },
1511
+ h(Field, { label: t('healthInterval') }, h('input', { type: 'number', min: 1, max: 360, step: 1,
1512
+ value: String(data.intervalMinutes), disabled: busy, onChange: event => {
1513
+ const value = Number(event.target.value);
1514
+ if (Number.isSafeInteger(value) && value >= 1 && value <= 360) onConfig({ enabled: true, intervalMinutes: value, autoDisableAfterFaults: data.autoDisableAfterFaults });
1515
+ } })),
1516
+ h(Field, { label: t('healthAutoDisable') }, h('input', { type: 'number', min: 0, max: 10, step: 1,
1517
+ value: String(data.autoDisableAfterFaults), disabled: busy, onChange: event => {
1518
+ const value = Number(event.target.value);
1519
+ if (Number.isSafeInteger(value) && value >= 0 && value <= 10) onConfig({ enabled: true, intervalMinutes: data.intervalMinutes, autoDisableAfterFaults: value });
1520
+ } }))),
1521
+ h('p', { className: 'mwb-hint' }, t('healthLog')),
1522
+ data.log.length ? h('ol', { className: 'mwb-health-log', role: 'list' }, data.log.map((row, index) => h('li', { key: row.at + ':' + index },
1523
+ h('i', { className: 'mwb-dot', 'data-tone': row.kind === 'fault' ? 'fault' : row.kind === 'recovered' ? 'online' : row.kind === 'auto-disabled' ? 'progress' : undefined, 'aria-hidden': true }),
1524
+ h('span', null, ['fault', 'recovered', 'auto-disabled'].includes(row.kind) ? t('healthKind.' + row.kind) : row.kind),
1525
+ h(Clock, { at: row.at, t, rel: true }),
1526
+ h('code', { className: 'mwb-hint mwb-tech' }, row.serverId),
1527
+ row.code && h('span', { className: 'mwb-hint mwb-tech' }, row.code))))
1528
+ : h('p', { className: 'mwb-hint' }, t('healthEmpty')),
1529
+ data.servers.length ? h('ul', { className: 'mwb-health-servers', role: 'list' }, data.servers.map(row => h('li', { key: row.id },
1530
+ h('code', { className: 'mwb-tech' }, row.id),
1531
+ h('span', { className: 'mwb-hint mwb-num' }, t('healthFaults').replace('{n}', number(t, row.faults)))))) : null,
1532
+ ) : h('div', { className: 'mwb-health-off' },
1533
+ h('p', { className: 'mwb-muted' }, t('healthOff')),
1534
+ h(Button, { kind: 'primary', disabled: busy, onClick: () => onConfig({ enabled: true, intervalMinutes: data.intervalMinutes, autoDisableAfterFaults: data.autoDisableAfterFaults }) }, t('healthEnable'))));
1535
+ }
1536
+ function TagEditor({ t, server, locked, busy, onSave }) {
1537
+ const initial = (server.tags ?? []).join(', ');
1538
+ const [text, setText] = useState(initial);
1539
+ const [error, setError] = useState(null);
1540
+ const tags = text.split(',').map(item => item.trim()).filter(Boolean);
1541
+ const save = () => {
1542
+ if (tags.length > 8 || tags.some(tag => tag.length > 24)) { setError('tagsInvalid'); return; }
1543
+ setError(null);
1544
+ onSave(tags);
1545
+ };
1546
+ return h('div', { className: 'mwb-tag-editor' },
1547
+ h(Field, { label: t('tags'), hint: t('tagsField') }, h('input', { value: text, maxLength: 220, spellCheck: false,
1548
+ disabled: locked || busy, onChange: event => { setText(event.target.value); setError(null); } })),
1549
+ error && h(Notice, { tone: 'error', alert: true }, t(error)),
1550
+ h('div', { className: 'mwb-actions' }, h(Button, { kind: 'quiet', disabled: locked || busy || text === initial, onClick: save }, t('tagsSave'))));
1551
+ }
1552
+ // The overview is the no-selection canvas: one flat KPI strip, then a bento
1553
+ function StatsCard({ t, stats }) {
1554
+ const data = stats.data;
1555
+ const max = Math.max(1, ...(data?.days ?? []).map(day => day.calls + day.failures));
1556
+ const totals = data?.totals ?? { calls: 0, failures: 0 };
1557
+ const rate = Math.round((data?.failureRate ?? 0) * 1000) / 10;
1558
+ const trend = data && data.days.length > 0 && h('div', { className: 'mwb-chart', role: 'img',
1559
+ 'aria-label': `${t('statsCalls')}: ${number(t, totals.calls)} · ${t('statsFailRate')}: ${rate}%` },
1560
+ data.days.map(day => h('div', { className: 'mwb-chart-col', key: day.date,
1561
+ title: `${day.date} · ${t('statsCalls')} ${day.calls} · ${t('statsFailures')} ${day.failures}` },
1562
+ h('span', { className: 'mwb-chart-bar', style: { blockSize: Math.max(2, Math.round(day.calls / max * 100)) + '%' } }),
1563
+ day.failures ? h('span', { className: 'mwb-chart-bar mwb-chart-fail',
1564
+ style: { blockSize: Math.max(2, Math.round(day.failures / max * 100)) + '%' } }) : null,
1565
+ h('span', { className: 'mwb-chart-day mwb-hint' }, day.date.slice(5)))));
1566
+ const slow = (data?.slow ?? []).slice(0, 3).map((row, index) => h('li', { key: row.at + ':' + index },
1567
+ h('span', { className: 'mwb-tech' }, row.tool), h('span', { className: 'mwb-hint mwb-num' }, duration(t, row.durationMs))));
1568
+ const top = (data?.top ?? []).slice(0, 5).map(row => h('li', { key: row.tool },
1569
+ h('span', { className: 'mwb-tech' }, row.tool), h('span', { className: 'mwb-hint mwb-num' }, number(t, row.calls))));
1570
+ return h('section', { className: 'mwb-card mwb-stats-card', 'aria-label': t('statsTitle') },
1571
+ h('h3', { className: 'mwb-subhead' }, t('statsTitle')),
1572
+ stats.error || !data || data.days.length === 0 ? h('p', { className: 'mwb-hint' }, t('statsNoData'))
1573
+ : h(React.Fragment, null, h('p', { className: 'mwb-hint' }, t('statsHint')), trend,
1574
+ h('p', { className: 'mwb-meta-line mwb-num' }, `${t('statsCalls')}: ${number(t, totals.calls)} · ${t('statsFailRate')}: ${rate}%`),
1575
+ slow.length > 0 && h('div', { className: 'mwb-stats-slow' }, h('h4', { className: 'mwb-hint' }, t('statsSlow')),
1576
+ h('ul', { role: 'list' }, slow)),
1577
+ top.length > 0 && h('div', { className: 'mwb-stats-top' }, h('h4', { className: 'mwb-hint' }, t('statsTop')),
1578
+ h('ul', { role: 'list' }, top))));
1579
+ }
1580
+ // with the trend given the wide slot. The server list on the left already
1581
+ // shows every server, so the canvas never repeats it as a card wall.
1582
+ function Dashboard({ t, data, aggregate, health, healthBusy, onHealth, stats }) {
1583
+ return h('section', { className: 'mwb-dashboard', 'aria-label': t('dashTitle') },
1584
+ h(Metrics, { t, data, aggregate }),
1585
+ h('div', { className: 'mwb-bento' },
1586
+ h(StatsCard, { t, stats }),
1587
+ h(Ranking, { t, aggregate }),
1588
+ h(HealthCard, { t, health, busy: healthBusy, onConfig: onHealth }),
1589
+ h(Conflicts, { t, aggregate })));
1590
+ }
1591
+ const BEATS = 12;
1592
+ // Heartbeat: the newest persisted tool-call outcomes of one server, oldest
1593
+ // first, right-aligned inside a fixed twelve-slot strip so every row in the
1594
+ // list shares the same rhythm. Slots are outcome-only; nothing else is shown.
1595
+ function Heartbeat({ t, recent }) {
1596
+ const rows = Array.isArray(recent) ? recent.slice(-BEATS) : [];
1597
+ const ok = rows.filter(row => row.ok === true).length;
1598
+ const label = rows.length
1599
+ ? t('heartbeatLabel').replace('{n}', number(t, rows.length)).replace('{ok}', number(t, ok)).replace('{fail}', number(t, rows.length - ok))
1600
+ : t('heartbeatNone');
1601
+ const lead = BEATS - rows.length;
1602
+ return h('span', { className: 'mwb-heartbeat', role: 'img', 'aria-label': label, title: label },
1603
+ Array.from({ length: BEATS }, (_, index) => {
1604
+ const row = index >= lead ? rows[index - lead] : null;
1605
+ return h('i', { key: index, className: 'mwb-beat', 'data-tone': !row ? 'none' : row.ok === true ? 'ok' : 'fault', 'aria-hidden': true });
1606
+ }));
1607
+ }
1608
+ // Secondary flows (registry, templates, import/export) open in a right-hand
1609
+ // drawer so the canvas keeps its place instead of being pushed down.
1610
+ function Drawer({ t, title, onClose, children }) {
1611
+ const titleId = useId(), panel = useRef(null);
1612
+ useEffect(() => {
1613
+ if (typeof document === 'undefined') return undefined;
1614
+ const previous = document.activeElement;
1615
+ const node = panel.current;
1616
+ (node?.querySelector?.('input,select,textarea') ?? node)?.focus?.();
1617
+ return () => { if (previous && previous.isConnected) previous.focus?.(); };
1618
+ }, []);
1619
+ return h('div', { className: 'mwb-overlay', onMouseDown: event => { if (event.target === event.currentTarget) onClose(); } },
1620
+ h('section', { className: 'mwb-drawer', role: 'dialog', 'aria-modal': true, 'aria-labelledby': titleId, ref: panel, tabIndex: -1,
1621
+ onKeyDown: event => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onClose(); } } },
1622
+ h('div', { className: 'mwb-drawer-head' },
1623
+ h('h2', { id: titleId, className: 'mwb-heading' }, title),
1624
+ h(Button, { kind: 'quiet', onClick: onClose }, t('drawerClose'))),
1625
+ h('div', { className: 'mwb-drawer-body' }, children)));
1626
+ }
1627
+ function Directory({ t, data, selected, headingRef, panelId, query, setQuery, sort, setSort, group, tags, onTag, reset, locked, editing, onSelect, onAdd, onClone, beats, bulk, onBulkMode, onBulkToggle, onBulkRun }) {
1628
+ const id = useId();
1629
+ const lang = localeOf(t), folded = query.trim().toLocaleLowerCase(lang);
1630
+ const compareName = (a, b) => displayName(a).localeCompare(displayName(b), lang, { numeric: true, sensitivity: 'base' }) || a.id.localeCompare(b.id);
1631
+ // Tag chips use OR semantics within themselves and combine freely with the
1632
+ // group and search filters.
1633
+ const servers = data.servers.filter(server => (group === 'all' || group === groupOf(server))
1634
+ && (tags.length === 0 || (server.tags ?? []).some(tag => tags.includes(tag)))
1635
+ && (!folded || [displayName(server), server.id, server.transport, transportLabel(t, server)].some(value => value.toLocaleLowerCase(lang).includes(folded))));
1636
+ const score = (server, key) => key === 'attention' ? attentionRank[groupOf(server)] : key === 'checked' ? -(server.lastCheck?.at ?? -1) : -(server.counts?.enabledTools ?? -1);
1637
+ servers.sort((a, b) => (sort === 'name' ? 0 : score(a, sort) - score(b, sort)) || compareName(a, b));
1638
+ // The list is the navigation: one row per server, a status pill, the call
1639
+ // heartbeat and the tool ratio on a single line, the fault reason below.
1640
+ return h('section', { className: 'mwb-directory', 'aria-labelledby': id },
1641
+ h('div', { className: 'mwb-section-head' }, h('h2', { className: 'mwb-subhead', id, ref: headingRef, tabIndex: -1 }, t('directory')),
1642
+ h('span', { className: 'mwb-hint mwb-num', role: 'status' }, t('results') + ': ' + number(t, servers.length) + ' / ' + number(t, data.servers.length))),
1643
+ h('div', { className: 'mwb-list-tools' },
1644
+ h(Field, { label: t('search') }, h('input', { type: 'search', value: query, maxLength: 160, placeholder: t('searchHint'), onChange: event => setQuery(event.target.value) })),
1645
+ h(Field, { label: t('sort') }, h('select', { value: sort, onChange: event => setSort(event.target.value) },
1646
+ sortKeys.map(item => h('option', { key: item, value: item }, t('sort.' + item))))),
1647
+ h(Button, { kind: 'quiet', disabled: locked, 'aria-pressed': bulk.mode, onClick: onBulkMode }, t(bulk.mode ? 'bulkExit' : 'bulkSelect'))),
1648
+ bulk.mode && h('div', { className: 'mwb-bulk-bar' },
1649
+ h('span', { className: 'mwb-hint mwb-num', role: 'status' }, number(t, bulk.ids.length) + ' / ' + number(t, data.servers.length)),
1650
+ h(Button, { kind: 'primary', disabled: !bulk.ids.length || bulk.busy != null || locked, onClick: () => onBulkRun('bulkEnable') }, t('bulkEnable')),
1651
+ h(Button, { disabled: !bulk.ids.length || bulk.busy != null || locked, onClick: () => onBulkRun('bulkDisable') }, t('bulkDisable')),
1652
+ h(Button, { disabled: !bulk.ids.length || bulk.busy != null || locked, onClick: () => onBulkRun('bulkConnect') }, t('bulkConnect')),
1653
+ bulk.busy && h('span', { className: 'mwb-hint' }, t('bulkBusy'))),
1654
+ editing && h('p', { className: 'mwb-hint' }, t('draftOpen')),
1655
+ !editing && selected && !servers.includes(selected) && h('p', { className: 'mwb-hint' }, t('outOfFilter')),
1656
+ servers.length > 0 ? h('ul', { className: 'mwb-server-list', role: 'list', 'aria-labelledby': id }, servers.map(server => {
1657
+ const hint = server.error ? shortFault(t, server.error) : null;
1658
+ const check = server.lastCheck;
1659
+ const current = selected === server;
1660
+ const row = { key: server.id, className: 'mwb-server', role: 'listitem', 'data-selected': current, 'data-locked': locked };
1661
+ if (!locked) row.onClick = event => onSelect(server.id, event.currentTarget.querySelector?.('button'));
1662
+ return h('li', row,
1663
+ bulk.mode && h('input', { type: 'checkbox', checked: bulk.ids.includes(server.id),
1664
+ disabled: bulk.busy != null || locked, 'aria-label': t('bulkColumn') + ': ' + displayName(server),
1665
+ onClick: event => event.stopPropagation(),
1666
+ onChange: () => onBulkToggle(server.id) }),
1667
+ h('div', { className: 'mwb-server-body' },
1668
+ h('div', { className: 'mwb-server-head' },
1669
+ h('button', { type: 'button', className: 'mwb-row-open', 'aria-controls': current ? panelId : undefined,
1670
+ 'aria-current': current ? 'true' : undefined, disabled: locked, onClick: event => {
1671
+ event.stopPropagation(); onSelect(server.id, event.currentTarget);
1672
+ } }, displayName(server)),
1673
+ h('span', { className: 'mwb-transport mwb-hint mwb-tech' }, transportLabel(t, server)),
1674
+ h('span', { className: 'mwb-server-spacer' }),
1675
+ h(Heartbeat, { t, recent: beats.get(server.id) }),
1676
+ h(Status, { t, server })),
1677
+ h('div', { className: 'mwb-server-meta' },
1678
+ h('span', { className: 'mwb-num', title: t('toolsRatio') }, number(t, server.counts?.enabledTools) + ' / ' + number(t, server.counts?.tools)),
1679
+ server.refreshing && h('span', { className: 'mwb-hint' }, t('refreshingTable')),
1680
+ h(Clock, { at: check?.at, t, short: true }),
1681
+ hint && h('span', { className: 'mwb-last-error', title: hint }, hint)),
1682
+ (server.tags ?? []).length > 0 && h('div', { className: 'mwb-chips' },
1683
+ server.tags.map(tag => h(Chip, { key: tag, tag, active: tags.includes(tag), onTag }))),
1684
+ h('div', { className: 'mwb-server-actions' },
1685
+ h(Button, { kind: 'quiet', className: 'mwb-row-clone', disabled: locked,
1686
+ 'aria-label': t('clone') + ': ' + displayName(server), onClick: event => {
1687
+ event.stopPropagation(); onClone(server);
1688
+ } }, t('clone')))))}
1689
+ )) : h('div', { className: 'mwb-empty' },
1690
+ h('strong', null, t(data.servers.length ? 'noMatches' : 'empty')),
1691
+ !data.servers.length && h('p', { className: 'mwb-muted' }, t('emptyHint')),
1692
+ h(Button, { disabled: !data.servers.length && !onAdd, onClick: data.servers.length ? reset : onAdd }, t(data.servers.length ? 'reset' : 'add'))));
1693
+ }
1694
+
1695
+ return { Icon, PanelIcon, Button, Notice, Field, Badge, Skeleton, StatusBar, Status, Clock, Confirm, Switch, Distribution, Chip, Metrics, Ranking, Conflicts, Playground, IoPanel, HealthCard, TagEditor, StatsCard, Dashboard, Heartbeat, Drawer, Directory };
1696
+ }
1697
+
1698
+ /* src/workbench/ui-detail.js */
1699
+
1700
+ function createDetailUi(React, ui) {
1701
+ const h = React.createElement;
1702
+ const { useEffect, useId, useRef, useState } = React;
1703
+ const { Icon, Button, Notice, Field, Badge, Skeleton, Status, Clock, Switch, Playground, TagEditor } = ui;
1704
+
1705
+ function Tabs({ t, current, base, disabled, onSection }) {
1706
+ const keys = useRef([]);
1707
+ return h('div', { className: 'mwb-tabs', role: 'tablist', 'aria-label': t('detailTabs') }, sections.map((item, index) =>
1708
+ h('button', { key: item, type: 'button', role: 'tab', className: 'mwb-tab', id: base + '-' + item,
1709
+ 'aria-selected': current === item, 'aria-controls': base + '-panel', tabIndex: current === item ? 0 : -1,
1710
+ 'aria-disabled': disabled || undefined, ref: node => { keys.current[index] = node; },
1711
+ onClick: () => { if (!disabled) onSection(item); }, onKeyDown: event => {
1712
+ if (disabled) return;
1713
+ const rtl = event.currentTarget.closest?.('[dir]')?.dir === 'rtl';
1714
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? sections.length - 1 : event.key === 'ArrowLeft'
1715
+ ? (index + sections.length + (rtl ? 1 : -1)) % sections.length : event.key === 'ArrowRight'
1716
+ ? (index + sections.length + (rtl ? -1 : 1)) % sections.length : null;
1717
+ if (next === null) return;
1718
+ event.preventDefault(); keys.current[next]?.focus(); onSection(sections[next]);
1719
+ },
1720
+ }, t('tab.' + item))));
1721
+ }
1722
+ function Readout({ rows, className = 'mwb-data' }) {
1723
+ return h('dl', { className }, rows.map(([key, label, value]) => h('div', { key }, h('dt', null, label), h('dd', null, value))));
1724
+ }
1725
+ function Connection({ t, data, server, detail, locked, onConnect, onRefresh, onEnable }) {
1726
+ const status = statusOf(server), live = online(data, server);
1727
+ const canRequest = !locked && data.active && data.autoConnect && server.enabled && !server.refreshing && groupOf(server) !== 'progress';
1728
+ const check = server.lastCheck;
1729
+ const info = [detail.serverInfo?.name, detail.serverInfo?.version].filter(Boolean).join(' ');
1730
+ const fields = [
1731
+ ['target', t('target'), h('code', { className: 'mwb-tech' }, detail.target || '—')],
1732
+ ...(info ? [['reported', t('reportedName'), info]] : []),
1733
+ ['lastCheck', t('lastCheck'), h('div', { className: 'mwb-lineup' }, h(Clock, { at: check?.at, t }),
1734
+ check && h(Badge, { tone: check.ok ? 'online' : 'fault' }, t(check.ok ? 'checkOk' : 'checkFailed')),
1735
+ check && h('span', { className: 'mwb-num' }, duration(t, check.durationMs)))],
1736
+ ...(detail.retries || detail.nextRetryAt != null ? [['retryCount', t('retryCount'), number(t, detail.retries)]] : []),
1737
+ ...(detail.nextRetryAt != null ? [['nextRetry', t('nextRetry'), h(Clock, { at: detail.nextRetryAt, t })]] : []),
1738
+ ];
1739
+ return h(React.Fragment, null,
1740
+ h('h3', { className: 'mwb-subhead' }, t('connectionReadout')),
1741
+ (server.error || status === 'error') && h(Notice, { tone: 'error' }, viewErrorText(t, server.error)),
1742
+ server.refreshing && h(Notice, null, t('refreshing')),
1743
+ !server.enabled && h('p', { className: 'mwb-hint' }, t('serverDisabled')),
1744
+ h(Readout, { rows: fields }),
1745
+ h(Readout, { className: 'mwb-meta-line mwb-num', rows: [['resources', t('resources'), number(t, detail.resources)], ['prompts', t('prompts'), number(t, detail.prompts)]] }),
1746
+ h('div', { className: 'mwb-actions' },
1747
+ h(Button, { kind: live ? undefined : 'primary', disabled: !canRequest, onClick: onConnect }, t(live ? 'tryConnect' : 'connect')),
1748
+ h(Button, { disabled: !canRequest || !live, onClick: onRefresh }, t('refresh')),
1749
+ h(Button, { kind: 'quiet', disabled: locked, onClick: () => onEnable(!server.enabled) }, t(server.enabled ? 'disableServer' : 'enableServer'))));
1750
+ }
1751
+ function Schema({ t, read, id }) {
1752
+ return h('div', { className: 'mwb-schema', id, 'aria-busy': read.reading },
1753
+ read.reading ? h('p', { role: 'status', className: 'mwb-hint' }, t('schemaLoading'))
1754
+ : read.error ? h(Notice, { tone: 'error', alert: true }, t(read.error))
1755
+ : read.data && h(React.Fragment, null, read.data.truncated && h('p', { className: 'mwb-hint' }, t('schemaTruncated')),
1756
+ h('pre', null, read.data.schemaJson),
1757
+ read.data.outputSchemaJson && h(React.Fragment, null,
1758
+ h('h4', { className: 'mwb-hint' }, t('outputDefinition')),
1759
+ read.data.outputTruncated && h('p', { className: 'mwb-hint' }, t('schemaTruncated')),
1760
+ h('pre', null, read.data.outputSchemaJson))));
1761
+ }
1762
+ function ToolRow({ t, row, schemaName, schema, locked, live, onSchema, onPolicy, onReview, confirmation, playground, playgroundReading,
1763
+ playgroundInfo, onPlayground, onPlayField, onPlayRaw, onPlayRun, onPlayAccept, onPlayCancel }) {
1764
+ const id = useId(), opened = schemaName === row.name, available = live && stamped(row);
1765
+ const readOnly = !available || !row.writable;
1766
+ return h('li', null,
1767
+ h('div', { className: 'mwb-tool-main' }, h('strong', { className: 'mwb-tool-name mwb-tech' }, row.name),
1768
+ h('div', { className: 'mwb-actions' },
1769
+ h(Button, { kind: 'quiet', disabled: !available || locked, 'aria-expanded': opened, 'aria-controls': opened ? id : undefined,
1770
+ 'aria-label': t(opened ? 'schemaClose' : 'schemaOpen') + ': ' + row.name, onClick: () => onSchema(row.name) }, t(opened ? 'schemaClose' : 'schemaOpen')),
1771
+ h(Button, { kind: 'quiet', disabled: !available || !row.enabled || row.pending || locked, 'aria-pressed': !!playground,
1772
+ 'aria-label': t('playground') + ': ' + row.name, onClick: () => onPlayground(row) }, t('playground')))),
1773
+ row.description && h('p', { className: 'mwb-hint mwb-tool-notes' }, row.description),
1774
+ row.hint && h(Badge, { tone: row.hint === 'destructive' ? 'fault' : 'quiet' },
1775
+ t(row.hint === 'destructive' ? 'toolDestructiveHint' : 'toolReadOnlyHint')),
1776
+ row.pending && h(Notice, { tone: 'warn' }, h('strong', null, t('toolPending') + ' · '), t('toolReviewNeeded')),
1777
+ h('div', { className: 'mwb-tool-controls' },
1778
+ h(Switch, { label: t('toolEnabled'), name: row.name, checked: row.enabled, disabled: locked || readOnly,
1779
+ onChange: (enabled, event) => onPolicy(row.name, { enabled }, event) }),
1780
+ h(Switch, { label: t('toolApproval'), name: row.name, checked: row.requireApproval, disabled: locked || readOnly || row.hint === 'destructive',
1781
+ onChange: (requireApproval, event) => onPolicy(row.name, { requireApproval }, event) }),
1782
+ readOnly && !row.pending && h('span', { className: 'mwb-hint' }, t('catalogReadOnly'))),
1783
+ opened && h(Schema, { t, read: schema, id }),
1784
+ row.pending && opened && schema.data?.name === row.name && !schema.data.truncated && !schema.data.outputTruncated
1785
+ && h(Button, { kind: 'primary', disabled: !available || locked, onClick: event => onReview(row, event) }, t('toolReview')),
1786
+ confirmation,
1787
+ playground && h(Playground, { t, pg: playground, reading: playgroundReading, info: playgroundInfo,
1788
+ onField: onPlayField, onRaw: onPlayRaw, onRun: onPlayRun, onAccept: onPlayAccept, onCancel: onPlayCancel }));
1789
+ }
1790
+ function Tools({ t, detail, query, setQuery, locked, sectionLive, refreshing, schemaName, schema, onSchema, onPolicy, onReview, confirmation, renderConfirm, onRefresh,
1791
+ playground, onPlayground, onPlayField, onPlayRaw, onPlayRun, onPlayAccept, onPlayCancel }) {
1792
+ const lang = localeOf(t), needle = query.trim().toLocaleLowerCase(lang);
1793
+ const rows = detail.rows ?? [];
1794
+ const visible = rows.filter(row => !needle || [row.name, row.description].some(value => (value ?? '').toLocaleLowerCase(lang).includes(needle)));
1795
+ const confirming = ['tool', 'review'].includes(confirmation?.kind) ? confirmation.name : null;
1796
+ return h(React.Fragment, null,
1797
+ h('div', { className: 'mwb-section-head' }, h('h3', { className: 'mwb-subhead' }, t('toolTitle')),
1798
+ h(Button, { kind: 'quiet', disabled: locked || !sectionLive || refreshing, onClick: onRefresh }, t('refresh'))),
1799
+ rows.length > 0 && h('p', { className: 'mwb-hint' }, t(sectionLive ? 'toolHint' : 'toolOffline')),
1800
+ rows.length > 0 && h('div', { className: 'mwb-compare-tools' },
1801
+ h(Field, { label: t('findTool') }, h('input', { type: 'search', value: query, maxLength: 160, placeholder: t('findToolHint'),
1802
+ onChange: event => setQuery(event.target.value) })),
1803
+ h('span', { className: 'mwb-hint mwb-num', role: 'status' }, t('toolCount') + ': ' + number(t, visible.length) + ' / ' + number(t, detail.total))),
1804
+ !visible.length && h('p', { className: 'mwb-muted' }, t(rows.length ? 'toolNoMatches' : sectionLive ? 'toolEmpty' : 'toolOffline')),
1805
+ visible.length > 0 && h('ul', { className: 'mwb-tool-list', role: 'list' }, visible.map(row => h(ToolRow, {
1806
+ key: row.name, t, row, schemaName, schema, onSchema, onPolicy, onReview, live: sectionLive,
1807
+ locked: locked || refreshing, confirmation: row.name === confirming ? renderConfirm() : null,
1808
+ playground: playground?.name === row.name ? playground : null,
1809
+ playgroundReading: playground?.name === row.name && schemaName === row.name && schema.reading,
1810
+ playgroundInfo: playground?.name === row.name && schemaName === row.name && schema.data ? playgroundInfo(schema.data.schemaJson) : null,
1811
+ onPlayground, onPlayField, onPlayRaw, onPlayRun, onPlayAccept, onPlayCancel,
1812
+ }))), confirming && !visible.some(row => row.name === confirming) && renderConfirm());
1813
+ }
1814
+ function Activity({ t, active, detail }) {
1815
+ const counts = detail.stats ?? {};
1816
+ const recent = (detail.history ?? []).slice(0, 20);
1817
+ return h(React.Fragment, null, h('h3', { className: 'mwb-subhead' }, t('activityTitle')),
1818
+ h('p', { className: 'mwb-hint' }, t('activityHint')),
1819
+ active && h(Readout, { className: 'mwb-meta-line mwb-num', rows: [['calls', t('calls'), number(t, counts.calls)],
1820
+ ['failures', t('failures'), number(t, counts.failures)], ['active', t('inFlight'), number(t, counts.active)]] }),
1821
+ recent.length ? h('ol', { className: 'mwb-history', role: 'list' }, recent.map((row, index) => h('li', { key: row.at + ':' + index, 'data-tone': row.ok ? 'online' : 'fault' },
1822
+ h('div', { className: 'mwb-history-head' }, h(Clock, { at: row.at, t, rel: true }),
1823
+ h('strong', { className: 'mwb-tech mwb-tool-name' }, row.tool),
1824
+ h(Badge, { tone: row.ok ? 'online' : 'fault' }, t(row.ok ? 'ok' : 'notOk')),
1825
+ h('span', { className: 'mwb-hint mwb-num' }, duration(t, row.durationMs))),
1826
+ !row.ok && (row.message || row.code) && h('p', { className: 'mwb-hint' }, viewErrorText(t, row)))))
1827
+ : h('p', { className: 'mwb-muted' }, t(active ? 'activityEmpty' : 'activityNoRuntime')));
1828
+ }
1829
+ function PairSummary({ t, rows }) {
1830
+ return rows?.length ? h('ul', { className: 'mwb-cred-summary', role: 'list' }, rows.map(row => h('li', { key: row.name },
1831
+ h('code', null, row.name), h('span', { className: 'mwb-hint' }, t(row.hasValue ? 'configPairsSet' : 'configPairsEmpty')))))
1832
+ : h('span', { className: 'mwb-hint' }, t('pairEmpty'));
1833
+ }
1834
+ function Config({ t, server, detail, locked, busy, onEdit, onTags, onRemove, confirmation }) {
1835
+ const launch = server.transport === 'stdio';
1836
+ const rows = [
1837
+ ['endpoint', t(launch ? 'command' : 'configEndpoint'), h('code', null, (launch ? detail.command : detail.url) || '—')],
1838
+ ...(launch ? [['args', t('args'), h('pre', null, JSON.stringify(detail.args ?? [], null, 2))],
1839
+ ['cwd', t('cwd'), h('code', null, detail.cwd || '—')]] : []),
1840
+ ['timeout', t('timeout'), h('span', { className: 'mwb-num' }, duration(t, detail.timeoutMs))],
1841
+ ['enable', t('configEnabled'), t(server.enabled ? 'on' : 'off')], ['approval', t('configApproval'), t(server.requireApproval ? 'on' : 'off')],
1842
+ ['headers', t('headers'), h(PairSummary, { t, rows: detail.headers })], ['env', t('env'), h(PairSummary, { t, rows: detail.env })],
1843
+ ];
1844
+ return h(React.Fragment, null, h('div', { className: 'mwb-section-head' }, h('h3', { className: 'mwb-subhead' }, t('configTitle')),
1845
+ h(Button, { kind: 'primary', disabled: locked, onClick: onEdit }, t('edit'))),
1846
+ h(Readout, { rows, className: 'mwb-data mwb-config-data' }),
1847
+ h(TagEditor, { t, server, locked, busy, onSave: onTags }),
1848
+ h('div', { className: 'mwb-danger-zone' }, h(Button, { kind: 'danger', disabled: locked, onClick: onRemove }, t('remove')), confirmation));
1849
+ }
1850
+
1851
+ function Pairs({ t, kind, rows, onRows, disabled }) {
1852
+ const id = useId(), serial = useRef(0);
1853
+ const patch = (key, next) => onRows(old => old.map(row => row.key === key ? { ...row, ...next } : row));
1854
+ const add = () => {
1855
+ const entry = { key: 'new-' + ++serial.current, name: '', value: '', keep: false, saved: false };
1856
+ onRows(old => old.length < 16 ? [...old, entry] : old);
1857
+ };
1858
+ return h('fieldset', { disabled, 'aria-describedby': id }, h('legend', null, t(kind)),
1859
+ h('p', { id, className: 'mwb-hint' }, t(kind + 'Hint')),
1860
+ rows.length > 0 && h('ul', { className: 'mwb-pairs', role: 'list' }, rows.map(row => h('li', { className: 'mwb-pair-row', key: row.key },
1861
+ h(Field, { label: t('pairName') }, h('input', { value: row.name, readOnly: row.saved, required: true, maxLength: 128,
1862
+ autoComplete: 'off', spellCheck: false, onChange: row.saved ? undefined : event => patch(row.key, { name: event.target.value }) })),
1863
+ row.saved && row.keep ? h('p', { className: 'mwb-pair-state' }, t('pairValue'),
1864
+ h('span', { className: 'mwb-hint' }, t(row.hasValue ? 'pairStored' : 'pairStoredEmpty')))
1865
+ : h(Field, { label: t('pairValue'), hint: row.saved ? t('pairClear') : null }, h('input', { type: 'password', value: row.value,
1866
+ maxLength: 2000, autoComplete: 'new-password', spellCheck: false, onChange: event => patch(row.key, { value: event.target.value }) })),
1867
+ h('div', { className: 'mwb-actions mwb-wide' }, row.saved && h(Button, { kind: 'quiet',
1868
+ 'aria-label': t(row.keep ? 'pairChange' : 'pairKeep') + ': ' + row.name,
1869
+ onClick: () => patch(row.key, { keep: !row.keep, value: '' }) }, t(row.keep ? 'pairChange' : 'pairKeep')),
1870
+ h(Button, { kind: 'quiet', 'aria-label': row.name ? t('removePair') + ': ' + row.name : t('removePair'),
1871
+ onClick: () => onRows(old => old.filter(item => item.key !== row.key)) }, t('removePair'))),
1872
+ ))),
1873
+ !rows.length && h('p', { className: 'mwb-hint' }, t('pairEmpty')),
1874
+ h(Button, { kind: 'quiet', onClick: add, disabled: rows.length >= 16, 'aria-label': t('addPair') + ': ' + t(kind) }, t('addPair')));
1875
+ }
1876
+ function Editor({ t, id, editor, patch, locked, saving, testing, canSave, stale, gone, canReopen, confirmation, onSave, onTest, onExit, onReopen }) {
1877
+ const { draft, mode } = editor;
1878
+ const heading = useRef(null);
1879
+ useEffect(() => { heading.current?.focus(); }, []);
1880
+ const text = (key, extra = {}) => h('input', { value: draft[key], onChange: event => patch({ [key]: event.target.value }), ...extra });
1881
+ const byKind = kind => change => patch(old => ({ [kind]: change(old[kind]) }));
1882
+ const local = draft.transport === 'stdio';
1883
+ const title = mode === 'create' ? 'createTitle' : 'editTitle';
1884
+ return h('section', { className: 'mwb-detail', id, 'aria-labelledby': id + '-title' },
1885
+ h('div', { className: 'mwb-pane-head' }, h('h2', { id: id + '-title', className: 'mwb-heading', tabIndex: -1, ref: heading }, t(title)),
1886
+ h(Button, { kind: 'quiet', icon: 'back', disabled: locked, onClick: onExit }, t('exit'))),
1887
+ h('div', { className: 'mwb-pane-body' }, h('p', { className: 'mwb-hint' }, t('formIntro')),
1888
+ editor.registryName && h(Notice, null, t('registryFrom').replace('{n}', editor.registryName)),
1889
+ h('form', { className: 'mwb-form', autoComplete: 'off', onSubmit: onSave },
1890
+ stale && h(Notice, { alert: true, tone: 'error' }, h('p', null, t(gone ? 'goneDraft' : 'staleDraft')),
1891
+ !gone && h(Button, { kind: 'quiet', disabled: !canReopen, onClick: onReopen }, t('reopen'))),
1892
+ editor.error && !stale && h(Notice, { alert: true, tone: 'error' }, t(editor.error)),
1893
+ h('fieldset', { disabled: locked }, h('legend', null, t('identity')),
1894
+ h('div', { className: 'mwb-fields' },
1895
+ h(Field, { label: t('id'), hint: t('idHint') }, text('id', { readOnly: mode === 'edit', required: true, maxLength: 32, spellCheck: false })),
1896
+ h(Field, { label: t('name'), hint: t('nameHint') }, text('name', { maxLength: 80 })),
1897
+ h(Field, { label: t('transport'), wide: true }, h('select', { value: draft.transport, onChange: event => patch({ transport: event.target.value }) },
1898
+ transports.map(transport => h('option', { key: transport, value: transport }, t('transport.' + transport))))),
1899
+ local ? [
1900
+ h(Field, { key: 'command', label: t('command'), wide: true }, text('command', { required: true, maxLength: 300, spellCheck: false })),
1901
+ h(Field, { key: 'args', label: t('args'), hint: t('argsHint'), wide: true }, h('textarea', { className: 'mwb-tech', rows: 2,
1902
+ value: draft.argsText, spellCheck: false, onChange: event => patch({ argsText: event.target.value }) })),
1903
+ h(Field, { key: 'cwd', label: t('cwd'), hint: t('cwdHint'), wide: true }, text('cwd', { maxLength: 1000, spellCheck: false })),
1904
+ ] : h(Field, { label: t('url'), wide: true }, text('url', { type: 'url', required: true, maxLength: 2000, spellCheck: false })),
1905
+ mode === 'edit' && h('p', { className: 'mwb-hint mwb-wide' }, t('targetReset')))),
1906
+ h('fieldset', { disabled: locked }, h('legend', null, t('policy')), h('div', { className: 'mwb-fields' },
1907
+ h('label', { className: 'mwb-check-field' }, h('input', { type: 'checkbox', checked: draft.enabled,
1908
+ onChange: event => patch({ enabled: event.target.checked }) }), t('formEnabled')),
1909
+ h('label', { className: 'mwb-check-field' }, h('input', { type: 'checkbox', checked: draft.requireApproval,
1910
+ onChange: event => patch({ requireApproval: event.target.checked }) }), t('formApproval')),
1911
+ h(Field, { label: t('timeout'), hint: t('timeoutHint') }, text('timeoutMs', { type: 'number', required: true, min: 1000, max: 180000, step: 1 })))),
1912
+ h(Pairs, { t, kind: 'headers', rows: draft.headers, onRows: byKind('headers'), disabled: locked }),
1913
+ h(Pairs, { t, kind: 'env', rows: draft.env, onRows: byKind('env'), disabled: locked }),
1914
+ confirmation,
1915
+ h('div', { className: 'mwb-actions mwb-form-actions' },
1916
+ h(Button, { onClick: onExit, disabled: locked }, t('exit')),
1917
+ h(Button, { kind: 'primary', disabled: !canSave || !!confirmation || testing || saving, onClick: onTest }, t(testing ? 'testing' : 'saveAndTest')),
1918
+ h(Button, { kind: 'primary', type: 'submit', disabled: !canSave || !!confirmation || saving || testing }, t(saving ? 'saving' : 'save'))),
1919
+ editor.test && h('div', { className: 'mwb-test-line', role: 'status' },
1920
+ h('span', { className: 'mwb-hint' }, t('testTitle')),
1921
+ h(Badge, { tone: statusTone(editor.test.status) }, t('status.' + editor.test.status)),
1922
+ editor.test.error?.code && h('code', { className: 'mwb-hint mwb-tech' }, editor.test.error.code),
1923
+ h('span', { className: 'mwb-num' }, duration(t, editor.test.durationMs)),
1924
+ editor.test.error?.message && h('span', { className: 'mwb-hint' }, editor.test.error.message)),
1925
+ )));
1926
+ }
1927
+ function useCopyFlash() {
1928
+ const [copied, setCopied] = useState(false);
1929
+ const copy = async text => {
1930
+ if (typeof navigator?.clipboard?.writeText !== 'function') return;
1931
+ try { await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 1600); }
1932
+ catch { /* Clipboard denial keeps the content selectable. */ }
1933
+ };
1934
+ return [copied, copy];
1935
+ }
1936
+ function ResourcesPanel({ t, serverId, detail, live, locked, api }) {
1937
+ const rows = detail.resourceRows ?? [], templates = detail.resourceTemplates ?? [];
1938
+ const canWatch = live && detail.canWatchResources === true;
1939
+ const [open, setOpen] = useState(null);
1940
+ const [values, setValues] = useState(Object.create(null));
1941
+ const [read, setRead] = useState(blankRead());
1942
+ const [watches, setWatches] = useState([]);
1943
+ const [watchBusy, setWatchBusy] = useState(false);
1944
+ const [watchError, setWatchError] = useState(null);
1945
+ const [copied, copy] = useCopyFlash();
1946
+ const seq = useRef(0), watchSeq = useRef(0), watched = useRef([]), watchMutation = useRef(false);
1947
+ const updateWatches = rows => { watched.current = rows; setWatches(rows); };
1948
+ const listWatches = async () => {
1949
+ if (watchMutation.current) return;
1950
+ const ticket = ++watchSeq.current;
1951
+ try {
1952
+ const reply = await api.call('resourceWatches', { id: serverId });
1953
+ if (watchSeq.current === ticket) updateWatches(reply.rows ?? []);
1954
+ } catch { /* A transient metadata read leaves the last confirmed state visible. */ }
1955
+ };
1956
+ useEffect(() => {
1957
+ if (!canWatch) { updateWatches([]); return; }
1958
+ void listWatches();
1959
+ const timer = setInterval(() => { void listWatches(); }, 3000);
1960
+ return () => { ++watchSeq.current; clearInterval(timer); };
1961
+ }, [api, serverId, canWatch]);
1962
+ useEffect(() => () => { ++seq.current; }, [api, serverId, live]);
1963
+ const preview = async input => {
1964
+ const ticket = ++seq.current, before = watched.current;
1965
+ setRead({ ...blankRead(), reading: true });
1966
+ try {
1967
+ const data = await api.call('readResource', { id: serverId, ...input });
1968
+ if (seq.current !== ticket) return;
1969
+ const last = before.find(row => row.uri === data.uri);
1970
+ setRead({ ...blankRead(), data, token: last?.token, input });
1971
+ } catch (error) {
1972
+ if (seq.current === ticket) setRead({ ...blankRead(), error: rpcErrorKey(error, 'faultReadFailed') });
1973
+ }
1974
+ };
1975
+ const watch = async (uri, enabled) => {
1976
+ if (!canWatch || locked || watchMutation.current) return;
1977
+ const ticket = ++watchSeq.current;
1978
+ watchMutation.current = true;
1979
+ setWatchBusy(true); setWatchError(null);
1980
+ try {
1981
+ const data = await api.call('setResourceWatch', { id: serverId, uri, enabled });
1982
+ if (watchSeq.current === ticket) updateWatches(data.rows ?? []);
1983
+ } catch (error) {
1984
+ if (watchSeq.current === ticket) setWatchError(rpcErrorKey(error, 'resWatchFailed'));
1985
+ } finally { watchMutation.current = false; setWatchBusy(false); }
1986
+ };
1987
+ const select = (key, input) => {
1988
+ ++seq.current;
1989
+ setRead(blankRead());
1990
+ setValues(Object.create(null));
1991
+ const next = open === key ? null : key;
1992
+ setOpen(next);
1993
+ if (next && input) void preview(input);
1994
+ };
1995
+ const controls = (name, uri) => {
1996
+ const payload = read.data;
1997
+ if (read.reading) return h('p', { className: 'mwb-hint', role: 'status' }, t('resLoading'));
1998
+ if (read.error) return h(Notice, { tone: 'error', alert: true }, t(read.error));
1999
+ if (!payload) return null;
2000
+ const previewUri = payload.uri || uri, entry = watches.find(row => row.uri === previewUri);
2001
+ const updated = entry?.changedAt != null && entry.token !== read.token;
2002
+ const image = payload.blob && /^image\/(?:png|jpeg|gif|webp)$/i.test(payload.mimeType ?? '');
2003
+ const display = payload.text != null ? h('pre', null, payload.text)
2004
+ : image ? h('img', { className: 'mwb-res-image', alt: name || previewUri, src: `data:${payload.mimeType};base64,${payload.blob}` })
2005
+ : h('p', { className: 'mwb-hint' }, t('resNoPreview'));
2006
+ return h('div', { className: 'mwb-res-preview' },
2007
+ previewUri && h('code', { className: 'mwb-hint mwb-tech' }, previewUri),
2008
+ updated && h(Notice, { tone: 'warn' }, t('resChanged')),
2009
+ payload.truncated && h('p', { className: 'mwb-hint' }, t('resTruncated')),
2010
+ display,
2011
+ h('div', { className: 'mwb-actions' },
2012
+ h(Button, { kind: 'quiet', disabled: locked, onClick: () => void preview(read.input) }, t('resRefresh')),
2013
+ canWatch && previewUri && h(Button, { kind: 'quiet', disabled: locked || watchBusy,
2014
+ onClick: () => void watch(previewUri, !entry) }, t(entry ? 'resUnwatch' : 'resWatch')),
2015
+ payload.text != null && h(Button, { kind: 'quiet', onClick: () => copy(payload.text) }, t(copied ? 'resCopied' : 'resCopy'))));
2016
+ };
2017
+ const items = rows.map(row => {
2018
+ const key = 'uri:' + row.uri;
2019
+ return h('li', { key },
2020
+ h('button', { type: 'button', className: 'mwb-res-row', 'aria-expanded': open === key, disabled: locked,
2021
+ onClick: () => select(key, {uri: row.uri}) },
2022
+ h('strong', { className: 'mwb-tech' }, row.name || row.uri),
2023
+ row.mimeType && h('span', { className: 'mwb-hint mwb-tech' }, row.mimeType)),
2024
+ row.description && h('p', { className: 'mwb-hint' }, row.description),
2025
+ open === key && controls(row.name, row.uri));
2026
+ });
2027
+ const templateItems = templates.map(row => {
2028
+ const key = 'template:' + row.uriTemplate;
2029
+ const args = () => row.variables.filter(name => Object.hasOwn(values, name) && values[name] !== '')
2030
+ .map(name => ({name, value: values[name]}));
2031
+ const form = open === key && h('form', { className: 'mwb-res-preview', onSubmit: event => {
2032
+ event.preventDefault();
2033
+ if (!locked && !read.reading) void preview({uriTemplate: row.uriTemplate, args: args()});
2034
+ } },
2035
+ row.variables.length > 0 && h('fieldset', null, h('legend', null, t('resParams')),
2036
+ h('p', { className: 'mwb-hint' }, t('resParamsHint')),
2037
+ row.variables.map(name => h(Field, { key: name, label: name }, h('input', { type: 'text', maxLength: 1024,
2038
+ value: Object.hasOwn(values, name) ? values[name] : '', disabled: locked, spellCheck: false,
2039
+ onChange: event => { const value = event.target.value; ++seq.current; setRead(blankRead());
2040
+ setValues(old => ({ ...old, [name]: value })); } })))),
2041
+ h('div', { className: 'mwb-actions' }, h(Button, { type: 'submit', kind: 'primary', disabled: locked || read.reading }, t('resOpen'))));
2042
+ return h('li', { key },
2043
+ h('button', { type: 'button', className: 'mwb-res-row', 'aria-expanded': open === key, disabled: locked,
2044
+ onClick: () => select(key) }, h('strong', null, row.name || row.uriTemplate)),
2045
+ h('code', { className: 'mwb-hint mwb-tech' }, row.uriTemplate),
2046
+ row.description && h('p', { className: 'mwb-hint' }, row.description), form, open === key && controls(row.name));
2047
+ });
2048
+ const watchList = canWatch && watches.length > 0 && h('details', null,
2049
+ h('summary', null, t('resWatchList') + ' (' + watches.length + ')'),
2050
+ h('p', { className: 'mwb-hint' }, t('resWatchHint')),
2051
+ h('ul', { className: 'mwb-res-list', role: 'list' }, watches.map(row => h('li', { key: row.uri },
2052
+ h('code', { className: 'mwb-hint mwb-tech' }, row.uri), ' ',
2053
+ h(Button, { kind: 'quiet', disabled: locked || watchBusy, onClick: () => void watch(row.uri, false) }, t('resUnwatch'))))));
2054
+ return h('div', { className: 'mwb-panel' }, h('h3', { className: 'mwb-subhead' }, t('resourcesTitle')),
2055
+ h('p', { className: 'mwb-hint' }, t(live ? 'resourcesHint' : 'needsLive')),
2056
+ live && watchError && h(Notice, { tone: 'error', alert: true }, t(watchError)),
2057
+ live && watchList,
2058
+ live && (items.length ? h('ul', { className: 'mwb-res-list', role: 'list' }, items)
2059
+ : !templates.length && h('p', { className: 'mwb-muted' }, t('resourcesEmpty'))),
2060
+ live && templates.length > 0 && h('section', { className: 'mwb-panel' },
2061
+ h('h4', { className: 'mwb-subhead' }, t('resTemplates')),
2062
+ h('ul', { className: 'mwb-res-list', role: 'list' }, templateItems)));
2063
+ }
2064
+ function PromptsPanel({ t, serverId, detail, live, locked, api }) {
2065
+ const rows = detail.promptRows ?? [];
2066
+ const [picked, setPicked] = useState(null);
2067
+ const [values, setValues] = useState({});
2068
+ const [read, setRead] = useState(blankRead());
2069
+ const [copied, copy] = useCopyFlash();
2070
+ const seq = useRef(0);
2071
+ const pick = row => { setPicked(old => old === row.name ? null : row.name); setValues({}); setRead(blankRead()); };
2072
+ const missing = row => (row.arguments ?? []).some(arg => arg.required && !String(values[arg.name] ?? '').trim());
2073
+ const render = async row => {
2074
+ if (missing(row)) return;
2075
+ const args = (row.arguments ?? []).map(arg => ({ name: arg.name, value: String(values[arg.name] ?? '') }))
2076
+ .filter(pair => pair.value !== '');
2077
+ const ticket = ++seq.current;
2078
+ setRead({ ...blankRead(), reading: true });
2079
+ try {
2080
+ const data = await api.call('getPrompt', { id: serverId, name: row.name, args });
2081
+ if (seq.current !== ticket) return;
2082
+ setRead({ ...blankRead(), data });
2083
+ } catch (error) {
2084
+ if (seq.current !== ticket) return;
2085
+ setRead({ ...blankRead(), error: rpcErrorKey(error, 'faultPromptFailed') });
2086
+ }
2087
+ };
2088
+ const head = h(React.Fragment, null, h('h3', { className: 'mwb-subhead' }, t('promptsTitle')),
2089
+ h('p', { className: 'mwb-hint' }, t(live || !rows.length ? 'promptsHint' : 'needsLive')));
2090
+ if (!live) return h('div', { className: 'mwb-panel' }, head,
2091
+ !rows.length && h('p', { className: 'mwb-muted' }, t('promptsEmpty')));
2092
+ return h('div', { className: 'mwb-panel' }, head,
2093
+ rows.length ? h('ul', { className: 'mwb-res-list', role: 'list' }, rows.map(row => h('li', { key: row.name },
2094
+ h('button', { type: 'button', className: 'mwb-res-row', 'aria-expanded': picked === row.name, disabled: locked,
2095
+ onClick: () => pick(row) },
2096
+ h('strong', { className: 'mwb-tech' }, row.name)),
2097
+ row.description && h('p', { className: 'mwb-hint' }, row.description),
2098
+ picked === row.name && h('div', { className: 'mwb-res-preview' },
2099
+ (row.arguments ?? []).length ? h('fieldset', { disabled: locked }, h('legend', null, t('promptArgs')),
2100
+ (row.arguments ?? []).map(arg => h(Field, { key: arg.name, label: arg.name + (arg.required ? ' · ' + t('promptRequired') : '') },
2101
+ h('input', { value: String(values[arg.name] ?? ''), maxLength: 2000, spellCheck: false,
2102
+ onChange: event => setValues(old => ({ ...old, [arg.name]: event.target.value })) }))))
2103
+ : h('p', { className: 'mwb-hint' }, t('promptArgs') + ': —'),
2104
+ h('div', { className: 'mwb-actions' }, h(Button, { kind: 'primary', disabled: locked || read.reading || missing(row),
2105
+ onClick: () => render(row) }, t(read.reading ? 'promptRendering' : 'promptRender'))),
2106
+ read.reading && h('p', { className: 'mwb-hint', role: 'status' }, t('promptRendering')),
2107
+ read.error && h(Notice, { tone: 'error', alert: true }, t(read.error)),
2108
+ read.data && h('div', { className: 'mwb-prompt-result' },
2109
+ h('h4', { className: 'mwb-hint' }, t('promptResult')),
2110
+ read.data.description && h('p', { className: 'mwb-hint' }, read.data.description),
2111
+ read.data.messages.map((message, index) => h('div', { key: index, className: 'mwb-prompt-message' },
2112
+ h('span', { className: 'mwb-hint mwb-tech' }, message.role),
2113
+ h('pre', null, message.text))),
2114
+ h('div', { className: 'mwb-actions' }, h(Button, { kind: 'quiet',
2115
+ onClick: () => copy(read.data.messages.map(message => message.text).join('\n\n')) },
2116
+ t(copied ? 'promptCopied' : 'promptCopy')))))))) : h('p', { className: 'mwb-muted' }, t('promptsEmpty')));
2117
+ }
2118
+ function LogsPanel({ t, serverId, local, live, retrying, locked, detail, api }) {
2119
+ const protocol = detail?.logging === true;
2120
+ const canRead = local || protocol;
2121
+ const poll = live || (local && retrying);
2122
+ const [read, setRead] = useState(() => ({ ...blankRead(), reading: true }));
2123
+ const [level, setLevel] = useState('');
2124
+ const [auto, setAuto] = useState(true);
2125
+ const [notice, setNotice] = useState(null);
2126
+ const seq = useRef(0);
2127
+ const tail = async () => {
2128
+ const ticket = ++seq.current;
2129
+ try {
2130
+ const data = await api.call('logTail', { id: serverId });
2131
+ if (seq.current !== ticket) return;
2132
+ setRead({ ...blankRead(), data });
2133
+ if (typeof data?.level === 'string' && data.level) setLevel(old => old || data.level);
2134
+ } catch (error) {
2135
+ if (seq.current !== ticket) return;
2136
+ setRead({ ...blankRead(), error: rpcErrorKey(error, 'failed') });
2137
+ }
2138
+ };
2139
+ useEffect(() => {
2140
+ if (!canRead) return undefined;
2141
+ void tail();
2142
+ const timer = auto && poll ? setInterval(() => { void tail(); }, 5000) : null;
2143
+ return () => { ++seq.current; if (timer !== null) clearInterval(timer); };
2144
+ }, [api, serverId, canRead, poll, auto]);
2145
+ const applyLevel = async value => {
2146
+ setLevel(value);
2147
+ if (!value) { setNotice(null); return; }
2148
+ try {
2149
+ await api.call('logConfig', { id: serverId, level: value });
2150
+ setNotice({ key: 'logsApplied' });
2151
+ void tail();
2152
+ } catch (error) { setNotice({ key: rpcErrorKey(error), error: true }); }
2153
+ };
2154
+ const lines = read.data?.lines ?? [];
2155
+ const toneOf = line => ['error', 'critical', 'alert', 'emergency'].includes(line.level) ? 'fault'
2156
+ : line.level === 'warning' ? 'warn' : undefined;
2157
+ return h('div', { className: 'mwb-panel' }, h('h3', { className: 'mwb-subhead' }, t('logsTitle')),
2158
+ h('p', { className: 'mwb-hint' }, t(local ? 'logsStdioHint' : !live ? 'logsPaused' : !protocol ? 'logsUnsupported' : 'logsHint')),
2159
+ canRead && h('div', { className: 'mwb-compare-tools' },
2160
+ protocol && live && h(Field, { label: t('logsLevel') }, h('select', { value: level, disabled: locked,
2161
+ onChange: event => applyLevel(event.target.value) }, h('option', { value: '' }, '—'),
2162
+ ['debug', 'info', 'notice', 'warning', 'error'].map(item => h('option', { key: item, value: item }, item)))),
2163
+ poll && h(Button, { kind: 'quiet', 'aria-pressed': auto, onClick: () => setAuto(old => !old) }, t('logsAuto')),
2164
+ h(Button, { kind: 'quiet', disabled: locked, onClick: () => void tail() }, t('reload'))),
2165
+ notice && h(Notice, { alert: notice.error, tone: notice.error ? 'error' : undefined }, t(notice.key)),
2166
+ canRead ? (read.reading && !lines.length ? h('p', { className: 'mwb-hint', role: 'status' }, t('loading'))
2167
+ : read.error ? h(Notice, { tone: 'error', alert: true }, t(read.error))
2168
+ : lines.length ? h('ol', { className: 'mwb-log-console', role: 'log' }, lines.map((line, index) =>
2169
+ h('li', { key: line.at + ':' + index, 'data-tone': toneOf(line) },
2170
+ h('span', { className: 'mwb-num' }, h(Clock, { at: line.at, t, short: true })),
2171
+ h('span', { className: 'mwb-log-level mwb-tech' }, line.level),
2172
+ line.logger && h('code', { className: 'mwb-hint mwb-tech' }, line.logger),
2173
+ h('span', { className: 'mwb-log-data' }, line.data))))
2174
+ : h('p', { className: 'mwb-muted' }, t('logsEmpty'))) : null);
2175
+ }
2176
+ function RegistryPanel({ t, reg, onQuery, onSearch, onPick, disabled }) {
2177
+ return h('div', { className: 'mwb-templates mwb-registry', role: 'group', 'aria-label': t('registryOpen') },
2178
+ h('p', { className: 'mwb-hint' }, t('registryHint')),
2179
+ h('div', { className: 'mwb-compare-tools' },
2180
+ h(Field, { label: t('search') }, h('input', { type: 'search', value: reg.query, maxLength: 100,
2181
+ placeholder: t('searchHint'), onChange: event => onQuery(event.target.value),
2182
+ onKeyDown: event => { if (event.key === 'Enter') { event.preventDefault(); onSearch(); } } })),
2183
+ h(Button, { kind: 'primary', disabled: disabled || reg.phase === 'busy' || !reg.query.trim(), onClick: onSearch },
2184
+ t('registrySearchBtn'))),
2185
+ reg.phase === 'busy' && h('p', { className: 'mwb-hint', role: 'status' }, t('registrySearching')),
2186
+ reg.phase === 'unreachable' && h(Notice, { tone: 'warn' },
2187
+ t(reg.reason === 'timeout' ? 'registryTimeout'
2188
+ : reg.reason === 'dns' ? 'registryDns' : reg.reason === 'tls' ? 'registryTls'
2189
+ : reg.reason?.startsWith('http-') ? 'registryHttp' : 'registryUnreachable')
2190
+ + (reg.reason?.startsWith('http-') ? ' (' + reg.reason.slice(5) + ')' : '')),
2191
+ reg.phase === 'error' && h(Notice, { tone: 'error', alert: true }, t(reg.error ?? 'registryFailed')),
2192
+ reg.phase === 'done' && !reg.rows.length && h('p', { className: 'mwb-muted' }, t('registryEmpty')),
2193
+ reg.rows.length > 0 && h('ul', { className: 'mwb-reg-list', role: 'list' }, reg.rows.map(row => h('li', { key: row.name },
2194
+ h('div', { className: 'mwb-reg-main' },
2195
+ h('strong', { className: 'mwb-tech' }, row.name),
2196
+ h('span', { className: 'mwb-hint' }, t('transport.' + row.transport)),
2197
+ row.status === 'active' && h('span', { className: 'mwb-hint' }, t('registryActive'))),
2198
+ row.description && h('p', { className: 'mwb-hint' }, row.description),
2199
+ row.packageRef && h('code', { className: 'mwb-hint mwb-tech' }, t('registryPackage') + ': ' + row.packageRef),
2200
+ row.registryType === 'oci' && h('p', { className: 'mwb-hint' }, t('registryDockerHint')),
2201
+ h('div', { className: 'mwb-actions' }, h(Button, { kind: 'quiet', disabled, onClick: () => onPick(row) },
2202
+ t('registryInstall')))))));
2203
+ }
2204
+ function Detail({ t, id, server, open, headingRef, section, read, blocked, navigationLocked, onBack, onSection, onRetry, render }) {
2205
+ const tabId = useId();
2206
+ if (!server) return open ? h('section', { className: 'mwb-detail', id, 'aria-labelledby': id + '-title' },
2207
+ h('div', { className: 'mwb-pane-head' }, h('h2', { id: id + '-title', className: 'mwb-heading', tabIndex: -1, ref: headingRef }, t('noSelection')),
2208
+ h(Button, { kind: 'quiet', icon: 'back', disabled: navigationLocked, onClick: onBack }, t('back'))),
2209
+ h('div', { className: 'mwb-pane-body' }, h('p', { className: 'mwb-muted' }, t('selectedGone')))) : null;
2210
+ return h('section', { className: 'mwb-detail', id, 'aria-labelledby': id + '-title' },
2211
+ h('header', { className: 'mwb-pane-head' }, h('div', null,
2212
+ h('h2', { id: id + '-title', className: 'mwb-heading', tabIndex: -1, ref: headingRef }, displayName(server)),
2213
+ h('div', { className: 'mwb-lineup' }, h(Status, { t, server }), h('span', { className: 'mwb-hint' }, transportLabel(t, server)),
2214
+ h('code', { className: 'mwb-hint' }, server.id))),
2215
+ h(Button, { kind: 'quiet', icon: 'back', disabled: navigationLocked, onClick: onBack }, t('back'))),
2216
+ h(Tabs, { t, base: tabId, current: section, disabled: navigationLocked, onSection }),
2217
+ h('div', { className: 'mwb-pane-body', role: 'tabpanel', tabIndex: 0, id: tabId + '-panel',
2218
+ 'aria-labelledby': tabId + '-' + section, 'aria-busy': read.reading },
2219
+ read.reading ? h(React.Fragment, null, h('p', { className: 'mwb-muted', role: 'status' }, t('detailLoading')), h(Skeleton, { rows: 3 }))
2220
+ : read.data ? render(read.data)
2221
+ : h('div', { className: 'mwb-empty' }, h(Notice, { tone: 'error', alert: true }, t(read.error ?? 'detailFailed')),
2222
+ h(Button, { disabled: blocked, onClick: onRetry }, t(read.error === 'detailStale' ? 'reload' : 'retry')))),
2223
+ );
2224
+ }
2225
+
2226
+ return { Tabs, Readout, Connection, Schema, ToolRow, Tools, Activity, PairSummary, Config, Pairs, Editor, useCopyFlash, ResourcesPanel, PromptsPanel, LogsPanel, RegistryPanel, Detail };
2227
+ }
2228
+
2229
+ /* src/workbench/ui.js */
2230
+
2231
+ function createUi(React) {
2232
+ const h = React.createElement;
2233
+ const { useEffect, useId, useRef, useState } = React;
2234
+ const dirUi = createDirectoryUi(React);
2235
+ const { PanelIcon, Button, Notice, Skeleton, StatusBar, Confirm, Distribution, IoPanel, Dashboard, Drawer, Directory } = dirUi;
2236
+ const { Connection, Tools, Activity, Config, Editor, ResourcesPanel, PromptsPanel, LogsPanel, RegistryPanel, Detail } = createDetailUi(React, dirUi);
2237
+
2238
+ // The DSH Web shell is a fixed-viewport app: its main column has a definite
2239
+ // height and clips overflow, so host pages own their scrolling. Without a
2240
+ // scroller, tall workbench content (long details on phones) is unreachable.
2241
+ // Constrain the root to the visible area of the nearest clipping ancestor
2242
+ // and scroll internally; do nothing when a native scroller already exists.
2243
+ function usePanelFit(rootRef) {
2244
+ useEffect(() => {
2245
+ const wb = rootRef.current;
2246
+ if (!wb || typeof wb.getBoundingClientRect !== 'function') return undefined;
2247
+ let raf = 0;
2248
+ const fit = () => {
2249
+ raf = 0;
2250
+ wb.style.maxBlockSize = ''; wb.style.overflowY = ''; delete wb.dataset.scroll;
2251
+ if (typeof getComputedStyle !== 'function') return;
2252
+ let clipper = null;
2253
+ for (let el = wb.parentElement; el; el = el.parentElement) {
2254
+ const flow = getComputedStyle(el).overflowY;
2255
+ if (flow === 'auto' || flow === 'scroll' || flow === 'overlay') return;
2256
+ if ((flow === 'hidden' || flow === 'clip') && el.clientHeight > 0) { clipper = el; break; }
2257
+ }
2258
+ if (!clipper) return;
2259
+ const pad = parseFloat(getComputedStyle(clipper).paddingBottom) || 0;
2260
+ const max = Math.floor(clipper.getBoundingClientRect().bottom - pad - wb.getBoundingClientRect().top);
2261
+ if (max > 120) {
2262
+ wb.style.maxBlockSize = max + 'px'; wb.style.overflowY = 'auto'; wb.dataset.scroll = 'y';
2263
+ }
2264
+ };
2265
+ const schedule = () => { if (!raf) raf = requestAnimationFrame(fit); };
2266
+ schedule();
2267
+ window.addEventListener('resize', schedule);
2268
+ window.visualViewport?.addEventListener('resize', schedule);
2269
+ let observer = null;
2270
+ if (typeof ResizeObserver === 'function') {
2271
+ observer = new ResizeObserver(schedule);
2272
+ for (let el = wb.parentElement; el && el !== document.body; el = el.parentElement) observer.observe(el);
2273
+ }
2274
+ return () => {
2275
+ window.removeEventListener('resize', schedule);
2276
+ window.visualViewport?.removeEventListener('resize', schedule);
2277
+ observer?.disconnect();
2278
+ if (raf) cancelAnimationFrame(raf);
2279
+ wb.style.maxBlockSize = ''; wb.style.overflowY = ''; delete wb.dataset.scroll;
2280
+ };
2281
+ }, [rootRef]);
2282
+ }
2283
+
2284
+ function Page({ api, t }) {
2285
+ const [model, publish] = useState(startModel);
2286
+ const [group, setGroup] = useState('all');
2287
+ const [sort, setSort] = useState('attention');
2288
+ const [query, setQuery] = useState('');
2289
+ const [tagFilter, setTagFilter] = useState([]);
2290
+ const [toolQuery, setToolQuery] = useState('');
2291
+ const [editor, setEditor] = useState(null);
2292
+ const [confirmation, setConfirmation] = useState(null);
2293
+ const [notice, setNotice] = useState(null);
2294
+ const [playground, setPlayground] = useState(null);
2295
+ const [io, setIo] = useState(null);
2296
+ const [tplOpen, setTplOpen] = useState(false);
2297
+ const [regOpen, setRegOpen] = useState(false);
2298
+ const [reg, setReg] = useState({ query: '', phase: 'idle', rows: [], error: null });
2299
+ const [bulk, setBulk] = useState({ mode: false, ids: [], busy: null });
2300
+ const pgSeq = useRef(0), regSeq = useRef(0), saveIntent = useRef('saveServer');
2301
+ const client = useRef(null), serial = useRef(0), directoryHeading = useRef(null), detailHeading = useRef(null);
2302
+ const directoryOrigin = useRef(null), editorOrigin = useRef(null), confirmationOrigin = useRef(null), focusTask = useRef(null);
2303
+ const rootRef = useRef(null);
2304
+ const id = useId();
2305
+ usePanelFit(rootRef);
2306
+ useEffect(() => {
2307
+ const requests = createRequests(api, publish);
2308
+ client.current = requests;
2309
+ setEditor(null); setConfirmation(null); setNotice(null); setToolQuery('');
2310
+ setPlayground(null); setIo(null); setTplOpen(false);
2311
+ directoryOrigin.current = null; editorOrigin.current = null; confirmationOrigin.current = null; focusTask.current = null;
2312
+ void requests.readOverview();
2313
+ return () => { requests.dispose(); client.current = null; };
2314
+ }, [api]);
2315
+ useEffect(() => {
2316
+ const task = focusTask.current;
2317
+ if (!task || model.pending || confirmation) return;
2318
+ focusTask.current = null;
2319
+ if (task.node?.isConnected && !task.node.disabled && task.node.getClientRects?.().length !== 0) task.node.focus();
2320
+ else (task.type === 'directory' ? directoryHeading : detailHeading).current?.focus();
2321
+ }, [model.route, model.pending, model.view.data, editor, confirmation]);
2322
+ const data = model.overview.data, route = model.route, current = model.view.data;
2323
+ const stamp = useRef({ data: null, at: 0 });
2324
+ if (stamp.current.data !== data) stamp.current = { data, at: Date.now() };
2325
+ const selected = route ? data?.servers.find(server => server.id === route.id) : null;
2326
+ const inspected = (current?.section !== 'config' ? current?.server : null) ?? selected;
2327
+ const blocked = !data || !!model.pending || model.overview.reading || !!model.overview.error;
2328
+ const navigationLocked = !!model.pending || !!editor || !!confirmation;
2329
+ const open = !!route || !!editor;
2330
+ const fresh = detail => client.current?.ready(data, detail) === true;
2331
+ const reload = () => { setNotice(null); void client.current?.readOverview(); };
2332
+ const chooseServer = (serverId, node) => {
2333
+ if (navigationLocked) return;
2334
+ directoryOrigin.current = node;
2335
+ if (route?.id === serverId) { detailHeading.current?.focus(); return; }
2336
+ focusTask.current = { type: 'detail' };
2337
+ setNotice(null); setToolQuery(''); client.current?.move(serverId);
2338
+ };
2339
+ const chooseSection = section => {
2340
+ if (!navigationLocked && selected && route.section !== section) client.current?.move(selected.id, section);
2341
+ };
2342
+ const back = (node = directoryOrigin.current) => {
2343
+ if (!route) return;
2344
+ focusTask.current = { type: 'directory', node };
2345
+ client.current?.move(null);
2346
+ };
2347
+ const newEditor = (mode, event) => {
2348
+ if (navigationLocked || !fresh(mode === 'edit' ? current : undefined) || (mode === 'create' && data.servers.length >= 32)) return;
2349
+ if (mode === 'edit' && current?.section !== 'config') return;
2350
+ editorOrigin.current = event?.currentTarget;
2351
+ client.current.stopFollowing();
2352
+ setNotice(null);
2353
+ setEditor(makeDraft(mode === 'edit' ? current.server : null, mode === 'edit' ? current.detail : null, data.revision, ++serial.current));
2354
+ };
2355
+ const exitEditor = () => {
2356
+ const type = route ? 'detail' : 'directory';
2357
+ focusTask.current = { type, node: editorOrigin.current };
2358
+ editorOrigin.current = null;
2359
+ setEditor(null);
2360
+ };
2361
+ const patchEditor = patch => setEditor(old => old && ({ ...old, error: null,
2362
+ draft: { ...old.draft, ...(typeof patch === 'function' ? patch(old.draft) : patch) } }));
2363
+ const gone = editor?.mode === 'edit' && !!data && !data.servers.some(server => server.id === editor.draft.id);
2364
+ const stale = !!editor && (editor.conflicted || editor.baseRevision !== data?.revision || gone
2365
+ || (editor.mode === 'edit' && ['conflict', 'detailStale'].includes(model.view.error)));
2366
+ const canSaveDraft = !!editor && !blocked && !stale && !gone && (editor.mode === 'create' || current?.section === 'config');
2367
+ const reOpen = () => {
2368
+ if (!editor || gone || confirmation) return;
2369
+ if (editor.mode === 'create' ? !fresh() : current?.section !== 'config' || !fresh(current)) return;
2370
+ setNotice(null);
2371
+ setEditor(makeDraft(editor.mode === 'edit' ? current.server : null, editor.mode === 'edit' ? current.detail : null,
2372
+ data.revision, ++serial.current));
2373
+ };
2374
+ const ask = (value, event) => {
2375
+ confirmationOrigin.current = event?.nativeEvent?.submitter ?? event?.currentTarget ?? null;
2376
+ setConfirmation(value);
2377
+ };
2378
+ const cancel = () => {
2379
+ const node = confirmationOrigin.current;
2380
+ confirmationOrigin.current = null;
2381
+ focusTask.current = { type: 'detail', node };
2382
+ setConfirmation(null);
2383
+ };
2384
+ const send = (method, input, okayKey, expected, after) => {
2385
+ if (!fresh(expected)) return;
2386
+ setNotice(null);
2387
+ void client.current.run(data, expected, method, input, outcome => {
2388
+ if (outcome.ok && okayKey) setNotice({ key: okayKey });
2389
+ else if (!outcome.ok && method !== 'saveServer' && method !== 'testServer') setNotice({ key: rpcErrorKey(outcome.error), error: true });
2390
+ after?.(outcome);
2391
+ });
2392
+ };
2393
+ const save = (event, approved = false, method = 'saveServer') => {
2394
+ event?.preventDefault();
2395
+ if (!canSaveDraft || (confirmation && !approved) || !fresh(editor.mode === 'edit' ? current : undefined)) return;
2396
+ const { input, error } = saveInput(editor, data.servers);
2397
+ if (error) { setEditor(old => old && ({ ...old, error })); return; }
2398
+ if (editor.beforeApproval && !input.server.requireApproval && !approved) {
2399
+ saveIntent.current = method;
2400
+ ask({ kind: 'server', serial: editor.serial, revision: editor.baseRevision, subject: input.server.name }, event);
2401
+ return;
2402
+ }
2403
+ saveIntent.current = method;
2404
+ send(method, input, method === 'testServer' ? null : 'saved', editor.mode === 'edit' ? current : undefined, outcome => {
2405
+ if (!outcome.ok) {
2406
+ setEditor(old => old?.serial === editor.serial ? { ...old,
2407
+ conflicted: conflictCodes.has(errorCode(outcome.error)), error: rpcErrorKey(outcome.error) } : old);
2408
+ return;
2409
+ }
2410
+ if (method === 'testServer') {
2411
+ setEditor(old => old?.serial === editor.serial
2412
+ ? { ...old, test: outcome.data, error: null, baseRevision: outcome.data?.revision ?? old.baseRevision } : old);
2413
+ return;
2414
+ }
2415
+ editorOrigin.current = null;
2416
+ focusTask.current = { type: 'detail' };
2417
+ setEditor(null);
2418
+ client.current?.move(input.server.id, editor.mode === 'edit' ? 'config' : 'connection');
2419
+ });
2420
+ };
2421
+ const saveAndTest = event => save(event, false, 'testServer');
2422
+ const canUseLiveTool = row => stamped(row) && online(data, inspected) && !inspected.refreshing && current?.section === 'tools';
2423
+ const writableTool = name => {
2424
+ const row = current?.section === 'tools' && current.detail.rows.find(item => item.name === name);
2425
+ return canUseLiveTool(row) && row.writable && name.length <= 256 ? row : null;
2426
+ };
2427
+ const policy = (name, change, event) => {
2428
+ const tool = writableTool(name);
2429
+ if (!tool || confirmation || !fresh(current)) return;
2430
+ const input = { revision: data.revision, id: selected.id, name, stamp: tool.stamp, enabled: tool.enabled, requireApproval: tool.requireApproval, ...change };
2431
+ if (tool.requireApproval && !input.requireApproval) {
2432
+ ask({ kind: 'tool', revision: data.revision, id: selected.id, name, subject: name, input }, event);
2433
+ } else send('setToolPolicy', input, 'toolSaved', current);
2434
+ };
2435
+ const review = (row, event) => {
2436
+ if (!row?.pending || !canUseLiveTool(row) || !fresh(current) || confirmation || model.schemaName !== row.name
2437
+ || !model.schema.data || model.schema.data.truncated || model.schema.data.outputTruncated) return;
2438
+ const input = { revision: data.revision, id: selected.id, name: row.name, stamp: row.stamp };
2439
+ ask({ kind: 'review', revision: data.revision, id: selected.id, name: row.name, subject: row.name, input }, event);
2440
+ };
2441
+ const toolChanged = ['tool', 'review'].includes(confirmation?.kind) && current?.section === 'tools'
2442
+ && current.detail.rows.find(row => row.name === confirmation.name)?.stamp !== confirmation.input.stamp;
2443
+ const confirmStale = !!confirmation && (toolChanged || confirmation.revision !== data?.revision || (confirmation.kind === 'server'
2444
+ ? confirmation.serial !== editor?.serial || stale
2445
+ : confirmation.id !== selected?.id || (confirmation.kind === 'tool' && !!current && !writableTool(confirmation.name))));
2446
+ const confirmRead = confirmation?.kind === 'server' ? undefined : current;
2447
+ const confirmDisabled = blocked || (confirmation?.kind !== 'server' && !current);
2448
+ const accept = () => {
2449
+ if (!confirmation || confirmStale || confirmDisabled || !fresh(confirmRead)) return;
2450
+ const decision = confirmation;
2451
+ cancel();
2452
+ if (decision.kind === 'server') { save(null, true, saveIntent.current); saveIntent.current = 'saveServer'; }
2453
+ else if (decision.kind === 'tool') send('setToolPolicy', decision.input, 'toolSaved', current);
2454
+ else if (decision.kind === 'review') send('reviewTool', decision.input, 'toolReviewOkay', current);
2455
+ else send('removeServer', { id: decision.id, revision: decision.revision }, 'removed', current, outcome => {
2456
+ if (outcome.ok) back();
2457
+ });
2458
+ };
2459
+ const renderConfirm = () => h(Confirm, { t, type: confirmation.kind, subject: confirmation.subject,
2460
+ stale: confirmStale, changedTool: toolChanged, disabled: confirmDisabled, onAccept: accept, onCancel: cancel });
2461
+ const requestConnection = method => {
2462
+ if (!current || !selected || confirmation || !fresh(current) || !data.active || !data.autoConnect || !inspected.enabled || inspected.refreshing) return;
2463
+ if (groupOf(inspected) === 'progress' || (method === 'refresh' && !online(data, inspected))) return;
2464
+ send(method, { id: selected.id, revision: data.revision }, method === 'connect' ? 'requestedConnect' : 'requestedRefresh', current);
2465
+ };
2466
+ const openPlayground = tool => {
2467
+ if (navigationLocked || confirmation || !canUseLiveTool(tool) || !tool.enabled || tool.pending) return;
2468
+ if (playground && playground.name === tool.name) { setPlayground(null); return; }
2469
+ setPlayground({ name: tool.name, stamp: tool.stamp, fields: {}, raw: '{}', phase: 'form', token: null, result: null, error: null });
2470
+ if (model.schemaName !== tool.name) void client.current?.toggleSchema(data, current, tool);
2471
+ };
2472
+ const patchPlay = patch => setPlayground(old => old && ({ ...old, ...(typeof patch === 'function' ? patch(old) : patch) }));
2473
+ const runPlayground = async token => {
2474
+ const pg = playground;
2475
+ if (!pg || pg.phase === 'running' || confirmation || !current || current.section !== 'tools' || !fresh(current)) return;
2476
+ const row = current.detail.rows.find(item => item.name === pg.name);
2477
+ if (!row || row.stamp !== pg.stamp || !row.enabled || row.pending || !online(data, inspected)) return;
2478
+ const info = model.schemaName === pg.name && model.schema.data ? playgroundInfo(model.schema.data.schemaJson) : null;
2479
+ let argsJson;
2480
+ if (info) {
2481
+ const args = {};
2482
+ for (const [key, spec] of Object.entries(info.properties)) {
2483
+ const value = pg.fields[key], type = spec?.type;
2484
+ if (value === undefined || value === '') continue;
2485
+ if (type === 'boolean') { if (value === 'true' || value === 'false') args[key] = value === 'true'; continue; }
2486
+ if (type === 'number') {
2487
+ const parsed = Number(value);
2488
+ if (!Number.isFinite(parsed)) { patchPlay({ error: 'argInvalid' }); return; }
2489
+ args[key] = parsed;
2490
+ continue;
2491
+ }
2492
+ if (type === 'object' || type === 'array') {
2493
+ try { args[key] = JSON.parse(value); } catch { patchPlay({ error: 'argInvalid' }); return; }
2494
+ continue;
2495
+ }
2496
+ args[key] = String(value);
2497
+ }
2498
+ argsJson = JSON.stringify(args);
2499
+ } else {
2500
+ try { JSON.parse(pg.raw); } catch { patchPlay({ error: 'argInvalid' }); return; }
2501
+ argsJson = pg.raw;
2502
+ }
2503
+ const ticket = ++pgSeq.current;
2504
+ patchPlay({ phase: 'running', error: null, result: null });
2505
+ try {
2506
+ const reply = await api.call('invokeTool', { id: selected.id, name: pg.name, stamp: pg.stamp, argsJson,
2507
+ ...(token ? { confirmToken: token } : {}) });
2508
+ if (pgSeq.current !== ticket) return;
2509
+ setPlayground(old => {
2510
+ if (!old || old.name !== pg.name || old.stamp !== pg.stamp) return old;
2511
+ if (reply?.approvalRequired === true) return { ...old, phase: 'confirm', token: reply.confirmToken, error: null };
2512
+ if (reply?.approvalRequired === false) return { ...old, phase: 'result', result: reply, error: null };
2513
+ return { ...old, phase: 'form', error: 'failed' };
2514
+ });
2515
+ } catch (error) {
2516
+ if (pgSeq.current !== ticket) return;
2517
+ patchPlay({ phase: 'form', error: rpcErrorKey(error) });
2518
+ }
2519
+ };
2520
+ const cloneServer = async server => {
2521
+ if (navigationLocked || confirmation || editor || !fresh()) return;
2522
+ try {
2523
+ const reply = await api.call('getServer', { id: server.id, section: 'config' });
2524
+ if (!client.current?.ready(data) || navigationLocked || confirmation || editor) return;
2525
+ if (reply?.section !== 'config' || !reply.detail) return;
2526
+ const draft = makeDraft(null, reply.detail, data.revision, ++serial.current);
2527
+ draft.draft.id = cloneId(server.id, data.servers.map(item => item.id));
2528
+ draft.draft.name = (server.name || server.id) + t('cloneSuffix');
2529
+ draft.draft.transport = reply.server?.transport ?? server.transport;
2530
+ draft.draft.enabled = false;
2531
+ draft.draft.requireApproval = reply.server?.requireApproval !== false;
2532
+ editorOrigin.current = null;
2533
+ focusTask.current = { type: 'detail' };
2534
+ client.current.stopFollowing();
2535
+ setNotice(null);
2536
+ setEditor(draft);
2537
+ } catch (error) { setNotice({ key: rpcErrorKey(error), error: true }); }
2538
+ };
2539
+ const openTemplate = template => {
2540
+ if (navigationLocked || !fresh() || data.servers.length >= 32) return;
2541
+ editorOrigin.current = null;
2542
+ focusTask.current = { type: 'detail' };
2543
+ client.current.stopFollowing();
2544
+ setNotice(null);
2545
+ setTplOpen(false);
2546
+ const draft = makeDraft(null, null, data.revision, ++serial.current);
2547
+ draft.draft.transport = template.transport;
2548
+ if (template.url) draft.draft.url = template.url; else draft.draft.command = template.command;
2549
+ draft.draft.name = template.label;
2550
+ setEditor(draft);
2551
+ };
2552
+ const exportNow = mode => {
2553
+ if (!fresh() || navigationLocked) return;
2554
+ void client.current.run(data, undefined, 'exportConfig', { mode }, outcome => {
2555
+ if (!outcome.ok) { setNotice({ key: rpcErrorKey(outcome.error), error: true }); return; }
2556
+ const reply = outcome.data;
2557
+ downloadText(reply.filename, reply.contentJson);
2558
+ setNotice({ key: 'exported', text: t('exported').replace('{n}', number(t, reply.servers)) });
2559
+ setIo(old => old && ({ ...old, phase: 'panel', result: { filename: reply.filename, contentJson: reply.contentJson, redacted: reply.redacted }, copied: false }));
2560
+ });
2561
+ };
2562
+ const runImport = () => {
2563
+ const draft = io;
2564
+ if (!draft?.text.trim() || !fresh() || navigationLocked) return;
2565
+ try { const parsed = JSON.parse(draft.text.replace(/^\uFEFF/, '')); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('bad'); } catch { setIo(old => old && ({ ...old, error: 'importJson' })); return; }
2566
+ void client.current.run(data, undefined, 'importConfig', { revision: data.revision, contentJson: draft.text, mode: draft.mode }, outcome => {
2567
+ if (!outcome.ok) { setNotice({ key: rpcErrorKey(outcome.error), error: true }); return; }
2568
+ setIo(old => old && ({ ...old, phase: 'panel', importResult: outcome.data, error: null }));
2569
+ });
2570
+ };
2571
+ const startImport = () => {
2572
+ const draft = io;
2573
+ if (!draft?.text.trim() || navigationLocked) return;
2574
+ if (draft.mode === 'replace') { setIo(old => old && ({ ...old, phase: 'confirm-import', error: null })); return; }
2575
+ runImport();
2576
+ };
2577
+ const copyExport = async () => {
2578
+ if (!io?.result || typeof navigator?.clipboard?.writeText !== 'function') return;
2579
+ try { await navigator.clipboard.writeText(io.result.contentJson); setIo(old => old && ({ ...old, copied: true })); }
2580
+ catch { setNotice({ key: 'failed', error: true }); }
2581
+ };
2582
+ const selectImportFile = async file => {
2583
+ const ticket = ++serial.current;
2584
+ const patch = value => setIo(old => old?.fileTicket === ticket ? { ...old, ...value } : old);
2585
+ setIo(old => old && ({ ...old, text: '', filename: null, fileTicket: ticket, fileReading: true, error: null, importResult: null }));
2586
+ if (file.size > 160000) { patch({ fileReading: false, error: 'importFileLarge' }); return; }
2587
+ try {
2588
+ const text = await file.text();
2589
+ patch({ text, filename: file.name, fileReading: false });
2590
+ } catch { patch({ fileReading: false, error: 'importFileFailed' }); }
2591
+ };
2592
+ const ioApi = {
2593
+ toggle: () => setIo(old => old ? null : { phase: 'panel', text: '', mode: 'merge', result: null, importResult: null, copied: false, error: null }),
2594
+ onText: value => setIo(old => old && ({ ...old, text: value, error: null, filename: null, fileTicket: null, fileReading: false })),
2595
+ onFile: selectImportFile,
2596
+ onMode: mode => setIo(old => old && ({ ...old, mode })),
2597
+ onExport: () => exportNow('redacted'),
2598
+ onExportFull: () => setIo(old => old && ({ ...old, phase: 'confirm-export', error: null })),
2599
+ onImport: startImport,
2600
+ onAcceptExport: () => exportNow('full'),
2601
+ onAcceptImport: runImport,
2602
+ onCancel: () => setIo(old => old && ({ ...old, phase: 'panel' })),
2603
+ onCopy: copyExport,
2604
+ };
2605
+ const configureHealth = input => send('healthConfig', input, 'healthSaved', undefined);
2606
+ const toggleBulk = () => setBulk(old => ({ mode: !old.mode, ids: [], busy: null }));
2607
+ const bulkToggle = id => setBulk(old => ({ ...old, ids: old.ids.includes(id) ? old.ids.filter(item => item !== id) : [...old.ids, id] }));
2608
+ // Sequential fleet mutations with fresh revisions; a conflict stops the
2609
+ // batch and reports the partial result instead of failing silently.
2610
+ const bulkRun = async method => {
2611
+ if (!fresh() || bulk.busy || !bulk.ids.length || navigationLocked || confirmation) return;
2612
+ const enabled = method === 'bulkEnable' ? true : method === 'bulkDisable' ? false : undefined;
2613
+ setBulk(old => ({ ...old, busy: method }));
2614
+ setNotice(null);
2615
+ let revision = data.revision, done = 0, failed = 0;
2616
+ for (const id of bulk.ids) {
2617
+ const row = data.servers.find(server => server.id === id);
2618
+ if (!row) { failed++; continue; }
2619
+ try {
2620
+ if (method === 'bulkConnect') {
2621
+ if (!row.enabled) { failed++; continue; }
2622
+ await api.call('connect', { id, revision: data.revision });
2623
+ } else {
2624
+ if (row.enabled === enabled) { done++; continue; }
2625
+ await api.call('setServerEnabled', { id, revision, enabled });
2626
+ revision += 1;
2627
+ }
2628
+ done++;
2629
+ } catch { failed++; break; }
2630
+ }
2631
+ setBulk(old => ({ ...old, busy: null, ids: failed ? old.ids : [] }));
2632
+ if (done) setNotice({ key: 'bulkDone', text: t('bulkDone').replace('{n}', number(t, done)) });
2633
+ if (failed) setNotice({ key: 'bulkPartial', error: true });
2634
+ void client.current?.readOverview();
2635
+ };
2636
+ const searchRegistry = async () => {
2637
+ const q = reg.query.trim();
2638
+ if (!q || reg.phase === 'busy' || navigationLocked) return;
2639
+ setReg(old => ({ ...old, phase: 'busy', rows: [], error: null }));
2640
+ const ticket = ++regSeq.current;
2641
+ try {
2642
+ const reply = await api.call('registrySearch', { query: q.slice(0, 100) });
2643
+ if (regSeq.current !== ticket) return;
2644
+ setReg(old => ({ ...old, phase: reply?.unreachable ? 'unreachable' : 'done', reason: reply?.reason ?? null, rows: reply?.servers ?? [], error: null }));
2645
+ } catch (error) {
2646
+ if (regSeq.current !== ticket) return;
2647
+ setReg(old => ({ ...old, phase: 'error', error: rpcErrorKey(error, 'registryFailed') }));
2648
+ }
2649
+ };
2650
+ const pickRegistry = entry => {
2651
+ if (!entry || navigationLocked || !fresh() || data.servers.length >= 32) return;
2652
+ editorOrigin.current = null;
2653
+ focusTask.current = { type: 'detail' };
2654
+ client.current.stopFollowing();
2655
+ setNotice(null);
2656
+ setRegOpen(false);
2657
+ const draft = makeDraft(null, null, data.revision, ++serial.current);
2658
+ draft.draft.transport = entry.transport;
2659
+ if (entry.transport === 'stdio') {
2660
+ draft.draft.command = entry.command ?? '';
2661
+ draft.draft.argsText = JSON.stringify(entry.args ?? []);
2662
+ } else draft.draft.url = entry.url ?? '';
2663
+ draft.draft.name = (entry.name.includes('/') ? entry.name.slice(entry.name.lastIndexOf('/') + 1) : entry.name).slice(0, 80);
2664
+ draft.draft.headers = (entry.headerNames ?? []).map((name, index) => ({ key: 'reg-h-' + index, name, value: '', keep: false, saved: false }));
2665
+ draft.draft.env = (entry.envNames ?? []).map((name, index) => ({ key: 'reg-e-' + index, name, value: '', keep: false, saved: false }));
2666
+ draft.registryName = entry.name;
2667
+ draft.draft.enabled = false;
2668
+ setEditor(draft);
2669
+ };
2670
+ const renderSection = response => {
2671
+ const { section, server, detail } = response;
2672
+ const locked = blocked || !!confirmation;
2673
+ if (section === 'connection') return h(Connection, { t, data, server, detail, locked,
2674
+ onConnect: () => requestConnection('connect'), onRefresh: () => requestConnection('refresh'), onEnable: enabled => {
2675
+ if (!confirmation) send('setServerEnabled', { id: selected.id, revision: data.revision, enabled }, enabled ? 'enabled' : 'disabled', response);
2676
+ } });
2677
+ if (section === 'tools') return h(Tools, { key: selected.id, t, detail, query: toolQuery, setQuery: setToolQuery, locked, sectionLive: online(data, server), refreshing: server.refreshing,
2678
+ schemaName: model.schemaName, schema: model.schema, confirmation, renderConfirm, onRefresh: () => requestConnection('refresh'), onPolicy: policy, onReview: review,
2679
+ playground, onPlayground: openPlayground, onPlayField: (key, value) => patchPlay(old => old && ({ ...old, fields: { ...old.fields, [key]: value } })),
2680
+ onPlayRaw: value => patchPlay(old => old && ({ ...old, raw: value })), onPlayRun: () => runPlayground(null),
2681
+ onPlayAccept: () => runPlayground(playground.token), onPlayCancel: () => patchPlay({ phase: 'form', error: null }),
2682
+ onSchema: name => {
2683
+ const tool = detail.rows.find(row => row.name === name);
2684
+ if (!confirmation && canUseLiveTool(tool)) void client.current?.toggleSchema(data, response, tool);
2685
+ } });
2686
+ if (section === 'activity') return h(Activity, { t, active: data.active, detail });
2687
+ if (section === 'resources') return h(ResourcesPanel, { key: selected.id, t, serverId: selected.id, detail, live: online(data, inspected), locked, api });
2688
+ if (section === 'prompts') return h(PromptsPanel, { key: selected.id, t, serverId: selected.id, detail, live: online(data, inspected), locked, api });
2689
+ if (section === 'logs') return h(LogsPanel, { key: selected.id, t, serverId: selected.id, detail,
2690
+ local: server.transport === 'stdio', live: online(data, server),
2691
+ retrying: ['reconnecting', 'connecting'].includes(server.status), locked, api });
2692
+ return h(Config, { t, server, detail, locked, busy: model.pending === 'setServerTags',
2693
+ onEdit: event => newEditor('edit', event), onTags: tags => send('setServerTags', { id: server.id, revision: data.revision, tags }, 'tagsSaved', response), onRemove: event => {
2694
+ if (fresh(response) && !confirmation) ask({ kind: 'remove', revision: data.revision, id: server.id, subject: displayName(server) }, event);
2695
+ }, confirmation: confirmation?.kind === 'remove' ? renderConfirm() : null });
2696
+ };
2697
+ const addBlocked = blocked || navigationLocked || (data?.servers.length ?? 0) >= 32;
2698
+ const toggleTag = tag => setTagFilter(old => old.includes(tag) ? old.filter(item => item !== tag) : [...old, tag]);
2699
+ const refreshed = data ? updated(t, stamp.current.at) : null;
2700
+ const aggregate = model.aggregate.data;
2701
+ // The dashboard is the default no-selection view; a failing or not-ready
2702
+ // aggregate degrades to the plain directory instead of empty bricks.
2703
+ const dash = aggregate?.runtimeReady === true && !route && !editor ? aggregate : null;
2704
+ const metaParts = [];
2705
+ if (data) {
2706
+ const tally = { online: 0, fault: 0, progress: 0, offline: 0, disabled: 0 };
2707
+ for (const server of data.servers) tally[groupOf(server)]++;
2708
+ const sep = localeOf(t) === 'zh-CN' ? ',' : ', ';
2709
+ for (const item of ['online', 'fault', 'progress', 'offline', 'disabled']) {
2710
+ if (!tally[item]) continue;
2711
+ if (metaParts.length) metaParts.push(sep);
2712
+ metaParts.push(h('span', { className: 'mwb-meta-count', key: item },
2713
+ h('i', { className: 'mwb-dot', 'data-tone': item, 'aria-hidden': true }),
2714
+ t('meta.' + item).replace('{n}', number(t, tally[item]))));
2715
+ }
2716
+ if (metaParts.length) metaParts.push(sep);
2717
+ metaParts.push(h('span', { key: 'updated' }, refreshed));
2718
+ }
2719
+ // Heartbeat samples come from the persisted stats read; servers without a
2720
+ // ledger entry simply render an idle strip.
2721
+ const beats = new Map((model.stats.data?.servers ?? []).map(row => [row.id, row.recent]));
2722
+ const drawer = regOpen ? 'registry' : tplOpen ? 'templates' : io ? 'io' : null;
2723
+ const closeDrawer = () => { setRegOpen(false); setTplOpen(false); setIo(null); };
2724
+ const drawerBusy = model.pending === 'exportConfig' || model.pending === 'importConfig';
2725
+ return h('div', { className: 'mwb', ref: rootRef }, h('style', null, styles),
2726
+ h('div', { className: 'mwb-shell', 'data-pane': open ? 'detail' : 'directory' },
2727
+ h('div', { className: 'mwb-console-top' },
2728
+ h('header', { className: 'mwb-header' },
2729
+ h('div', { className: 'mwb-title-block' }, h('h1', { className: 'mwb-title' }, h(PanelIcon), t('title')),
2730
+ data && h('p', { className: 'mwb-header-meta' }, metaParts)),
2731
+ h('div', { className: 'mwb-actions' },
2732
+ h(Button, { icon: 'reload', disabled: !!model.pending || model.overview.reading, onClick: reload }, t('reload')),
2733
+ h(Button, { disabled: navigationLocked || !!drawer && drawer !== 'io', 'aria-expanded': drawer === 'io', onClick: () => { if (io) closeDrawer(); else ioApi.toggle(); } }, t('io')),
2734
+ h(Button, { disabled: addBlocked || !!drawer && drawer !== 'registry', 'aria-expanded': drawer === 'registry', onClick: () => { if (regOpen) closeDrawer(); else { setTplOpen(false); setIo(null); setRegOpen(true); } } }, t('registryOpen')),
2735
+ h(Button, { disabled: addBlocked || !!drawer && drawer !== 'templates', 'aria-expanded': drawer === 'templates', onClick: () => { if (tplOpen) closeDrawer(); else { setRegOpen(false); setIo(null); setTplOpen(true); } } }, t('templateOpen')),
2736
+ h(Button, { className: 'mwb-header-add', kind: 'primary', icon: 'add', disabled: addBlocked || !!drawer,
2737
+ onClick: event => { closeDrawer(); newEditor('create', event); } }, t('add')))),
2738
+ data && h(Distribution, { t, servers: data.servers, group, setGroup })),
2739
+ h('div', { className: 'mwb-messages' },
2740
+ model.overview.error && h(Notice, { alert: true, tone: 'error' }, h('p', null, t(model.overview.error)),
2741
+ data && h('p', { className: 'mwb-hint' }, t('oldSnapshot'))),
2742
+ model.pending ? h(Notice, null, t('busy')) : model.overview.reading && h(Notice, null, t('loading')),
2743
+ data && !model.overview.error && !data.active && h(Notice, { tone: 'warn' }, t('runtimeOff')),
2744
+ data && !model.overview.error && !data.autoConnect && h(Notice, { tone: 'warn' }, t('masterOff')),
2745
+ notice && h(Notice, { alert: notice.error, tone: notice.error ? 'error' : undefined }, notice.text ?? t(notice.key))),
2746
+ !data && !model.overview.error && h(Skeleton, { rows: 5 }),
2747
+ data && h('div', { className: 'mwb-grid', 'data-open': open, 'data-editing': !!editor, 'data-dash': !!dash || undefined },
2748
+ h(Directory, { t, data, selected, headingRef: directoryHeading, panelId: id, query, setQuery, sort, setSort, group, tags: tagFilter, onTag: toggleTag,
2749
+ reset: () => { setQuery(''); setGroup('all'); setTagFilter([]); }, locked: navigationLocked, editing: !!editor,
2750
+ onSelect: chooseServer, onAdd: addBlocked ? undefined : event => newEditor('create', event), onClone: cloneServer, beats,
2751
+ bulk, onBulkMode: toggleBulk, onBulkToggle: bulkToggle, onBulkRun: bulkRun }),
2752
+ editor ? h(Editor, { key: editor.serial, id, t, editor, patch: patchEditor, locked: !!model.pending || !!confirmation,
2753
+ saving: model.pending === 'saveServer', testing: model.pending === 'testServer', canSave: canSaveDraft, stale, gone,
2754
+ canReopen: !blocked && !confirmation && (editor.mode === 'create' || current?.section === 'config'),
2755
+ confirmation: confirmation?.kind === 'server' ? renderConfirm() : null, onSave: save, onTest: saveAndTest, onExit: exitEditor, onReopen: reOpen })
2756
+ : route || dash ? (route ? h(Detail, { t, id, server: inspected, open: !!route, headingRef: detailHeading, section: route?.section,
2757
+ read: model.view, blocked, navigationLocked, onBack: () => back(), onSection: chooseSection,
2758
+ onRetry: () => { if (model.view.error === 'detailStale') reload(); else void client.current?.readView(); }, render: renderSection })
2759
+ : h(Dashboard, { t, data, aggregate, stats: model.stats, health: model.health, healthBusy: model.pending === 'healthConfig', onHealth: configureHealth })) : null,
2760
+ confirmation && confirmation.kind !== 'server' && !current && h('div', { className: 'mwb-pane-body' }, renderConfirm()),
2761
+ ),
2762
+ h(StatusBar, { t, data, aggregate: model.aggregate, locked: navigationLocked, refreshed }),
2763
+ // The drawer lives inside the shell so it inherits the shell's color tokens.
2764
+ drawer && data && h(Drawer, { t, title: t(drawer === 'registry' ? 'registryOpen' : drawer === 'templates' ? 'templateOpen' : 'io'), onClose: closeDrawer },
2765
+ drawer === 'registry' ? h(RegistryPanel, { t, reg, onQuery: value => setReg(old => ({ ...old, query: value })),
2766
+ onSearch: () => void searchRegistry(), onPick: pickRegistry, disabled: navigationLocked || (data.servers.length ?? 0) >= 32 })
2767
+ : drawer === 'templates' ? h('div', { className: 'mwb-templates', role: 'group', 'aria-label': t('templates') },
2768
+ h('p', { className: 'mwb-hint' }, t('templateHint')),
2769
+ h('ul', { className: 'mwb-template-list', role: 'list' }, TEMPLATES.map(template => h('li', { key: template.key },
2770
+ h(Button, { kind: 'quiet', 'aria-label': t('templateOpen') + ': ' + template.label, disabled: navigationLocked,
2771
+ onClick: () => openTemplate(template) }, h('span', { className: 'mwb-tpl-label' }, template.label),
2772
+ h('span', { className: 'mwb-hint mwb-tech' }, template.url ?? template.command)),
2773
+ h('span', { className: 'mwb-hint' }, t(template.hint))))))
2774
+ : h(IoPanel, { t, io, busy: drawerBusy, ...ioApi }))));
2775
+ }
2776
+
2777
+
2778
+ return { Page, PanelIcon, locale: { zh, en } };
2779
+ }
2780
+
2781
+ /* src/workbench/client-entry.js */
2782
+
2783
+ const LOCALE = 'localMcpWorkbench'
2784
+ const COPY = {
2785
+ zh: {
2786
+ openWorkbench: '打开管理面板', unconnected: '未连接到管理服务。请重新打开页面或检查引擎。',
2787
+ forbidden: '仅主机所有者可管理 MCP 服务器。', invalidInput: '请检查表单中的必填项和格式。',
2788
+ },
2789
+ en: {
2790
+ openWorkbench: 'Open workbench', unconnected: 'The management service is unavailable. Reopen the page or check the engine.',
2791
+ forbidden: 'Only the host owner can manage MCP servers.', invalidInput: 'Check required fields and formatting.',
2792
+ 'error.REVISION_CONFLICT': 'The settings changed since you opened this form.',
2793
+ 'error.SERVER_NOT_FOUND': 'This server no longer exists. Reload the list.',
2794
+ 'error.SERVER_EXISTS': 'That server ID is in use.',
2795
+ 'error.SERVER_LIMIT': 'You can configure up to 32 servers.',
2796
+ 'error.PAIR_NOT_FOUND': 'A saved field no longer exists. Reopen the form.',
2797
+ 'error.TARGET_CHANGED_WITH_CREDENTIALS': 'Remove or replace retained credentials before changing the connection target.',
2798
+ 'error.TOOL_NOT_FOUND': 'This tool is no longer in the current catalog.',
2799
+ 'error.TOOL_CHANGED': 'The tool definition changed. Reopen it before applying a policy.',
2800
+ 'error.AUTO_CONNECT_DISABLED': 'MCP connections are turned off on this host.',
2801
+ 'error.RUNTIME_NOT_READY': 'The connection runtime is not ready.',
2802
+ 'error.SERVER_DISABLED': 'Enable this server before connecting.',
2803
+ 'error.VAULT_UNAVAILABLE': 'The credential store is not available on this host.',
2804
+ 'error.CREDENTIAL_WRITE_FAILED': 'The credential could not be stored. The original configuration was kept.',
2805
+ 'error.INTERNAL': 'The operation did not finish. Reload to check the state before retrying.',
2806
+ 'error.INVALID_INPUT': 'Check required fields and formatting.',
2807
+ },
2808
+ }
2809
+ const actionError = (code, message) => Object.assign(new Error(message), { code })
2810
+
2811
+ function createClientPlugin(React, loadZod, uiFactory = createUi) {
2812
+ const h = React.createElement
2813
+ const { Page, PanelIcon, locale } = uiFactory(React)
2814
+ async function apply(ctx) {
2815
+ ctx.effect(() => ctx.locale.register(LOCALE, {
2816
+ zh: { ...locale.zh, ...COPY.zh }, en: { ...locale.en, ...COPY.en },
2817
+ }), 'MCP workbench: dictionaries')
2818
+ const t = ctx.locale.bind(LOCALE)
2819
+ let unmount, ready = false
2820
+ try {
2821
+ // The client mount creates remote.<namespace>. Requiring that namespace
2822
+ // in inject would deadlock the entire Web shell before apply can run.
2823
+ unmount = await ctx.remote.$mount(createContract(loadZod()).client)
2824
+ ready = true
2825
+ } catch {
2826
+ ctx.logger?.warn?.('MCP workbench: browser RPC registration unavailable')
2827
+ }
2828
+ const call = async (method, input) => {
2829
+ if (!METHODS.includes(method)) throw actionError('INVALID_INPUT', t('invalidInput'))
2830
+ const remote = ready ? ctx.get(`remote.${NAMESPACE}`) : undefined
2831
+ if (typeof remote?.[method] !== 'function') throw actionError('UNAVAILABLE', t('unconnected'))
2832
+ let reply
2833
+ try {
2834
+ // Parameterless wire methods (overview, aggregate, healthStatus) must be
2835
+ // invoked without an argument; the gateway rejects surplus arguments.
2836
+ reply = input === undefined ? await remote[method]() : await remote[method](input)
2837
+ } catch { throw actionError('UNAVAILABLE', t('unconnected')) }
2838
+ if (!reply?.ok) {
2839
+ const code = reply?.error?.code
2840
+ if (code === 'remote-access/denied') throw actionError('FORBIDDEN', t('forbidden'))
2841
+ if (code === 'gateway/input-invalid' || code === 'gateway/arguments-invalid') throw actionError('INVALID_INPUT', t('invalidInput'))
2842
+ throw actionError('UNAVAILABLE', t('unconnected'))
2843
+ }
2844
+ const result = reply.value
2845
+ if (result?.ok === true) return result.data
2846
+ const code = result?.code ?? 'INTERNAL'
2847
+ if (code === 'FORBIDDEN') throw actionError(code, t('forbidden'))
2848
+ const key = `error.${code}`, translated = t(key)
2849
+ throw actionError(code, translated && translated !== key ? translated : result?.message || t('unconnected'))
2850
+ }
2851
+ const api = Object.freeze({ call })
2852
+ const label = () => t('nav')
2853
+ function OpenWorkbench({ subject }) {
2854
+ if (subject?.kind !== 'bundle' || subject.pkg?.name !== PACKAGE) return null
2855
+ const layout = ctx.get('layout')
2856
+ if (!layout) return null
2857
+ return h('button', { type: 'button',
2858
+ style: { color: 'var(--dsw-alias-label-primary)', background: 'transparent', font: 'inherit',
2859
+ border: '1px solid var(--dsw-alias-border-l2)', borderRadius: '6px', padding: '6px 12px', cursor: 'pointer' },
2860
+ onClick: () => layout.selectPanel(PANEL_ID),
2861
+ }, t('openWorkbench'))
2862
+ }
2863
+ const seats = ctx.inject(['remoteAccess'], child => {
2864
+ return child.remoteAccess.whenAccess(`${NAMESPACE}/overview`, function* () {
2865
+ yield child.slots.inject('sidebar.panellist', () => child.slots.register({
2866
+ name: 'sidebar.panellist', id: PANEL_ID, order: 6, label, locale: LOCALE,
2867
+ }, PanelIcon))
2868
+ yield child.slots.inject('main', () => child.slots.register({
2869
+ name: 'main', key: PANEL_ID, locale: LOCALE, inject: () => ({ api }),
2870
+ }, Page))
2871
+ yield child.slots.inject('plugins.detail.actions', () => child.slots.register({
2872
+ name: 'plugins.detail.actions', id: PANEL_ID, locale: LOCALE,
2873
+ }, OpenWorkbench))
2874
+ })
2875
+ })
2876
+ return async () => {
2877
+ ready = false
2878
+ await seats.dispose()
2879
+ await unmount?.()
2880
+ }
2881
+ }
2882
+ return { inject: ['slots', 'locale', 'remote'], apply }
2883
+ }
2884
+
2885
+ return createClientPlugin(require('react'), () => require('zod').z)
2886
+ },
2887
+ })