dsh-project-mcp 0.3.1 → 0.4.1

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.
package/lib/client.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["en","zh","ru","en","translateOf","fallbackTranslate","BORDER","STYLE","useState","useCallback","h","h","STYLE","EN","translateOf","fallbackTranslate","STYLE","useState","h","useCallback","useRef","useMemo","useSyncExternalStore","h","STYLE","useState","EN","viewEn","configEn","useState","useState","h","STYLE","h","useState","translateOf","translateOf","h","STYLE","useState","hostZh","hostEn","hostRu","hostZh","hostEn","hostRu","createElement"],"sources":["../src/shared.ts","../src/client/locales/host.ts","../src/types.ts","../src/client/policy.ts","../src/client/usage-view.ts","../src/client/view.ts","../src/client/settings-tools.ts","../src/client/settings.ts","../src/client/plugin-config.ts","../src/client/locales/ui.ts","../src/client/tab-locale.ts","../src/client/sidebar-tab.ts","../src/client/toasts.ts","../src/client/design-fixtures.ts","../src/client/design.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Contract shared by the host half and the browser half of the panel.\n *\n * Import-free on purpose: the client bundle must not pull host code in, and the\n * right sidebar exists only in the browser half, so the two halves meet at these\n * routes over HTTP.\n *\n * @module dsh-project-mcp/shared\n */\n\nimport type { ConflictChoice, EntrySnapshot, ToolMode } from './types.ts'\n\n/** Route prefix the host serves and the sidebar panel fetches. */\nexport const ROUTE_PREFIX = '/project-mcp'\n\n/** Sidebar tab id; also the `SidebarTab.type` the panel opens as. */\nexport const TAB_ID = 'dsh-project-mcp:servers'\n\n/** Plugin name, shared by both halves. */\nexport const PACKAGE_NAME = 'dsh-project-mcp'\n\n/** Actions the host serves under {@link ROUTE_PREFIX}, and the panel fetches. */\nexport const ROUTE_ACTIONS = {\n /** `GET`: the current snapshot. */\n snapshot: 'snapshot',\n /** `POST`: ask for a rescan; answers as soon as the request is accepted. */\n sync: 'sync',\n /** `POST`: drop this project's failed mounts and re-mount them; answers once they are dropped. */\n retry: 'retry',\n /** `GET`: the status channel — one pushed frame per change, held open. */\n events: 'events',\n /** `GET`: one page of a project's log ring, oldest first, for \"show older\". */\n logs: 'logs',\n /**\n * `GET`: one tool's detail — its description, its accepted fields, its\n * measured size and the reason it is not offered — read once per opened row\n * so that neither the snapshot nor a change frame carries it.\n */\n tool: 'tool',\n /** `POST`: release this session's mounts. */\n release: 'release',\n /** `POST`: write one edited entry back to its declaring document. */\n save: 'save',\n /** `POST`: pin or unpin one tool of one project. */\n pin: 'pin',\n /** `POST`: set one project's tool mode. */\n policy: 'policy',\n /** `POST`: choose which declaration of a contested `serverName` shows. */\n conflict: 'conflict',\n} as const\n\n/**\n * One operator request: the body of `POST sync` and `POST retry`.\n *\n * `projectRoot` scopes the action, so a surface that shows one project never\n * starts or restarts a server for another. `full` is the answer shape: a\n * single-project surface leaves it out and gets that project's slice back, while\n * a surface that lists every project — the settings page — asks for the whole\n * snapshot, since narrowing would empty the list it renders.\n */\nexport interface OperatorRequest {\n /** Project the action applies to; omitted covers every project. */\n readonly projectRoot?: string\n /** Answer with the whole snapshot rather than `projectRoot`'s slice. */\n readonly full?: boolean\n}\n\n/** Pin or unpin one tool of one project. */\nexport interface PinRequest {\n /** Project root the tool belongs to. */\n readonly projectRoot: string\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly tool: string\n /** `true` pins it, `false` unpins it. */\n readonly pinned: boolean\n}\n\n/** Set one project's tool mode. Pins travel in their own request. */\nexport interface PolicyRequest {\n /** Project root the mode applies to. */\n readonly projectRoot: string\n /** The mode to store. */\n readonly mode: ToolMode\n}\n\n/**\n * Choose which declaration of one contested `serverName` a project shows.\n *\n * The name stays the profile's either way; the answer decides whether the\n * project's own entry mounts beside it under a local namespace. The name is\n * carried as declared — the sanitized `mcpServers` key — because that is what\n * the conflict report names, and the local name is the plugin's to compute.\n */\nexport interface ConflictRequest {\n /** Project root the name belongs to. */\n readonly projectRoot: string\n /** Contested `serverName`, as the project declared it. */\n readonly server: string\n /** The declaration to show. */\n readonly choice: ConflictChoice\n}\n\n/**\n * One entry a save writes.\n *\n * The panel submits the {@link EntrySnapshot} it was given, with the fields the\n * user changed. A masked `env`/`headers` key submitted without a `value` keeps\n * whatever the document declares for it; a key the submission omits is removed.\n */\nexport interface SaveRequest {\n /** Project root the edited row belongs to. */\n readonly projectRoot: string\n /** `serverName` being edited. */\n readonly server: string\n /** Absolute path of the document the entry came from. */\n readonly document: string\n /** `documentRevision` the edit was built from; a mismatch refuses the write. */\n readonly revision: string\n /** `true` acknowledges a write to the global tier; required only there. */\n readonly consent?: boolean\n /** The entry body to write. */\n readonly entry: EntrySnapshot\n}\n\n/** Error codes a save answers with, each with its own sentence in the panel. */\nexport type SaveErrorCode =\n /** The entry is not one this plugin would mount; nothing was written. */\n | 'invalid'\n /** The document may not be written: profile, `<DSH_HOME>`, or no consent. */\n | 'blocked'\n /** The document changed since the snapshot was taken; nothing was written. */\n | 'conflict'\n /** The document or the server is no longer there. */\n | 'not-found'\n /** The write itself failed; the document is left as it was. */\n | 'failed'","/**\n * The `projectMcp.host` namespace: the wire contract for every message the\n * plugin's host half produces that a human can read (F-48).\n *\n * Host messages travel as `{ code, params, message }` — a dotted, stable code\n * plus its flat params for translation, and the English `message` always\n * present as the fallback. The keys below are the contract: a code, once\n * shipped, is never renamed, and rewording happens in dictionary values only.\n * That is why this namespace is separate from `settings.projectMcp`, whose\n * camelCase copy is reworded freely.\n *\n * The tables are declared `Record<HostCode, string>`, so the compiler reads\n * every code of the union off each literal and a table that lacks one does not\n * build — the same gate F-46 put on the UI namespace. The `en` values\n * duplicate the emission-time English messages on purpose: intentional\n * redundancy across a wire, not drift (the table serves the harness's own\n * fallback chain, the payload's `message` field serves old clients and the\n * resolver's last step). `tests/host-resolve.spec.ts` asserts the two are\n * byte-identical where a test can see both.\n *\n * The `zh` and `ru` tables reuse the F-46 terminology of `./ui.ts`\n * (deployment → 部署 / установка, document → 文档 / документ) and,\n * like it, are maintainer-authored and pending review.\n *\n * @module src/client/locales/host\n */\n\nimport type { TabLocale } from '../tab-locale.ts'\nimport type { Translate } from '../view.ts'\n\n/** Locale namespace the host's coded messages are registered under. */\nexport const NS_HOST = 'projectMcp.host'\n\n/**\n * Every wire code the host half can emit. The union grows per task of F-48;\n * the tables below are what force per-commit completeness. Each code carries a\n * one-line comment naming the channel that emits it.\n */\nexport type HostCode =\n | 'write.blocked.notConfigured'\n | 'write.blocked.notWritable'\n | 'write.blocked.globalDisabled'\n // The parse channel (Task 2): parseDocument's diagnostics, plus the runtime's\n // multi-document merge warning — the code the client compares, never the prose.\n | 'parse.json.invalid'\n | 'parse.doc.notObject'\n | 'parse.server.duplicateName'\n | 'parse.server.badName'\n | 'parse.server.renamedName'\n | 'parse.server.multiDocument'\n | 'parse.entry.notObject'\n | 'parse.entry.badType'\n | 'parse.entry.typeUnknown'\n | 'parse.entry.noCommand'\n | 'parse.entry.badArgs'\n | 'parse.entry.badEnv'\n | 'parse.entry.badCwd'\n | 'parse.entry.noUrl'\n | 'parse.entry.badHeaders'\n | 'parse.ref.empty'\n | 'parse.ref.inputUnset'\n | 'parse.ref.varUnset'\n | 'parse.ref.failedInKey'\n // The lifecycle channel (Task 3): the five logLifecycle events, the two\n // sharing phrases `mount.starting` nests two-level, the twelve unmount\n // reasons `unmounting` nests, and the four idle row details.\n | 'mount.starting'\n | 'mount.sharingShared'\n | 'mount.sharingForwarded'\n | 'mount.failed'\n | 'mount.failedDetail'\n | 'mount.up'\n | 'mount.stalled'\n | 'mount.stalledDetail'\n | 'unmounting'\n | 'unmount.reason.operatorRetry'\n | 'unmount.reason.unloading'\n | 'unmount.reason.sessionGone'\n | 'unmount.reason.sessionUnlisted'\n | 'unmount.reason.sessionMoved'\n | 'unmount.reason.sessionIdle'\n | 'unmount.reason.operatorReleased'\n | 'unmount.reason.profileShown'\n | 'unmount.reason.undeclared'\n | 'unmount.reason.nameChanged'\n | 'unmount.reason.declarationChanged'\n | 'unmount.reason.nothingMountable'\n | 'idle.lazy'\n | 'idle.disabled'\n | 'idle.releasedInactive'\n | 'idle.releasedRequest'\n // The conflict channel (Task 4): the two shapes of the profile-conflict\n // report, the duplicate-document report, the two readings of a shadowed\n // row's detail, and the presentation owner's note.\n | 'conflict.profile'\n | 'conflict.profileAlias'\n | 'conflict.documents'\n | 'conflict.profileDetail'\n | 'conflict.profileAliasDetail'\n | 'present.ownerNote'\n // The save channel (Task 5): every refusal of saveEntry and of the three\n // policy writes (setPin/setPolicy/setConflictChoice). The five\n // SaveErrorCodes stay the HTTP-status axis — these code the messages.\n | 'save.noPolicyStore'\n | 'save.noLiveSession'\n | 'save.unknownMode'\n | 'save.unknownChoice'\n | 'save.serverNotDeclared'\n | 'save.noDeclaringDocument'\n | 'save.notWritable'\n | 'save.needsConsent'\n | 'save.globalDisabled'\n | 'save.declaredElsewhere'\n | 'save.documentGone'\n | 'save.documentChanged'\n | 'save.invalidJson'\n | 'save.noMcpServers'\n | 'save.noLongerDeclared'\n | 'save.entryNotParsed'\n | 'save.writeFailed'\n // The trio applyEntry (src/write.ts) throws as WriteDocError and the save\n // path reuses beside its `invalid` refusal.\n | 'write.doc.invalidJson'\n | 'write.doc.notObject'\n | 'write.doc.noMcpServers'\n\n/**\n * English. Byte-identical to the literals `writeScopeFor` (`src/write.ts`)\n * emits as `reason` — the harness's own fallback chain ends here, one step\n * before the resolver falls back to the payload's `message`.\n */\nexport const en: Record<HostCode, string> = {\n // writeScopeFor: the document is none the deployment reads, and none is configured to write.\n 'write.blocked.notConfigured':\n '{document} is not a document this deployment reads, and it configures none to write',\n // writeScopeFor: the document is not among the deployment's MCP documents; {writable} lists them.\n 'write.blocked.notWritable':\n \"{document} is not one of this deployment's MCP documents; only {writable} can be written\",\n // writeScopeFor: a global-tier document with the deployment's allowGlobalWrite off.\n 'write.blocked.globalDisabled':\n 'writing the global tier is disabled by this deployment (allowGlobalWrite: false); {document} stays read-only here',\n // parseDocument: the document's text is not JSON at all.\n 'parse.json.invalid': 'invalid JSON: {error}',\n // parseDocument: no `mcpServers`/`servers` map and not a flat server map either.\n 'parse.doc.notObject': 'expected an object with an \"mcpServers\" object',\n // parseDocument: two keys sanitize to one serverName inside one document.\n 'parse.server.duplicateName': 'serverName \"{name}\" is declared twice in this document',\n // sanitizeName: nothing of the key survives slugification.\n 'parse.server.badName': '\"{key}\" cannot be converted into a valid serverName ({pattern})',\n // sanitizeName: the key mounts under its slug instead.\n 'parse.server.renamedName': 'serverName \"{key}\" is not a valid mcp-client name; using \"{slug}\"',\n // The runtime's merge pass: a later document overrode this name's earlier declaration.\n 'parse.server.multiDocument':\n 'serverName \"{name}\" was declared in more than one document; the highest-priority definition wins',\n // toEntry: the entry's value is not an object.\n 'parse.entry.notObject': 'entry must be an object',\n // toEntry: a `type`/`transport` that is not a string.\n 'parse.entry.badType': '\"type\" must be a string',\n // toEntry: a `type` outside the four known transports.\n 'parse.entry.typeUnknown': '\"type\" must be one of \"stdio\", \"http\", \"streamable-http\" or \"sse\"',\n // buildStdioEntry: no command to run.\n 'parse.entry.noCommand': 'stdio servers require a \"command\"',\n // buildStdioEntry: `args` present but not a string array.\n 'parse.entry.badArgs': '\"args\" must be an array of strings',\n // buildStdioEntry: `env` present but not a string map.\n 'parse.entry.badEnv': '\"env\" must be an object of strings',\n // buildStdioEntry: `cwd` present but not a string.\n 'parse.entry.badCwd': '\"cwd\" must be a string',\n // buildHttpEntry: no url to connect to.\n 'parse.entry.noUrl': 'http servers require a \"url\"',\n // buildHttpEntry: `headers` present but not a string map.\n 'parse.entry.badHeaders': '\"headers\" must be an object of strings',\n // resolveRef: `${input:}` with no name.\n 'parse.ref.empty': 'empty ${input:} reference',\n // resolveRef: an `${input:NAME}` no source answers.\n 'parse.ref.inputUnset':\n 'input \"{key}\" is not set (looked in plugin inputs, the project .env, the environment, and the credentials file)',\n // resolveRef: a `${NAME}` no source answers.\n 'parse.ref.varUnset':\n 'variable \"{name}\" is not set (looked in the project .env, the environment, and the credentials file)',\n // expandRecord: a reference failed inside an env/headers value; {name} is the inner message.\n 'parse.ref.failedInKey': '{key}: {name}',\n // mount(): a mount is registered. {sharing} is the two-level nesting of\n // mount.sharingShared / mount.sharingForwarded, substituted from sharingCode.\n 'mount.starting': 'mounting for session {sessionId} (trigger: {trigger}; {sharing})',\n // mount(): the session shares the project's instance directly (parent-linked).\n 'mount.sharingShared': 'one shared instance for every session of this project',\n // mount(): the session's key could not be linked, so the bridge forwards.\n 'mount.sharingForwarded':\n \"one shared instance for this project, forwarded into this session's own layer\",\n // recordMountFailure(): the activation or the registration threw.\n 'mount.failed': 'mount failed — {error}',\n // failureDetail(): one template, three lines — the name and the error, the\n // endpoint, the declaring document.\n 'mount.failedDetail': '{name}: mount failed — {error}\\nendpoint: {endpoint}\\ndeclared in: {source}',\n // refreshStatuses(): the mount's tools became visible to the session.\n 'mount.up': 'is up — tools visible to session {sessionId} after {elapsed}',\n // refreshStatuses(): the connect watchdog fired.\n 'mount.stalled': 'no tool appeared in {elapsed}',\n // stallDetail(): the same three facts as mount.failedDetail, for a stall.\n 'mount.stalledDetail': '{name}: no tool appeared in {elapsed}\\nendpoint: {endpoint}\\ndeclared in: {source}',\n // logUnmount(): a mount is going away. {reason} is the two-level nesting of\n // one of the unmount.reason.* codes, substituted from reasonCode.\n 'unmounting': 'unmounting — {reason} (it ran for {ran})',\n // retry(): the dropped error mount is being replaced by the operator pass.\n 'unmount.reason.operatorRetry': 'an operator retry replaces it',\n // disposeAll(): the whole runtime is going down.\n 'unmount.reason.unloading': 'the plugin is unloading',\n // agent scope event: the session's agent disappeared.\n 'unmount.reason.sessionGone': 'the session went away',\n // session sweep: the host registry dropped the session.\n 'unmount.reason.sessionUnlisted': 'the registry no longer lists the session',\n // syncAgent()/holdProject(): the session's cwd resolved to another root.\n 'unmount.reason.sessionMoved': 'the session moved to another project',\n // evictIdle(): the session was quiet past idleTimeoutMs.\n 'unmount.reason.sessionIdle': 'the session went idle',\n // release(): the operator asked for the release.\n 'unmount.reason.operatorReleased': 'an operator released it',\n // syncAgent(): a reserved name whose shadowing declaration disappeared.\n 'unmount.reason.profileShown': 'this project shows the profile-level copy instead',\n // syncAgent(): the documents stopped declaring the mounted name.\n 'unmount.reason.undeclared': 'the documents no longer declare it',\n // syncAgent(): the chosen local alias changed under a live mount.\n 'unmount.reason.nameChanged': 'its local name changed',\n // syncAgent(): the declaration's fingerprint changed under a live mount.\n 'unmount.reason.declarationChanged': 'its declaration changed',\n // syncAgent(): the declarations left mount nothing.\n 'unmount.reason.nothingMountable': 'nothing it declares is mountable any more',\n // syncAgent(): a declaration `lazy` has not mounted yet.\n 'idle.lazy': 'not mounted yet — this session has not started a turn (lazy mounting is on)',\n // syncAgent(): the entry declares `enabled: false`.\n 'idle.disabled': 'declared with enabled: false',\n // evictIdle() via releaseMounts(): the idle release's row detail.\n 'idle.releasedInactive':\n 'released after {seconds} without activity — {count} server(s) stopped; the next turn mounts them again',\n // release() via releaseMounts(): the requested release's row detail.\n 'idle.releasedRequest':\n 'released on request — {count} server(s) stopped; the next turn mounts them again',\n // conflictsFor(): a profile-level instance owns the name, and this project\n // has no local alias to offer.\n 'conflict.profile':\n '\"{name}\" is owned by a profile-level mcp-client instance, so the project entry does not mount under it; remove the profile entry to use the project one everywhere, or let this project\\'s copy take the name in this project\\'s sessions alone.',\n // conflictsFor(): the same, with the local alias the choice would mount under.\n 'conflict.profileAlias':\n '\"{name}\" is owned by a profile-level mcp-client instance; this project\\'s copy mounts as \"{alias}\" when chosen beside it, or under the contested name when chosen to shadow it in this project\\'s sessions, and does not mount at all while the profile\\'s copy is the one shown.',\n // conflictsFor(): one name declared by {count} documents; {winner} is the\n // document the merge kept.\n 'conflict.documents':\n '\"{name}\" is declared in {count} documents; {winner} wins and the other declaration is not mounted.',\n // conflictDetail(): the shadowed row's detail, no alias to offer.\n 'conflict.profileDetail':\n 'serverName \"{name}\" is already provided by a profile-level mcp-client instance — remove that entry from the profile to use the project one everywhere, or choose this project\\'s copy to let it take the name in this project\\'s sessions',\n // conflictDetail(): the shadowed row's detail, with the local alias.\n 'conflict.profileAliasDetail':\n 'serverName \"{name}\" is already provided by a profile-level mcp-client instance — choose this project\\'s copy to mount it as \"{alias}\", or under the contested name to shadow the profile instance here',\n // presentationOwner(): why this plugin and a second owner cannot shape one\n // request. No params — one fixed sentence.\n 'present.ownerNote':\n 'a second presentation owner rewrites assembly.tools after this plugin does, so the two never combine in one request: either this plugin shapes only its own mcp__* entries, or the other owner is unmounted.',\n // setPin/setPolicy/setConflictChoice: the host was built without a policy store.\n 'save.noPolicyStore': 'this host has no tool-policy store',\n // setPin/setPolicy/setConflictChoice: the named project has no live session here.\n 'save.noLiveSession': 'no live session in {projectRoot}',\n // setPolicy: a mode no assembly knows; {mode} is the JSON-stringified value.\n 'save.unknownMode': 'unknown tool mode {mode}',\n // setConflictChoice: an answer no build knows; {choice} is the JSON-stringified value.\n 'save.unknownChoice': 'unknown conflict choice {choice}',\n // saveEntry: no live row of this project carries the name.\n 'save.serverNotDeclared': 'server \"{server}\" is not declared for {projectRoot}',\n // saveEntry: the row names no declaring document to write to.\n 'save.noDeclaringDocument': 'server \"{server}\" has no declaring document to write',\n // saveEntry: the defensive readonly fallback — writeScopeFor's own reason\n // arrives coded (write.blocked.*) and is reused instead whenever it exists.\n 'save.notWritable': '{document} is not writable',\n // saveEntry: a global-tier write submitted without the explicit consent.\n 'save.needsConsent': 'writing {document} needs explicit consent',\n // saveEntry: a global-tier write with the deployment's allowGlobalWrite off.\n 'save.globalDisabled': 'writing the global tier is disabled by this deployment (allowGlobalWrite: false)',\n // saveEntry: the editor's document no longer declares the name.\n 'save.declaredElsewhere': 'server \"{server}\" is now declared by {document}',\n // saveEntry: the declaring document could not be read back at all.\n 'save.documentGone': 'the declaring document {document} is gone',\n // saveEntry: the document's revision moved past the one the editor read.\n 'save.documentChanged': '{document} changed since the entry was read; reload it and edit again',\n // saveEntry: the document read back is not JSON any more.\n 'save.invalidJson': 'the declaring document is not valid JSON: {error}',\n // saveEntry: the document holds no \"mcpServers\" object to rewrite.\n 'save.noMcpServers': '{document} does not use an \"mcpServers\" object, so this editor cannot rewrite it',\n // saveEntry: the document parses, but no key of it names the server.\n 'save.noLongerDeclared': 'server \"{server}\" is no longer declared in {document}',\n // saveEntry: the written-back entry failed the mount path's own parse. When\n // the parse named its failure, that failure's own code (parse.*) is reused\n // instead — this code names only the shapeless fallback.\n 'save.entryNotParsed': 'the edited entry \"{server}\" did not parse',\n // saveEntry: writeDocument threw (the backup, the temporary write or the rename).\n 'save.writeFailed': 'writing {document} failed: {error}',\n // applyEntry: the document text is not JSON at all.\n 'write.doc.invalidJson': 'the document is not valid JSON: {error}',\n // applyEntry: the document parses to something that is not an object.\n 'write.doc.notObject': 'the document is not a JSON object',\n // applyEntry: the document holds no \"mcpServers\" object.\n 'write.doc.noMcpServers': 'the document has no \"mcpServers\" object',\n}\n\n/** Chinese, complete across the namespace: the `Record<HostCode, string>` annotation proves it. */\nexport const zh: Record<HostCode, string> = {\n 'write.blocked.notConfigured': '{document} 不是此部署读取的文档,它也未配置任何可写入的文档',\n 'write.blocked.notWritable': '{document} 不是此部署的 MCP 文档之一;只能写入 {writable}',\n 'write.blocked.globalDisabled':\n '此部署已禁用全局级的写入(allowGlobalWrite: false);{document} 在此处保持只读',\n 'parse.json.invalid': '无效的 JSON:{error}',\n 'parse.doc.notObject': '预期是一个带有 \"mcpServers\" 对象的对象',\n 'parse.server.duplicateName': 'serverName \"{name}\" 在此文档中声明了两次',\n 'parse.server.badName': '\"{key}\" 无法转换为有效的 serverName({pattern})',\n 'parse.server.renamedName': 'serverName \"{key}\" 不是有效的 mcp-client 名称;改用 \"{slug}\"',\n 'parse.server.multiDocument': 'serverName \"{name}\" 在不止一份文档中声明;优先级最高的定义生效',\n 'parse.entry.notObject': '条目必须是对象',\n 'parse.entry.badType': '\"type\" 必须是字符串',\n 'parse.entry.typeUnknown': '\"type\" 必须是 \"stdio\"、\"http\"、\"streamable-http\" 或 \"sse\" 之一',\n 'parse.entry.noCommand': 'stdio 服务器需要 \"command\"',\n 'parse.entry.badArgs': '\"args\" 必须是字符串数组',\n 'parse.entry.badEnv': '\"env\" 必须是字符串组成的对象',\n 'parse.entry.badCwd': '\"cwd\" 必须是字符串',\n 'parse.entry.noUrl': 'http 服务器需要 \"url\"',\n 'parse.entry.badHeaders': '\"headers\" 必须是字符串组成的对象',\n 'parse.ref.empty': '空的 ${input:} 引用',\n 'parse.ref.inputUnset': '输入 \"{key}\" 未设置(已在插件 inputs、项目 .env、环境和凭据文件中查找)',\n 'parse.ref.varUnset': '变量 \"{name}\" 未设置(已在项目 .env、环境和凭据文件中查找)',\n 'parse.ref.failedInKey': '{key}:{name}',\n 'mount.starting': '正在为会话 {sessionId} 挂载(触发方式:{trigger};{sharing})',\n 'mount.sharingShared': '此项目的所有会话共享一个实例',\n 'mount.sharingForwarded': '此项目共享一个实例,已转发进此会话自己的层',\n 'mount.failed': '挂载失败 — {error}',\n 'mount.failedDetail': '{name}:挂载失败 — {error}\\n端点:{endpoint}\\n声明于:{source}',\n 'mount.up': '已就绪 — {elapsed} 后工具对会话 {sessionId} 可见',\n 'mount.stalled': '{elapsed} 内没有出现任何工具',\n 'mount.stalledDetail': '{name}:{elapsed} 内没有出现任何工具\\n端点:{endpoint}\\n声明于:{source}',\n 'unmounting': '正在卸载 — {reason}(已运行 {ran})',\n 'unmount.reason.operatorRetry': '操作员发起的重试将取代它',\n 'unmount.reason.unloading': '插件正在退出',\n 'unmount.reason.sessionGone': '会话已消失',\n 'unmount.reason.sessionUnlisted': '注册表不再列出该会话',\n 'unmount.reason.sessionMoved': '会话已移动到另一个项目',\n 'unmount.reason.sessionIdle': '会话已空闲',\n 'unmount.reason.operatorReleased': '操作员释放了它',\n 'unmount.reason.profileShown': '此项目改为显示配置文件级的副本',\n 'unmount.reason.undeclared': '文档不再声明它',\n 'unmount.reason.nameChanged': '它的本地名称已更改',\n 'unmount.reason.declarationChanged': '它的声明已更改',\n 'unmount.reason.nothingMountable': '它声明的内容不再有可挂载的',\n 'idle.lazy': '尚未挂载 — 此会话还没有开始任何一轮对话(惰性挂载已开启)',\n 'idle.disabled': '以 enabled: false 声明',\n 'idle.releasedInactive': '在 {seconds} 无活动后释放 — 已停止 {count} 个服务器;下一轮对话会重新挂载它们',\n 'idle.releasedRequest': '已按请求释放 — 已停止 {count} 个服务器;下一轮对话会重新挂载它们',\n 'conflict.profile':\n '\"{name}\" 已由配置文件级的 mcp-client 实例占用,因此项目条目不会以该名称挂载;请从配置文件中移除该条目以在各处使用项目副本,或让此项目的副本仅在此项目的会话中使用该名称。',\n 'conflict.profileAlias':\n '\"{name}\" 已由配置文件级的 mcp-client 实例占用;选择并存时此项目的副本以 \"{alias}\" 挂载,选择遮蔽时则在此项目的会话中使用被争用的名称,而在显示配置文件副本期间完全不挂载。',\n 'conflict.documents': '\"{name}\" 在 {count} 份文档中声明;{winner} 生效,另一份声明不会被挂载。',\n 'conflict.profileDetail':\n 'serverName \"{name}\" 已由配置文件级的 mcp-client 实例提供 — 从配置文件中移除该条目以在各处使用项目副本,或选择此项目的副本让它在此项目的会话中使用该名称',\n 'conflict.profileAliasDetail':\n 'serverName \"{name}\" 已由配置文件级的 mcp-client 实例提供 — 选择此项目的副本将其挂载为 \"{alias}\",或选择被争用的名称以在此处遮蔽配置文件实例',\n 'present.ownerNote':\n '第二个呈现所有者会在此插件之后重写 assembly.tools,因此两者永远不会在同一请求中合并:要么此插件只塑造自己的 mcp__* 条目,要么卸载另一个所有者。',\n 'save.noPolicyStore': '此宿主没有工具策略存储',\n 'save.noLiveSession': '{projectRoot} 中没有活跃会话',\n 'save.unknownMode': '未知的工具模式 {mode}',\n 'save.unknownChoice': '未知的冲突选择 {choice}',\n 'save.serverNotDeclared': '服务器 \"{server}\" 未在 {projectRoot} 中声明',\n 'save.noDeclaringDocument': '服务器 \"{server}\" 没有可写入的声明文档',\n 'save.notWritable': '{document} 不可写入',\n 'save.needsConsent': '写入 {document} 需要明确同意',\n 'save.globalDisabled': '此部署已禁用全局级的写入(allowGlobalWrite: false)',\n 'save.declaredElsewhere': '服务器 \"{server}\" 现在由 {document} 声明',\n 'save.documentGone': '声明文档 {document} 已不存在',\n 'save.documentChanged': '{document} 自读取条目后已更改;请重新加载后再编辑',\n 'save.invalidJson': '声明文档不是有效的 JSON:{error}',\n 'save.noMcpServers': '{document} 未使用 \"mcpServers\" 对象,因此此编辑器无法重写它',\n 'save.noLongerDeclared': '服务器 \"{server}\" 不再在 {document} 中声明',\n 'save.entryNotParsed': '编辑后的条目 \"{server}\" 无法解析',\n 'save.writeFailed': '写入 {document} 失败:{error}',\n 'write.doc.invalidJson': '文档不是有效的 JSON:{error}',\n 'write.doc.notObject': '文档不是 JSON 对象',\n 'write.doc.noMcpServers': '文档没有 \"mcpServers\" 对象',\n}\n\n/** Russian, complete across the namespace on the same annotation. */\nexport const ru: Record<HostCode, string> = {\n 'write.blocked.notConfigured':\n '{document} — не документ, который читает эта установка, и она не настраивает ни одного для записи',\n 'write.blocked.notWritable':\n '{document} не входит в MCP-документы этой установки; записать можно только {writable}',\n 'write.blocked.globalDisabled':\n 'запись в глобальный уровень отключена этой установкой (allowGlobalWrite: false); {document} остаётся здесь доступным только для чтения',\n 'parse.json.invalid': 'недопустимый JSON: {error}',\n 'parse.doc.notObject': 'ожидался объект с объектом \"mcpServers\"',\n 'parse.server.duplicateName': 'serverName \"{name}\" объявлен в этом документе дважды',\n 'parse.server.badName': '\"{key}\" невозможно преобразовать в допустимый serverName ({pattern})',\n 'parse.server.renamedName':\n 'serverName \"{key}\" не является допустимым именем mcp-client; используется \"{slug}\"',\n 'parse.server.multiDocument':\n 'serverName \"{name}\" объявлен более чем в одном документе; побеждает определение с наивысшим приоритетом',\n 'parse.entry.notObject': 'запись должна быть объектом',\n 'parse.entry.badType': '\"type\" должно быть строкой',\n 'parse.entry.typeUnknown': '\"type\" должно быть одним из \"stdio\", \"http\", \"streamable-http\" или \"sse\"',\n 'parse.entry.noCommand': 'stdio-серверы требуют \"command\"',\n 'parse.entry.badArgs': '\"args\" должно быть массивом строк',\n 'parse.entry.badEnv': '\"env\" должно быть объектом из строк',\n 'parse.entry.badCwd': '\"cwd\" должно быть строкой',\n 'parse.entry.noUrl': 'http-серверы требуют \"url\"',\n 'parse.entry.badHeaders': '\"headers\" должно быть объектом из строк',\n 'parse.ref.empty': 'пустая ссылка ${input:}',\n 'parse.ref.inputUnset':\n 'input \"{key}\" не задан (искали в inputs плагина, в .env проекта, в окружении и в файле учётных данных)',\n 'parse.ref.varUnset':\n 'переменная \"{name}\" не задана (искали в .env проекта, в окружении и в файле учётных данных)',\n 'parse.ref.failedInKey': '{key}: {name}',\n 'mount.starting': 'монтирование для сессии {sessionId} (триггер: {trigger}; {sharing})',\n 'mount.sharingShared': 'один общий экземпляр для каждой сессии этого проекта',\n 'mount.sharingForwarded':\n 'один общий экземпляр на этот проект, проброшенный в собственный слой этой сессии',\n 'mount.failed': 'монтирование не удалось — {error}',\n 'mount.failedDetail':\n '{name}: монтирование не удалось — {error}\\nэндпоинт: {endpoint}\\nобъявлено в: {source}',\n 'mount.up': 'поднят — инструменты видны сессии {sessionId} спустя {elapsed}',\n 'mount.stalled': 'за {elapsed} не появилось ни одного инструмента',\n 'mount.stalledDetail':\n '{name}: за {elapsed} не появилось ни одного инструмента\\nэндпоинт: {endpoint}\\nобъявлено в: {source}',\n 'unmounting': 'снятие — {reason} (проработал {ran})',\n 'unmount.reason.operatorRetry': 'его заменяет повторная попытка оператора',\n 'unmount.reason.unloading': 'плагин выгружается',\n 'unmount.reason.sessionGone': 'сессия исчезла',\n 'unmount.reason.sessionUnlisted': 'реестр больше не содержит эту сессию',\n 'unmount.reason.sessionMoved': 'сессия перешла в другой проект',\n 'unmount.reason.sessionIdle': 'сессия простаивает',\n 'unmount.reason.operatorReleased': 'оператор освободил его',\n 'unmount.reason.profileShown': 'этот проект вместо него показывает копию уровня профиля',\n 'unmount.reason.undeclared': 'документы больше не объявляют его',\n 'unmount.reason.nameChanged': 'его локальное имя изменилось',\n 'unmount.reason.declarationChanged': 'его объявление изменилось',\n 'unmount.reason.nothingMountable': 'ничего из объявленного им больше нельзя смонтировать',\n 'idle.lazy':\n 'ещё не смонтирован — эта сессия ещё не начала ни одного шага (ленивое монтирование включено)',\n 'idle.disabled': 'объявлен с enabled: false',\n 'idle.releasedInactive':\n 'освобождено после {seconds} без активности — остановлено серверов: {count}; следующий шаг смонтирует их снова',\n 'idle.releasedRequest':\n 'освобождено по запросу — остановлено серверов: {count}; следующий шаг смонтирует их снова',\n 'conflict.profile':\n '\"{name}\" принадлежит экземпляру mcp-client уровня профиля, поэтому запись проекта не монтируется под этим именем; удалите запись из профиля, чтобы использовать проектную везде, или позвольте копии этого проекта занять имя только в сессиях этого проекта.',\n 'conflict.profileAlias':\n '\"{name}\" принадлежит экземпляру mcp-client уровня профиля; копия этого проекта монтируется как \"{alias}\" при выборе рядом с ним или под спорным именем при выборе затенения в сессиях этого проекта и не монтируется вовсе, пока показана копия профиля.',\n 'conflict.documents':\n '\"{name}\" объявлен в документах: {count}; побеждает {winner}, а другое объявление не монтируется.',\n 'conflict.profileDetail':\n 'serverName \"{name}\" уже предоставлен экземпляром mcp-client уровня профиля — удалите эту запись из профиля, чтобы использовать проектную везде, или выберите копию этого проекта, чтобы она заняла имя в сессиях этого проекта',\n 'conflict.profileAliasDetail':\n 'serverName \"{name}\" уже предоставлен экземпляром mcp-client уровня профиля — выберите копию этого проекта, чтобы смонтировать её как \"{alias}\", или спорное имя, чтобы затенить экземпляр профиля здесь',\n 'present.ownerNote':\n 'второй владелец представления перезаписывает assembly.tools после этого плагина, поэтому оба никогда не объединяются в одном запросе: либо этот плагин формирует только свои записи mcp__*, либо другой владелец выгружается.',\n 'save.noPolicyStore': 'у этого хоста нет хранилища политики инструментов',\n 'save.noLiveSession': 'нет активной сессии в {projectRoot}',\n 'save.unknownMode': 'неизвестный режим инструментов {mode}',\n 'save.unknownChoice': 'неизвестный выбор конфликта {choice}',\n 'save.serverNotDeclared': 'сервер \"{server}\" не объявлен для {projectRoot}',\n 'save.noDeclaringDocument': 'у сервера \"{server}\" нет объявляющего документа для записи',\n 'save.notWritable': '{document} недоступен для записи',\n 'save.needsConsent': 'запись {document} требует явного согласия',\n 'save.globalDisabled': 'запись в глобальный уровень отключена этой установкой (allowGlobalWrite: false)',\n 'save.declaredElsewhere': 'сервер \"{server}\" теперь объявлен в {document}',\n 'save.documentGone': 'объявляющий документ {document} исчез',\n 'save.documentChanged': '{document} изменился с момента чтения записи; перезагрузите его и отредактируйте заново',\n 'save.invalidJson': 'объявляющий документ не является допустимым JSON: {error}',\n 'save.noMcpServers': '{document} не использует объект \"mcpServers\", поэтому этот редактор не может его переписать',\n 'save.noLongerDeclared': 'сервер \"{server}\" больше не объявлен в {document}',\n 'save.entryNotParsed': 'изменённая запись \"{server}\" не разобралась',\n 'save.writeFailed': 'запись {document} не удалась: {error}',\n 'write.doc.invalidJson': 'документ не является допустимым JSON: {error}',\n 'write.doc.notObject': 'документ не является JSON-объектом',\n 'write.doc.noMcpServers': 'в документе нет объекта \"mcpServers\"',\n}\n\n/**\n * The translator of last resort: every code echoes, so {@link resolveHost}\n * reads the harness's miss signal and falls back to the payload's `message`.\n */\nconst echo: Translate = (key) => key\n\n/**\n * A translator bound to the host namespace — and nothing more.\n *\n * This is deliberately not `uiTranslate`'s shape: the UI seat falls back to\n * the merged English table of its module, but this namespace has no merged\n * English table — the per-message fallback is the design, and it lives in\n * {@link resolveHost}, which detects the echo itself. Without a locale\n * service, or when the service refuses the namespace, the seat echoes, which\n * is exactly the miss signal the resolver reads.\n * @param locale - the shell's locale service, when there is one.\n * @returns a translate seat over `projectMcp.host`.\n */\nexport function hostTranslate(locale: TabLocale | undefined): Translate {\n if (locale === undefined) return echo\n try {\n return locale.bind(NS_HOST) as Translate\n } catch {\n // A service that refuses the namespace leaves the payload its own English.\n return echo\n }\n}\n\n/**\n * Resolve one host payload to the sentence the screen shows.\n *\n * The chain: the bound namespace answers first (the harness's own fallback —\n * active language, then this namespace's `en` table — rides inside it); a\n * miss, which the harness signals by echoing the code, falls back to the\n * payload's English `message`; a payload without a code renders its `message`\n * directly, so an old host's prose shows exactly as it did before codes\n * existed. The raw code survives only when the payload is malformed (no\n * `message` either) — the documented last resort.\n *\n * Params are flat, with one two-level convention: a param whose name ends in\n * `Code` is itself a wire code, resolved through `bound` first and substituted\n * under the plain name (`reasonCode` → `reason`). A nested lookup that misses —\n * the harness echoes the sub-code, which substituted would put a raw code on\n * screen inside an otherwise translated sentence — fails the whole lookup:\n * the payload's `message` answers instead.\n * @param bound - the host-namespace seat from {@link hostTranslate}.\n * @param code - the payload's wire code, when it carries one.\n * @param params - the payload's flat params, when it carries any.\n * @param message - the payload's English fallback text.\n * @returns the sentence to render.\n */\nexport function resolveHost(\n bound: Translate,\n code: string | undefined,\n params: Record<string, string> | undefined,\n message: string | undefined,\n): string {\n if (code === undefined) return message ?? ''\n const resolved = resolveParams(bound, params)\n if (resolved.missed) return message ?? code\n const text = bound(code, resolved.params)\n return text === code ? (message ?? code) : text\n}\n\n/**\n * The params a bound seat is called with: `*Code` values resolved two-level.\n * `missed` is the nested miss signal: a sub-code the namespace does not know\n * echoes, and an echo is never substituted into a sentence.\n */\nfunction resolveParams(\n bound: Translate,\n params: Record<string, string> | undefined,\n): { params: Record<string, string> | undefined; missed: boolean } {\n if (params === undefined) return { params: undefined, missed: false }\n const resolved: Record<string, string> = {}\n let missed = false\n for (const [name, value] of Object.entries(params)) {\n if (name.endsWith('Code') && name.length > 'Code'.length) {\n const nested = bound(value)\n if (nested === value) missed = true\n resolved[name.slice(0, -'Code'.length)] = nested\n } else {\n resolved[name] = value\n }\n }\n return { params: resolved, missed }\n}\n","/**\n * Shared row/snapshot vocabulary for `dsh-project-mcp`.\n *\n * The host half publishes a {@link ProjectSnapshot} through the `projectMcp`\n * service so a future Web UI (or a test) can read what is mounted without\n * importing the runtime.\n *\n * @module dsh-project-mcp/types\n */\n\n/**\n * Type-only, and imported for its effect on the ambient types rather than for\n * anything this module uses: `@deepseek-ai/dsh-tools` declares `Context.tools`\n * and the `tools/change` / `tools/result` events as module augmentation of\n * `@deepseek-ai/cordis`, and TypeScript applies an augmentation only when the\n * augmenting module is part of the compilation. Nothing of the package reaches\n * the runtime — the import is erased by the compiler, and the plugin still\n * takes the service off the context it is handed instead of importing the\n * module.\n */\nimport type {} from '@deepseek-ai/dsh-tools'\n\n/** Runtime state of one project-declared MCP server. */\nexport type ServerStatus =\n /** Mounted and its tools are visible in the owning scope. */\n | 'active'\n /** Mounted; activation or the initial connection has not settled yet. */\n | 'connecting'\n /**\n * Declared, parsed, and not mounted: either `lazy` has not seen this\n * session's first turn yet, or the session went idle and its mounts were\n * released (`idleTimeoutMs`). The next turn mounts it again.\n */\n | 'idle'\n /** Declared with `enabled: false` — never mounted. */\n | 'disabled'\n /** The same `serverName` is reserved by a live profile-level instance. */\n | 'conflict'\n /** The entry or its mount failed; `detail` carries the reason. */\n | 'error'\n\n/** One server row of a project snapshot. */\nexport interface ServerRow {\n /** `serverName` (the `mcpServers` key, sanitized). */\n name: string\n /** Current lifecycle state. */\n status: ServerStatus\n /** Project root the entry was read from. */\n projectRoot: string\n /** Absolute path of the declaring document. */\n source?: string\n /** `stdio` or `streamable-http`, when the entry parsed. */\n transport?: 'stdio' | 'streamable-http'\n /**\n * Failure, stall or conflict explanation. Redacted on purpose: it names the\n * command but never its arguments, and an HTTP endpoint keeps its path but\n * drops the query string, because both can carry credentials.\n */\n detail?: string\n /**\n * Stable wire code of `detail` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive, exactly like\n * {@link blockedCode}: the prose field keeps its byte-identical English and\n * stays the fallback, so a client and a host of different builds degrade\n * rather than break.\n */\n detailCode?: string\n /**\n * Flat params of {@link detailCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n detailParams?: Record<string, string>\n /**\n * Parsed body of the entry, for the editor. Absent when the entry did not\n * parse — there is nothing to edit then.\n */\n entry?: EntrySnapshot\n /** Where this row may be written back, when it may be written at all. */\n writeScope?: WriteScope\n /** One line saying why writing is unavailable; always set for `readonly`. */\n writeBlockedReason?: string\n /**\n * Stable wire code of `writeBlockedReason` (`projectMcp.host` namespace),\n * for client-side translation. Optional and additive: the prose field keeps\n * its byte-identical English and stays the fallback, so a client and a host\n * of different builds degrade rather than break.\n */\n blockedCode?: string\n /**\n * Flat params of {@link blockedCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n blockedParams?: Record<string, string>\n /**\n * Opaque content revision of the declaring document at snapshot time. A save\n * must carry the revision it was built from: a mismatch means the document\n * changed underneath the editor, and the write is refused rather than merged.\n */\n documentRevision?: string\n}\n\n/**\n * How one `env` or `headers` entry is known to the host.\n *\n * A value can come from the declaring document, be answered outside it (the\n * project's own `.env` or the credentials file), or be withheld because it is a\n * credential. {@link EntryField.masked} is the field\n * that changes how a write treats it: a masked key submitted without a `value` is\n * kept exactly as the document declares it, so an editor that cannot see a secret\n * can never erase or replace one.\n */\nexport interface EntryField {\n /** Key exactly as declared. */\n readonly key: string\n /** Literal value; absent when the host withholds it. */\n readonly value?: string\n /** `true` when `value` is absent because the value is a secret. */\n readonly masked?: true\n /**\n * `true` when the key is answered outside the document — by the project's\n * `.env` or by the credentials file. The name predates the project dotenv\n * sources; the meaning the write path reads is \"never write this value back\".\n */\n readonly fromCredentials?: true\n}\n\n/**\n * One server entry as the host parsed it, for an editor.\n *\n * Every field is what the declaring document holds — a resolved default is never\n * folded in, because a save replaces the declaration, not the runtime config.\n */\nexport interface EntrySnapshot {\n /** Transport the entry declares. */\n readonly transport: 'stdio' | 'streamable-http'\n /** `stdio`: the program to run. */\n readonly command?: string\n /** `stdio`: its arguments, verbatim. */\n readonly args?: readonly string[]\n /** `stdio`: working directory, when the entry declares one. */\n readonly cwd?: string\n /** `stdio`: declared environment, secrets masked. */\n readonly env?: readonly EntryField[]\n /** `streamable-http`: the endpoint, with a credential-bearing query dropped. */\n readonly url?: string\n /** `streamable-http`: declared headers, secrets masked. */\n readonly headers?: readonly EntryField[]\n /** `false` when the declaration disables the server; absent means enabled. */\n readonly enabled?: boolean\n /** Declared connect timeout in milliseconds, when the entry sets one. */\n readonly connectTimeoutMs?: number\n /**\n * Keys the editor does not present, kept in their declared order and written\n * back untouched. A save replaces the entry wholesale, so dropping them would\n * delete configuration the panel never showed.\n */\n readonly extra?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Whether one row's declaring document may be rewritten.\n *\n * - `project` — one of the deployment's project documents (`localFiles`,\n * `<project>/.dsh/mcp.json` out of the box);\n * - `global` — one of its global documents (`globalFiles`), written only with an\n * explicit per-write consent;\n * - `readonly` — the profile, `<DSH_HOME>` or a bundled document: never written.\n */\nexport type WriteScope = 'project' | 'global' | 'readonly'\n\n/**\n * One document a project is configured to read.\n *\n * The list a project publishes is exactly its read order — global documents\n * first, then the project's own — so the panel's priority number is an index\n * into it and never a table of hardcoded file names.\n */\nexport interface ConfiguredFile {\n /** Absolute path of the document. */\n readonly path: string\n /**\n * `global` — read for every project, before its own documents; `project` —\n * read from the project root.\n */\n readonly scope: 'global' | 'project'\n}\n\n/** Diagnostics surfaced alongside the rows. */\nexport interface SnapshotIssue {\n /** Absolute path of the declaring document. */\n source: string\n /** Server the diagnostic belongs to, when entry-scoped. */\n server?: string\n /** `error` or `warning`. */\n level: 'error' | 'warning'\n /** Human-readable text. */\n message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive: `message` keeps its\n * byte-identical English and stays the fallback. Behavioural matches key on\n * this field — never on the prose, which the client may have translated.\n */\n code?: string\n /**\n * Flat params of {@link SnapshotIssue.code}; a name ending in `Code` is\n * itself a wire code the client resolves two-level.\n */\n params?: Record<string, string>\n}\n\n/**\n * One session's own view of the project it works in.\n *\n * Sessions of one project are independent: each mounts its own servers, and one\n * may have them running while another has not started a turn yet. The panel\n * needs that split, because a project-level merge alone cannot say *which*\n * session holds a mount.\n */\nexport interface SessionSnapshot {\n /** Agent (session) id. */\n id: string\n /** Rows for this session alone, in document order. */\n rows: ServerRow[]\n /** Diagnostics this session surfaced. */\n issues: SnapshotIssue[]\n /** What this session offers the model, when the host has mounted for it. */\n tools?: SessionTools\n /**\n * How many events of the project's ring belong to this session. Absent for a\n * session that produced none, so the tab's log badge reads a real `0`.\n */\n logCount?: number\n /**\n * `serverName` conflicts this session last reconciled: a profile-level\n * instance that already owns a name, or one name two project documents\n * declare. Published even when empty, so a reader can tell \"this session\n * reported none\" from a host that does not report conflicts at all.\n */\n conflicts?: readonly ServerConflict[]\n}\n\n/** One tool a session offers the model, and what put it in the request. */\nexport interface OfferedTool {\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly name: string\n /**\n * The tier that offered it: `session` activated on demand through the search\n * tool, `context` ranked from the task text of the current conversation. The\n * counter-seeded baseline is not this shape — it is a plain name list in\n * {@link SessionTools.baseline}.\n */\n readonly via: 'session' | 'context'\n /**\n * Epoch milliseconds of the last offer or call. Absent for the context tier,\n * whose live state stamps an advance rather than a clock reading.\n */\n readonly at?: number\n /**\n * Number of the agent step (from `1`) the tool was offered at, or `undefined`\n * for a host that does not count steps. A panel that reads no number draws no\n * step tag at all rather than a made-up one.\n */\n readonly step?: number\n}\n\n/**\n * One accepted field of a tool's `parameters` schema, as the panel lists it.\n *\n * A field is listed from the definition the host already holds, so its type and\n * its `required` flag are the schema's own and neither is inferred from the\n * tool's name. Nesting stops at the top level: an object or array field is drawn\n * as its type, not expanded, because the panel lists what a call takes rather\n * than mirroring a schema. Schema `default` values are deliberately not part of\n * this shape — a default can carry a value the tool did not mean to publish.\n */\nexport interface ToolField {\n /** Property name, as the schema declares it. */\n readonly name: string\n /** JSON Schema `type` of the field, or `any` when the schema names none. */\n readonly type: string\n /** `true` when the schema's own `required` array names this property. */\n readonly required: boolean\n /** The property's own `description`, when the schema publishes one. */\n readonly description?: string\n}\n\n/**\n * Why one name is not in this session's request, in the host's own terms.\n *\n * The decision belongs to the host and the panel does not recompute it, so the\n * reason travels as data and its copy lives in the client's dictionaries. Every\n * figure here is a host measurement — the definition's own serialized size, the\n * session's budget, what the offered set already carries — so a reason line\n * invents no number. That is the same discipline as contract C2's step tag.\n */\nexport interface ToolReason {\n /**\n * Which decision left the name out. `budget` is the disclosure mode pushing it\n * past {@link ToolReason.budget}: the whole mounted surface is registered, and\n * this definition did not fit the request.\n */\n readonly kind: 'budget'\n /** Serialized size of this definition, in characters — the host's own figure. */\n readonly chars?: number\n /** The session's tool budget in characters, when the host budgeted one. */\n readonly budget?: number\n /** Characters the offered set already carries, when the host measured them. */\n readonly used?: number\n}\n\n/**\n * One tool's detail, answered on demand for a row the reader opened.\n *\n * The panel fetches this instead of carrying it in the snapshot: the snapshot\n * travels on every change frame and every poll, while a description and a schema\n * are read once per opened row. The text is model-facing and arrives as data —\n * it is never copied into a dictionary, is not translated, and is drawn as the\n * host published it.\n */\nexport interface ToolFacts {\n /** Public registry name this record answers about. */\n readonly name: string\n /** The definition's model-facing description, when the host holds one. */\n readonly description?: string\n /** Accepted fields, in schema order; empty when the tool declares none. */\n readonly fields: readonly ToolField[]\n /** Why the name is not offered, when it is not. Absent for an offered name. */\n readonly reason?: ToolReason\n}\n\n/**\n * Another loaded plugin that owns the assembled tool list.\n *\n * The plugin and such an owner cannot shape one request together: the outer\n * listener of whoever assembles last rewrites `assembly.tools`, so the plugin's\n * own deferral would be re-applied over an already-trimmed list. The host\n * reports the owner instead of silently composing with it, and a panel prints\n * the coexistence note only when this record is published.\n */\nexport interface PresentationOwner {\n /** Loader entry name, for example `dsh-progressive-tools`. */\n readonly name: string\n /** One line saying why coexisting in one request is impossible. */\n readonly note: string\n /**\n * The `projectMcp.host` code of {@link note} (F-48): the client translates\n * by it and falls back to `note`'s English, byte-identical, when the code is\n * absent or unknown. No params — the note is one fixed sentence.\n */\n readonly noteCode?: string\n}\n\n/**\n * One `serverName` two declarations fight over.\n *\n * `profile` is the profile-level `mcp-client` instance that already owns the\n * name: the project entry mounts only through the local alias the user chose,\n * and never under the contested name itself. `duplicate` is one name declared by\n * more than one project document: the highest-priority document wins and the\n * others are ignored.\n */\nexport interface ServerConflict {\n /** `serverName` the declarations share. */\n readonly server: string\n /** `profile` — a profile-level instance owns the name; `duplicate` — two documents. */\n readonly kind: 'profile' | 'duplicate'\n /** Declaring documents, the winner first. */\n readonly sources: readonly string[]\n /** One line: who wins, and why. */\n readonly message: string\n /**\n * The `projectMcp.host` code of {@link message} (F-48): the client translates\n * by it and falls back to `message`'s English, byte-identical, when the code\n * is absent (a host older than the field) or unknown to its dictionaries.\n */\n readonly code?: string\n /**\n * Flat params of {@link code}; numbers stringify at emission. A name ending\n * in `Code` is itself a wire code, resolved two-level through the same\n * namespace and substituted under the plain name.\n */\n readonly params?: Record<string, string>\n /**\n * The local name this project's entry mounts under when the user chose\n * `local`, as `mcp__<alias>__<tool>` in the model's own list. Published on a\n * `profile` conflict even while the choice is still the profile's, so the\n * panel can offer the alias it would use rather than inventing one.\n */\n readonly alias?: string\n /**\n * What the project's policy says about this name. Absent on a `duplicate`,\n * which no choice resolves, and on a host older than this field.\n */\n readonly choice?: ConflictChoice\n}\n\n/**\n * What one live session currently offers the model.\n *\n * Measured from the session's own state, not from the project: two sessions of\n * one project differ as soon as one of them has called a tool, and the panel's\n * promise is to show what *this* session's model sees.\n */\nexport interface SessionTools {\n /** Live agent (session) id this row describes. */\n readonly sessionId: string\n /**\n * Names offered because the durable counters proved them hot, plus the pins;\n * empty in `off`, which offers none of the project's tools.\n */\n readonly baseline: readonly string[]\n /** Names this session activated on demand, oldest first; empty in `off`. */\n readonly activated: readonly OfferedTool[]\n /** Names the task context offered, oldest first; empty in `off`. */\n readonly context: readonly OfferedTool[]\n /**\n * Names mounted for the project but not offered by this plugin, sorted. In\n * `disclosure` these are the names the budget pushed out of the request; in\n * `direct` the list is empty, because nothing is filtered; in `off` it is the\n * whole mounted surface, because a project that is switched off is offered not\n * at all. Its length is exactly the count a panel shows as hidden — and such a\n * panel has to read {@link ToolPolicy.mode} first, since tools another\n * presentation plugin leaves in the request are not this one's offers.\n */\n readonly deferred: readonly string[]\n /** Tools mounted for the project in total. */\n readonly mounted: number\n /** Serialized size of the mounted surface, in characters. */\n readonly surfaceChars: number\n /**\n * Serialized size of the offered set — {@link SessionTools.baseline} plus the\n * `activated` and `context` names — in characters. Absent from a host that\n * does not split the surface, and then a panel prints no request estimate\n * rather than inventing one.\n */\n readonly visibleChars?: number\n /**\n * Serialized size of {@link SessionTools.deferred}, in characters: exactly the\n * part of the mounted surface this plugin leaves out of the request. `0` when\n * nothing is deferred, so a panel that found this field may divide it by four\n * for a token estimate.\n */\n readonly deferredChars?: number\n /**\n * Configured deferral budget in characters. `0` means there is no threshold at\n * all: every surface counts as over budget, so tools are deferred however small\n * the project is. Read {@link SessionTools.deferring} rather than comparing this\n * with {@link SessionTools.surfaceChars} — the host owns the rule.\n */\n readonly budgetChars: number\n /**\n * `true` while the surface is over the budget, so tools really are deferred.\n * Only `disclosure` can defer: `direct` filters nothing and `off` offers\n * nothing, so both report `false` however large the mounted surface is.\n */\n readonly deferring: boolean\n}\n\n/** How one project's MCP tools are offered to the model. */\nexport type ToolMode =\n /** Offer the baseline and the on-demand tiers (the shipped behaviour). */\n | 'disclosure'\n /** Never defer: every mounted tool is listed in every request. */\n | 'direct'\n /** Do not offer this project's MCP tools at all. */\n | 'off'\n\n/**\n * How one `serverName` a project shares with a live profile instance is shown.\n *\n * The profile's instance owns the name in every scope, so the two declarations\n * cannot both mount under it. `profile` keeps the profile's tools exactly as\n * they are and leaves the project's entry unmounted; `local` mounts the\n * project's entry under a local namespace (see `src/naming.ts`) so both toolsets\n * reach the model — the only difference being the names they carry; `native`\n * mounts the project's entry under the name it declares, which is the nearer\n * declaration in this project's own sessions and so shadows the profile's tools\n * of that name there, while every other project keeps seeing the profile's.\n */\nexport type ConflictChoice =\n /** The profile instance keeps the name; the project entry does not mount. */\n | 'profile'\n /** The project entry mounts under its local alias, next to the profile's. */\n | 'local'\n /** The project entry mounts under the declared name, shadowing the profile's in this project. */\n | 'native'\n\n/**\n * One project's tool policy.\n *\n * The mode decides whether tools are deferred, the pins are the names the user\n * insists on — a pinned tool is offered from the first step of every request, is\n * never dropped by idle pruning or by a compaction, and is not counted against\n * the deferral budget's reading of what is hidden — and the aliases remember, per\n * conflicting `serverName`, which of the two declarations the user chose to see.\n */\nexport interface ToolPolicy {\n /** Mode in force. */\n readonly mode: ToolMode\n /**\n * Public registry names pinned for this project, in the order the user pinned\n * them. A name the project no longer mounts is kept: the declaration may come\n * back, and a pin that silently disappeared would be a surprise.\n */\n readonly pins: readonly string[]\n /**\n * Choice per contested `serverName`. Optional so every fixture, host and\n * stored document written before this field existed keeps meaning exactly\n * what it meant: a name that is absent is one the user never chose about,\n * and the shipped answer is the profile's instance. The store publishes an\n * empty map rather than dropping the field, so a reader may treat `undefined`\n * and `{}` alike.\n */\n readonly aliases?: Readonly<Record<string, ConflictChoice>>\n}\n\n/** The policy every project follows until one is configured. */\nexport const DEFAULT_TOOL_POLICY: ToolPolicy = { mode: 'disclosure', pins: [], aliases: {} }\n\n/**\n * How much one MCP server of one project has been used.\n *\n * Counted on the host from the tool registry's own events, so it is exact rather\n * than sampled, and keyed by project root: sessions come and go, the numbers\n * stay, which is what makes them usable for later decisions about a project.\n */\nexport interface ServerUsage {\n /** Calls dispatched through the registry, successful or not. */\n calls: number\n /** Calls whose result carried an error. */\n errors: number\n /** ISO timestamp of the most recent call. */\n lastUsedAt?: string\n /**\n * Per tool counts, keyed by the tool name as declared by the server, i.e.\n * without the `mcp__<serverName>__` prefix the registry publishes it under.\n */\n tools: Record<string, number>\n /**\n * The same readings split by session, keyed by the session (agent) id the\n * panel already uses everywhere else.\n *\n * Additive since F-34: a document written before this field existed is read as\n * it is — `USAGE_VERSION` does not move, because a reader that meets an unknown\n * version refuses the whole document and every counter would start from zero.\n * Absent means \"counted before the split\", never \"no calls\".\n */\n sessions?: Record<string, SessionUsage>\n}\n\n/**\n * One session's share of a server's counters.\n *\n * A server is mounted for a project and a project's sessions share it, so the\n * project total says what the project used while this says what *this* session\n * did; the two differ exactly when other sessions of the project called the\n * server, which is the case a panel scoped to one session could not show.\n */\nexport interface SessionUsage {\n /** Calls this session dispatched through the registry. */\n calls: number\n /** Of those, the ones whose result carried an error. */\n errors: number\n /** ISO timestamp of this session's most recent call. */\n lastUsedAt?: string\n /** This session's counts, keyed by the tool name as the server declares it. */\n tools: Record<string, number>\n}\n\n/**\n * How serious one plugin event is, as the Logs tab colours it.\n *\n * Four levels, mapped from the lifecycle line the host already writes: `info`\n * for a mount being registered, `up` for one whose tools became visible, `warn`\n * for a stall or a release, `error` for a failed mount and the unmount that\n * follows it. They are the labels the tab draws, not a host severity scale.\n */\nexport type LogLevel =\n /** The instance is being registered (`project-mcp: mounting …`). */\n | 'info'\n /** The instance's tools are visible (`… is up …`). */\n | 'up'\n /** A stall, a repeated pass, or a release the operator did not ask for. */\n | 'warn'\n /** The mount failed, or a failed mount is being torn down. */\n | 'error'\n\n/**\n * One lifecycle event, as the Logs tab lists it.\n *\n * The plugin's own events only — a mount, a start, a stop, a failure — mirroring\n * the lines the host writes to the DSH log, so the two readers see the same\n * facts. Events live in a per-project ring (`src/logs.ts`); the newest ones ride\n * in the snapshot, the rest are paged over the route.\n */\nexport interface LogEvent {\n /** When the event happened, epoch ms. */\n readonly at: number\n /** How serious it is, as the tab colours it. */\n readonly level: LogLevel\n /** Project root the event belongs to; the ring is keyed by it. */\n readonly projectRoot: string\n /**\n * Session the event is attributed to. Set exactly when the lifecycle line it\n * mirrors names one — `mounting`, `is up`, a stall — and absent on a\n * project-level event such as a shared instance's unmount.\n */\n readonly sessionId?: string\n /** `serverName` the event is about; absent for an event with no server. */\n readonly server?: string\n /** One line, without a newline: one event is one row of the tab. */\n readonly message: string\n /**\n * The three facts an error carries — the failure, the endpoint, the declaring\n * document — and no advice: the server row already offers the retry.\n */\n readonly detail?: string\n /**\n * Wire code of {@link LogEvent.message} (F-48), into the `projectMcp.host`\n * namespace. Optional: a host older than the field sends prose only, and the\n * client falls back to {@link LogEvent.message}.\n */\n readonly code?: string\n /** Flat params of {@link LogEvent.code}; numbers are stringified at emission. */\n readonly params?: Record<string, string>\n /** Wire code of {@link LogEvent.detail}, the same additive companion. */\n readonly detailCode?: string\n /** Flat params of {@link LogEvent.detailCode}. */\n readonly detailParams?: Record<string, string>\n}\n\n/** Everything one project contributes to the live runtime. */\nexport interface ProjectSnapshot {\n /** Project root the agents below resolved to. */\n projectRoot: string\n /**\n * Documents this project is configured to read, in priority order — global\n * ones first, then the project's own. Published even when empty, so a panel\n * can tell \"this deployment reads nothing\" from a host that does not report\n * its documents at all. Absent only from a snapshot a host older than this\n * field produced, and then a reader falls back to the shipped names rather\n * than inventing a priority.\n */\n files?: readonly ConfiguredFile[]\n /**\n * The tool policy in force for this project. Absent only from a snapshot a host\n * older than the policy store produced; a reader treats that as the shipped\n * default, {@link DEFAULT_TOOL_POLICY}.\n */\n policy?: ToolPolicy\n /** Live agent (session) ids currently bound to this project. */\n sessionIds: string[]\n /**\n * Merged rows for every declared server, in document order. When sessions\n * disagree about one server, the more actionable state wins, so a mounted or\n * broken server is never hidden behind a session that has not turned yet.\n */\n rows: ServerRow[]\n /** Parse and lifecycle diagnostics, deduplicated across the sessions. */\n issues: SnapshotIssue[]\n /** The same data split per session, in session-registration order. */\n sessions: SessionSnapshot[]\n /**\n * Usage counters keyed by `serverName`, remembered across sessions. Absent\n * while the host half has counted nothing for this project yet.\n */\n usage?: Record<string, ServerUsage>\n /**\n * Another loaded plugin that owns the assembled tool list, when the profile\n * has one. Absent means this plugin is the only owner — a panel that reads no\n * record draws no coexistence notice.\n */\n presentation?: PresentationOwner\n /**\n * Real `serverName` conflicts of this project: a profile-level instance that\n * already owns a name, or one name two project documents declare. The list is\n * always published — an empty one is the honest answer \"no conflicts\", which\n * is what lets a panel report that instead of offering a disabled button.\n */\n conflicts?: readonly ServerConflict[]\n /**\n * The newest events of this project's ring, oldest first, at most the page\n * size (50). Absent for a project that has recorded nothing, so a tab draws\n * its empty state rather than an empty list.\n */\n logs?: readonly LogEvent[]\n /**\n * How many events the project's ring holds right now, `0…200`. Absent exactly\n * when {@link ProjectSnapshot.logs} is: no events, nothing to count.\n */\n logCount?: number\n}\n\n/** Whole-plugin snapshot: one entry per project with live agents. */\nexport interface McpSnapshot {\n /** `true` while the agents service has been observed. */\n ready: boolean\n /** Projects with at least one live agent. */\n projects: ProjectSnapshot[]\n /**\n * Documents this deployment is configured to read, exactly as the config\n * spells them — `local` relative to a project root, `global` relative to\n * `$HOME` (or absolute). Published for the surfaces that must speak about the\n * deployment itself, with no project at hand: the empty state names what would\n * be read instead of a file name baked into the client. Absent from a snapshot\n * a host older than this field produced.\n */\n sources?: { readonly local: readonly string[]; readonly global: readonly string[] }\n /** Absolute paths currently watched for config edits. */\n watchedFiles: string[]\n}\n\n/**\n * One pushed picture: what the status channel sends.\n *\n * The snapshot travels whole rather than as a delta, so a frame that arrives\n * after a gap is still a complete answer — the panel can apply it without\n * asking for anything back. `revision` counts the changes the host has announced\n * and is what a late or repeated frame is judged by.\n */\nexport interface SnapshotChange {\n /** Monotonic change counter, starting at `0` for the picture a stream opens on. */\n revision: number\n /** The whole picture at that revision. */\n snapshot: McpSnapshot\n}\n","/**\n * The per-project tool policy, as the browser half reads and writes it.\n *\n * The host owns the policy: it stores it next to the usage counters, applies it\n * on every request assembly, and answers with the fresh snapshot. This module\n * only shapes what the panel asks for and turns what came back into the two\n * readings the surfaces print — the mode in force and the list the user pinned.\n * Keeping the shapes here (instead of in a component) is what lets a no-DOM test\n * assert the exact body a `Pin` click posts.\n *\n * Nothing here invents a value: a project the host has no policy for follows\n * {@link DEFAULT_TOOL_POLICY}, which is the frozen contract's own default.\n *\n * @module dsh-project-mcp/client/policy\n */\n\nimport { ROUTE_ACTIONS, ROUTE_PREFIX } from '../shared.ts'\nimport type { ConflictRequest, OperatorRequest, PinRequest, PolicyRequest } from '../shared.ts'\nimport { DEFAULT_TOOL_POLICY } from '../types.ts'\nimport type { ConflictChoice, ProjectSnapshot, ToolMode, ToolPolicy } from '../types.ts'\n\n/**\n * The project's effective policy.\n *\n * `policy` is absent only from a snapshot a host older than the policy store\n * produced; the contract makes that the shipped default, so the panel reads a\n * bare project correctly instead of guarding for the field everywhere.\n * @param project - one project of the host snapshot.\n * @returns the policy in force, never undefined.\n */\nexport function policyOf(project: Pick<ProjectSnapshot, 'policy'>): ToolPolicy {\n return project.policy ?? DEFAULT_TOOL_POLICY\n}\n\n/** The body the host expects for one pin or unpin, per `PinRequest`. */\nexport function pinBody(projectRoot: string, tool: string, pinned: boolean): PinRequest {\n return { projectRoot, tool, pinned }\n}\n\n/** The body the host expects for one mode change, per `PolicyRequest`. */\nexport function policyBody(projectRoot: string, mode: ToolMode): PolicyRequest {\n return { projectRoot, mode }\n}\n\n/**\n * The body the host expects for one conflict choice, per `ConflictRequest`.\n *\n * The name travels as the project declared it, never as the local alias: the\n * alias is the host's own computation from its config and the project folder,\n * and a panel that sent one back would disagree with the host the moment either\n * changed.\n * @param projectRoot - the project the contested name belongs to.\n * @param server - the contested `serverName`, as declared.\n * @param choice - the declaration to show.\n * @returns the request body.\n */\nexport function conflictBody(\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n): ConflictRequest {\n return { projectRoot, server, choice }\n}\n\n/**\n * The body of one operator request — `Sync`, `Retry`.\n *\n * A surface that shows a single project names it: the host then touches only\n * that project's servers and answers with that project's slice of the snapshot.\n * `full` keeps the answer whole for a surface that lists every project — the\n * settings page — while the action itself still stays inside `projectRoot`.\n * @param projectRoot - the project the action applies to, when the surface has one.\n * @param full - ask for the whole snapshot in the answer.\n * @returns the request body; `{}` when there is no project to name.\n */\nexport function operatorBody(projectRoot: string | undefined, full = false): OperatorRequest {\n if (projectRoot === undefined) return {}\n return full ? { projectRoot, full: true } : { projectRoot }\n}\n\n/**\n * Submit one pin or unpin and read the host's answer.\n *\n * The host answers with the fresh snapshot on success and with an explanation\n * otherwise (unknown project, unknown tool). Both are returned rather than\n * thrown, because a refusal is a state the panel shows, not a crash.\n * @param body - the `PinRequest` to post.\n * @returns the fresh snapshot, or the host's refusal.\n */\nexport async function postPin(body: PinRequest): Promise<PolicyAnswer> {\n return postPolicy(ROUTE_ACTIONS.pin, body)\n}\n\n/**\n * Submit one mode change and read the host's answer.\n * @param body - the `PolicyRequest` to post.\n * @returns the fresh snapshot, or the host's refusal.\n */\nexport async function postPolicyMode(body: PolicyRequest): Promise<PolicyAnswer> {\n return postPolicy(ROUTE_ACTIONS.policy, body)\n}\n\n/**\n * Submit one conflict choice and read the host's answer.\n * @param body - the `ConflictRequest` to post.\n * @returns the fresh snapshot, or the host's refusal.\n */\nexport async function postConflict(body: ConflictRequest): Promise<PolicyAnswer> {\n return postPolicy(ROUTE_ACTIONS.conflict, body)\n}\n\n/**\n * A refusal the host answered with: the English prose, plus the wire code and\n * its flat params when the host coded it (F-48). The companions are what the\n * render sites resolve through the host namespace; an old host's refusal\n * carries none and renders its `message` exactly as before.\n */\nexport interface PolicyRefusal {\n /** The host's own English sentence. */\n readonly message: string\n /** Wire code of {@link message} (`projectMcp.host` namespace), when coded. */\n readonly messageCode?: string | undefined\n /** Flat params of {@link messageCode}, when it has any. */\n readonly messageParams?: Record<string, string> | undefined\n}\n\n/** Either the snapshot the host re-read after a write, or the reason it refused. */\nexport type PolicyAnswer = { ok: true; snapshot: unknown } | ({ ok: false } & PolicyRefusal)\n\ninterface PolicyEnvelope {\n ok?: boolean\n value?: unknown\n error?: { code?: string; message?: string; messageCode?: string; messageParams?: Record<string, string> }\n}\n\n/**\n * `POST` one policy write and unwrap the host's envelope.\n *\n * Both call sites pass the frozen route constant rather than a literal, so a\n * rename cannot leave one of the two routes behind.\n * @param action - route action under `ROUTE_PREFIX`.\n * @param body - the pin or mode request.\n * @returns the fresh snapshot or the refusal message.\n */\nasync function postPolicy(\n action: typeof ROUTE_ACTIONS.pin | typeof ROUTE_ACTIONS.policy | typeof ROUTE_ACTIONS.conflict,\n body: PinRequest | PolicyRequest | ConflictRequest,\n): Promise<PolicyAnswer> {\n try {\n const response = await fetch(`${ROUTE_PREFIX}/${action}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n const payload = (await response.json()) as PolicyEnvelope\n if (payload.ok === true) return { ok: true, snapshot: payload.value }\n return {\n ok: false,\n message: payload.error?.message ?? `request failed (${response.status})`,\n // The coded companions are optional on the wire: an old host's refusal\n // has none, and the render sites fall back to the message.\n ...(typeof payload.error?.messageCode === 'string'\n ? { messageCode: payload.error.messageCode, messageParams: payload.error.messageParams }\n : {}),\n }\n } catch (error) {\n return { ok: false, message: error instanceof Error ? error.message : String(error) }\n }\n}\n\n/** Hooks a pin write reports through, so one row can disable and explain. */\nexport interface PinWriteHooks {\n /** Called before the request goes out, with the tool it is about. */\n onStart?: (tool: string) => void\n /** Called after it settles, successfully or not. */\n onSettled?: (tool: string) => void\n /**\n * Called only when the host refused, with its own words — and with the\n * refusal's wire code and flat params when the host coded them (F-48).\n */\n onRefused?: (message: string, messageCode?: string, messageParams?: Record<string, string>) => void\n}\n\n/**\n * Write one tool's pin and report what happened.\n *\n * The twin of {@link requestMode} for the other half of the policy: it `POST`s\n * through {@link postPin}, which answers rather than throws, and leaves the\n * pending set and the refusal line to the caller — so one row disables while its\n * own write is in flight and a refusal is shown instead of swallowed.\n * @param body - the project, the public tool name and the wanted pin state.\n * @param hooks - lifecycle callbacks; all optional.\n * @returns the host's answer, for a caller that wants to keep the snapshot.\n */\nexport async function requestPin(\n body: PinRequest,\n hooks: PinWriteHooks = {},\n): Promise<PolicyAnswer> {\n hooks.onStart?.(body.tool)\n const answer = await postPin(body)\n hooks.onSettled?.(body.tool)\n if (!answer.ok) hooks.onRefused?.(answer.message, answer.messageCode, answer.messageParams)\n return answer\n}\n\n/** Hooks a mode write reports through, so a surface can disable and explain. */\nexport interface ModeWriteHooks {\n /** Called before the request goes out. */\n onStart?: (projectRoot: string) => void\n /** Called after it settles, successfully or not. */\n onSettled?: (projectRoot: string) => void\n /**\n * Called only when the host refused, with its own words — and with the\n * refusal's wire code and flat params when the host coded them (F-48).\n */\n onRefused?: (message: string, messageCode?: string, messageParams?: Record<string, string>) => void\n}\n\n/**\n * Hooks a conflict choice reports through, so one card can disable its buttons.\n */\nexport interface ChoiceWriteHooks {\n /** Called before the request goes out, with the name it is about. */\n onStart?: (server: string) => void\n /** Called after it settles, successfully or not. */\n onSettled?: (server: string) => void\n /**\n * Called only when the host refused, with its own words — and with the\n * refusal's wire code and flat params when the host coded them (F-48).\n */\n onRefused?: (message: string, messageCode?: string, messageParams?: Record<string, string>) => void\n}\n\n/**\n * Write one conflict choice and report what happened.\n *\n * The twin of {@link requestPin} for the other durable decision a project\n * carries. A choice is what moves an entry between a conflict report and a\n * mounted server under its local name, so the host answers with the snapshot\n * that already reflects it and the caller can draw the new state at once.\n * @param body - the project, the contested name and the declaration to show.\n * @param hooks - lifecycle callbacks; all optional.\n * @returns the host's answer, for a caller that wants to keep the snapshot.\n */\nexport async function requestConflict(\n body: ConflictRequest,\n hooks: ChoiceWriteHooks = {},\n): Promise<PolicyAnswer> {\n hooks.onStart?.(body.server)\n const answer = await postConflict(body)\n hooks.onSettled?.(body.server)\n if (!answer.ok) hooks.onRefused?.(answer.message, answer.messageCode, answer.messageParams)\n return answer\n}\n\n/**\n * Write one project's mode and report what happened.\n *\n * `POST`s through {@link postPolicyMode}, which already answers rather than\n * throws, and is deliberately plain: the caller owns the pending set and the\n * error line, so the whole write is a pure function of the request and three\n * callbacks. That is what makes the disabled and refusal states of the switch\n * testable without a DOM.\n * @param body - the project and mode to store.\n * @param hooks - lifecycle callbacks; all optional.\n * @returns the host's answer, for a caller that wants to keep the snapshot.\n */\nexport async function requestMode(\n body: PolicyRequest,\n hooks: ModeWriteHooks = {},\n): Promise<PolicyAnswer> {\n hooks.onStart?.(body.projectRoot)\n const answer = await postPolicyMode(body)\n hooks.onSettled?.(body.projectRoot)\n if (!answer.ok) hooks.onRefused?.(answer.message, answer.messageCode, answer.messageParams)\n return answer\n}\n","/**\n * The host's own usage counters, read where a surface shows them.\n *\n * Nothing here is measured, sampled or invented: `ProjectSnapshot.usage`\n * (`src/types.ts:425`) is published by the host half from the tool registry's\n * own events, keyed by server name, and these two readings are the whole of it\n * — how often a tool was called, and how long a server has not been used. A\n * surface that has no record draws no text (the plugin's \"no data, no label\"\n * rule), which is why both functions answer `undefined` rather than `0` when\n * the host said nothing: an invented zero reads as a fact the host never\n * published.\n *\n * Pure and React-free, so the sidebar tab, the settings page and the pin picker\n * share one reading of the same numbers.\n *\n * @module dsh-project-mcp/client/usage-view\n */\n\nimport type { ServerUsage } from '../types.ts'\n\n/**\n * The prefix the registry publishes project MCP tools under.\n *\n * Five characters, underscores included: a name is `mcp__<server>__<tool>`, so\n * the server starts after the prefix, not after `mcp`. The vocabulary lives here\n * rather than in `view.ts` because this module reads the same names and must not\n * import the panel back — a cycle between the panel and its counter reader would\n * make the counter's own module graph depend on the surface that draws it.\n * `view.ts` re-exports both names, so every existing caller keeps its import.\n */\nexport const MCP_TOOL_PREFIX = 'mcp__'\n\n/** The `__` that closes the server segment of a registry name, and opens the tool's. */\nconst SEPARATOR = '__'\n\n/**\n * The server part of a registry tool name.\n * @param name - a public registry name, e.g. `mcp__tglider__workspace`.\n * @returns the server name, or undefined when the name is not an MCP one.\n */\nexport function serverOfToolName(name: string): string | undefined {\n if (!name.startsWith(MCP_TOOL_PREFIX)) return undefined\n const separator = name.indexOf(SEPARATOR, MCP_TOOL_PREFIX.length)\n return separator === -1 ? undefined : name.slice(MCP_TOOL_PREFIX.length, separator)\n}\n\n/** One project's counters, as the host published them; `undefined` — the host said nothing. */\nexport type ProjectUsage = Record<string, ServerUsage> | undefined\n\n/**\n * How often one tool was called, by its public registry name.\n *\n * The name is `mcp__<server>__<tool>` (see `serverOfToolName`), and the counter\n * is keyed by the tool name as the server declared it — everything after the\n * second separator, which is why the split is not `name.split('__')`.\n * @param name - a public registry name, e.g. `mcp__tglider__workspace`.\n * @param usage - the project's counters, when the host published any.\n * @returns the call count, or undefined when the host recorded nothing for it.\n */\nexport function callsOfToolName(name: string, usage: ProjectUsage): number | undefined {\n const split = splitToolName(name)\n if (split === undefined) return undefined\n return usage?.[split.server]?.tools[split.tool]\n}\n\n/**\n * Both readings one tool row may print: the project's counter and this session's.\n *\n * A server is mounted for a project and shared by its sessions, so the two\n * numbers answer different questions and differ exactly when another session of\n * the project called the tool (F-34). `recorded` is the host's mere existence of\n * a record for the name's server, which is what separates \"never called\" from\n * \"not counted at all\".\n */\nexport interface ToolCalls {\n /** `true` when the host published a record for this name's server. */\n recorded: boolean\n /**\n * `true` when the host published this session's own slice of that record.\n *\n * It is the difference between \"the host does not split by session yet\" and\n * \"this session is counted and has never called this tool\" — two states whose\n * `session` reading is both `undefined`, and which a row must not print the\n * same way.\n */\n split: boolean\n /** Calls the project counted for this tool, when it counted any. */\n project: number | undefined\n /** Calls this session counted for this tool, when it counted any. */\n session: number | undefined\n}\n\n/**\n * Read both counters of one tool, by its public registry name.\n * @param name - a public registry name, e.g. `mcp__tglider__workspace`.\n * @param usage - the project's counters, when the host published any.\n * @param sessionId - the session to read the split for; absent reads the project only.\n * @returns the two readings, and whether the host recorded the server at all.\n */\nexport function toolCalls(\n name: string,\n usage: ProjectUsage,\n sessionId: string | undefined,\n): ToolCalls {\n const split = splitToolName(name)\n const record = split === undefined ? undefined : usage?.[split.server]\n if (split === undefined || record === undefined) {\n return { recorded: false, split: false, project: undefined, session: undefined }\n }\n const own = sessionId === undefined ? undefined : record.sessions?.[sessionId]\n return {\n recorded: true,\n split: own !== undefined,\n project: record.tools[split.tool],\n session: own?.tools[split.tool],\n }\n}\n\n/** The server and the declared tool name inside one public registry name. */\nfunction splitToolName(name: string): { server: string; tool: string } | undefined {\n const server = serverOfToolName(name)\n if (server === undefined) return undefined\n // Past `mcp__<server>__`: the tool name as the server declared it, separator\n // included, because a declared name may hold one of its own.\n return { server, tool: name.slice(MCP_TOOL_PREFIX.length + server.length + SEPARATOR.length) }\n}\n\n/** How long a server has been unused, in the one unit its row prints. */\nexport interface IdleSpan {\n /** The largest whole unit the span holds. */\n unit: 'day' | 'hour' | 'minute'\n /** How many of that unit, floored. */\n count: number\n}\n\nconst MINUTE_MS = 60_000\nconst HOUR_MS = 60 * MINUTE_MS\nconst DAY_MS = 24 * HOUR_MS\n\n/**\n * The span since a server was last used, in its largest whole unit.\n *\n * `≥ 24 h → days`, `≥ 1 h → hours`, otherwise whole minutes (`0` is a real\n * answer: the call just landed). A date the parser does not accept, a missing\n * one, and one in the future are all \"nothing to print\" — the last one because\n * a host clock ahead of this viewer's is not a negative idle span.\n * @param lastUsedAt - ISO timestamp of the server's most recent call.\n * @param now - epoch milliseconds to measure against.\n * @returns the span, or undefined when there is no usable date.\n */\nexport function idleOf(lastUsedAt: string | undefined, now: number): IdleSpan | undefined {\n if (lastUsedAt === undefined) return undefined\n const at = Date.parse(lastUsedAt)\n if (!Number.isFinite(at)) return undefined\n const elapsed = now - at\n if (elapsed < 0) return undefined\n if (elapsed >= DAY_MS) return { unit: 'day', count: Math.floor(elapsed / DAY_MS) }\n if (elapsed >= HOUR_MS) return { unit: 'hour', count: Math.floor(elapsed / HOUR_MS) }\n return { unit: 'minute', count: Math.floor(elapsed / MINUTE_MS) }\n}\n\n/**\n * The order a list of tool names is drawn in: the most-called first.\n *\n * Sorting follows the figure the row leads with — this session's counter when\n * the host published the split, the project's otherwise — so the list is ordered\n * by the number a reader can see. That cuts both ways: a tool other sessions\n * called 290 times and this one never called leads with `never called`, so it\n * sinks below a tool this session really used, even though the project figure\n * printed beside it is larger. The host's counter is the only frequency there\n * is; a name with no reading of its own is \"not measured\", not \"zero\", and it\n * neither outranks a measured name nor loses the order it arrived in (the sort\n * is stable and this comparator returns `0` for a tie), so a list the host\n * already ordered is never reshuffled for no reason.\n * @param usage - the project's counters, as the host published them.\n * @param sessionId - the session whose split leads the ordering; absent reads the project.\n * @returns comparator for `Array.prototype.sort`.\n */\nexport function byCalls(\n usage: ProjectUsage,\n sessionId?: string,\n): (left: string, right: string) => number {\n const count = (name: string): number => {\n const calls = toolCalls(name, usage, sessionId)\n // The lead figure, and only it: a name the session is in the split without\n // is unmeasured, however loud the project total beside it is.\n return (calls.split ? calls.session : calls.project) ?? -1\n }\n return (left, right) => count(right) - count(left)\n}\n","/**\n * Browser half of the panel: the tab shows one surface for the project of the\n * session it is open in — the session's declared servers, the sessions that read\n * differently from the project, what the model sees, and the problems and the\n * event ring under their own disclosures — while the settings popup, opened from\n * the tab's actions menu, keeps the whole picture across every project with a\n * live session. The native Settings page (`settings.section`, see\n * `./settings.ts`) is the third surface and shares this module's fetch/poll path,\n * status colours and storage helpers.\n *\n * Data comes from the host over `/project-mcp/*` (see `src/ui.ts`): the browser\n * half has nothing to call in process. The host half's types are imported\n * type-only, which the bundler erases — the client bundle stays free of host\n * code.\n *\n * @module dsh-project-mcp/client/view\n */\n\nimport { createElement as h, useCallback, useEffect, useState } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { ROUTE_ACTIONS, ROUTE_PREFIX, TAB_ID } from '../shared.ts'\nimport type { LogEvent, McpSnapshot, ProjectSnapshot, ServerRow, ServerStatus, SessionTools, SnapshotChange, ToolFacts, ToolField, ToolMode, ToolPolicy, ToolReason } from '../types.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\nimport { operatorBody, pinBody, policyOf } from './policy.ts'\nimport { MCP_TOOL_PREFIX, idleOf, serverOfToolName, toolCalls } from './usage-view.ts'\nimport type { ProjectUsage, ToolCalls } from './usage-view.ts'\n\n// The registry-name vocabulary is defined in `./usage-view.ts` — the counter\n// reader, which must not import this module back — and re-exported here: the\n// panel and every caller outside it (`settings-tools.ts`, the tests) have always\n// read `MCP_TOOL_PREFIX` and `serverOfToolName` from this module.\nexport { MCP_TOOL_PREFIX, serverOfToolName, toolCalls }\nexport type { ToolCalls }\n\n/**\n * The panel's own English copy.\n *\n * The tab is created through the sidebar service rather than through a slot, so\n * it carries its English table here and reaches the render functions through\n * {@link Translate}; `./tab-locale.ts` binds that table to the shell's locale\n * service and repaints the tab when the language changes. The settings page\n * registers the same table with `ctx.locale.register` (see\n * `./settings.ts`), which is why both halves share one namespace: one plugin,\n * one dictionary.\n */\nexport const en = {\n // The tab itself: its label in the sidebar and the line under it.\n tab: 'Project MCP',\n tabDescription:\n 'MCP servers each project declares, and what is mounted for its sessions',\n sync: 'Sync',\n retryFailed: 'Retry failed',\n // Tool presentation: the tab's tools block and the settings page's Tools rows.\n toolsSeeModel: 'what the model sees',\n toolsPinned: 'pinned',\n toolsByCounters: 'by the counters',\n toolsDisclosed: 'disclosed',\n toolsHidden: 'hidden',\n toolsNotMounted: 'Nothing to hide yet',\n toolsNotMountedHint:\n 'lazy mounting: the project’s servers come up on the session’s first step, so the catalog is empty until then',\n toolsNotMountedCode: 'tools[] = built-ins only · mcp__* not registered yet',\n // The declared servers of this session, on the tools block: the reason an\n // apparently empty catalog is empty.\n toolsServers: 'Servers',\n toolsServersUp: '{up}/{total} up',\n toolsGroupPinned: 'pinned · always in the request',\n toolsGroupCounters: 'offered by the counters',\n toolsGroupDisclosed: 'disclosed by the model · until the session ends',\n toolsGroupHidden: 'hidden',\n toolsPin: 'Pin',\n toolsPinHint: 'Keep this tool in every request of this project',\n toolsUnpin: 'Unpin',\n toolsUnpinHint: 'Stop pinning this tool in every request of this project',\n toolsHide: 'Hide',\n toolsHideHint: 'Drop this disclosure and stop offering the tool',\n toolsHiddenVia: 'available to the model through mcp_search_tools only',\n // The tools block's own filter (F-43): the counter chips above the list stop\n // being a reading and become the tier switch, and a query narrows by name.\n toolsFilterPlaceholder: 'filter by name…',\n toolsFilterLabel: 'filter this session’s tools by registry name',\n toolsFilterTier: 'Show this tier alone; press again for every tier',\n toolsFilterClear: 'Clear',\n toolsFilterClearHint: 'Show every tier and drop the query',\n toolsFilterShown: 'showing {shown} of {total}',\n toolsFilterNone: 'No tool of this session matches the filter.',\n // The server-level pin (F-44): one press for a whole server's names, since a\n // server is how the hidden tier and the settings page both group them.\n toolsPinAll: 'Pin all',\n toolsPinAllHint: 'Pin every hidden tool of this server in every request',\n // The other direction of the same press, said by both surfaces when the set is\n // already wholly pinned. A tier's names are usually unpinned, but the snapshot\n // can hold a pin that is still listed as deferred — a pin written between two\n // assemblies, or one the host itself defers — and a button that read `Pin all`\n // while it released it would be a lie.\n toolsUnpinAll: 'Unpin all',\n toolsUnpinAllHint: 'Stop pinning every hidden tool of this server',\n // The same press on the pinned tier, where the names it releases are the ones\n // the user pinned rather than the ones the host hid.\n toolsUnpinServerHint: 'Stop pinning every tool of this server',\n toolsBudget: '{used} chars of {total} · ≈ {tokens} tokens',\n toolsBudgetExhausted: 'the budget is spent: further disclosures are rejected with a reason',\n toolsBudgetFree: 'free room in the budget or pin the tool in the project settings',\n toolsBudgetGateOff: 'the disclosure gate is off: every mounted tool goes into the request',\n toolsBudgetBreakdown: '{used} of {total} ({percent}%)',\n toolsModeOff: 'this project’s MCP tools are switched off',\n toolsModeOffCounters: '{mounted} mounted · none offered',\n toolsModeOffHint:\n 'Nothing from this project is offered to the model. Set the mode to “Disclosure” on the Tools page to offer them again.',\n toolsModeDirect: 'nothing is deferred: every mounted tool goes into the request',\n toolsPresentationOwner: 'Another plugin is shaping the request',\n toolsOtherOwner: 'Another presentation owner',\n toolsDemo: 'demo',\n toolsStep: 'step {step}',\n // The host's own usage counters (`ProjectSnapshot.usage`), read as two quiet\n // labels: how often one tool was called, and how long one server has gone\n // unused. Both are drawn only where the host published a record — no data, no\n // label — so `never called` means \"the server is in the counters and this tool\n // is not\", never \"the host said nothing\".\n callsOne: '1 call',\n callsMany: '{count} calls',\n callsNone: 'never called',\n callsProject: '{count} in the project',\n idleDay: 'idle {count}d',\n idleHour: 'idle {count}h',\n idleMinute: 'idle {count}m',\n // One tool row's detail block (F-56): the server the name was registered\n // under with the state it is in, the tier said as a sentence, the two counter\n // readings apart, and then what only the host can answer — the definition's\n // own description, its fields, and why a hidden name is not in the request.\n // The name, the clock and the step stay in the header, and the block prints\n // them again in its own fact line because the contract's own probe reads the\n // full `mcp__<server>__<tool>`, the step and the clock out of the open body\n // (`contracts/surfaces.md` §1.5) — see the `idea` row that parks that question\n // in `docs/features.md`. The host publishes no size for a single tool, so the\n // budget estimate stays in the group line above — the only figure the reason\n // line prints is a measurement the host sent it.\n toolServer: 'server {server}',\n toolServerState: '{server} · {state}',\n toolTierPinned: 'pinned — always in the request',\n toolTierSession: 'offered by this session',\n toolTierContext: 'offered by the context ranking',\n showTool: 'show this tool’s server, description, fields and how it was offered',\n hideTool: 'hide this tool’s detail',\n toolCallsSession: '{count} this session',\n toolLoading: 'reading this definition from the host…',\n toolFailed: 'the host did not answer for this definition',\n toolFieldsLabel: 'takes',\n toolFieldRequiredHint: 'required field',\n toolReasonBudget: 'not offered: {chars} chars over the {budget}-char budget',\n toolReasonChars: '{chars} chars',\n toolReasonBudgetOnly: '{budget}-char budget',\n toolReasonUsed: '{used} already offered',\n toolReason: 'not offered',\n // The errors and logs blocks, under their own disclosures: the event ring is\n // the plugin's own, one project at a time.\n errorsSection: 'Problems',\n showErrors: 'show the servers that need a look',\n hideErrors: 'hide the servers that need a look',\n logsSection: 'Logs',\n showLogs: 'show this project’s events',\n hideLogs: 'hide this project’s events',\n logsThisSession: 'this session',\n logsAllSessions: 'all sessions',\n logsAllLevels: 'all levels',\n logsErrorsOnly: 'errors',\n logsLevelInfo: 'info',\n logsLevelUp: 'up',\n logsLevelWarn: 'warn',\n logsLevelError: 'error',\n logsClear: 'Clear',\n logsClearHint: 'Hide every event recorded so far; new ones still appear',\n logsEmptyTitle: 'No events yet',\n logsEmptyHint:\n 'This project’s servers come up on the session’s first step or when you press Sync; mounting, start and stop will show up here.',\n logsNoErrorsTitle: 'No errors',\n logsNoErrorsHint:\n 'This project’s ring holds other events; switch the level filter to “all levels” to read them.',\n logsMore: 'Show older',\n logsMoreHint: 'Load the events older than the ones on screen',\n logsShown: 'showing {shown} of {total}',\n logsProjectCount: '{count} in this project',\n logsLoading: 'loading older events…',\n logsLoadFailed: 'older events could not be read',\n // The tab's own states, in the same table for the same reason.\n noSession: 'No session is attached to this tab.',\n noSessionHint: 'The panel reads the project of the session it is open in.',\n noProject: 'This session’s folder is not inside a project yet.',\n noProjectHint:\n 'The host walks up from the session cwd looking for .git · .dsh · .kimi-code · package.json · *.sln.',\n nothingNeedsAttention: 'Nothing needs attention.',\n noServersDeclared: 'This project declares no MCP servers.',\n noServersDeclaredHint: 'Add {documents}.',\n noServersDeclaredUnknown: 'Add an MCP document to the project.',\n noServersDeclaredNowhere:\n 'This deployment reads no project document, so there is nowhere to declare one — list one in the plugin config (`localFiles`).',\n // Surface A's own header and the vocabulary its rows are built from. The\n // segment bar is gone (F-26): the toolbar names the project and carries one\n // phrase on its right edge, and every count a mode segment used to badge lives\n // on the block it describes.\n thisSession: 'this session',\n noProjectLabel: 'no project',\n retry: 'Retry',\n retryHint: 'Retry this project’s failed mounts now',\n sessionsSection: 'sessions',\n // The `sessions` section is the project's *disagreement* view: its chip counts\n // the sessions whose own reading differs from the merged rows, not the\n // sessions that exist. The count of existing sessions lives on the toolbar's\n // right edge, which keeps `sessionsOne` / `sessionsMany` for itself.\n differsOne: '1 differs',\n differsMany: '{count} differ',\n sessionsOne: '1 session',\n sessionsMany: '{count} sessions',\n serversOne: '1 server',\n serversMany: '{count} servers',\n mergedAcrossSessions: 'merged across sessions',\n release: 'Release',\n nothingDeclared: 'nothing declared',\n showSessions: 'show the sessions of this project',\n hideSessions: 'hide the sessions of this project',\n showSession: 'show this session’s servers',\n hideSession: 'hide this session’s servers',\n mountedPerProject: 'Mounted per project',\n projectsCount: '{count} project(s)',\n nothingMounted: 'Nothing is mounted yet.',\n // The status vocabulary (F-47): the word a row wears and the one-line\n // explanation its tooltip carries. Both are read through `STATUS_KEYS` /\n // `STATUS_HINT` — `Record<ServerStatus, LocaleKey>` tables — so a new enum\n // member without a key is a compile error, never a raw token on screen.\n statusActive: 'active',\n statusConnecting: 'connecting',\n statusConflict: 'conflict',\n statusError: 'error',\n statusIdle: 'idle',\n statusDisabled: 'disabled',\n statusHintActive: 'mounted, its tools are visible in this session',\n statusHintConnecting: 'mounted, no tool published yet',\n statusHintIdle: 'declared but not mounted — mounts on the next turn',\n statusHintDisabled: 'declared with enabled: false',\n statusHintConflict: 'the same serverName is reserved by a profile-level instance',\n statusHintError: 'see the detail',\n // One project's or session's status line (`2 active, 1 idle`): one template\n // per status, so the count is a `{count}` placeholder in every language and\n // never a concatenation. `summarize` names no `disabled` count today; the\n // template is here so the day it does, the word is too.\n summaryActive: '{count} active',\n summaryConnecting: '{count} connecting',\n summaryIdle: '{count} idle',\n summaryDisabled: '{count} disabled',\n summaryError: '{count} error',\n summaryConflict: '{count} conflict',\n summaryNone: 'nothing declared',\n close: 'Close',\n // The frame-wide toasts (F-47): drafts carry these keys, and the stack\n // resolves them at render, so a language switch repaints the banners on\n // screen. The quieter line weaves the project around the fact behind the\n // moment — the host's own detail sentence, or a status hint.\n toastUp: '{server} is up',\n toastFailed: '{server} failed',\n toastReleased: '{server} released',\n toastDetail: '{project} · {detail}',\n // The poll interval's row in the settings panel, read live through the seat\n // on every render.\n refreshTitle: 'Refresh interval',\n refreshDesc: 'How often the panel re-reads the host snapshot',\n // The tab's actions menu (the chip's own menu): the row that opens the\n // settings popup, which used to be the sidebar's side card.\n settingsMenuItem: 'Panel settings…',\n // The design stand's own tab title and description (design.ts).\n designTitle: 'Project MCP · design ({variant})',\n designDesc: 'design mode: the {variant} fixture, no host behind it',\n}\n\n/** A dictionary key of this namespace. */\nexport type LocaleKey = keyof typeof en\n\n/** Translate one key, with optional `{name}` template params (the DSH seat). */\nexport type Translate = (key: string, params?: Record<string, unknown>) => string\n\n/**\n * Bind the translate seat a surface was given, falling back to this module's own\n * English dictionary when it renders outside a DSH shell (tests, or a browser\n * half newer than the host).\n * @param t - the injected `t` seat, when there is one.\n * @returns a translate function that always answers.\n */\nexport function translateOf(t?: Translate): Translate {\n return t ?? fallbackTranslate\n}\n\n/** The panel's own English copy, same shape as the settings page's fallback. */\nexport function fallbackTranslate(key: string, params?: Record<string, unknown>): string {\n const template = (en as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in params ? String(params[name]) : match,\n )\n}\n\n/** Name of the poll interval inside {@link REFRESH_STORAGE_KEY}. */\nexport const REFRESH_KEY = 'refreshMs'\n\n/**\n * `localStorage` key the poll interval is persisted under.\n *\n * The interval used to ride the side card's own settings blob\n * (`prefs.pluginSettings[TAB_ID]` of `dsh-better-sidebar`). That surface is gone\n * with the dependency, so the interval is a browser-local preference beside the\n * view, the log filters and the Clear mark — same lifetime, same hostile-storage\n * rule, one less service to read it from.\n */\nexport const REFRESH_STORAGE_KEY = `${TAB_ID}:${REFRESH_KEY}`\n\n/** Poll interval used until the setting is read. */\nexport const DEFAULT_REFRESH_MS = 5_000\n\n/**\n * Status colours, taken from the design system's alias layer\n * (`packages/client/ui-theme/src/styles/design-platform.css` in the DSH\n * checkout): `state-*` for the lifecycle, `label-tertiary` for the two quiet\n * states. The fallbacks only ever fire outside the DSH web client, where that\n * alias layer is not loaded.\n */\nexport const STATUS_COLOR: Record<ServerStatus, string> = {\n active: 'var(--dsw-alias-state-success-primary, #22c55e)',\n connecting: 'var(--dsw-alias-state-warn-primary, #f59e0b)',\n conflict: 'var(--dsw-alias-state-warn-primary, #f59e0b)',\n error: 'var(--dsw-alias-state-error-primary, #ec1313)',\n idle: 'var(--dsw-alias-label-tertiary, #81858c)',\n disabled: 'var(--dsw-alias-label-tertiary, #81858c)',\n}\n\n/**\n * The dictionary key of the word each status wears on its row, so the panel\n * never prints the enum token itself: a `ServerStatus` member without a key\n * here is a compile error, not a silent English leak in another language.\n */\nexport const STATUS_KEYS: Record<ServerStatus, LocaleKey> = {\n active: 'statusActive',\n connecting: 'statusConnecting',\n conflict: 'statusConflict',\n error: 'statusError',\n idle: 'statusIdle',\n disabled: 'statusDisabled',\n}\n\n/**\n * The dictionary key of each status's one-line explanation, so the panel needs\n * no legend. Readers translate through their own seat —\n * `t(STATUS_HINT[row.status])` — which keeps the sentence the tooltip or the\n * toast shows in the reader's language.\n */\nexport const STATUS_HINT: Record<ServerStatus, LocaleKey> = {\n active: 'statusHintActive',\n connecting: 'statusHintConnecting',\n idle: 'statusHintIdle',\n disabled: 'statusHintDisabled',\n conflict: 'statusHintConflict',\n error: 'statusHintError',\n}\n\nconst BORDER = '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))'\n\n/**\n * The alias layer's own tones, named once.\n *\n * The mockup's vocabulary has two levels of quiet text — `.muted` (secondary)\n * and `.dim` (tertiary) — and this surface used to paint both by dropping the\n * opacity of the primary colour, which is close to the token but not the same\n * value. Reading the token keeps the two tones distinguishable in both themes.\n */\nconst TONE = {\n /** `.muted`: the secondary label tone, for text the user reads next. */\n secondary: 'var(--dsw-alias-label-secondary, inherit)',\n /** `.dim`: the tertiary label tone, for captions and quiet states. */\n tertiary: 'var(--dsw-alias-label-tertiary, #81858c)',\n} as const\n\n/** The alias layer's layer-3 fill — the mockup's chip and the ring's filters. */\nconst LAYER_3 = 'var(--dsw-alias-bg-layer-3, rgba(127, 127, 127, 0.12))'\n\n/**\n * The counter chip's plate, named once because it has two readers now: the\n * reading chip of {@link STYLE.tag} and the pressable tier chip of the tools\n * block's filter (F-43). The two differ only in the three resets a `<button>`\n * needs and in the fill the pressed one takes, so the words and the count read\n * the same whether the tier is a label or a switch.\n */\nconst LAYER_3_CHIP = {\n background: LAYER_3,\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n fontSize: '0.85em',\n borderRadius: 4,\n padding: '0 5px',\n color: TONE.secondary,\n} satisfies CSSProperties\n\n/**\n * One step of the Servers surface's indentation ladder, in pixels.\n *\n * Surface A nests four levels and every one sits exactly one step right of the\n * one above it — `project 0 → sessions 12 → session 24 → that session's servers\n * 36`. The `sessions` rung is conditional: it exists only while at least one\n * session disagrees with the project's merged rows, so a project whose sessions\n * all agree stops at rung `0`. The scale lives here, once, and each level asks\n * for its rung through {@link STYLE.indent}; the hand-picked `paddingLeft`\n * values this replaced had drifted out of step with one another.\n */\nexport const INDENT = 12\n\n/**\n * The panel's own inline styles.\n *\n * Exported for the design-only render mode (`./design.ts`), which composes the\n * same `PanelHeader` / `tabBody` from a fixture and must therefore frame them\n * with the very same root and body — a second copy of these two objects is\n * exactly how a mockup drifts from the product.\n */\nexport const STYLE = {\n root: {\n display: 'flex',\n flexDirection: 'column',\n height: '100%',\n minHeight: 0,\n color: 'inherit',\n } satisfies CSSProperties,\n bar: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n // The mock's `.panel-bar` (`docs/design/mockups/harness.html`) — the panel's own inset, so the\n // chips and the project name start on the picture's margin.\n padding: '7px 9px',\n borderBottom: BORDER,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n body: {\n flex: 1,\n minHeight: 0,\n overflow: 'auto',\n // The one surface's blocks are direct children of this container (F-26), so\n // the inset the old per-mode wrapper used to supply is here now — the\n // mock's `.body { padding: 9px 10px }` (`docs/design/mockups/harness.html`).\n padding: '9px 10px',\n } satisfies CSSProperties,\n /** The rows' own inset: the mock's `.body` (`docs/design/mockups/harness.html`). */\n project: { padding: '9px 10px', borderBottom: BORDER } satisfies CSSProperties,\n projectHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n justifyContent: 'space-between',\n } satisfies CSSProperties,\n /**\n * `.muted`: the secondary tone, at the text's own size.\n *\n * The mock's `.muted` states a colour and nothing else (`docs/design/mockups/harness.html`),\n * and the dictionary's obligation is \"a muted colour, not a blindly reduced\n * size\" — so the tone is here and the size is the neighbouring text's.\n */\n muted: { color: TONE.secondary } satisfies CSSProperties,\n /** `.dim`: the tertiary tone, one step quieter than `.muted`. */\n dim: { color: TONE.tertiary, fontSize: '0.9em' } satisfies CSSProperties,\n row: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n padding: '2px 0',\n } satisfies CSSProperties,\n sessions: {\n marginTop: 4,\n paddingTop: 4,\n borderTop: BORDER,\n } satisfies CSSProperties,\n session: { padding: '2px 0' } satisfies CSSProperties,\n sessionHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n sessionToggle: {\n padding: 0,\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n textAlign: 'left',\n } satisfies CSSProperties,\n /**\n * `tag`: the mockup's chip is a short plate on a layer fill in mono type — not\n * a word in the row, and not a bordered box either (`docs/design/mockups/harness.html`,\n * dictionary line 13).\n */\n tag: { ...LAYER_3_CHIP } satisfies CSSProperties,\n /** The `idle` / `disabled` chip: the mockup's `.dim` tone, one step quieter. */\n tagQuiet: {\n color: TONE.tertiary,\n } satisfies CSSProperties,\n /** The `up/total` chip once a declared server is failing: red, not quiet. */\n tagWarn: {\n color: 'var(--dsw-alias-state-error-primary, #ec1313)',\n } satisfies CSSProperties,\n /**\n * One counter chip of the tools block, as the filter's tier switch (F-43).\n *\n * The same plate {@link STYLE.tag} draws — the words and the count do not\n * change with the tier — with the resets a `<button>` needs to sit in a row of\n * spans without becoming a form control the shell styles. The chip is a leaf\n * holding its text directly, which is also what lets the parity gate read\n * `{count} pinned` off it.\n *\n * `font: inherit` comes **before** the plate, and the order is the whole\n * point: `font` is a shorthand that resets `font-family` and `font-size` too,\n * and React writes the inline style in this object's own order — behind the\n * plate it silently turned the chips into the shell's sans face, which is the\n * one thing a chip of this vocabulary is not (see the neighbouring\n * `STYLE.logFilter`, where the shorthand is the last word on purpose because\n * that chip is the shell's own type).\n */\n filterChip: {\n font: 'inherit',\n cursor: 'pointer',\n border: 'none',\n ...LAYER_3_CHIP,\n } satisfies CSSProperties,\n /** The pressed tier chip: the applied filter is the one that reads as active. */\n filterChipOn: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n color: 'var(--dsw-alias-label-primary, inherit)',\n } satisfies CSSProperties,\n /**\n * The filter's query field: the shell's own input plate, one size down and\n * full width, so the field reads as the panel's own row rather than a form\n * control borrowed from the settings page.\n */\n filterInput: {\n flex: 1,\n minWidth: 0,\n border: BORDER,\n borderRadius: 4,\n padding: '2px 6px',\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.85em',\n } satisfies CSSProperties,\n /**\n * A group label that shares its line with a chip. {@link STYLE.group} owns a\n * whole line at the tertiary tone, which would bleach the chip with it.\n */\n groupInline: {\n color: TONE.tertiary,\n fontSize: '0.8em',\n letterSpacing: '0.08em',\n textTransform: 'uppercase',\n } satisfies CSSProperties,\n /** The session's declared-servers block, the single surface's first block. */\n serversBlock: {\n margin: '0 0 6px',\n paddingBottom: 4,\n borderBottom: BORDER,\n } satisfies CSSProperties,\n /**\n * One rung of the Servers surface's indentation ladder: `level` steps right of\n * the project's own rows, so `0` is the project, `1` the `sessions` section,\n * `2` one session of it, `3` that session's own servers. The only left padding\n * the surface has; nothing else may hand-pick one.\n */\n indent: (level: number): CSSProperties => ({ paddingLeft: level * INDENT }),\n // An identifier is one unbreakable token (`mcp__tglider__workspace`), and the\n // panel is 330px wide at its narrowest: without a break opportunity the name\n // overflows its own row button instead of wrapping inside it. `anywhere` rather\n // than `break-word` because only `anywhere` shrinks the item's own min-content\n // width, which is what the flex row measures.\n name: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n detail: { opacity: 0.7, overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' } satisfies CSSProperties,\n button: {\n padding: '2px 8px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n } satisfies CSSProperties,\n error: { padding: 8, color: STATUS_COLOR.error } satisfies CSSProperties,\n /**\n * The poll interval's row in the settings panel: a label that stacks the\n * toggle's own title and hint, the field it points at, and the unit beside it.\n * Laid out as one row so the panel reads like the side card the row came from.\n */\n settingRow: {\n display: 'flex',\n alignItems: 'center',\n gap: 8,\n padding: '8px 8px 0',\n } satisfies CSSProperties,\n settingLabel: { display: 'flex', flexDirection: 'column', gap: 2, flex: 1 } satisfies CSSProperties,\n settingTitle: { fontSize: 12 } satisfies CSSProperties,\n settingDesc: { fontSize: 11, color: TONE.tertiary } satisfies CSSProperties,\n settingInput: {\n width: 72,\n padding: '2px 6px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n } satisfies CSSProperties,\n settingUnit: { fontSize: 11, color: TONE.tertiary } satisfies CSSProperties,\n /**\n * One disclosure of the single surface (F-26): a block of the scrolling body\n * whose head is a button and whose body exists only while it is open. The\n * parity gate finds it as a `div` with a `button[aria-expanded]` child, so the\n * head is the block's first child and the body its second — the shape the\n * mockup's `.disclosure` declares.\n */\n disclosure: { marginTop: 5 } satisfies CSSProperties,\n disclosureHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n width: '100%',\n padding: '2px 0',\n border: 'none',\n background: 'transparent',\n font: 'inherit',\n textAlign: 'left',\n cursor: 'pointer',\n // `.disclosure-head`: the label is the control's word, read in the quiet\n // tone (`docs/design/mockups/harness.html`, F-26 block).\n color: TONE.tertiary,\n } satisfies CSSProperties,\n disclosureBody: { paddingLeft: 12 } satisfies CSSProperties,\n /**\n * One tool row: the line the user reads with its one action beside it, and the\n * detail block on its own line while it is open. The line is the disclosure's\n * `button[aria-expanded]` and a direct child of this wrapper, so a parity probe\n * that looks for `div > button[aria-expanded]` finds the row, and the action\n * stays a sibling — a button inside a button is not a thing HTML has.\n */\n tool: {\n display: 'flex',\n flexWrap: 'wrap',\n alignItems: 'baseline',\n gap: 6,\n } satisfies CSSProperties,\n /** The tool row's own line: the tier dot, the name, and the time and step. */\n toolLine: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n flex: 1,\n minWidth: 0,\n padding: '2px 0',\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n textAlign: 'left',\n } satisfies CSSProperties,\n /**\n * The open detail of one tool (F-56): the server it was registered under with\n * the state it is in, the tier as a sentence, the counter readings this row does\n * not show, and then the host's own on-demand answer about the definition — its\n * description, the fields it takes, and why a hidden name is not in the request.\n * One rung in from the row, like every other body of a disclosure.\n */\n toolDetail: {\n flexBasis: '100%',\n padding: '2px 0 4px 12px',\n } satisfies CSSProperties,\n /** One accepted field of a definition: its mono name, type, marker and description. */\n field: {\n display: 'flex',\n flexWrap: 'wrap',\n alignItems: 'baseline',\n gap: 5,\n padding: '1px 0',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldName: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldDesc: { color: TONE.secondary, opacity: 0.75 } satisfies CSSProperties,\n group: {\n opacity: 0.6,\n fontSize: '0.8em',\n letterSpacing: '0.08em',\n textTransform: 'uppercase',\n margin: '7px 0 1px',\n } satisfies CSSProperties,\n empty: {\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n gap: 6,\n padding: '14px 10px',\n textAlign: 'center',\n } satisfies CSSProperties,\n emptyTitle: { opacity: 0.9 } satisfies CSSProperties,\n hint: { opacity: 0.6, fontSize: '0.85em', overflowWrap: 'anywhere' } satisfies CSSProperties,\n dot: {\n width: 8,\n height: 8,\n borderRadius: '50%',\n display: 'inline-block',\n flex: 'none',\n alignSelf: 'center',\n } satisfies CSSProperties,\n codeLine: {\n margin: 8,\n padding: '5px 8px',\n border: BORDER,\n borderRadius: 5,\n background: 'var(--dsw-alias-markdown-code-block, transparent)',\n color: 'var(--dsw-alias-link, inherit)',\n fontSize: '0.8em',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n budget: {\n height: 4,\n margin: '4px 0 2px',\n borderRadius: 2,\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n overflow: 'hidden',\n } satisfies CSSProperties,\n budgetUsed: {\n display: 'block',\n height: '100%',\n background: 'var(--dsw-alias-state-business-primary, currentColor)',\n } satisfies CSSProperties,\n warnNote: {\n margin: '8px 0',\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-warn-primary, #f59e0b)',\n background: 'var(--dsw-alias-state-warn-tertiary, transparent)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n /** A quiet row — `idle` or `disabled` — reads at the same size, dimmed. */\n rowQuiet: { opacity: 0.6 } satisfies CSSProperties,\n /** A row of chips: the hidden-by-server tags the tools block draws. */\n chips: {\n display: 'inline-flex',\n alignItems: 'center',\n gap: 4,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n /** The header row of the collapsed sessions section. */\n sessionsHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n /** A failure banner: the coloured left rule carries the severity, not a word. */\n banner: {\n margin: '2px 0 4px',\n padding: '4px 7px',\n borderRadius: '0 5px 5px 0',\n borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',\n background: 'var(--dsw-alias-interactive-bg-hover-danger, transparent)',\n color: 'var(--dsw-alias-label-primary, inherit)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n // A mount detail is a multi-line diagnostic (error, endpoint, declaration,\n // next step); collapsing its line breaks is what made it unreadable.\n whiteSpace: 'pre-wrap',\n } satisfies CSSProperties,\n /** Laid over {@link STYLE.banner} for a restriction rather than a failure. */\n bannerWarn: {\n borderLeftColor: 'var(--dsw-alias-state-warn-primary, #f59e0b)',\n background: 'var(--dsw-alias-state-warn-tertiary, transparent)',\n } satisfies CSSProperties,\n /**\n * One log event's first line: time, level, server, message.\n *\n * `flexWrap` is the point of this row. A sidebar is narrow, and a message kept\n * in a trailing column turns into a staircase of two-word fragments; wrapping\n * the row lets the message take the rest of the line and the whole of the next\n * one, which is how the mockup reads.\n */\n logRow: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n padding: '2px 0',\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n /** The event's clock: mono, tertiary, fixed width so the column aligns. */\n logTime: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n color: TONE.tertiary,\n fontSize: '0.85em',\n flex: 'none',\n } satisfies CSSProperties,\n /**\n * The level chip. It reuses {@link STYLE.tag}'s plate and is only coloured on\n * top of it, so `info` reads as the quiet chip it is and `error` as the alarm.\n */\n logLevel: { flex: 'none', textTransform: 'none', fontWeight: 500 } satisfies CSSProperties,\n /**\n * A filter chip of the Logs toolbar: a button that reads like {@link STYLE.tag}\n * but keeps the interface font, since it is a control rather than a value.\n */\n logFilter: {\n padding: '1px 6px',\n border: 'none',\n borderRadius: 4,\n background: LAYER_3,\n color: TONE.secondary,\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.85em',\n } satisfies CSSProperties,\n /** The filter currently applied: one pressed chip per pair. */\n logFilterOn: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n color: 'var(--dsw-alias-label-primary, inherit)',\n } satisfies CSSProperties,\n /** Server name of the event, in the same mono face as every other name. */\n logName: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n color: TONE.secondary,\n flex: 'none',\n } satisfies CSSProperties,\n /** The message: its own width, so it never becomes a two-word column. */\n logMessage: {\n flex: '1 1 100%',\n marginTop: 1,\n overflowWrap: 'anywhere',\n color: 'var(--dsw-alias-label-primary, inherit)',\n } satisfies CSSProperties,\n /** One fact line under a failing event; `marginLeft` sits it under the text. */\n logDetail: {\n margin: '0 0 3px',\n paddingLeft: 7,\n borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',\n color: 'var(--dsw-alias-label-primary, inherit)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n /** `error` chip: the alarm tone of {@link STATUS_COLOR}. */\n logError: { color: STATUS_COLOR.error } satisfies CSSProperties,\n /** `warn` chip: the same tone a stalled server row uses. */\n logWarn: { color: STATUS_COLOR.connecting } satisfies CSSProperties,\n /** `up` chip: a successful mount reads like an active server. */\n logUp: { color: STATUS_COLOR.active } satisfies CSSProperties,\n}\n\ninterface Envelope<T> {\n ok: boolean\n value?: T\n error?: { code?: string; message?: string }\n}\n\n/**\n * Call one host route, unwrapping the `{ ok, value }` envelope.\n *\n * Exported so a surface that needs the snapshot outside the tab's own polling\n * hook reads the same route the same way.\n * @param path - route action under `ROUTE_PREFIX`.\n * @param body - JSON body for a `POST` action; omitted for a `GET`.\n * @returns the unwrapped snapshot.\n */\nexport async function request(path: string, body?: unknown): Promise<McpSnapshot> {\n const response = await fetch(`${ROUTE_PREFIX}/${path}`, routeInit(path, body))\n const payload = (await response.json()) as Envelope<McpSnapshot>\n if (payload.ok !== true || payload.value === undefined) {\n throw new Error(payload.error?.message ?? `request failed (${response.status})`)\n }\n return payload.value\n}\n\n/**\n * The `fetch` init for one route call.\n *\n * The method follows the **action**, never whether a payload happened to be\n * passed: the reads — the snapshot, the status channel and a page of logs — are\n * `GET`, and every other action is a `POST` the host refuses for `GET`. Deciding\n * this from the body was a real defect — `Sync` and `Retry` pass no payload, so\n * they were sent as `GET` and answered `404` from both panels, while `Release`\n * (which sends a session id) worked.\n *\n * @param path - route action under `ROUTE_PREFIX`.\n * @param body - JSON body; an action without one sends `{}` rather than nothing.\n * @returns the init to hand to `fetch`.\n */\nexport function routeInit(path: string, body?: unknown): RequestInit {\n // `logs` is read out of the registry rather than repeated as a literal: the\n // contract gives the route one owner, and this stays correct once it lands.\n const logs = (ROUTE_ACTIONS as Record<string, string | undefined>).logs\n const reads = [ROUTE_ACTIONS.snapshot, ROUTE_ACTIONS.events, ...(logs === undefined ? [] : [logs])]\n if (reads.includes(path)) return {}\n return {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n }\n}\n\ninterface SnapshotState {\n snapshot: McpSnapshot | undefined\n error: string | undefined\n busy: boolean\n}\n\n/**\n * Poll the host snapshot while the panel is visible; the Settings page polls it\n * unconditionally. Exported so both surfaces share one fetch/unwrap/poll path.\n *\n * The poll is the **fallback**: the host pushes every change over the status\n * channel (`GET /project-mcp/events`, see `createEventStream` in `src/ui.ts`),\n * and a panel whose stream is open polls nothing. A host half older than the\n * route, a browser without `EventSource`, or a dropped connection all land in the\n * same place — the poll keeps the picture fresh, and `EventSource` reconnects on\n * its own until the stream is back.\n * @param visible - false suspends polling (the sidebar tab does this while hidden).\n * @param refreshMs - poll interval while the status channel is not connected.\n * @param path - route action to poll; the snapshot unless a surface asks for another.\n * @returns the latest snapshot, the last error, the in-flight flag and `run`.\n */\nexport function useSnapshot(visible: boolean, refreshMs: number, path: string = 'snapshot') {\n const [state, setState] = useState<SnapshotState>({ snapshot: undefined, error: undefined, busy: false })\n const [pushed, setPushed] = useState(false)\n const load = useCallback(async () => {\n try {\n const snapshot = await request(path)\n setState((previous) => ({ ...previous, snapshot, error: undefined }))\n } catch (error) {\n setState((previous) => ({ ...previous, error: messageOf(error) }))\n }\n }, [path])\n /**\n * Apply one pushed frame. Every frame carries the whole picture, so one that\n * arrived after a gap is still a complete answer — nothing to refetch.\n */\n const apply = useCallback((change: SnapshotChange) => {\n setState((previous) => ({ snapshot: change.snapshot, error: undefined, busy: previous.busy }))\n }, [])\n useEffect(() => {\n if (!visible || typeof EventSource === 'undefined') return\n const source = new EventSource(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.events}`)\n const onFrame = (event: Event): void => {\n try {\n apply(JSON.parse(String((event as MessageEvent).data)) as SnapshotChange)\n } catch {\n // A frame the panel cannot read is one poll away; the connection stays.\n }\n }\n source.addEventListener('hello', onFrame)\n source.addEventListener('change', onFrame)\n source.addEventListener('open', () => setPushed(true))\n source.addEventListener('error', () => setPushed(false))\n return () => {\n source.close()\n setPushed(false)\n }\n }, [visible, apply])\n useEffect(() => {\n if (!visible || pushed) return\n void load()\n const timer = setInterval(() => void load(), Math.max(1_000, refreshMs))\n return () => clearInterval(timer)\n }, [visible, pushed, refreshMs, load])\n /**\n * Run one action. The method comes from {@link routeInit}, so an action with\n * no payload is still a `POST`.\n * @param path - route action under `ROUTE_PREFIX`.\n * @param body - JSON body, when the action takes one.\n */\n const run = useCallback(async (path: string, body?: unknown) => {\n setState((previous) => ({ ...previous, busy: true }))\n try {\n setState({ snapshot: await request(path, body), error: undefined, busy: false })\n } catch (error) {\n setState((previous) => ({ ...previous, busy: false, error: messageOf(error) }))\n }\n }, [])\n /**\n * Run one action once per body, and set the picture once.\n *\n * The pin route writes exactly one name per call (`PinRequest`), so a server's\n * worth of names is a fan-out rather than one request — and a server-level\n * press is one intent, so it deserves one repaint: the requests go out\n * together and the last body's answer becomes the picture, instead of the\n * panel painting itself once per name and racing its own writes.\n *\n * That answer is the state *after* the last write of the batch, not\n * necessarily after the last one to settle: the host answers every call with\n * the whole picture, so a straggler's effect arrives with the next pushed\n * frame or poll, and the panel's own error line reports a refusal either way.\n * @param path - route action under `ROUTE_PREFIX`.\n * @param bodies - one body per write; nothing is sent for an empty batch.\n */\n const runAll = useCallback(async (path: string, bodies: readonly unknown[]) => {\n if (bodies.length === 0) return\n setState((previous) => ({ ...previous, busy: true }))\n try {\n const answers = await Promise.all(bodies.map((body) => request(path, body)))\n const fresh = answers[answers.length - 1]\n setState((previous) =>\n fresh === undefined\n ? { ...previous, busy: false }\n : { snapshot: fresh, error: undefined, busy: false },\n )\n } catch (error) {\n setState((previous) => ({ ...previous, busy: false, error: messageOf(error) }))\n }\n }, [])\n return { ...state, run, runAll, reload: load }\n}\n\n/**\n * Just enough of `Storage` for the log-filter and Clear-mark helpers, so tests\n * need no DOM. The tab has no mode to remember since F-26: one surface means one\n * screen, and browser-local storage only carries the ring's own filters.\n */\nexport interface PanelStorage {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n}\n\n/** The browser's storage, or undefined when this half runs without one. */\nexport function browserStorage(): PanelStorage | undefined {\n try {\n return (globalThis as { localStorage?: PanelStorage }).localStorage\n } catch {\n // Reading the property itself throws when a policy blocks storage.\n return undefined\n }\n}\n\n/**\n * Read one preference out of browser-local storage.\n *\n * Both the tab and the Settings page persist a single small choice; every\n * storage access is guarded, so a policy that blocks storage (or a browser\n * without one) only costs the choice at the next reload.\n * @param key - storage key.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored string, or undefined when absent or unavailable.\n */\nexport function storedString(\n key: string,\n storage: PanelStorage | undefined = browserStorage(),\n): string | undefined {\n try {\n return storage?.getItem(key) ?? undefined\n } catch {\n // Reading the property itself throws when a policy blocks storage.\n return undefined\n }\n}\n\n/**\n * Persist one preference; a storage that refuses the write only costs the\n * choice at the next reload.\n * @param key - storage key.\n * @param value - value to store.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function storeString(\n key: string,\n value: string,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n try {\n storage?.setItem(key, value)\n } catch {\n // Storage disabled: the value still applies until the page is reloaded.\n }\n}\n\n/**\n * Read the poll interval out of browser-local storage.\n *\n * A missing, unreadable or nonsensical value is not an error: the panel falls\n * back to {@link DEFAULT_REFRESH_MS}, exactly as it did when the value arrived\n * in an untyped plugin-settings blob.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored interval in milliseconds, or the default.\n */\nexport function storedRefreshMs(storage: PanelStorage | undefined = browserStorage()): number {\n const raw = storedString(REFRESH_STORAGE_KEY, storage)\n if (raw === undefined) return DEFAULT_REFRESH_MS\n const value = Number(raw)\n return Number.isFinite(value) && value > 0 ? value : DEFAULT_REFRESH_MS\n}\n\n/**\n * The poll interval as a live preference.\n *\n * Two surfaces read it — the panel it paces and the settings that change it —\n * and they are not in one tree (the settings live in the tab's actions menu), so\n * the value needs a seat both can subscribe to. The store is the same shape the\n * toast stack uses: a value, a setter, and listeners for whoever renders it.\n * Writes go to browser storage first, so a reload keeps the interval even when\n * no surface is left to re-render.\n */\nexport interface RefreshStore {\n /** The current interval in milliseconds. */\n get(): number\n /** Persist and publish a new interval; a value the surface cannot render is the caller's business. */\n set(value: number): void\n /** Subscribe to changes; the returned function unsubscribes. */\n subscribe(listener: () => void): () => void\n}\n\n/**\n * Build a {@link RefreshStore} on top of browser storage.\n * @param storage - storage to read and write; defaults to the browser's own.\n * @returns the store, seeded from what is already persisted.\n */\nexport function createRefreshStore(\n storage: PanelStorage | undefined = browserStorage(),\n): RefreshStore {\n let value = storedRefreshMs(storage)\n const listeners = new Set<() => void>()\n return {\n get: () => value,\n set: (next: number): void => {\n if (!Number.isFinite(next) || next <= 0 || next === value) return\n value = next\n storeString(REFRESH_STORAGE_KEY, String(next), storage)\n for (const listener of listeners) listener()\n },\n subscribe: (listener: () => void): (() => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\n/**\n * Read the store as a re-rendering hook.\n * @param store - the store to follow.\n * @returns the current interval, re-read after every change.\n */\nexport function useRefreshMs(store: RefreshStore): number {\n const [value, setValue] = useState(() => store.get())\n useEffect(() => store.subscribe(() => setValue(store.get())), [store])\n return value\n}\n\n/**\n * Which sessions the Logs tab reads: the tab's own session, or every session of\n * the project. The mockup offers exactly these two.\n */\nexport type LogScope = 'session' | 'all'\n\n/** Which levels the Logs tab reads: everything, or the failures only. */\nexport type LogLevelFilter = 'all' | 'error'\n\n/** `localStorage` key of the Logs tab's session-scope filter. */\nexport const LOG_SCOPE_KEY = `${TAB_ID}:logsScope`\n\n/** `localStorage` key of the Logs tab's level filter. */\nexport const LOG_LEVEL_KEY = `${TAB_ID}:logsLevel`\n\n/**\n * `localStorage` key of the Logs tab's **client-side** Clear mark.\n *\n * `Clear` has no route (see the frozen contract, C1): the tab remembers the\n * moment and stops drawing events at or before it. The host's ring is untouched,\n * so a later `Sync` still answers with the whole buffer.\n */\nexport const LOGS_CLEARED_KEY = `${TAB_ID}:logsClearedAt`\n\n/** Scope read when nothing valid is persisted: this tab's own session. */\nexport const DEFAULT_LOG_SCOPE: LogScope = 'session'\n\n/**\n * Level read when nothing valid is persisted: errors only.\n *\n * The ring records the whole lifecycle, and at a project's first step that is a\n * wall of `mounting`/`is up` lines; the owner asked for the tab to answer \"did\n * anything break\" before it answers anything else. Every level is one click\n * away, and a level the user chose is persisted and wins over this default.\n */\nexport const DEFAULT_LOG_LEVEL: LogLevelFilter = 'error'\n\n/**\n * Events one snapshot carries and one `GET logs` page answers with.\n *\n * A mirror of the host's `LOG_PAGE_SIZE` (`src/logs.ts`), not a second owner of\n * the rule: the client asks for a page and reads what it is handed.\n */\nexport const LOG_PAGE_SIZE = 50\n\n/**\n * Read the persisted session-scope filter.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored scope, or {@link DEFAULT_LOG_SCOPE}.\n */\nexport function logScopeOf(storage: PanelStorage | undefined = browserStorage()): LogScope {\n return storedString(LOG_SCOPE_KEY, storage) === 'all' ? 'all' : DEFAULT_LOG_SCOPE\n}\n\n/**\n * Read the persisted level filter.\n *\n * Both stored values are answered as themselves; only an unknown or absent\n * entry falls back to {@link DEFAULT_LOG_LEVEL}. Testing against the default\n * instead would silently swallow the other valid value whenever the default\n * changes — the filter has two states, so both are named here.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored filter, or {@link DEFAULT_LOG_LEVEL}.\n */\nexport function logLevelOf(storage: PanelStorage | undefined = browserStorage()): LogLevelFilter {\n const stored = storedString(LOG_LEVEL_KEY, storage)\n return stored === 'all' || stored === 'error' ? stored : DEFAULT_LOG_LEVEL\n}\n\n/**\n * Read the Clear mark.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the epoch ms of the last Clear, or undefined when none was pressed.\n */\nexport function logsClearedAt(storage: PanelStorage | undefined = browserStorage()): number | undefined {\n const stored = storedString(LOGS_CLEARED_KEY, storage)\n if (stored === undefined) return undefined\n const at = Number(stored)\n return Number.isFinite(at) ? at : undefined\n}\n\n/**\n * Persist one of the Logs tab's own choices.\n * @param key - {@link LOG_SCOPE_KEY} or {@link LOG_LEVEL_KEY}.\n * @param value - the choice to store.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function persistLogFilter(\n key: string,\n value: string,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n storeString(key, value, storage)\n}\n\n/**\n * Record a Clear: events at or before `at` stop being drawn from now on.\n * @param at - the moment Clear was pressed, in epoch ms.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function persistLogsClearedAt(\n at: number,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n storeString(LOGS_CLEARED_KEY, String(at), storage)\n}\n\n/** One page of events as `GET logs` answers it (contract C1). */\nexport interface LogPage {\n /** Events, oldest first. */\n readonly events: readonly LogEvent[]\n /** How many events the project's ring holds in total. */\n readonly total: number\n /** Whether the ring holds events older than the last one on this page. */\n readonly more: boolean\n}\n\n/** Build the `GET logs` query for one page request. */\nfunction logsQuery(projectRoot: string, before: number | undefined, limit: number): URLSearchParams {\n const query = new URLSearchParams({ projectRoot, limit: String(limit) })\n if (before !== undefined) query.set('before', String(before))\n return query\n}\n\n/**\n * Read one page of older events over the contract's `GET logs` route.\n *\n * The snapshot carries the newest {@link LOG_PAGE_SIZE} events; \"show older\"\n * asks the route for the page before the oldest one on screen. `before` is the\n * exclusive cursor the host pages on (`at < before`).\n * @param projectRoot - project the page belongs to.\n * @param before - epoch ms to page before; the snapshot page is requested without one.\n * @param limit - page size; {@link LOG_PAGE_SIZE} unless a test asks otherwise.\n * @param fetchImpl - `fetch` to use; defaults to the browser's.\n * @returns the page, or `undefined` when the host refused or the answer was unreadable.\n */\nexport async function fetchLogs(\n projectRoot: string,\n before?: number,\n limit: number = LOG_PAGE_SIZE,\n fetchImpl: typeof fetch | undefined = (globalThis as { fetch?: typeof fetch }).fetch,\n): Promise<LogPage | undefined> {\n if (fetchImpl === undefined) return undefined\n // The action is read out of the shared registry, so this route has one owner:\n // adding it there (contract C1) is what makes this line compile.\n const action = (ROUTE_ACTIONS as Record<string, string | undefined>).logs\n if (action === undefined) return undefined\n try {\n const query = logsQuery(projectRoot, before, limit)\n const response = await fetchImpl(`${ROUTE_PREFIX}/${action}?${query.toString()}`)\n const payload = (await response.json()) as Envelope<LogPage>\n if (payload.ok !== true || payload.value === undefined) return undefined\n return payload.value\n } catch {\n return undefined\n }\n}\n\n/**\n * What one opened row's definition costs to answer, and what is already known\n * about it: the one place a `GET tool` answer is held (F-56).\n *\n * One cache for the module, keyed by the route's own three parameters, rather\n * than one per mount. The answer is a fact about the name, not about a render —\n * folding a row and opening it again must not re-read the host, and the design\n * stand seeds this map directly instead of mounting a host to fake one. The key\n * carries the project and the session because the route takes them and two\n * surfaces of the panel may read different ones in one process.\n *\n * An entry is written **only** by answers that arrived: a fetch in flight is in\n * {@link toolFactsPending} and a failed one in {@link toolFactsFailed}, so a\n * mount that skipped the tool routes pulls in no fixture code and draws no\n * invented answer.\n */\ninterface ToolFactsEntry {\n readonly projectRoot: string\n readonly sessionId: string\n readonly name: string\n}\n\nconst TOOL_FACTS_SEPARATOR = '\\u0000'\nconst toolFacts = new Map<string, ToolFacts>()\nconst toolFactsPending = new Set<string>()\nconst toolFactsFailed = new Set<string>()\n\n/** The cache key of one `GET tool` answer. */\nfunction toolFactsKey(projectRoot: string, sessionId: string, name: string): string {\n return [projectRoot, sessionId, name].join(TOOL_FACTS_SEPARATOR)\n}\n\n/** Build the `GET tool` query for one opened row's definition. */\nfunction toolFactsQuery(projectRoot: string, sessionId: string, name: string): URLSearchParams {\n return new URLSearchParams({ projectRoot, sessionId, name })\n}\n\n/**\n * Read one tool's facts over the contract's `GET tool` route.\n *\n * The snapshot carries no definition, and cannot: a description and a schema are\n * the expensive part of a tool, while every change frame and every poll carries\n * the whole snapshot. This route is therefore read once per row the reader\n * opens, exactly as `GET logs` is read once per page — and it answers a\n * **deferred** name the same way as an offered one, because the definition is\n * read from the scope the bridge registered it in and not from the offer.\n * Unknown names answer `ok: false` and are indistinguishable here from a refusal,\n * which is the route's own decision: the panel draws its one failure line.\n * @param projectRoot - project the definition belongs to.\n * @param sessionId - session the row is open in; the host scopes the read to it.\n * @param name - public registry name, eg `mcp__tglider__workspace`.\n * @param fetchImpl - `fetch` to use; defaults to the browser's.\n * @returns the facts, or `undefined` when the host refused or the answer was unreadable.\n */\nexport async function fetchToolFacts(\n projectRoot: string,\n sessionId: string,\n name: string,\n fetchImpl: typeof fetch | undefined = (globalThis as { fetch?: typeof fetch }).fetch,\n): Promise<ToolFacts | undefined> {\n if (fetchImpl === undefined) return undefined\n // Read out of the shared registry like `logs`, so a build whose contract has\n // no `tool` action asks for nothing rather than for a route nobody serves.\n const action = (ROUTE_ACTIONS as Record<string, string | undefined>).tool\n if (action === undefined) return undefined\n try {\n const query = toolFactsQuery(projectRoot, sessionId, name)\n const response = await fetchImpl(`${ROUTE_PREFIX}/${action}?${query.toString()}`)\n const payload = (await response.json()) as Envelope<ToolFacts>\n if (payload.ok !== true || payload.value === undefined) return undefined\n // A host that answered the envelope with something that is not a record is\n // as unreadable as a refusal: caching it under the row's key would put a\n // shape the body cannot draw on screen, so the panel takes the failure line\n // instead of an invented definition.\n const value = payload.value as Partial<ToolFacts>\n if (typeof value.name !== 'string' || !Array.isArray(value.fields)) return undefined\n return payload.value\n } catch {\n return undefined\n }\n}\n\n/**\n * The facts known about one name, asked for at most once per route.\n *\n * Called from the render of a row that is open — the only moment the answer is\n * wanted — so a folded row costs nothing. A synchronous answer already in the\n * map is returned now; otherwise the read starts once and the caller draws\n * {@link toolFactsLoading}'s line until the promise settles and re-renders. The\n * name-only entry is read first because that is where a seeded stand writes, and\n * a definition is the same record whichever panel asked for it.\n * @param entry - the route's own parameters.\n * @returns the facts while they are held; `undefined` while the read is on its way.\n */\nfunction toolFactsOf(entry: ToolFactsEntry): ToolFacts | undefined {\n const seeded = toolFacts.get(entry.name)\n if (seeded !== undefined) return seeded\n const key = toolFactsKey(entry.projectRoot, entry.sessionId, entry.name)\n const held = toolFacts.get(key)\n if (held !== undefined || toolFactsPending.has(key) || toolFactsFailed.has(key)) return held\n toolFactsPending.add(key)\n void fetchToolFacts(entry.projectRoot, entry.sessionId, entry.name).then((facts) => {\n toolFactsPending.delete(key)\n if (facts === undefined) toolFactsFailed.add(key)\n else toolFacts.set(key, facts)\n })\n return undefined\n}\n\n/** `true` once the host refused to answer for this name. */\nfunction toolFactsUnreadable(entry: ToolFactsEntry): boolean {\n return toolFactsFailed.has(toolFactsKey(entry.projectRoot, entry.sessionId, entry.name))\n}\n\n/**\n * Publish one definition into the panel's cache, as the design mode's own host\n * would answer.\n *\n * The stand renders the same components with no host at all, so the body of an\n * opened row would sit on a read that never resolves. Seeding the very map the\n * product reads — rather than a second \"fixture mode\" branch inside the row —\n * is what keeps the product's drawing and the stand's one drawing: `view.ts`\n * has no code path that knows whether the answer came from a socket. The entry is\n * written under the name alone, which is the key a row with no route of its own\n * looks up; a panel that does hold one looks there first, for the same reason.\n * @param name - the public registry name the record answers about.\n * @param facts - the record the fixture host publishes for that name.\n */\nexport function seedToolFacts(name: string, facts: ToolFacts): void {\n toolFacts.set(name, facts)\n}\n\n/**\n * Forget every held definition.\n *\n * Exported for the specs: one process renders several panels for several\n * projects, and an answer held for one of them must not decide another's body.\n * The product never calls this — a definition does not change while a panel is\n * mounted.\n */\nexport function clearToolFacts(): void {\n toolFacts.clear()\n toolFactsPending.clear()\n toolFactsFailed.clear()\n}\n\n/**\n * The events one session's ring holds, as the logs disclosure's badge counts them.\n *\n * The snapshot field is the **session's** own count (contract C1) — not the\n * project's — so the badge answers \"how much happened here\" rather than \"how\n * busy is this folder\".\n * @param session - the session, or undefined when the tab has none.\n * @returns the session's event count, `0` when the field is absent.\n */\nexport function sessionLogCount(session: { readonly logCount?: number } | undefined): number {\n return session?.logCount ?? 0\n}\n\n/**\n * Keep the newest `at`-time first, and drop the duplicates a page overlap can\n * produce, so \"show older\" appends rather than repeats.\n * @param older - the page just read.\n * @param shown - what is already on screen.\n * @returns the merged list, newest first.\n */\nexport function mergeLogs(older: readonly LogEvent[], shown: readonly LogEvent[]): LogEvent[] {\n const seen = new Set(shown.map((event) => `${event.at}:${event.level}:${event.message}`))\n const fresh = older.filter((event) => !seen.has(`${event.at}:${event.level}:${event.message}`))\n return [...shown, ...fresh]\n}\n\n/**\n * Whether the ring holds events older than the ones on screen, and where the\n * next page starts.\n *\n * The exclusive cursor is the oldest event drawn, which is what the host pages\n * on. A cursor already asked for is spent: a page that added nothing the filters\n * let through must not ask for itself again, or a short session inside a busy\n * project would loop. Absent a project total the client trusts the snapshot's\n * own length, so a host half that predates `logCount` simply draws no button.\n * @param props - the visible events, the project's total, and the cursors already asked for.\n * @returns `more` and the `cursor` the next page starts at.\n */\nexport function logsPaging(props: {\n visible: readonly LogEvent[]\n total: number\n attempted: readonly number[]\n}): { more: boolean; cursor: number | undefined } {\n const cursor = props.visible.at(-1)?.at\n return {\n more: props.visible.length < props.total && cursor !== undefined && !props.attempted.includes(cursor),\n cursor,\n }\n}\n\n/**\n * The empty state of the Logs tab: nothing recorded yet, and where to look.\n * @param t - translate seat.\n * @returns the element, so the copy can be asserted without a DOM.\n */\nexport function logsEmptyState(t: Translate): ReactNode {\n return emptyState(t('logsEmptyTitle'), t('logsEmptyHint'), 'logs-empty')\n}\n\n/**\n * The empty state of the level filter, not of the ring.\n *\n * The tab opens on `errors`; a project whose ring holds only `mounting`/`is up`\n * lines would otherwise read \"no events yet\" while the counter beside the\n * disclosure's badge says it holds several. Saying so is the difference between a quiet\n * project and a hidden list.\n * @param t - translate seat.\n * @returns the element, keyed for the array {@link logList} returns.\n */\nexport function logsNoErrorsState(t: Translate): ReactNode {\n return emptyState(t('logsNoErrorsTitle'), t('logsNoErrorsHint'), 'logs-empty')\n}\n\n/**\n * The one project this tab belongs to: the project whose live sessions include\n * the tab's session. A tab never shows another project — the settings popup and\n * the native settings page are the surfaces with the whole picture.\n * @param snapshot - host snapshot, or undefined before the first poll lands.\n * @param sessionId - the session this tab is open in.\n * @returns the matching project, or undefined when there is none (yet).\n */\nexport function currentProject(\n snapshot: McpSnapshot | undefined,\n sessionId: string | undefined,\n): ProjectSnapshot | undefined {\n if (snapshot === undefined || sessionId === undefined) return undefined\n return snapshot.projects.find(\n (project) =>\n project.sessionIds.includes(sessionId) ||\n (project.sessions ?? []).some((session) => session.id === sessionId),\n )\n}\n\n/**\n * Statuses the \"Problems\" view lists, most actionable first. The quiet states —\n * `active`, `idle`, `disabled` — are answers, not problems.\n */\nexport const PROBLEM_STATUSES = ['error', 'conflict', 'connecting'] as const\n\n/** One status and the rows currently in it. */\nexport interface StatusGroup {\n status: ServerStatus\n rows: ServerRow[]\n}\n\n/**\n * Split merged rows into the groups the \"Problems\" view shows.\n * @param rows - merged project rows, in document order.\n * @returns one entry per non-empty group, in {@link PROBLEM_STATUSES} order.\n */\nexport function statusGroups(rows: readonly ServerRow[]): StatusGroup[] {\n const groups: StatusGroup[] = []\n for (const status of PROBLEM_STATUSES) {\n const matching = rows.filter((row) => row.status === status)\n if (matching.length > 0) groups.push({ status, rows: matching })\n }\n return groups\n}\n\n/**\n * Tab body: the project this session works in, and nothing else.\n *\n * The whole picture — every project with a live session — lives in the side card\n * settings popup, not in a tab that belongs to one conversation.\n */\nexport function ProjectMcpPanel(props: {\n visible: boolean\n sessionId: string | undefined\n refreshMs: number\n /**\n * The shell's translate seat for this namespace. Required on purpose: the\n * panel is one of the surfaces whose copy must follow the language\n * preference, so `./index.ts` composes it with the seat from `./tab-locale.ts`\n * rather than letting a missing prop silently fall back to English.\n */\n t: Translate\n /**\n * Host-namespace seat for the Logs tab's coded events (F-48); without one\n * the events render their payload's English, byte-identical to before codes.\n */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = props.t\n const { snapshot, error, busy, run, runAll } = useSnapshot(props.visible, props.refreshMs)\n const project = currentProject(snapshot, props.sessionId)\n const groups = project === undefined ? [] : statusGroups(project.rows)\n const policy = project === undefined ? undefined : policyOf(project)\n // The Logs disclosure counts this session's own events, not the project's: the\n // number the contract puts on `SessionSnapshot.logCount` (C1). A host half\n // without the field reports `0`, which the block prints as a real `0`.\n const session = (project?.sessions ?? []).find((entry) => entry.id === props.sessionId)\n const logsSession = sessionLogCount(session)\n // The pin keeps its own route and answers with the fresh snapshot, so the\n // panel's own `run` carries it: a refusal lands in the same line as every\n // other host refusal instead of being swallowed by a silent refresh.\n const onPin = useCallback(\n (tool: string, pinned: boolean): void => {\n if (project === undefined) return\n void run(ROUTE_ACTIONS.pin, pinBody(project.projectRoot, tool, pinned))\n },\n [project, run],\n )\n // A server's worth of names is one intent and one press (F-44): the names come\n // from the surface that showed them, the direction from what the project\n // already pins, and the writes go out as one batch.\n const onPinServer = useCallback(\n (server: string, names: readonly string[]): void => {\n if (project === undefined) return\n const press = serverPinPress(names, policy?.pins ?? [])\n void runAll(\n ROUTE_ACTIONS.pin,\n press.names.map((name) => pinBody(project.projectRoot, name, press.pinned)),\n )\n },\n [project, policy, runAll],\n )\n // Both operator actions are scoped to the project this tab shows: the panel\n // answers with that project's slice, and the host never starts a server for\n // another project because a row here was retried. Without a project there is\n // nothing to scope, so the request stays the global one it always was.\n const retry = useCallback(\n (): void => void run(ROUTE_ACTIONS.retry, operatorBody(project?.projectRoot)),\n [project, run],\n )\n const sync = useCallback(\n (): void => void run(ROUTE_ACTIONS.sync, operatorBody(project?.projectRoot)),\n [project, run],\n )\n const release = useCallback(\n (sessionId: string): void => void run(ROUTE_ACTIONS.release, { sessionId }),\n [run],\n )\n return h(\n 'div',\n { style: STYLE.root },\n h(PanelHeader, {\n project,\n sessions: project?.sessionIds.length ?? 0,\n busy,\n onSync: sync,\n t,\n }),\n h(\n 'div',\n { style: STYLE.body },\n // The host's refusal is the body's first line, so the toolbar is the\n // body's immediate sibling in the panel (the contract's own gate anchor)\n // whatever the read did.\n error === undefined ? null : h('div', { style: STYLE.error }, error),\n tabBody({\n project,\n sessionId: props.sessionId,\n groups,\n busy,\n policy,\n onPin,\n onPinServer,\n onRelease: release,\n onRetry: retry,\n sessionLogCount: logsSession,\n t,\n hostT: props.hostT,\n }),\n ),\n )\n}\n\n/**\n * The one-phrase reading of the toolbar's right edge.\n *\n * F-26 left the surface with one screen and no mode to branch on, so the phrase\n * answers the one question no block above it answers on its own: how many\n * sessions the project has. The problems block badges its own groups, the logs\n * block its own events, and the tools block its own counters, so nothing here\n * repeats them.\n * @param props - the project's session count.\n * @param t - translate seat.\n * @returns the phrase the toolbar's right edge prints.\n */\nexport function panelSummary(props: { sessions: number }, t: Translate): string {\n return sessionCount(props.sessions, t)\n}\n\n/** Everything the tab's toolbar reads. */\nexport interface PanelHeaderProps {\n /** The tab's own project, or undefined when its session has none. */\n project: ProjectSnapshot | undefined\n /** Sessions attached to the project; what the right edge counts. */\n sessions: number\n busy: boolean\n onSync: () => void\n t: Translate\n}\n\n/**\n * The tab's one toolbar row.\n *\n * The project's own header — the folder, the `this session` chip that says whose\n * tab this is, the summary phrase and the action at the right edge. The segment\n * bar that used to be the second row is gone (F-26): there is one screen, so\n * there is nothing to switch. Pure and exported: the panel around it owns the\n * poll and the state.\n * @param props - see {@link PanelHeaderProps}.\n * @returns the toolbar row.\n */\nexport function PanelHeader(props: PanelHeaderProps): ReactNode {\n const { t, project } = props\n return h(\n 'div',\n { style: STYLE.bar },\n project === undefined\n ? h('span', { style: STYLE.muted }, t('noProjectLabel'))\n : h(\n 'span',\n { style: STYLE.name, title: project.projectRoot },\n basename(project.projectRoot),\n ),\n project === undefined ? null : h('span', { style: STYLE.tag }, t('thisSession')),\n h('span', { style: { flex: 1 } }),\n h('button', { style: STYLE.button, disabled: props.busy, onClick: props.onSync }, t('sync')),\n // The toolbar's right edge is the mockup's `.dim`\n // (`docs/design/mockups/harness.html`, `.dim` — the tertiary tone):\n // one phrase, at the tertiary tone, and the only summary reading in the bar.\n h('span', { style: STYLE.dim }, panelSummary({ sessions: props.sessions }, t)),\n )\n}\n\n/** Everything the tab renders under its toolbar. */\nexport interface TabBodyProps {\n /** The tab's own project, or undefined when this session has none. */\n project: ProjectSnapshot | undefined\n /** Session this tab is open in. */\n sessionId: string | undefined\n /** Problem groups of {@link project}, precomputed by the panel. */\n groups: StatusGroup[]\n busy: boolean\n /** The project's policy, precomputed by the panel; read from the project when absent. */\n policy?: ToolPolicy | undefined\n /** Pin or unpin one tool of {@link project}; absent while nothing can be written. */\n onPin?: ((tool: string, pinned: boolean) => void) | undefined\n /**\n * Pin every name of one server in one press (F-44); absent while nothing can\n * be written. The names are the ones the surface that called it lists — the\n * hidden tier's own names — and the expansion into names is the whole\n * meaning: the host stores no server pin (`docs/design/contracts/policy.md`).\n */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n /**\n * Retry every failed mount of {@link project}; absent while nothing can be\n * written. The host route is project-scoped, so a row's own `Retry` sends the\n * request the errors block's button sends.\n */\n onRetry?: (() => void) | undefined\n onRelease: (sessionId: string) => void\n /** Events of this tab's own session, at the moment the snapshot was taken. */\n sessionLogCount?: number\n /** Storage the Logs block persists its filters and Clear mark in. */\n storage?: PanelStorage | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate\n /** Host-namespace seat for the Logs block's coded events (F-48). */\n hostT?: Translate | undefined\n}\n\n/**\n * What to add where, said from the host's own document list.\n *\n * The files a project is read from are a config fact — `ProjectSnapshot.files`,\n * published in read order — so the empty state names the project's own documents\n * instead of a path baked into this bundle, and says plainly when the deployment\n * reads none at all. A host older than the field reports nothing, and then no\n * file name is promised: the hint speaks about declaring one, not about a path\n * that host may never read.\n */\nfunction declaredHint(project: ProjectSnapshot, t: Translate): string {\n const files = project.files\n // No list at all is a host older than the field, and then no file name is\n // promised: the hint asks for a document without naming a path that host may\n // never read.\n if (files === undefined) return t('noServersDeclaredUnknown')\n const documents = files.filter((file) => file.scope === 'project').map((file) => file.path)\n if (documents.length === 0) return t('noServersDeclaredNowhere')\n return t('noServersDeclaredHint', { documents: documents.join(' · ') })\n}\n\n/**\n * The tab body: one screen, its blocks in the contract's order.\n *\n * F-26 folded the four modes into one surface, so the body is a list of blocks\n * rather than a branch: the session's declared servers, the sessions that\n * disagree with the project (F-24's section, still only while some do), the tool\n * offer, and the two disclosures — the problems, only while there are any, and\n * the event ring, always. Every situation where a surface has nothing to list\n * still answers for itself above the blocks.\n * @param props - see {@link TabBodyProps}.\n * @returns the blocks below the toolbar, in order.\n */\nexport function tabBody(props: TabBodyProps): ReactNode {\n const t = translateOf(props.t)\n if (props.sessionId === undefined) {\n return emptyState(t('noSession'), t('noSessionHint'))\n }\n const { project } = props\n if (project === undefined) {\n return emptyState(t('noProject'), t('noProjectHint'))\n }\n // This session's own rows, not the merged project view: what this conversation\n // resolves is the first thing the screen answers (`sessionRowsOf`).\n const rows = sessionRowsOf(project, props.sessionId)\n const sessions = sessionBreakdown(project, props.sessionId, t)\n const disagreeing = sessions.filter((session) => session.deviates)\n return [\n rows.length === 0\n ? emptyState(t('noServersDeclared'), declaredHint(project, t), 'servers')\n : h(ServersBlock, {\n key: 'servers',\n rows,\n usage: project.usage,\n t,\n hostT: props.hostT,\n onRetry: props.onRetry,\n busy: props.busy,\n }),\n // The F-24 disagreement view. The merged project rows are no longer drawn\n // here — the block above is this session's own reading — but `Release` for a\n // single session still lives only in this section.\n h(SessionList, {\n key: 'sessions',\n sessions: disagreeing,\n busy: props.busy,\n onRelease: props.onRelease,\n merged: sessions.length > 1,\n t: props.t,\n hostT: props.hostT,\n }),\n h(ToolsSection, {\n key: 'tools',\n project,\n sessionId: props.sessionId,\n policy: props.policy,\n onPin: props.onPin,\n onPinServer: props.onPinServer,\n pending: props.busy,\n t,\n hostT: props.hostT,\n }),\n // The errors disclosure exists only while there are problem groups; there is\n // no \"all quiet\" copy to draw, because an absent block is the quiet answer.\n props.groups.length === 0\n ? null\n : h(\n Disclosure,\n {\n key: 'errors',\n label: t('errorsSection'),\n count: props.groups.length,\n showHint: t('showErrors'),\n hideHint: t('hideErrors'),\n body: [\n h(IssueView, {\n key: 'issues',\n project,\n groups: props.groups,\n onRetry: props.onRetry,\n busy: props.busy,\n t,\n hostT: props.hostT,\n }),\n // `Retry failed` used to sit on the mode bar; the errors block is\n // where the action belongs now that the bar is gone.\n props.onRetry === undefined\n ? null\n : h(\n 'button',\n {\n key: 'retry',\n style: STYLE.button,\n title: t('retryHint'),\n disabled: props.busy,\n onClick: props.onRetry,\n },\n t('retryFailed'),\n ),\n ],\n t,\n },\n ),\n h(Disclosure, {\n key: 'logs',\n label: t('logsSection'),\n count: props.sessionLogCount ?? 0,\n showHint: t('showLogs'),\n hideHint: t('hideLogs'),\n body: h(LogsView, {\n project,\n sessionId: props.sessionId,\n t,\n hostT: props.hostT,\n storage: props.storage,\n }),\n t,\n }),\n ]\n}\n\n/**\n * The tools block of the one surface.\n *\n * {@link ToolsView} stays pure — the pure specs resolve it directly — so the\n * row whose detail block is open lives here, one state for the section, the way\n * {@link SessionList} keeps one session open at a time. Exported like the other\n * stateful block so {@link tabBody}'s block order can be asserted by type.\n *\n * The filter panel's query and pressed tiers (F-43) live here for the same\n * reason and outlive a snapshot\n * refresh: a poll repaints the block, and a filter that reset itself every five\n * seconds would be unusable.\n *\n * The filter is this component's own state and is not persisted anywhere: a\n * query is a reading aid for the minute, and the two filters the panel does\n * store — the log ring's — are stored because a page of that ring costs a\n * request. Nothing here does.\n * @param props - what {@link ToolsView} takes.\n * @returns the session's tool offer, with one row open at most.\n */\nexport function ToolsSection(props: {\n project: ProjectSnapshot\n sessionId: string\n policy?: ToolPolicy | undefined\n onPin?: ((tool: string, pinned: boolean) => void) | undefined\n /** Pin every hidden name of one server in one press (F-44). */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n pending?: boolean\n t: Translate\n /** Host-namespace seat for the presentation owner's coded note (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const [openTool, setOpenTool] = useState<string | undefined>(undefined)\n // Three states, not two: `undefined` is \"nobody has pressed the head\", and it\n // is what lets the filter open the hidden tier on its own without stealing the\n // press that follows (see {@link ToolsView}'s own `openHidden`).\n const [openHidden, setOpenHidden] = useState<boolean | undefined>(undefined)\n const [query, setQuery] = useState('')\n const [tiers, setTiers] = useState<readonly ToolTier[]>([])\n // The filter this section hands to the block, built once here because the\n // hidden head's own toggle has to know it: the press inverts the state the\n // user is *looking at*, and while a filter is live that state may be the one\n // the filter opened the tier in (`undefined`), not `false`.\n const filter: ToolFilter = { query, tiers }\n const filterActive = toolFilterActive(filter)\n const onToggleTool = useCallback((name: string): void => {\n setOpenTool((current) => (current === name ? undefined : name))\n }, [])\n const onToggleHidden = useCallback((): void => {\n setOpenHidden((value) => !(value ?? filterActive))\n }, [filterActive])\n const onQuery = useCallback((value: string): void => setQuery(value), [])\n const onTier = useCallback((tier: ToolTier): void => {\n setTiers((held) => toggledTier(held, tier))\n }, [])\n const onClearFilter = useCallback((): void => {\n setQuery('')\n setTiers([])\n }, [])\n return h(ToolsView, {\n ...props,\n openTool,\n onToggleTool,\n openHidden,\n onToggleHidden,\n filter,\n onQuery,\n onTier,\n onClearFilter,\n })\n}\n\n/**\n * One disclosure of the single surface: a head button and, while it is open, its\n * body.\n *\n * The `div`/`button[aria-expanded]` pair is the shape the parity gate reads a\n * disclosure by, which is why the head is a button of its own and the body is\n * the only thing that appears when it opens. The state is local on purpose: what\n * is folded away is this block's, not the panel's, so the panel keeps rendering\n * one pure tree per snapshot.\n */\n/**\n * The head one disclosure draws: toggled marker, label and the count badge.\n *\n * A pure function of its props on purpose. {@link Disclosure} is a component\n * with state, and the tools block is a pure tree of elements resolved by tests\n * without a React runtime — a stateful child in that tree would be invoked\n * outside a component and break the walk. The tiers that must be pure (the\n * hidden list) draw this head themselves and keep their open state one level up,\n * which is why the head exists apart from the wrapper that usually wears it.\n * @param props - label, count, open state and the head's tooltip.\n * @returns the `button[aria-expanded]` the parity gate reads a disclosure by.\n */\nexport function disclosureHead(props: {\n label: string\n count?: number | undefined\n open: boolean\n hint?: string | undefined\n onToggle: () => void\n}): ReactNode {\n return h(\n 'button',\n {\n style: STYLE.disclosureHead,\n 'aria-expanded': props.open,\n title: props.hint,\n onClick: props.onToggle,\n },\n `${props.open ? '▾' : '▸'} ${props.label}`,\n props.count === undefined ? null : h('span', { style: STYLE.tag }, String(props.count)),\n )\n}\n\nexport function Disclosure(props: {\n /** The head's word-label; the marker is drawn beside it, not stored. */\n label: string\n /** The number the head's badge prints, when it has one. */\n count?: number | undefined\n /** The head's tooltip while the block is open. */\n showHint?: string | undefined\n /** The head's tooltip while the block is closed. */\n hideHint?: string | undefined\n /** What the head reveals; rendered only while the disclosure is open. */\n body: ReactNode\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n}): ReactNode {\n const [open, setOpen] = useState(false)\n return h(\n 'div',\n { style: STYLE.disclosure },\n disclosureHead({\n label: props.label,\n count: props.count,\n open,\n hint: open ? props.hideHint : props.showHint,\n onToggle: (): void => setOpen((value) => !value),\n }),\n open ? h('div', { style: STYLE.disclosureBody }, props.body) : null,\n )\n}\n\n/**\n * The session's own tool offer, when the host half published one.\n * @param project - the project this tab belongs to.\n * @param sessionId - the tab's session.\n * @returns the per-session `tools`, or undefined when the host has none yet.\n */\nexport function sessionToolsOf(\n project: ProjectSnapshot,\n sessionId: string | undefined,\n): SessionTools | undefined {\n if (sessionId === undefined) return undefined\n const sessions = (project.sessions ?? []) as readonly { id: string; tools?: SessionTools }[]\n return sessions.find((session) => session.id === sessionId)?.tools\n}\n\n/**\n * The declared servers of the session this tab belongs to: the session's own\n * rows when the host published that session, the project's merged rows\n * otherwise.\n *\n * Per-session rows, not the merged project view: with the own-scope fallback a\n * session can run its own instance of a declaration, so its state — running,\n * stalled or released — is what this conversation actually has, and another\n * session of the same project may be in a different one.\n * @param project - the project snapshot the tab read.\n * @param sessionId - the conversation the tab is open in.\n * @returns the declared servers this session resolves.\n */\nexport function sessionRowsOf(\n project: ProjectSnapshot,\n sessionId: string | undefined,\n): readonly ServerRow[] {\n if (sessionId === undefined) return []\n const sessions = (project.sessions ?? []) as readonly { id: string; rows?: ServerRow[] }[]\n const session = sessions.find((entry) => entry.id === sessionId)\n return session === undefined ? project.rows : (session.rows ?? [])\n}\n\n/** The three counts the tools block answers for. */\nexport interface ToolCounts {\n /** Offered because the durable counters proved them hot. */\n pinned: number\n /** Offered because this session disclosed them, from either on-demand tier. */\n disclosed: number\n /** Mounted for the project but not offered in the request. */\n hidden: number\n /** Every tool the model would see: pins plus disclosures. */\n offering: number\n}\n\n/**\n * Count one session's offer into the three tiers the mockup names.\n *\n * Real data throughout — it reads only {@link SessionTools} — so every figure it\n * returns is a fact, not an invention.\n * @param tools - one session's tool offer.\n * @returns the pinned, disclosed and hidden counts.\n */\nexport function toolCounts(tools: SessionTools): ToolCounts {\n const pinned = tools.baseline.length\n const disclosed = tools.activated.length + tools.context.length\n return {\n pinned,\n disclosed,\n hidden: tools.deferred.length,\n offering: pinned + disclosed,\n }\n}\n\n/** One server's share of one list of registry names. */\nexport interface ServerNames {\n /** Registry names one list holds for this server, in that list's own order. */\n readonly names: readonly string[]\n /** Server the tools belong to, or `unknown` when the name is not prefixed. */\n server: string\n /** How many names of that list are this server's. */\n count: number\n}\n\n/**\n * The hidden tier's reading of {@link ServerNames}, under the name its callers\n * know it by: the grouping is the same one, only the list differs.\n */\nexport type HiddenServer = ServerNames\n\n/**\n * Split hidden tool names by the server they were mounted from.\n *\n * The registry's own naming is `mcp__<server>__<tool>` (a project-level prefix\n * is added by `mcp-client` only on a collision), so the server is the second\n * `__`-separated segment. A name that does not follow that shape is counted\n * under `unknown` rather than dropped: the hidden count must stay exact.\n * @param deferred - names the session mounted but did not offer.\n * @returns one entry per server, by descending count, then by name.\n */\nexport function hiddenByServer(deferred: readonly string[]): HiddenServer[] {\n return byServer(deferred)\n}\n\n/**\n * Split the pinned names by the server each one came from (F-44).\n *\n * The pinned tier reads its names per server for the same reason the hidden tier\n * does: a server is the unit a user thinks in when the list gets long, and it is\n * what the one press that releases a whole server acts on. The grouping is\n * {@link hiddenByServer}'s own, so the two tiers of one block order their groups\n * alike — biggest first, then by name — while each keeps its own list's order\n * inside a group.\n * @param pins - the project's pin list, as the host published it.\n * @returns one entry per server, each holding the names it contributed.\n */\nexport function pinnedByServer(pins: readonly string[]): ServerNames[] {\n return byServer(pins)\n}\n\n/**\n * One list of registry names, grouped by the server each name carries.\n *\n * A name without the registry's prefix belongs to no server and is filed under\n * `unknown` rather than dropped or attributed to a made-up one: the group is\n * real even when the name cannot be traced, and a row that vanished would hide a\n * pin the user wrote.\n * @param list - the names to group, in the order they are read in.\n * @returns one entry per server, biggest group first, then by server name.\n */\nfunction byServer(list: readonly string[]): ServerNames[] {\n const names = new Map<string, string[]>()\n for (const name of list) {\n const server = serverOfToolName(name) ?? 'unknown'\n const held = names.get(server)\n if (held === undefined) names.set(server, [name])\n else held.push(name)\n }\n return [...names.entries()]\n .map(([server, held]) => ({ server, count: held.length, names: held }))\n .sort((left, right) => right.count - left.count || left.server.localeCompare(right.server))\n}\n\n/**\n * The prefix the registry publishes project MCP tools under, and the server part\n * of one such name — defined in `./usage-view.ts` and re-exported at the top of\n * this module, where the panel's callers have always found them.\n */\n\n/** How much of the disclosure budget the session has spent. */\nexport interface BudgetSplit {\n /** Tools the model sees. */\n used: number\n /** Tools mounted for the project. */\n total: number\n /** `used / total` as a whole percentage, `0` when nothing is mounted. */\n percent: number\n /** `true` while the surface is over its configured budget. */\n exhausted: boolean\n}\n\n/**\n * Split the session's tool offer against the mounted surface: the bar and the\n * tooltip of the budget line. Both numbers are real counts the host published.\n * @param tools - one session's tool offer.\n * @returns the offering against the mounted total.\n */\nexport function budgetSplit(tools: SessionTools): BudgetSplit {\n const used = toolCounts(tools).offering\n const total = tools.mounted\n return {\n used,\n total,\n percent: total === 0 ? 0 : Math.min(100, Math.round((used / total) * 100)),\n exhausted: tools.deferring,\n }\n}\n\n/**\n * One tier of the tools block: the four parts its counter chips count, and the\n * four the filter panel switches between (F-43).\n */\nexport type ToolTier = 'pinned' | 'counters' | 'disclosed' | 'hidden'\n\n/**\n * The tools block's filter: one query over the registry names, and the tiers the\n * user narrowed the list to.\n *\n * The two halves answer different questions and are kept apart because of it: a\n * query asks \"where is this name\", a tier asks \"show me this rung alone\", and\n * the block draws the names that pass both. The filter is the tools block's own\n * state rather than a persisted one — unlike the log ring's filters, which are\n * stored because a page of the ring costs a request — because a query is a\n * reading aid for the minute, and a panel that reopened onto a stale one would\n * read as an empty catalogue.\n */\nexport interface ToolFilter {\n /** Free text, matched against the registry name; empty passes every name. */\n query: string\n /** Tiers to draw; empty — every tier — is the state the block opens in. */\n tiers: readonly ToolTier[]\n}\n\n/** The filter of a block nobody has narrowed, where everything passes. */\nexport const NO_TOOL_FILTER: ToolFilter = { query: '', tiers: [] }\n\n/**\n * `true` when `name` passes the query.\n *\n * A case-insensitive substring, so `grafana` finds `mcp__grafana-local__query`:\n * the registry name carries its server as its own prefix, and one field answers\n * both readings. The query is trimmed first, because a search field with a\n * trailing space would otherwise match nothing and look broken.\n * @param name - the registry name of the row.\n * @param query - what the user typed.\n * @returns whether the name passes.\n */\nexport function matchesToolQuery(name: string, query: string): boolean {\n const needle = query.trim().toLowerCase()\n return needle === '' || name.toLowerCase().includes(needle)\n}\n\n/**\n * `true` while the filter narrows anything at all — a query, a tier, or both.\n *\n * The block asks this to decide whether it is showing a filtered list: the\n * counts line, the empty state and the hidden tier's own opening all turn on it.\n * @param filter - the block's filter.\n * @returns whether the filter is doing something.\n */\nexport function toolFilterActive(filter: ToolFilter): boolean {\n return filter.query.trim() !== '' || filter.tiers.length > 0\n}\n\n/**\n * `true` when the filter lets this tier through: no tier pressed means every\n * tier, which is the reading the block opens in.\n * @param filter - the block's filter.\n * @param tier - the tier being drawn.\n * @returns whether the tier is drawn.\n */\nexport function tierVisible(filter: ToolFilter, tier: ToolTier): boolean {\n return filter.tiers.length === 0 || filter.tiers.includes(tier)\n}\n\n/**\n * The rows of one tier that pass the query, in the order they were given.\n * @param rows - the tier's rows, already in the block's own order.\n * @param query - what the user typed.\n * @returns the rows to draw.\n */\nexport function filterToolRows<T extends { name: string }>(rows: readonly T[], query: string): T[] {\n return rows.filter((row) => matchesToolQuery(row.name, query))\n}\n\n/**\n * The hidden names that pass the query, grouped by server as they were.\n *\n * A server whose every hidden name is filtered out goes with its count: the\n * group head prints `{server} · {count}` of what is drawn under it, and a head\n * over an empty list would be a number the user cannot spend.\n * @param servers - the hidden names, grouped by server ({@link hiddenByServer}).\n * @param query - what the user typed.\n * @returns the groups that kept at least one name, their counts renumbered.\n */\nexport function filterHiddenServers(\n servers: readonly HiddenServer[],\n query: string,\n): HiddenServer[] {\n const kept: HiddenServer[] = []\n for (const entry of servers) {\n const names = entry.names.filter((name) => matchesToolQuery(name, query))\n if (names.length > 0) kept.push({ server: entry.server, names, count: names.length })\n }\n return kept\n}\n\n/**\n * The tier list with one tier toggled: a press adds it, a second press releases\n * it. An empty list means every tier, so releasing the last one hands the block\n * its full list back.\n * @param tiers - the tiers currently pressed.\n * @param tier - the tier the user pressed.\n * @returns the new tier list, in the order the presses happened.\n */\nexport function toggledTier(tiers: readonly ToolTier[], tier: ToolTier): ToolTier[] {\n return tiers.includes(tier) ? tiers.filter((held) => held !== tier) : [...tiers, tier]\n}\n\n/** How much of one server's tool set a project already pins. */\nexport type ServerPinState = 'all' | 'some' | 'none'\n\n/**\n * How much of one server's names the project already pins (F-44).\n *\n * The question a server-level control answers is about a *set* of names — the\n * ones its own surface lists — so the reading is a proportion and not a flag:\n * `all`, a part, or none. Both surfaces ask it before they draw their switch and\n * again before they write.\n * @param names - the names this control speaks for, as its surface lists them.\n * @param pins - the project's own pin list.\n * @returns the proportion of `names` the pin list holds.\n */\nexport function serverPinState(\n names: readonly string[],\n pins: readonly string[],\n): ServerPinState {\n const held = new Set(pins)\n const pinned = names.filter((name) => held.has(name)).length\n if (pinned === 0) return 'none'\n return pinned === names.length ? 'all' : 'some'\n}\n\n/**\n * What one press of a server-level control writes (F-44).\n *\n * A server pin is the names themselves — the same list, the same route — and not\n * a rule of its own: this unit expands a server into its names, so a tool the\n * server mounts later is covered by no earlier press (the limits are in\n * `docs/design/contracts/policy.md`).\n *\n * The direction is the reading's own: a set that is wholly pinned is released,\n * and any other set is completed. A half-pinned server therefore *adds* the\n * names it is missing rather than throwing the pinned ones away, so one press\n * ever moves the set towards a state the user asked for and never loses a pin\n * nobody touched.\n * @param names - the names this control speaks for.\n * @param pins - the project's own pin list.\n * @returns the names to write and the state to write them in. The names are\n * empty only when the set is empty: a set that is wholly pinned is released\n * whole, and any other set has at least one name missing.\n */\nexport function serverPinPress(\n names: readonly string[],\n pins: readonly string[],\n): { pinned: boolean; names: string[] } {\n const held = new Set(pins)\n if (serverPinState(names, pins) === 'all') {\n return { pinned: false, names: names.filter((name) => held.has(name)) }\n }\n return { pinned: true, names: names.filter((name) => !held.has(name)) }\n}\n\n/** One counter of the tools vocabulary: which tier, its label, and the count. */\nexport interface CounterPart {\n /** Tier the counter answers for. */\n key: ToolTier\n /** Locale label of the tier, already translated. */\n label: string\n count: number\n}\n\n/**\n * The four counters, one part each.\n *\n * Two of them are tiers of one list and have to be told apart: `pinned` is the\n * user's own pin list, `counters` is the rest of the baseline — the names the\n * durable usage counters proved hot. As one number they could say \"2 pinned\"\n * over a pin list of one, which is exactly what the block drew before: the\n * sentence promised an action on rows that carried none. The budget still counts\n * both, because both are offered in every request ({@link toolCounts}).\n *\n * One source for every reading of these numbers: the tools block draws one chip\n * per part, and the settings page's Tools rows read the same parts, so the two\n * surfaces can never disagree. A part whose count is zero is not a chip — the\n * block prints numbers, not the absence of them.\n * @param tools - one session's tool offer.\n * @param policy - the project's tool policy, which owns the pin list.\n * @param t - translate seat.\n * @returns pinned, counters, disclosed and hidden, in that order.\n */\nexport function counterParts(\n tools: SessionTools,\n policy: ToolPolicy,\n t: Translate,\n): CounterPart[] {\n const counts = toolCounts(tools)\n const byCounters = tools.baseline.filter((name) => !policy.pins.includes(name)).length\n return [\n { key: 'pinned', label: t('toolsPinned'), count: policy.pins.length },\n { key: 'counters', label: t('toolsByCounters'), count: byCounters },\n { key: 'disclosed', label: t('toolsDisclosed'), count: counts.disclosed },\n { key: 'hidden', label: t('toolsHidden'), count: counts.hidden },\n ]\n}\n\n/** A tool row the tools block draws, with the action it offers. */\nexport interface ToolRow {\n /** Registry name. */\n name: string\n /** `true` when the project's own pin list holds this name, not the counters. */\n pinned?: boolean\n /** Clock time of the last offer or call, as `HH:MM`, when the host published one. */\n time?: string | undefined\n /** Short label shown on the row, when there is one. */\n note?: string | undefined\n /**\n * Both of the host's readings for this row: the project's counter and this\n * session's, and whether the host recorded the row's server at all.\n *\n * The property is absent where the host published nothing for the project,\n * which is what keeps a row the counters never saw from reading as a row of\n * zeroes.\n */\n calls?: ToolCalls | undefined\n}\n\n/**\n * The pinned rows to draw: the user's own pin list, then the counter-seeded\n * remainder of the baseline tier.\n *\n * The pin list is the only durable user choice here, so it comes first and is\n * the only part with an `Unpin` action. The rest of `baseline` is offered for\n * the same reason the counters say \"pinned\": the durable usage counters proved\n * those names hot, and a name that disappeared from the list would make the\n * toolbar's own badge disagree with what is under it. Those rows carry no\n * action — unpinning a name the user never pinned is not a thing this panel\n * offers — and get {@link ToolRow.pinned} `false`.\n * @param tools - one session's tool offer.\n * @param policy - the project's policy, whose `pins` are the user's own list.\n * @returns one row per offered name, user-pinned first, in list order.\n */\nexport function pinnedRows(tools: SessionTools, policy: ToolPolicy): ToolRow[] {\n const pinned = policy.pins.map((name) => ({ name, pinned: true }))\n const pinnedNames = new Set(policy.pins)\n const counted = tools.baseline\n .filter((name) => !pinnedNames.has(name))\n .map((name) => ({ name, pinned: false }))\n return [...pinned, ...counted]\n}\n\n/**\n * The clock time of one offer, as a disclosed row shows it.\n *\n * Only the `session` tier carries `at`; the `context` tier records a step, not a\n * time, so a row without one renders no clock at all.\n * @param at - epoch milliseconds of the last offer or call.\n * @returns `HH:MM` in the viewer's own zone.\n */\nexport function toolTime(at: number): string {\n const date = new Date(at)\n const pad = (value: number): string => String(value).padStart(2, '0')\n return `${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\n/**\n * Surface A's budget line, one branch per state the host can publish.\n *\n * `deferring` decides first, because it is the same flag that fills `deferred`:\n * a line that claimed the gate was off while the list below it showed hidden\n * tools would contradict itself. With nothing deferred, `budgetChars: 0` means\n * the gate is switched off in this deployment — the contract's own reading of a\n * zero budget — and any other budget means the surface simply fits, which is\n * not a state: a fitting surface gets no line at all, because the chips above\n * already carry `0 hidden` and a sentence repeating that is the empty row the\n * block stopped drawing.\n *\n * The figure is the host's own measurement in **characters** (`surfaceChars` /\n * `budgetChars`, contract C7), with the token count derived from it at the\n * contract's own rate of four characters per token. There are no slots here:\n * the host has never modelled them, so the line no longer invents them.\n * @param tools - one session's tool offer.\n * @param t - translate seat.\n * @returns the budget row, `null` when there is nothing to say, without the\n * exhausted note above it.\n */\nexport function budgetLine(tools: SessionTools, t: Translate): ReactNode {\n if (tools.deferring) {\n const split = budgetSplit(tools)\n const tokens = Math.round(tools.surfaceChars / 4)\n return h(\n 'div',\n null,\n h(\n 'div',\n {\n style: STYLE.budget,\n title: t('toolsBudgetBreakdown', {\n used: split.used,\n total: split.total,\n percent: split.percent,\n }),\n },\n h('span', { style: { ...STYLE.budgetUsed, width: `${split.percent}%` } }),\n ),\n h(\n 'div',\n { style: STYLE.muted },\n t('toolsBudget', {\n used: tools.surfaceChars,\n total: tools.budgetChars,\n tokens,\n }),\n ),\n )\n }\n if (tools.budgetChars === 0) return h('div', { style: STYLE.muted }, t('toolsBudgetGateOff'))\n return null\n}\n\n/**\n * What one tool row's detail block is opened with (F-26, F-56).\n *\n * The block prints only what the host published about this one name. `SessionTools`\n * measures the whole set (`surfaceChars` / `visibleChars` / `deferredChars`), not\n * a single tool, so there is no per-tool size here to print and none is derived:\n * the group's own budget line is where an estimate is real.\n *\n * What F-56 removed from the block is what the header already carries: the\n * registry name, the clock and the step. The tier stays here, but as the one\n * thing the header's dot cannot say while nobody hovers — and it reads as a\n * sentence rather than as the wire word.\n */\nexport interface ToolDetail {\n /** Tier that offered the name: the pin list, this session, or context ranking. */\n via: 'pin' | 'session' | 'context'\n /** The host's own step counter, when it published one (contract C2). */\n step?: number | undefined\n /** Epoch milliseconds of the last offer or call, when the host published one. */\n at?: number | undefined\n /** `true` while this row's detail block is open. */\n open: boolean\n /** Toggle this row's detail block. */\n onToggle: () => void\n /**\n * The session's own declared rows, read for the serving server's state — the\n * same {@link ServerRow} the block above draws. Absent on a surface that has no\n * servers to hand down (a unit test of the row, the design stand's own rows),\n * and then the state is simply not printed: the panel never guesses a status.\n */\n rows?: readonly ServerRow[] | undefined\n /**\n * Both counter readings the row's header was seeded with, so the block can\n * print the two of them apart: the header keeps the lead figure\n * ({@link callsLabel}'s choice) and the body adds the reading the header had no\n * room for. Absent where the host published no record for the row's server.\n */\n calls?: ToolCalls | undefined\n /**\n * Project the definition belongs to — the route's own first parameter.\n *\n * Absent together with {@link ToolDetail.sessionId} on a surface that is not\n * reading a host at all (the design stand's fixtures are seeded straight into\n * the cache, and a unit test of the row composes it without a route): the body\n * then draws no line rather than asking an address it was never given.\n */\n projectRoot?: string | undefined\n /** Session the row is open in — the route's own second parameter. */\n sessionId?: string | undefined\n}\n\n/**\n * The state of the server one registry name was registered under, as the row's\n * own block prints it.\n *\n * The rows handed down are the session's declared ones — `sessionRowsOf`'s list\n * — so a name whose server the host never declared gets no status, and neither\n * does a name without the `mcp__` prefix. \"The server is not in the list\" and\n * \"the server is idle\" are different facts, and only the second is printable.\n * @param name - the registry name on the row.\n * @param rows - the session's declared rows; absent draws no state at all.\n * @param t - translate seat.\n * @returns the sentence, or `undefined` when there is no server row to read.\n */\nexport function toolServerState(\n name: string,\n rows: readonly ServerRow[] | undefined,\n t: Translate,\n): string | undefined {\n const server = serverOfToolName(name)\n if (server === undefined) return undefined\n const row = (rows ?? []).find((entry) => entry.name === server)\n if (row === undefined) return undefined\n return t('toolServerState', { server, state: t(STATUS_KEYS[row.status]) })\n}\n\n/** The tier one row was offered by, said as a sentence (F-56). */\nexport function toolTierSentence(via: ToolDetail['via'], t: Translate): string {\n return via === 'pin'\n ? t('toolTierPinned')\n : via === 'session'\n ? t('toolTierSession')\n : t('toolTierContext')\n}\n\n/**\n * The two counter readings of one row's block (F-56), one line, each figure\n * labelled by what it counts.\n *\n * The block no longer repeats what the header shows — the header keeps the lead\n * figure, `callsLabel`'s own choice — so the project's total comes back only when\n * the host published it, and the session's own only when the session's slice\n * exists. A server the host never recorded draws nothing at all: this is the same\n * \"no data, no label\" rule the row obeys, one level down.\n * @param calls - the two readings, absent when the host published no record.\n * @param t - translate seat.\n * @returns the line, or `undefined` when there is no figure to print.\n */\nexport function toolCallsLine(calls: ToolCalls | undefined, t: Translate): string | undefined {\n if (calls === undefined || !calls.recorded) return undefined\n const project = calls.project\n const session = calls.session\n const parts = [\n project === undefined ? undefined : t('callsProject', { count: project }),\n session === undefined ? undefined : t('toolCallsSession', { count: session }),\n ].filter((part): part is string => part !== undefined)\n return parts.length === 0 ? undefined : parts.join(' · ')\n}\n\n/**\n * Why one name is not in this session's request, in the host's own figures\n * (F-56).\n *\n * Every number here arrived in `ToolFacts.reason`; a figure the host did not\n * measure leaves its phrase out rather than printing a zero, which is the same\n * discipline as contract C2's step tag. The whole sentence uses the complete\n * template while all three figures are there, so a reader of any language gets\n * its own grammar; a shorter answer falls back to the phrases that did arrive.\n * @param reason - the host's reason, or `undefined` for an offered name.\n * @param t - translate seat.\n * @returns the sentence, or `undefined` when there is nothing to print.\n */\nexport function toolReasonLine(reason: ToolReason | undefined, t: Translate): string | undefined {\n if (reason === undefined) return undefined\n const { chars, budget, used } = reason\n if (chars !== undefined && budget !== undefined && used !== undefined) {\n return t('toolReasonBudget', { chars, budget, used })\n }\n return [\n chars === undefined ? undefined : t('toolReasonChars', { chars }),\n budget === undefined ? undefined : t('toolReasonBudgetOnly', { budget }),\n used === undefined ? undefined : t('toolReasonUsed', { used }),\n ].filter((part): part is string => part !== undefined)\n .join(', ') || t('toolReason')\n}\n\n/**\n * The view model one opened row's body is drawn from.\n *\n * `loading` is the state of a read that has started and not landed, and it is\n * drawn as its own muted line rather than as an empty body: the answer is on its\n * way, and a block that drew nothing would read as \"there is nothing to say\".\n * `failure` is the host's refusal — an unknown name, or an older host without the\n * route — and it is drawn as a muted line too. Neither state invents a fact.\n */\nexport interface ToolFactsView {\n readonly state: 'loading' | 'failure' | 'facts'\n readonly facts?: ToolFacts | undefined\n}\n\n/**\n * What one opened row currently knows, read from the module's own cache.\n *\n * This is the **only** place the row's body asks for the definition: one call per\n * open row, from the row's own render, so a folded row costs nothing and a\n * refolded one is answered from {@link toolFacts}. A row with no route to ask —\n * the stand's seeded rows carry one, a unit test's may not — still reads the\n * cache, so a seeded answer is answered synchronously and an unseeded one draws\n * the loading line instead of contacting an address nobody gave.\n * @param name - the registry name on the row.\n * @param detail - the row's disclosure state and the session's own rows.\n * @returns the view model for the body; `loading` while the read is in flight.\n */\nexport function toolFactsView(name: string, detail: ToolDetail): ToolFactsView {\n const { projectRoot, sessionId } = detail\n // No route to ask: read what the cache already holds and start nothing. This\n // is the design stand's and a unit test's own path — a seeded answer is drawn,\n // an unseeded one waits, and neither opens a connection nobody asked for.\n if (projectRoot === undefined || sessionId === undefined) {\n // With no route in hand the panel reads the cache the way the seeded stand\n // does: a name is looked up as itself, so \"no route\" costs a definition\n // nothing rather than hiding it behind parameters nobody has.\n const failed = toolFactsFailed.has(name)\n const held = failed ? undefined : toolFacts.get(name)\n if (held !== undefined) return { state: 'facts', facts: held }\n return failed ? { state: 'failure' } : { state: 'loading' }\n }\n const entry: ToolFactsEntry = { projectRoot, sessionId, name }\n const held = toolFactsOf(entry)\n if (held !== undefined) return { state: 'facts', facts: held }\n return toolFactsUnreadable(entry) ? { state: 'failure' } : { state: 'loading' }\n}\n\n/** One accepted field, as the block lists it: mono name, type, marker, description. */\nfunction fieldLine(field: ToolField, index: number, t: Translate): ReactNode {\n return h(\n 'div',\n { key: `${field.name}-${String(index)}`, style: STYLE.field },\n // The marker rides with the type rather than with the name: `name*` reads as\n // part of the identifier, and a `*` the schema did not mean would be a\n // requirement the tool never declared.\n h('span', { style: STYLE.fieldName }, field.name),\n h('span', { style: STYLE.muted }, field.type),\n field.required ? h('span', { title: t('toolFieldRequiredHint') }, '*') : null,\n field.description === undefined\n ? null\n : h('span', { style: STYLE.fieldDesc }, `— ${field.description}`),\n )\n}\n\n/**\n * The one line that says where the definition is coming from: the read on its\n * way, or the host's own refusal. Nothing at all once the record is in hand —\n * the record draws itself.\n * @param view - what the cache holds for this name right now.\n * @param t - translate seat.\n * @returns the read's own line, or `null` while there is nothing to say.\n */\nfunction toolFactsReadLine(view: ToolFactsView, t: Translate): ReactNode {\n if (view.state === 'facts') return null\n const copy = view.state === 'failure' ? t('toolFailed') : t('toolLoading')\n return h('div', { key: 'read', style: STYLE.dim }, copy)\n}\n\n/**\n * The row's own fact line: the server the name was registered under — carrying\n * the state the session's declared rows give that server, when they name it —\n * the tier as a sentence, and the step and the clock only while the host\n * published them. A name without the `mcp__` prefix names no server and gets no\n * server phrase rather than an invented one.\n * @param name - the registry name on the row.\n * @param detail - the tier, the step, the clock and the session's own rows.\n * @param t - translate seat.\n * @returns the facts joined as one line, in the contract's order.\n */\nfunction toolFactsLine(name: string, detail: ToolDetail, t: Translate): string {\n const server = serverOfToolName(name)\n const state = toolServerState(name, detail.rows, t)\n return [\n server === undefined ? undefined : t('toolServer', { server: state ?? server }),\n toolTierSentence(detail.via, t),\n detail.step === undefined ? undefined : t('toolsStep', { step: detail.step }),\n detail.at === undefined ? undefined : toolTime(detail.at),\n ]\n .filter((part): part is string => part !== undefined)\n .join(' · ')\n}\n\n/**\n * The body of one opened tool row: the facts the header does not hold.\n *\n * A row that reads a host shows the full registry name, then one fact line —\n * the serving server with its state, the tier as a sentence, the step and the\n * clock, each only while the host published it — then the two counter readings,\n * and then the host's own answer about the definition: its model-facing\n * description verbatim, the fields it accepts, and the reason a hidden name is\n * not in the request. Empty groups are not printed, which is this file's rule\n * everywhere: no fields, no field list.\n *\n * A row composed without a route (a unit test's own row, a surface that never\n * read a host) has no address to ask and no declared rows to name: its body is\n * the read's own line alone, never a name and a fact line the block would then\n * have to invent.\n *\n * The reason leads the definition for a **hidden** row: there, it is the answer\n * to the question the reader opened the row with, while for an offered name the\n * same block is a definition rather than an apology.\n * @param name - the registry name on the row.\n * @param detail - the tier, the disclosure state and the session's own rows.\n * @param view - what the cache holds for this name right now.\n * @param t - translate seat.\n * @returns the body's lines, in order.\n */\nexport function toolFactsBody(\n name: string,\n detail: ToolDetail,\n view: ToolFactsView,\n t: Translate,\n): ReactNode {\n const read = toolFactsReadLine(view, t)\n if (detail.projectRoot === undefined || detail.sessionId === undefined) return read\n const facts = view.state === 'facts' ? view.facts : undefined\n const calls = toolCallsLine(detail.calls, t)\n const reason = facts === undefined ? undefined : toolReasonLine(toolReasonOf(name, facts), t)\n const fieldsLabel = t('toolFieldsLabel')\n return [\n h('div', { key: 'name', style: STYLE.name }, name),\n h('div', { key: 'facts', style: STYLE.detail }, toolFactsLine(name, detail, t)),\n ...(calls === undefined ? [] : [h('div', { key: 'calls', style: STYLE.muted }, calls)]),\n // The reason leads a hidden row's body: there it is the answer to the\n // question the reader opened the row with, while for an offered name the same\n // block is a definition rather than an apology.\n ...(reason === undefined ? [] : [h('div', { key: 'reason', style: STYLE.muted }, reason)]),\n read,\n ...(facts?.description === undefined\n ? []\n : [\n // The host's own model-facing text, exactly as it arrived: not\n // translated, not shortened, and not passed through a dictionary.\n h('div', { key: 'description', style: STYLE.detail }, facts.description),\n ]),\n ...(facts === undefined || facts.fields.length === 0\n ? []\n : [\n h('div', { key: 'fields', style: STYLE.group }, fieldsLabel),\n ...facts.fields.map((field, index) => fieldLine(field, index, t)),\n ]),\n ]\n}\n\n/**\n * The host's reason for one name, read from the record the row is holding.\n *\n * A record whose `name` is not the row's own is a host bug, and the panel draws\n * no reason rather than another tool's: the fact belongs to the definition the\n * body was asked about.\n * @param name - the registry name on the row.\n * @param facts - the record the cache holds.\n * @returns the reason, or `undefined` for an offered name.\n */\nfunction toolReasonOf(name: string, facts: ToolFacts): ToolReason | undefined {\n return facts.name === name ? facts.reason : undefined\n}\n\n/**\n * One row of the one surface's tools block: a header button that opens the\n * registry name and how the tool was offered, and the row's one action beside it.\n *\n * F-26 turned the row into a disclosure. The header keeps what it always showed\n * — the tier dot, the name, the time and the step the host gave, and the pin\n * action — and lives in a `button[aria-expanded]` so the row itself is the parity\n * gate's tool line. The action stays a sibling: a button inside a button is not a\n * thing HTML has.\n * @param row - the name, its time and its note.\n * @param action - the row's one action, when it has one.\n * @param tier - which tier offered the row; `pinned` when not given.\n * @param detail - the disclosure state and the facts it opens.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the row element.\n */\nexport function toolRow(\n row: ToolRow,\n action: { label: string; hint: string; onClick: () => void; disabled?: boolean } | undefined,\n tier: 'pinned' | 'disclosed' | 'hidden',\n detail: ToolDetail,\n t: Translate = translateOf(),\n): ReactNode {\n const open = detail.open\n const calls = callsLabel(row.calls, t)\n // Read once, and only while this row is the open one (F-56): the host route\n // answers one definition at a time, and a folded row asks for nothing.\n const facts = open\n ? toolFactsBody(row.name, { ...detail, calls: row.calls }, toolFactsView(row.name, detail), t)\n : null\n return h(\n 'div',\n { key: row.name, style: STYLE.tool },\n h(\n 'button',\n {\n style: STYLE.toolLine,\n 'aria-expanded': open,\n title: open ? t('hideTool') : t('showTool'),\n onClick: detail.onToggle,\n },\n h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[tier === 'pinned' ? 'active' : 'idle'] },\n }),\n h('span', { style: STYLE.name }, row.name),\n // The host's own counter, immediately after the name it counts: the one\n // reading on the row that is about how the tool has been used rather than\n // about what it is.\n calls === undefined ? null : h('span', { style: STYLE.dim }, calls),\n row.time === undefined ? null : h('span', { style: STYLE.muted }, row.time),\n row.note === undefined ? null : h('span', { style: STYLE.muted }, row.note),\n ),\n action === undefined\n ? null\n : h(\n 'button',\n { style: STYLE.button, title: action.hint, disabled: action.disabled === true, onClick: action.onClick },\n action.label,\n ),\n open\n ? h(\n 'div',\n { style: STYLE.toolDetail },\n // What the header cannot hold (F-56): the full registry name, the fact\n // line — the server with its state, the tier as a sentence, the step and\n // the clock only while the host published them — the counter readings\n // apart, and then the host's own answer about the definition, read once,\n // on demand, while this row is the one that is open.\n facts,\n )\n : null,\n )\n}\n\n/**\n * The declared servers of this session, in document order, with the state each\n * one is in.\n *\n * The first block of the one surface answers \"what is declared, and what is it\n * doing right now\", and a server that is declared but not serving is exactly why\n * an apparently empty catalog is empty: without this list `Nothing to hide yet`\n * reads as \"nothing is wrong\" while a stalled process quietly withholds all of\n * its tools.\n *\n * The row is the status and nothing else — the dot, the name, the status word\n * and the transport chip. Its `title` still carries the host's own multi-line\n * diagnostic, so hovering answers \"why\" without a click, but the diagnostic is\n * not drawn under the rows: F-26 hid it behind the errors disclosure, which\n * prints the same host text through {@link IssueView}'s rows. Drawing it in both\n * places put an amber wall between the model's tools and the reader.\n * @param props - the rows to list and the translate seat.\n * @returns the section, or `null` when the session declares nothing.\n */\nexport function ServersBlock(props: {\n rows: readonly ServerRow[]\n /** The project's usage counters, when the host published any (`idle {n}d`). */\n usage?: ProjectUsage\n t: Translate\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n /**\n * The project's retry, handed down to the failing rows so a broken server can\n * be pressed where it shows instead of behind the errors disclosure (F-55).\n */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight; the row button goes still with it. */\n busy?: boolean | undefined\n}): ReactNode {\n const { rows, t } = props\n if (rows.length === 0) return null\n const up = rows.filter((row) => row.status === 'active').length\n const failed = rows.filter((row) => row.status === 'error').length\n return h(\n 'div',\n { style: STYLE.serversBlock },\n h(\n 'div',\n { style: STYLE.row },\n h('span', { style: STYLE.groupInline }, t('toolsServers')),\n h('span', { style: { flex: 1 } }),\n h(\n 'span',\n {\n style: failed === 0 ? STYLE.tag : { ...STYLE.tag, ...STYLE.tagWarn },\n title: rows.map((row) => `${row.name}: ${t(STATUS_KEYS[row.status])}`).join('\\n'),\n },\n t('toolsServersUp', { up, total: rows.length }),\n ),\n ),\n ...rows.map((row) => {\n // The host's own record of this server; a row the counters never saw has\n // no `lastUsedAt` to read and the quiet word is simply not drawn.\n const idle = idleNote(row.status, props.usage?.[row.name]?.lastUsedAt, t)\n // The one job a row here can carry: a failing server gets the project's\n // retry, at the row's right edge, and nothing else does.\n const retry = row.status === 'error' ? props.onRetry : undefined\n return h(\n 'div',\n {\n style: STYLE.row,\n key: `tools#server#${row.name}`,\n title: rowDetail(row, props.hostT) ?? t(STATUS_HINT[row.status]),\n },\n h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[row.status] },\n 'aria-hidden': true,\n }),\n h('span', { style: STYLE.name }, row.name),\n // The status as a word, not only as the dot's colour: the question this\n // block answers is asked by someone who may not know the palette.\n h('span', { style: { ...STYLE.muted, color: STATUS_COLOR[row.status] } }, t(STATUS_KEYS[row.status])),\n idle === undefined ? null : h('span', { style: STYLE.dim }, idle),\n row.transport === undefined\n ? null\n : h('span', { style: STYLE.tag }, shortTransport(row.transport)),\n retry === undefined ? null : h('span', { style: { flex: 1 } }),\n retryButton(t, retry, props.busy),\n )\n }),\n )\n}\n\n/**\n * The hidden tier of the tools block: the names the model does not see, in a\n * list the user can open and act on.\n *\n * Hidden is the one tier whose contents are a list rather than a reading. The\n * counters already say how many names are left out, so this block adds the two\n * things they cannot: the names themselves, grouped by the server they were\n * mounted from, and the `Pin` that pulls one back into every request. The open\n * state arrives from the parent, so the tier is a pure function of its props —\n * the same reason the head is drawn by {@link disclosureHead} rather than by\n * {@link Disclosure}.\n * @param props - the hidden names, the requested `Pin` write and the open state.\n * @returns the head and, while open, one row per server and name.\n */\nexport function HiddenTier(props: {\n /** How many names the head's badge prints, the counters' own hidden figure. */\n count: number\n /** The hidden names, grouped by server, in the host's order. */\n servers: readonly HiddenServer[]\n /** `true` while the list is open. */\n open: boolean\n /** Toggle the list. */\n onToggle: () => void\n /** Pin one name, or absent while there is nothing to write to. */\n onChange?: ((tool: string, pinned: boolean) => void) | undefined\n /**\n * Pin every name of one server in one press (F-44), or absent while there is\n * nothing to write to. The names are this group's own: the list is what the\n * user is reading, and a server action that wrote names the tier does not show\n * would be a press with a hidden meaning.\n */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n /**\n * The project's own pin list, read for one thing only: whether a server's group\n * is already wholly pinned, which decides whether the line says `Pin all` or\n * `Unpin all`. A tier's names are usually unpinned, but nothing in the snapshot\n * forbids a pinned name to sit in `deferred` — a pin written between two\n * assemblies, or one the host itself still defers — and the label may not\n * promise the opposite of what the press does.\n */\n pins?: readonly string[] | undefined\n /** `true` while a pin write is in flight, so the buttons stay still. */\n pending: boolean\n /**\n * The one name of this tier whose body is open (F-56), as {@link ToolsView}\n * holds it, plus the writer that toggles it.\n *\n * Until F-56 every row here was handed `onToggle: () => undefined`: the tier\n * drew a disclosure that had nothing to disclose. The very reason a name is\n * hidden is what its body now prints, so the press that opens it is real.\n */\n openTool?: string | undefined\n /** Toggle one row's body. */\n onToggleTool?: ((name: string) => void) | undefined\n /**\n * The project the definitions belong to and the session the tier is read in —\n * the `GET tool` route's own two parameters, handed down by {@link ToolsView}.\n */\n projectRoot?: string | undefined\n sessionId?: string | undefined\n /** The session's own declared rows, for each open body's server state. */\n rows?: readonly ServerRow[] | undefined\n t: Translate\n}): ReactNode {\n const { t } = props\n /**\n * One server line's own press.\n *\n * The words follow the reading both surfaces share ({@link serverPinState}): a\n * group that is wholly pinned says `Unpin all`, anything else says `Pin all` —\n * and the direction the parent writes is {@link serverPinPress}'s, which is the\n * same rule. In the ordinary case a group's names are unpinned and the second\n * word never appears: it exists for the snapshot where a name is pinned and\n * still deferred — a pin written between two assemblies, or a hidden name the\n * user pinned from this very list — because there the first word would be the\n * opposite of what the press does.\n * @param entry - one server's hidden names.\n * @returns the press of that line.\n */\n const serverPress = (entry: HiddenServer): ReactNode => {\n const all = serverPinState(entry.names, props.pins ?? []) === 'all'\n return h(\n 'button',\n {\n type: 'button',\n style: STYLE.button,\n title: all ? t('toolsUnpinAllHint') : t('toolsPinAllHint'),\n disabled: props.pending,\n onClick: () => props.onPinServer?.(entry.server, entry.names),\n },\n all ? t('toolsUnpinAll') : t('toolsPinAll'),\n )\n }\n return h(\n 'div',\n { style: STYLE.disclosure },\n disclosureHead({\n label: t('toolsGroupHidden'),\n count: props.count,\n open: props.open,\n hint: t('toolsHiddenVia'),\n onToggle: props.onToggle,\n }),\n props.open\n ? h(\n 'div',\n { style: STYLE.disclosureBody },\n ...props.servers.flatMap((entry) => [\n // The server's own line, with the one press that takes all of it\n // (F-44): the label stays the reading it was, and the action sits at\n // the right edge the way every other action in the block does.\n h(\n 'div',\n { key: `${entry.server}-group`, style: STYLE.row },\n h('span', { style: STYLE.group }, `${entry.server} · ${entry.count}`),\n h('span', { style: { flex: 1 } }),\n props.onPinServer === undefined ? null : serverPress(entry),\n ),\n // One row per name, the full `mcp__<server>__<tool>` the registry\n // carries, with the pin that moves it into the always-offered list.\n // Since F-56 the row is a real disclosure: its body carries the\n // reason the name is not in the request, which is the question this\n // list is open to answer.\n ...entry.names.map((name) =>\n toolRow(\n { name },\n {\n label: t('toolsPin'),\n hint: t('toolsPinHint'),\n onClick: () => props.onChange?.(name, true),\n disabled: props.pending,\n },\n 'hidden',\n {\n via: 'pin',\n open: props.openTool === name,\n onToggle: () => props.onToggleTool?.(name),\n rows: props.rows,\n projectRoot: props.projectRoot,\n sessionId: props.sessionId,\n },\n t,\n ),\n ),\n ]),\n )\n : null,\n )\n}\n\n/**\n * The tools block's filter row (F-43): one query over the registry names, the\n * count of what is left on screen, and the `Clear` that hands the whole list\n * back.\n *\n * The tier half of the filter is not here but in the counter chips of the row\n * above, which stop being a reading and become the switch. The block prints one\n * number per tier (F-28) and says it once (F-37), so a second row of the same\n * four words without their counts would be a copy of a figure the chips already\n * carry.\n *\n * Nothing is drawn while the caller hands in no writer: a pure tree composed by\n * a spec keeps the block it had — an input whose value could never change is the\n * worse half of a control. The design-only render mode is not that caller: it\n * composes {@link tabBody}, so its panel is the product's own. The caption is\n * the exception: a filter the block was handed still hides rows, and hiding them\n * without saying so is the one thing the row exists to prevent.\n * @param props - the filter, what it kept, and the writers behind it.\n * @returns the panel's row with its own caption; the caption alone without a\n * writer, and `null` when a filter nobody applied has no writer either.\n */\nexport function ToolsFilter(props: {\n filter: ToolFilter\n /** Names passing the filter, and every name the block holds before it. */\n shown: number\n total: number\n /** Replace the query; absent leaves the field out of the tree. */\n onQuery?: ((query: string) => void) | undefined\n /** Drop the query and every pressed tier. */\n onClear?: (() => void) | undefined\n t: Translate\n}): ReactNode {\n const { t } = props\n const active = toolFilterActive(props.filter)\n // The caption is the only place the filter's own effect is readable: the chips\n // above it count the tiers, not what the query left of them.\n const caption = active\n ? h(\n 'div',\n { style: STYLE.dim },\n props.shown === 0\n ? t('toolsFilterNone')\n : t('toolsFilterShown', { shown: props.shown, total: props.total }),\n )\n : null\n if (props.onQuery === undefined) return caption\n return h(\n 'div',\n null,\n h(\n 'div',\n { style: STYLE.row },\n h('input', {\n type: 'search',\n style: STYLE.filterInput,\n value: props.filter.query,\n placeholder: t('toolsFilterPlaceholder'),\n 'aria-label': t('toolsFilterLabel'),\n onChange: (event: { target: { value: string } }) => props.onQuery?.(event.target.value),\n }),\n active && props.onClear !== undefined\n ? h(\n 'button',\n {\n type: 'button',\n style: STYLE.button,\n title: t('toolsFilterClearHint'),\n onClick: () => props.onClear?.(),\n },\n t('toolsFilterClear'),\n )\n : null,\n ),\n caption,\n )\n}\n\n/**\n * The tools block of the single surface: what this session's model sees now.\n *\n * Answers with the three counters, the pinned list, the tools the session\n * disclosed, and the hidden remainder grouped by the server it was mounted from.\n * Every reading is the host's own: `policy.pins` for the list a user wrote by\n * hand, `SessionTools` for the offer counters, `OfferedTool.step` for the\n * disclosure step (contract C2), and `ProjectSnapshot.presentation` for a second\n * owner of the request (contract C3). Pure and without state: the row whose\n * detail block is open is handed in by {@link ToolsSection}, which keeps one\n * open at a time.\n *\n * The filter (F-43) arrives the same way, from {@link ToolsSection}: the query,\n * the pressed tiers and the three writers. Without them the block draws every\n * tier and every name, exactly as it did before the panel existed.\n */\nexport function ToolsView(props: {\n project: ProjectSnapshot\n sessionId: string\n /** Policy to read the pin list from; the project's own when omitted. */\n policy?: ToolPolicy | undefined\n /** Pin or unpin one name; absent while there is nothing to write to. */\n onPin?: ((tool: string, pinned: boolean) => void) | undefined\n /**\n * Pin every hidden name of one server in one press (F-44). The names travel\n * with the call because this block is what grouped them; the writer above\n * expands them into the pin list the host stores.\n */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n /** `true` while a pin request is in flight, so the buttons stay still. */\n pending?: boolean\n /** The one row whose detail block is open, when a row is open. */\n openTool?: string | undefined\n /** Toggle one row's detail block. */\n onToggleTool?: ((name: string) => void) | undefined\n /**\n * The hidden list's own state: `true` / `false` once the user has pressed its\n * head, `undefined` while nobody has — which is the state the filter is\n * allowed to open the tier in. Held by {@link ToolsSection} and not by the\n * tier itself, so this block stays a pure tree of elements: its tests resolve\n * it without a React runtime.\n */\n openHidden?: boolean | undefined\n /** Toggle the hidden list. */\n onToggleHidden?: (() => void) | undefined\n /** The filter the panel shows; absent means every tier, every name. */\n filter?: ToolFilter | undefined\n /** Replace the query. */\n onQuery?: ((query: string) => void) | undefined\n /** Fold one tier in or out of the filter. */\n onTier?: ((tier: ToolTier) => void) | undefined\n /** Drop the query and every pressed tier. */\n onClearFilter?: (() => void) | undefined\n t: Translate\n /** Host-namespace seat for the presentation owner's coded note (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t } = props\n const tools = sessionToolsOf(props.project, props.sessionId)\n /**\n * One row's disclosure state: the tier, the host's own step and time, this\n * session's declared rows (so the open body can name the serving server's\n * state) and the route the body's definition is read from (F-56).\n */\n const detailOf = (\n name: string,\n via: ToolDetail['via'],\n step?: number | undefined,\n at?: number | undefined,\n ): ToolDetail => ({\n via,\n step,\n at,\n open: props.openTool === name,\n onToggle: () => props.onToggleTool?.(name),\n rows: serverRows,\n projectRoot: props.project.projectRoot,\n sessionId: props.sessionId,\n })\n // This session's own declared rows, read once for the open body's server state\n // — the same list `tabBody` draws above this block (`sessionRowsOf`).\n const serverRows = sessionRowsOf(props.project, props.sessionId)\n // `tools` absent is the host's only \"not mounted yet\" signal: a session with a\n // published offer that happens to be empty has real zeroes to print, and the\n // two states must not be conflated. The declared servers of the session are not\n // part of this block any more — the one surface draws them above it (F-26).\n if (tools === undefined) {\n return h(\n 'div',\n { style: STYLE.project },\n emptyState(t('toolsNotMounted'), t('toolsNotMountedHint')),\n h('div', { style: STYLE.codeLine }, t('toolsNotMountedCode')),\n )\n }\n const counts = toolCounts(tools)\n const split = budgetSplit(tools)\n const policy = props.policy ?? policyOf(props.project)\n // A mode the owner chose is not this plugin hiding tools, and the counters\n // cannot say which it is: `deferred` is the whole surface under `off` and empty\n // under `direct`, so printing them raw would report a switched-off project as\n // `0 pinned` and `N hidden` — the plugin taking credit for a decision it did not\n // make, and inviting the user to free slots that would change nothing.\n if (policy.mode === 'off') {\n return h(\n 'div',\n { style: STYLE.project },\n h(\n 'div',\n { style: STYLE.row },\n h('span', { style: STYLE.muted }, t('toolsSeeModel')),\n h('span', { style: { flex: 1 } }),\n h('span', null, t('toolsModeOffCounters', { mounted: tools.mounted })),\n ),\n h('div', { style: STYLE.warnNote }, t('toolsModeOff')),\n h('div', { style: STYLE.muted }, t('toolsModeOffHint')),\n )\n }\n // The host's own counters for this project and for the session the block is\n // open in: one row reads its server's record by registry name, and a row whose\n // server the host never recorded carries a value that draws nothing (no data,\n // no label) rather than a zero.\n const usage = props.project.usage\n const withCalls = (row: ToolRow): ToolRow => ({\n ...row,\n calls: toolCalls(row.name, usage, props.sessionId),\n })\n const rows = pinnedRows(tools, policy).map(withCalls)\n // The filter arrives from {@link ToolsSection}; a block nobody can write a\n // filter to draws the unfiltered tree it always did.\n const filter = props.filter ?? NO_TOOL_FILTER\n const active = toolFilterActive(filter)\n const everyPinned = rows.filter((row) => row.pinned)\n const everyCounted = rows.filter((row) => !row.pinned)\n const everyHidden = hiddenByServer(tools.deferred)\n // Only the `session` tier carries `at`; the `context` tier has no timestamp to\n // render, and the step tag both tiers show comes from the host's counter\n // (contract C2). The detail block prints the step and the time only while the\n // host published them, so each raw value is kept beside the row it belongs to;\n // the header keeps the note and the clock it always had.\n const everyDisclosed: { row: ToolRow; detail: ToolDetail }[] = [\n ...tools.activated.map((tool) => ({\n row: withCalls({\n name: tool.name,\n time: tool.at === undefined ? undefined : toolTime(tool.at),\n // The step is real once the host stamps it (contract C2). Absent, the row\n // shows no tag at all — no invented `step 4`.\n note: tool.step === undefined ? undefined : t('toolsStep', { step: tool.step }),\n }),\n detail: detailOf(tool.name, 'session', tool.step, tool.at),\n })),\n ...tools.context.map((tool) => ({\n row: withCalls({\n name: tool.name,\n note: tool.step === undefined ? undefined : t('toolsStep', { step: tool.step }),\n }),\n detail: detailOf(tool.name, 'context', tool.step),\n })),\n ]\n // What each tier draws once the filter has had its say: a tier the filter left\n // out draws nothing at all, a tier it kept draws the rows the query kept, and\n // the two figures below answer for exactly those rows. `total` is every row the\n // block holds before the filter — the denominator counts rows, not distinct\n // names, because rows are what the block draws: a name the session both pinned\n // and disclosed is two lines, and the caption answers for the lines.\n const pinned = tierVisible(filter, 'pinned') ? filterToolRows(everyPinned, filter.query) : []\n const counted = tierVisible(filter, 'counters') ? filterToolRows(everyCounted, filter.query) : []\n const disclosed = tierVisible(filter, 'disclosed')\n ? everyDisclosed.filter(({ row }) => matchesToolQuery(row.name, filter.query))\n : []\n const hidden = tierVisible(filter, 'hidden') ? filterHiddenServers(everyHidden, filter.query) : []\n const hiddenShown = hidden.reduce((sum, entry) => sum + entry.count, 0)\n const shown = pinned.length + counted.length + disclosed.length + hiddenShown\n const total =\n everyPinned.length +\n everyCounted.length +\n everyDisclosed.length +\n everyHidden.reduce((sum, entry) => sum + entry.names.length, 0)\n const onChange = props.onPin\n // The counters as chips, and only the ones that carry a number: `0 pinned` is\n // the empty row this block no longer draws, one chip at a time. With all four\n // at zero the row keeps its label and stops there, rather than printing four\n // zeroes at a panel that has nothing to count.\n //\n // One exception, and it is the price of the chip having become a control: a\n // tier the user pressed keeps its chip even after a host refresh drove its\n // count to zero, because a filter whose switch vanished would leave an empty\n // list nobody can explain — `Clear` is reachable, the chip that caused it is\n // not. It prints `0 {label}` while it is pressed, and the moment it is\n // released the zero is not drawn again.\n const chips = counterParts(tools, policy, t).filter(\n (part) => part.count > 0 || filter.tiers.includes(part.key),\n )\n // One pinned row per name, so a server's group can draw the row it stands for\n // without searching the list again.\n const pinnedByName = new Map(pinned.map((row) => [row.name, row]))\n // The chips are the filter's tier half (F-43): the same plate, the same\n // `{count} {label}` words, a button instead of a span while the block can write\n // the filter to something. A pressed chip means \"this tier alone\", and pressing\n // it again hands every tier back — an empty tier list is what \"every tier\"\n // means, so there is no fifth `all` chip to press and no state where none of\n // the four reads as applied.\n const tierChip = (part: CounterPart): ReactNode => {\n const on = filter.tiers.includes(part.key)\n const label = `${part.count} ${part.label}`\n if (props.onTier === undefined) return h('span', { key: part.key, style: STYLE.tag }, label)\n return h(\n 'button',\n {\n key: part.key,\n type: 'button',\n style: on ? { ...STYLE.filterChip, ...STYLE.filterChipOn } : STYLE.filterChip,\n 'aria-pressed': on,\n title: t('toolsFilterTier'),\n onClick: () => props.onTier?.(part.key),\n },\n label,\n )\n }\n return h(\n 'div',\n { style: STYLE.project },\n h(\n 'div',\n { style: STYLE.row },\n h('span', { style: STYLE.muted }, t('toolsSeeModel')),\n h('span', { style: { flex: 1 } }),\n chips.length === 0 ? null : h('span', { style: STYLE.chips }, chips.map(tierChip)),\n ),\n policy.mode === 'direct'\n ? h('div', { style: STYLE.muted }, t('toolsModeDirect'))\n : budgetLine(tools, t),\n split.exhausted\n ? h('div', { style: STYLE.warnNote }, `${t('toolsBudgetExhausted')} — ${t('toolsBudgetFree')}`)\n : null,\n // The filter sits between the head's readings and the list it narrows: the\n // counters above it say what the session offers, this row says what is left\n // of it on screen. Without a writer it draws nothing at all.\n h(ToolsFilter, {\n key: 'filter',\n filter,\n shown,\n total,\n onQuery: props.onQuery,\n onClear: props.onClearFilter,\n t,\n }),\n // A tier with nothing in it is not a heading over an apology, it is nothing:\n // each group below is drawn only while it has rows, and the zero it would\n // have printed lives in the chips above. One number per block (F-28), said\n // once (F-37). A tier the filter left out is nothing too — the chip that\n // pressed it is what says so.\n pinned.length === 0\n ? null\n : [\n h('div', { key: 'pinned', style: STYLE.group }, t('toolsGroupPinned')),\n // Since F-44 the pinned list is grouped by the server each name came\n // from, and each group carries the press that releases that whole\n // server — the counterpart of pinning one from the hidden tier or from\n // the settings page. The rows keep their own order inside a group: the\n // order the user pinned them in.\n ...pinnedByServer(pinned.map((row) => row.name)).flatMap((group) => [\n h(\n 'div',\n { key: `${group.server}-pinned`, style: STYLE.row },\n h('span', { style: STYLE.group }, `${group.server} · ${group.count}`),\n h('span', { style: { flex: 1 } }),\n props.onPinServer === undefined\n ? null\n : h(\n 'button',\n {\n type: 'button',\n style: STYLE.button,\n title: t('toolsUnpinServerHint'),\n disabled: props.pending === true,\n onClick: () => props.onPinServer?.(group.server, group.names),\n },\n t('toolsUnpinAll'),\n ),\n ),\n // The only real user choice on this surface: it is the host's pin list\n // that decides the row, so the action writes it back.\n ...group.names.map((name) => {\n const row = pinnedByName.get(name)\n return row === undefined\n ? null\n : toolRow(\n row,\n {\n label: t('toolsUnpin'),\n hint: t('toolsUnpinHint'),\n onClick: () => onChange?.(row.name, false),\n disabled: props.pending === true,\n },\n 'pinned',\n detailOf(row.name, 'pin'),\n t,\n )\n }),\n ]),\n ],\n counted.length === 0\n ? null\n : [\n h('div', { key: 'counters', style: STYLE.group }, t('toolsGroupCounters')),\n // Offered by the counters rather than chosen by the user, which is why\n // the action here is the pin that turns one into a user pin: the host's\n // own `POST pin` writes the very list the pinned group above reads.\n ...counted.map((row) =>\n toolRow(\n row,\n {\n label: t('toolsPin'),\n hint: t('toolsPinHint'),\n onClick: () => onChange?.(row.name, true),\n disabled: props.pending === true,\n },\n 'pinned',\n detailOf(row.name, 'pin'),\n t,\n ),\n ),\n ],\n disclosed.length === 0\n ? null\n : [\n h('div', { key: 'disclosed', style: STYLE.group }, t('toolsGroupDisclosed')),\n ...disclosed.map(({ row, detail }) =>\n toolRow(\n row,\n { label: t('toolsHide'), hint: t('toolsHideHint'), onClick: () => undefined },\n 'disclosed',\n detail,\n t,\n ),\n ),\n ],\n hidden.length === 0\n ? null\n : [\n // The one tier whose contents are a list rather than a reading: the\n // counters can say how many names are hidden, but only the names\n // themselves let a user pull one back. So the head opens, and the\n // sentence that used to sit under it as a caption became the head's own\n // tooltip — nothing hidden draws no head at all.\n h(HiddenTier, {\n key: 'hidden',\n // While the filter is on, the head counts what is under it, so the\n // number and the list agree: the chip above keeps the tier's own\n // total, which is why the two read differently and neither lies.\n count: active ? hiddenShown : counts.hidden,\n servers: hidden,\n // A query that found hidden names is a question about them: the tier\n // opens itself rather than leaving the matches behind a fold the user\n // has to guess at. The user's own press outranks that, which is why\n // `openHidden` has three states and not two: `undefined` — nobody has\n // pressed the head — is where the filter may open the tier, and the\n // first press replaces it with a choice that stands, filter or not.\n open: props.openHidden ?? active,\n onToggle: () => props.onToggleHidden?.(),\n onChange,\n onPinServer: props.onPinServer,\n pins: policy.pins,\n pending: props.pending === true,\n // One open body at a time across the whole block (F-56), and the\n // route its definition is read from: the hidden list's own rows are\n // rows of this same surface, so they open on the same writer.\n openTool: props.openTool,\n onToggleTool: props.onToggleTool,\n projectRoot: props.project.projectRoot,\n sessionId: props.sessionId,\n rows: serverRows,\n t,\n }),\n ],\n // Another plugin owning `assembly.tools` is the host's finding, not the\n // mockup's (contract C3). No field, no banner; the banner is a fact the host\n // reported.\n props.project.presentation === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.warnNote },\n `${t('toolsPresentationOwner')}: ${props.project.presentation.name}. ${resolveHost(props.hostT ?? hostTranslate(undefined), props.project.presentation.noteCode, undefined, props.project.presentation.note)}`,\n ),\n )\n}\n\n/**\n * \"Problems\" body: the rows that need a look, grouped by status.\n *\n * This is the body of the errors disclosure (F-26), so nothing above it repeats\n * the groups: the block starts at the first group — `error`, then `conflict`,\n * then `connecting`, in the order {@link statusGroups} triage puts them in —\n * and the disclosure's own badge is what says how many groups there are.\n * @param props - the project, its problem groups and the row action.\n * @returns the grouped rows.\n */\nexport function IssueView(props: {\n project: ProjectSnapshot\n groups: StatusGroup[]\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight, so the row buttons stay still. */\n busy?: boolean | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n return h(\n 'div',\n { style: STYLE.project },\n props.groups.map((group) =>\n h(\n 'div',\n { key: group.status },\n h('div', { style: STYLE.group }, `${t(STATUS_KEYS[group.status])} · ${group.rows.length}`),\n group.rows.flatMap((row) =>\n serverRow(row, `problem-${group.status}`, {\n onRetry: props.onRetry,\n busy: props.busy,\n t: props.t,\n hostT: props.hostT,\n }),\n ),\n ),\n ),\n )\n}\n\n/**\n * Centred message for a state that has nothing to list.\n * @param title - the headline.\n * @param hint - the line under it.\n * @param key - React key, for the callers that place the result inside an array\n * (React requires one there); variadic callers leave it out.\n */\nexport function emptyState(title: string, hint: string, key?: string): ReactNode {\n return h(\n 'div',\n key === undefined ? { style: STYLE.empty } : { key, style: STYLE.empty },\n h('div', { style: STYLE.emptyTitle }, title),\n h('div', { style: STYLE.hint }, hint),\n )\n}\n\n/** `info` and `up` are the quiet half of the level vocabulary. */\nconst LOG_CHIP: Record<LogEvent['level'], CSSProperties> = {\n info: {},\n up: { color: STATUS_COLOR.active },\n warn: { color: STATUS_COLOR.connecting },\n error: { color: STATUS_COLOR.error },\n}\n\n/** `12:41:31` — the clock the mockup's log rows carry, seconds included. */\nfunction logTime(at: number): string {\n const date = new Date(at)\n const pad = (value: number): string => String(value).padStart(2, '0')\n return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n}\n\n/**\n * The three facts of a failure, one per line.\n *\n * The host hands the facts over as separate lines — the endpoint, the document\n * that declared the server, and what did not appear — so they are relayed as\n * they are: split, trimmed, and with anything labelled as advice dropped. The\n * hint and the reminder about `Retry` are not facts, and `Retry` is already a\n * button on the server's own row.\n * @param detail - the event's `detail`, when it has one.\n * @returns the lines to draw under the event, empty when there is nothing to say.\n */\nexport function logFacts(detail: string | undefined): string[] {\n if (detail === undefined) return []\n return detail\n .split('\\n')\n .map((line) => line.trim())\n // The host's own advice is not a fact: the row above already carries the\n // reason, and `Retry` is a button on the server's row, not a sentence here.\n .filter((line) => !/^(hint|note|next step)\\s*:/i.test(line))\n .filter((line) => line.length > 0)\n}\n\n/**\n * One line of the event list.\n *\n * The message takes its own width (see {@link STYLE.logRow}) rather than a right\n * column, which is what keeps the row readable in a sidebar. A coded event is\n * resolved through the host seat (F-48): the translated template wins, and a\n * code the namespace does not know — or an event that carries none — renders\n * the payload's English exactly as before.\n * @param event - the event to draw.\n * @param key - React key for the row.\n * @param t - translate seat.\n * @param hostT - host-namespace seat; without one the payload's English shows.\n * @returns the row, plus the failure's fact lines under it.\n */\nexport function logRow(event: LogEvent, key: string, t: Translate, hostT?: Translate | undefined): ReactNode {\n const host = hostT ?? hostTranslate(undefined)\n const detail = resolveHost(host, event.detailCode, event.detailParams, event.detail)\n const facts = logFacts(detail === '' ? undefined : detail)\n return h(\n 'div',\n { key },\n h(\n 'div',\n { style: STYLE.logRow },\n h('span', { style: STYLE.logTime }, logTime(event.at)),\n h(\n 'span',\n { style: { ...STYLE.tag, ...STYLE.logLevel, ...LOG_CHIP[event.level] ?? {} } },\n t(`logsLevel${event.level.charAt(0).toUpperCase()}${event.level.slice(1)}`),\n ),\n event.server === undefined ? null : h('span', { style: STYLE.logName }, event.server),\n h('span', { style: STYLE.logMessage }, resolveHost(host, event.code, event.params, event.message)),\n ),\n facts.map((fact, index) => h('div', { key: `${key}#fact${index}`, style: STYLE.logDetail }, fact)),\n )\n}\n\n/**\n * The events the toolbar's two filters let through, newest first.\n *\n * Scope and level first, then the Clear mark: a cleared event is one the user\n * has said they are done with, whatever the filters say. The ring holds oldest\n * first, so the result is reversed to read newest first, like every log view.\n * @param props - the events and the three filters.\n * @returns the visible events, newest first.\n */\nexport function logVisible(props: {\n logs: readonly LogEvent[]\n scope: LogScope\n level: LogLevelFilter\n sessionId: string | undefined\n clearedAt: number | undefined\n}): LogEvent[] {\n return props.logs\n .filter(\n (event) =>\n (props.level === 'all' || event.level === 'error') &&\n (props.scope === 'all' || event.sessionId === props.sessionId) &&\n (props.clearedAt === undefined || event.at > props.clearedAt),\n )\n .sort((left, right) => right.at - left.at)\n}\n\n/**\n * The event ring, as the logs block reads it.\n *\n * The snapshot carries the newest page (contract C1); everything older is one\n * route call behind \"Show older\". The two filters and the Clear mark are the\n * tab's own, stored locally — Clear has no route, by contract, so it only\n * remembers a moment and stops drawing events at or before it.\n * Exported and pure (no hooks) so a test can drive the toolbar and the list\n * directly; {@link LogsView} is the stateful wrapper around it.\n * @param project - the project whose ring is shown.\n * @param logs - events to draw, newest first.\n * @param props - the filters, the paging state and the callbacks behind them.\n * @returns the toolbar and the list.\n */\nexport function logList(\n project: ProjectSnapshot,\n logs: readonly LogEvent[],\n props: {\n scope: LogScope\n level: LogLevelFilter\n total: number\n loading: boolean\n failed: boolean\n t: Translate\n /** Host-namespace seat for the coded events (F-48); the payload's English shows without one. */\n hostT?: Translate | undefined\n onScope: (scope: LogScope) => void\n onLevel: (level: LogLevelFilter) => void\n onClear: () => void\n onOlder: () => void\n more: boolean\n },\n): ReactNode {\n const { t } = props\n const chip = (\n filter: { label: string; on: boolean; onClick: () => void },\n ): ReactNode =>\n h(\n 'button',\n {\n key: filter.label,\n style: filter.on ? { ...STYLE.logFilter, ...STYLE.logFilterOn } : STYLE.logFilter,\n // The applied chip of each pair is the pressed one. The mode switch is\n // what F-26 took away, and with it every `[aria-pressed]` outside a\n // disclosure; these two pairs live inside the logs body, where the gate\n // reads them as such.\n 'aria-pressed': filter.on,\n onClick: filter.on ? undefined : filter.onClick,\n },\n filter.label,\n )\n return [\n h(\n 'div',\n { style: STYLE.bar, key: 'logs-toolbar' },\n chip({\n label: t('logsThisSession'),\n on: props.scope === 'session',\n onClick: () => props.onScope('session'),\n }),\n chip({\n label: t('logsAllSessions'),\n on: props.scope === 'all',\n onClick: () => props.onScope('all'),\n }),\n h('span', { style: { flex: 1 } }),\n chip({\n label: t('logsAllLevels'),\n on: props.level === 'all',\n onClick: () => props.onLevel('all'),\n }),\n chip({\n label: t('logsErrorsOnly'),\n on: props.level === 'error',\n onClick: () => props.onLevel('error'),\n }),\n h(\n 'button',\n { style: STYLE.button, title: t('logsClearHint'), onClick: props.onClear },\n t('logsClear'),\n ),\n ),\n logs.length === 0\n ? props.level === 'error' && props.total > 0\n ? logsNoErrorsState(t)\n : logsEmptyState(t)\n : h(\n 'div',\n { key: 'logs-events' },\n h('div', { style: STYLE.group }, t('logsProjectCount', { count: props.total })),\n logs.map((event, index) => logRow(event, `${event.at}-${index}`, t, props.hostT)),\n ),\n props.failed ? h('div', { style: STYLE.muted, key: 'logs-failed' }, t('logsLoadFailed')) : null,\n props.loading\n ? h('div', { style: STYLE.muted, key: 'logs-loading' }, t('logsLoading'))\n : props.more\n ? h(\n 'div',\n { key: 'logs-more' },\n h(\n 'button',\n { style: STYLE.button, title: t('logsMoreHint'), onClick: props.onOlder },\n t('logsMore'),\n ),\n h(\n 'span',\n { style: STYLE.muted },\n t('logsShown', { shown: logs.length, total: props.total }),\n ),\n )\n : null,\n ]\n}\n\n/**\n * The logs block of the tab: this plugin's own event ring, one project's\n * worth of it, with the two filters the mockup shows.\n * @param props - the project, the tab's session, that session's event count and\n * the storage the filters live in.\n * @returns the toolbar plus the newest events.\n */\nexport function LogsView(props: {\n project: ProjectSnapshot\n sessionId: string | undefined\n /** Storage seam for tests; defaults to the browser's own. */\n storage?: PanelStorage | undefined\n t: Translate\n /** Host-namespace seat for the coded events (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t, project } = props\n const [scope, setScope] = useState<LogScope>(() => logScopeOf(props.storage))\n const [level, setLevel] = useState<LogLevelFilter>(() => logLevelOf(props.storage))\n const [clearedAt, setClearedAt] = useState<number | undefined>(() => logsClearedAt(props.storage))\n const [older, setOlder] = useState<readonly LogEvent[]>([])\n const [request, setRequest] = useState<number | undefined>(undefined)\n const [failed, setFailed] = useState(false)\n // Cursors already paged for. A page whose events the filters hide still\n // advances the buffer, so this only ever stops a genuinely spent cursor.\n const [attempted, setAttempted] = useState<readonly number[]>([])\n const projectRoot = project.projectRoot\n const snapshot = project.logs ?? []\n // The page buffer is unfiltered on purpose: the filters decide what is drawn,\n // not what is buffered, so a page whose events the filters hide still moves\n // the cursor past itself instead of being asked for again.\n const buffered = [...older, ...snapshot]\n const visible = logVisible({ logs: buffered, scope, level, sessionId: props.sessionId, clearedAt })\n const total = project.logCount ?? snapshot.length\n const { more, cursor } = logsPaging({ visible, total, attempted })\n useEffect(() => {\n if (request === undefined) return\n let live = true\n setAttempted((seen) => (seen.includes(request) ? seen : [...seen, request]))\n setFailed(false)\n void fetchLogs(projectRoot, request).then((page) => {\n if (!live) return\n if (page === undefined) setFailed(true)\n else setOlder((shown) => mergeLogs(page.events, shown))\n setRequest(undefined)\n })\n return () => {\n live = false\n }\n }, [request, projectRoot])\n const changeScope = (next: LogScope): void => {\n setScope(next)\n persistLogFilter(LOG_SCOPE_KEY, next, props.storage)\n }\n const changeLevel = (next: LogLevelFilter): void => {\n setLevel(next)\n persistLogFilter(LOG_LEVEL_KEY, next, props.storage)\n }\n const clear = (): void => {\n // One millisecond back, so the next event landing in the same millisecond as\n // the click is not swallowed with the ones the user cleared.\n const at = Date.now() - 1\n setClearedAt(at)\n persistLogsClearedAt(at, props.storage)\n }\n return h(\n 'div',\n { style: STYLE.project },\n logList(project, visible, {\n scope,\n level,\n total,\n loading: request !== undefined,\n failed,\n t,\n hostT: props.hostT,\n onScope: changeScope,\n onLevel: changeLevel,\n onClear: clear,\n onOlder: () => setRequest(cursor),\n more,\n }),\n )\n}\n\n/**\n * Side card settings panel: the poll interval, the declaration detail and\n * per-project release.\n *\n * The interval row used to be drawn by the sidebar itself, out of the tab\n * descriptor's `pluginToggles`; the surface that drew it went with\n * `dsh-better-sidebar`, so the row is part of this panel now, next to the state\n * it paces. Everywhere else the panel is read-only.\n */\nexport function ProjectMcpSettings(props: {\n refreshMs: number\n /** Write a new interval; absent makes the row read-only (the design stand). */\n onRefreshMs?: ((value: number) => void) | undefined\n onClose?: (() => void) | undefined\n /** Translate seat; the popup follows the shell's language when it is given one. */\n t?: Translate | undefined\n /** Host-namespace seat for the wire-coded payload fields (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const { snapshot, error, busy, run } = useSnapshot(true, props.refreshMs)\n const projects = snapshot?.projects ?? []\n return h(\n 'div',\n { style: STYLE.root },\n h(\n 'div',\n { style: STYLE.bar },\n h('span', { style: STYLE.name }, t('mountedPerProject')),\n h('span', { style: STYLE.muted }, t('projectsCount', { count: projects.length })),\n h('span', { style: { flex: 1 } }),\n h(\n 'button',\n { style: STYLE.button, disabled: busy, onClick: () => void run(ROUTE_ACTIONS.sync) },\n t('sync'),\n ),\n props.onClose === undefined\n ? null\n : h('button', { style: STYLE.button, onClick: () => props.onClose?.() }, t('close')),\n ),\n h(RefreshRow, { refreshMs: props.refreshMs, onRefreshMs: props.onRefreshMs, t }),\n error === undefined ? null : h('div', { style: STYLE.error }, error),\n h(\n 'div',\n { style: STYLE.body },\n projects.length === 0\n ? h('div', { style: { ...STYLE.muted, padding: 8 } }, t('nothingMounted'))\n : projects.map((project) =>\n h(ProjectBlock, {\n key: project.projectRoot,\n project,\n busy,\n onRelease: (sessionId) => void run('release', { sessionId }),\n hostT: props.hostT,\n }),\n ),\n ),\n )\n}\n\n/** Bounds the row offers, the steps a press moves it by, and the unit it prints. */\nexport const REFRESH_MIN_MS = 1_000\nexport const REFRESH_MAX_MS = 60_000\nexport const REFRESH_STEP_MS = 500\n/** The unit symbol beside the field; a symbol, not copy, so it is not translated. */\nexport const REFRESH_UNIT = 'ms'\n/** The field's id, so the row's label can point at it. */\nexport const REFRESH_INPUT_ID = 'dsh-project-mcp-refresh-ms'\n\n/**\n * The poll interval as one labelled row: the copy the sidebar's toggle used,\n * the number field that replaces it, and the unit beside it.\n *\n * One implementation for both renderers — the product's settings panel and the\n * design stand's popup draw this same row — so the two cannot drift. Without a\n * writer the field is `readOnly` rather than absent: the stand shows the control\n * the product shows, it just does not pretend a press changed anything.\n */\nexport function RefreshRow(props: {\n refreshMs: number\n onRefreshMs?: ((value: number) => void) | undefined\n t?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n return h(\n 'div',\n { style: STYLE.settingRow },\n h(\n 'label',\n { style: STYLE.settingLabel, htmlFor: REFRESH_INPUT_ID },\n h('span', { style: STYLE.settingTitle }, t('refreshTitle')),\n h('span', { style: STYLE.settingDesc }, t('refreshDesc')),\n ),\n h('input', {\n id: REFRESH_INPUT_ID,\n style: STYLE.settingInput,\n type: 'number',\n min: REFRESH_MIN_MS,\n max: REFRESH_MAX_MS,\n step: REFRESH_STEP_MS,\n value: props.refreshMs,\n readOnly: props.onRefreshMs === undefined,\n 'aria-label': t('refreshTitle'),\n onChange: (event: { target: { value: string } }) => {\n const next = Number(event.target.value)\n if (Number.isFinite(next)) props.onRefreshMs?.(next)\n },\n }),\n h('span', { style: STYLE.settingUnit }, REFRESH_UNIT),\n )\n}\n\n/**\n * One project block: the merged rows (what the project as a whole reports) plus\n * the per-session breakdown underneath — but only for the sessions whose own\n * reading differs from the merge.\n *\n * The project is the subject now that one project-level mount serves every\n * session: a session that reads exactly like the merged rows adds no answer, so\n * the section is left out entirely and the block is just the project. A session\n * that mounts something else, or has not turned yet, is the only reason to show\n * the breakdown under it.\n */\nexport function ProjectBlock(props: {\n project: ProjectSnapshot\n /** Session this tab belongs to; missing in the settings popup. */\n currentSessionId?: string | undefined\n /** True while a host action is in flight. */\n busy: boolean\n /** Called with the id of the session whose servers should be released. */\n onRelease: (sessionId: string) => void\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /**\n * `false` when the surface above already names the project and carries its\n * `this session` chip — the sidebar tab's own header does. Defaults to `true`.\n */\n showName?: boolean | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /**\n * Host-namespace seat for the wire-coded payload fields (F-48); without one\n * the echo seat applies and every coded field shows its payload's English.\n */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const hostT = props.hostT ?? hostTranslate(undefined)\n const { project } = props\n const totals = countStatuses(project.rows)\n const sessions = sessionBreakdown(project, props.currentSessionId, t)\n const current = sessions.some((session) => session.current)\n // Project-first: the section is the disagreement view, so it is handed only\n // the sessions that read differently. An empty list makes it render nothing at\n // all — the header included — which is the quiet case this exists for.\n const deviating = sessions.filter((session) => session.deviates)\n return h(\n 'div',\n { style: STYLE.project, key: project.projectRoot },\n props.showName === false\n ? null\n : h(\n 'div',\n { style: STYLE.projectHead },\n h(\n 'span',\n { style: STYLE.name, title: project.projectRoot },\n basename(project.projectRoot),\n ),\n current ? h('span', { style: STYLE.tag }, t('thisSession')) : null,\n h('span', { style: { flex: 1 } }),\n h('span', { style: STYLE.muted }, summarize(totals, t)),\n ),\n h(\n 'div',\n // Rung 0: the project's merged rows are the ladder's baseline.\n { style: STYLE.indent(0) },\n project.rows.flatMap((row) =>\n serverRow(row, 'merged', { onRetry: props.onRetry, busy: props.busy, t: props.t, hostT: props.hostT }),\n ),\n ),\n projectIssueLines(project).map((issue, index) =>\n h(\n 'div',\n { style: STYLE.detail, key: `${issue.source}#${index}` },\n `${issue.level}: ${resolveHost(hostT, issue.code, issue.params, issue.message)}`,\n ),\n ),\n h(SessionList, {\n key: `${project.projectRoot}#sessions`,\n sessions: deviating,\n busy: props.busy,\n onRelease: props.onRelease,\n // The note is about the rows above, which stay the merge of *all* the\n // project's sessions even when only one of them is out of step.\n merged: sessions.length > 1,\n t: props.t,\n hostT: props.hostT,\n }),\n )\n}\n\n/**\n * The issues the rows below do not already carry.\n *\n * A failing mount is reported twice by the host: once as the row's own `detail`,\n * which the row renders in its banner, and once as a snapshot issue naming the\n * same server. Only the issues that no banner repeats belong under the rows —\n * the document-level ones.\n * @param project - one project from the host snapshot.\n * @returns the issues left to print, in host order.\n */\nexport function projectIssueLines(project: ProjectSnapshot): ProjectSnapshot['issues'] {\n return project.issues.filter(\n (issue) =>\n issue.server === undefined ||\n !project.rows.some((row) => row.name === issue.server && row.detail !== undefined),\n )\n}\n\n/** Per-session view model the panel renders under one project. */\nexport interface SessionBreakdown {\n /** Agent (session) id; shown truncated, in full in the tooltip. */\n id: string\n /** True when this is the session the tab is open in. */\n current: boolean\n /** This session's own rows, in document order. */\n rows: ServerRow[]\n /** One-line status summary. */\n summary: string\n /**\n * True when this session's own reading disagrees with the project's merged\n * rows. The `sessions` section exists only for these sessions: the project's\n * rows come first, and a session that reads exactly like them says nothing.\n */\n deviates: boolean\n}\n\n/**\n * Whether one session's own rows disagree with the project's merged rows.\n *\n * The project's `rows` are the merge of every session, so one that mounts a\n * different set, or that has not turned yet, reads differently from them. The\n * comparison is per server and order-insensitive: each side is read as a\n * `name → set of statuses` map, so the same rows in another order are not a\n * disagreement. A name declared twice counts only for what it says — the same\n * status twice collapses into one, while two different statuses are a\n * disagreement whichever order the two sides list them in. A session whose own\n * `rows` are empty claims nothing and therefore never disagrees — a host half\n * older than the per-session field must not make the section appear.\n * @param merged - the project's merged rows.\n * @param own - one session's own rows.\n * @returns `true` when the two readings differ.\n */\nexport function sessionDeviates(merged: readonly ServerRow[], own: readonly ServerRow[]): boolean {\n if (own.length === 0) return false\n const projectStatus = statusesByName(merged)\n const sessionStatus = statusesByName(own)\n if (projectStatus.size !== sessionStatus.size) return true\n for (const [name, statuses] of projectStatus) {\n const ownStatuses = sessionStatus.get(name)\n if (ownStatuses === undefined || ownStatuses.size !== statuses.size) return true\n for (const status of statuses) {\n if (!ownStatuses.has(status)) return true\n }\n }\n return false\n}\n\n/** One side's rows as `name → the statuses that name was declared with`. */\nfunction statusesByName(rows: readonly ServerRow[]): Map<string, Set<ServerRow['status']>> {\n const byName = new Map<string, Set<ServerRow['status']>>()\n for (const row of rows) {\n const statuses = byName.get(row.name)\n if (statuses === undefined) byName.set(row.name, new Set([row.status]))\n else statuses.add(row.status)\n }\n return byName\n}\n\n/**\n * Split a project's snapshot into its per-session view.\n *\n * Sessions of one project mount independently, so the merged `rows` cannot say\n * which session holds a server. Each entry also carries whether that session's\n * own reading {@link sessionDeviates} from the merge: the panel prints the\n * project's rows first and the section only for the sessions that differ, so the\n * answer to \"is anything not as the project says\" is computed once, here.\n * `sessions`, and each entry's `rows` with it, are read defensively: the browser\n * half hot-reloads while the host half only picks up a new build at restart, so\n * a newer panel can meet a host that predates either field.\n * @param project - one project from the host snapshot.\n * @param currentSessionId - the session this tab belongs to, if known.\n * @param t - translate seat for the summary line; English without one.\n * @returns one entry per session, in host order.\n */\nexport function sessionBreakdown(\n project: ProjectSnapshot,\n currentSessionId: string | undefined,\n t?: Translate,\n): SessionBreakdown[] {\n return (project.sessions ?? []).map((session) => {\n const rows = session.rows ?? []\n return {\n id: session.id,\n current: currentSessionId !== undefined && session.id === currentSessionId,\n rows,\n summary: summarize(countStatuses(rows), translateOf(t)),\n deviates: sessionDeviates(project.rows, rows),\n }\n })\n}\n\n/**\n * The deviating sessions' own rows, read as one summary line.\n *\n * The collapsed `sessions` section answers \"who is not holding this project the\n * way the rows above say\", so its header counts the statuses across the sessions\n * it lists — the deviating ones — not across the whole project.\n * @param sessions - the deviating part of the project's per-session breakdown.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the merged status summary, e.g. `2 active, 1 idle`.\n */\nexport function sessionsSummary(sessions: readonly SessionBreakdown[], t?: Translate): string {\n return summarize(countStatuses(sessions.flatMap((session) => session.rows)), translateOf(t))\n}\n\n/**\n * The header row of the collapsed sessions section.\n *\n * Collapsed is the default: the section is a disclosure, so the header has to\n * carry the whole answer on its own — the label, how many sessions are out of\n * step, and their merged status. The list handed to it is already the deviating\n * one, so the count chip counts those, never how many sessions the project has\n * (the toolbar's right edge is where that count lives). Exported and pure so\n * the shape is asserted without a renderer; {@link SessionList} owns the open\n * state and the rows below it.\n * @param props - the deviating sessions, the open flag and the toggle.\n * @returns the header row.\n */\nexport function sessionsHeader(props: {\n sessions: readonly SessionBreakdown[]\n open: boolean\n onToggle: () => void\n /** `true` when the rows above are a merge of these sessions, not one session's own. */\n merged?: boolean | undefined\n t?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n return h(\n 'div',\n // Rung 1: the `sessions` section sits one step right of the project rows.\n { style: { ...STYLE.sessionHead, ...STYLE.indent(1) } },\n h(\n 'button',\n {\n // The mockup draws the section label in the tertiary tone\n // (`docs/design/mockups/harness.html`) — it names the seam, it is not the content.\n style: { ...STYLE.sessionToggle, ...STYLE.dim },\n 'aria-expanded': props.open,\n title: props.open ? t('hideSessions') : t('showSessions'),\n onClick: props.onToggle,\n },\n `${props.open ? '▾' : '▸'} ${t('sessionsSection')}`,\n ),\n h('span', { style: STYLE.tag }, deviationCount(props.sessions.length, t)),\n h('span', { style: STYLE.muted }, sessionsSummary(props.sessions, t)),\n h('span', { style: { flex: 1 } }),\n props.merged === true ? h('span', { style: STYLE.muted }, t('mergedAcrossSessions')) : null,\n )\n}\n\n/**\n * The list of the sessions that read differently from the project.\n *\n * Project-first: the rows above are the project's own reading, and a session\n * that reads exactly like them adds nothing, so the panel hands this component\n * only the sessions whose own rows disagree. An empty list therefore means the\n * whole project agrees with itself — the quiet case — and the section renders\n * nothing at all: no header, no rows. When there is something to explain, the\n * section still starts collapsed so a single out-of-step session does not push\n * the project's rows out of the way; opening it lists one row per deviating\n * session, and each of those opens its own rows.\n */\nexport function SessionList(props: {\n sessions: SessionBreakdown[]\n busy: boolean\n onRelease: (sessionId: string) => void\n /** `true` when the rows above are a merge of the project's sessions, not one session's own. */\n merged?: boolean | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const [section, setSection] = useState(false)\n const [open, setOpen] = useState<string | undefined>(undefined)\n // Nothing to explain: the section is the whole disagreement view, header\n // included, and a project that reads like every one of its sessions gets none.\n if (props.sessions.length === 0) return null\n return h(\n 'div',\n { style: STYLE.sessions },\n sessionsHeader({\n sessions: props.sessions,\n open: section,\n merged: props.merged,\n onToggle: () => setSection((value) => !value),\n t: props.t,\n }),\n section\n ? props.sessions.map((session) =>\n h(sessionEntry, {\n key: session.id,\n session,\n expanded: open === session.id,\n onToggle: () => setOpen((value) => (value === session.id ? undefined : session.id)),\n busy: props.busy,\n onRelease: props.onRelease,\n t: props.t,\n hostT: props.hostT,\n }),\n )\n : null,\n )\n}\n\n/**\n * One session's block inside the expanded `sessions` section: its own header row\n * (the short id, `this session` when it is, the summary, `Release`) and, when it\n * is open, the servers that session holds.\n *\n * Pure, with the disclosure state given to it rather than owned, so the ladder it\n * draws — rung `2` for the header, rung `3` for the rows under it — is asserted\n * without rendering {@link SessionList}.\n * @param props - the session, its open state and the row action.\n * @returns the session's block.\n */\nexport function sessionEntry(props: {\n session: SessionBreakdown\n expanded: boolean\n onToggle: () => void\n busy: boolean\n onRelease: (sessionId: string) => void\n t?: Translate | undefined\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const { session } = props\n return h(\n 'div',\n // Rung 2: one session of the section, one step right of its header.\n { style: { ...STYLE.session, ...STYLE.indent(2) } },\n h(\n 'div',\n { style: STYLE.sessionHead },\n h(\n // The marker belongs to a **collapsed** row only (mockup `:323`): an\n // expanded session already shows its servers, so a turned-down triangle\n // beside them would be a second, redundant marker. The button stays\n // either way, so the row is still the control that folds it back up.\n 'button',\n {\n // A collapsed session's id is the mock's `.dim` (`docs/design/mockups/harness.html`):\n // once open, the id is content and reads in the primary tone.\n style: props.expanded ? STYLE.sessionToggle : { ...STYLE.sessionToggle, ...STYLE.dim },\n title: props.expanded ? t('hideSession') : t('showSession'),\n 'aria-expanded': props.expanded,\n onClick: props.onToggle,\n },\n props.expanded ? shortSessionId(session.id) : `▸ ${shortSessionId(session.id)}`,\n ),\n session.current ? h('span', { style: STYLE.tag }, t('thisSession')) : null,\n h('span', { style: STYLE.muted }, session.summary),\n h('span', { style: { flex: 1 } }),\n h(\n 'button',\n {\n style: STYLE.button,\n disabled: props.busy,\n title: session.id,\n onClick: () => props.onRelease(session.id),\n },\n t('release'),\n ),\n ),\n props.expanded ? sessionRows(session, props.t, props.hostT) : null,\n )\n}\n\n/**\n * One session's own server rows, or the placeholder when that session declared\n * nothing, at rung `3` — the deepest level of the surface's indentation ladder.\n * Exported so the panel tests can assert what a session block shows without a\n * DOM.\n * @param session - one entry of {@link sessionBreakdown}.\n * @param t - translate seat; falls back to this module's English copy.\n * @param hostT - host-namespace seat for the rows' coded details (F-48).\n * @returns the rows element tree for that session.\n */\nexport function sessionRows(session: SessionBreakdown, t?: Translate, hostT?: Translate): ReactNode {\n return h(\n 'div',\n // Rung 3: the servers a session holds, one step right of the session row.\n { style: STYLE.indent(3) },\n session.rows.length === 0\n ? h('div', { style: STYLE.muted }, translateOf(t)('nothingDeclared'))\n : session.rows.map((row) => serverRow(row, session.id, { t, hostT })),\n )\n}\n\n/** `session-8fce1c` reads better as `8fce1c` in a narrow sidebar. */\nfunction shortSessionId(id: string): string {\n const trimmed = id.replace(/^session-/, '')\n return trimmed.length > 8 ? `${trimmed.slice(0, 8)}…` : trimmed\n}\n\n/**\n * `1 session` / `3 sessions`, through the locale table.\n *\n * The toolbar's right edge answers how many sessions the project has; the\n * `sessions` section counts something else and uses\n * {@link deviationCount} instead.\n */\nexport function sessionCount(count: number, t: Translate): string {\n return count === 1 ? t('sessionsOne') : t('sessionsMany', { count })\n}\n\n/**\n * `1 differs` / `3 differ` — how many sessions are out of step with the project.\n *\n * A chip of its own phrase rather than `{count} sessions`: the section lists the\n * deviating sessions only, and \"1 session\" beside one row would read as the\n * project having a single session, which the toolbar already says.\n */\nexport function deviationCount(count: number, t: Translate): string {\n return count === 1 ? t('differsOne') : t('differsMany', { count })\n}\n\n/** `1 server` / `3 servers`, through the locale table. */\nexport function serverCount(count: number, t: Translate): string {\n return count === 1 ? t('serversOne') : t('serversMany', { count })\n}\n\n/**\n * The short form of a transport: the mockup's rows carry `http` / `stdio`.\n * @param transport - the transport the host reported.\n * @returns the chip's label.\n */\nexport function shortTransport(transport: string): string {\n return transport === 'streamable-http' ? 'http' : transport\n}\n\n/** Everything one server row needs beyond the row itself. */\nexport interface ServerRowOptions {\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight, so the row's button stays still. */\n busy?: boolean | undefined\n /**\n * The host's own `lastUsedAt` for this server, when it published a record for\n * it: the quiet row then reads `idle 3d` beside its status word\n * ({@link idleNote}).\n */\n lastUsedAt?: string | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /**\n * Host-namespace seat for the row's coded detail (F-48); without one the\n * payload's English shows, byte-identical to before codes existed.\n */\n hostT?: Translate | undefined\n}\n\n/**\n * A row's detail line as the screen shows it (F-48): the coded companions\n * resolved through the host seat, and the payload's English prose when they\n * are absent (an old host) or the seat does not know the code (a client older\n * than the host). `undefined` stays `undefined`, so a detail-less row keeps\n * its status hint as the tooltip.\n * @param row - the server row.\n * @param hostT - the host-namespace seat, when the surface has one.\n * @returns the sentence to render, or `undefined` for a row with no detail.\n */\nexport function rowDetail(row: ServerRow, hostT?: Translate | undefined): string | undefined {\n if (row.detail === undefined) return undefined\n return resolveHost(hostT ?? hostTranslate(undefined), row.detailCode, row.detailParams, row.detail)\n}\n\n/**\n * The quiet `idle {n}d` word a server row shows beside its status word.\n *\n * Only the two quiet statuses get one: `active`, `connecting`, `error` and\n * `conflict` already say what the server is doing, and a figure of inactivity\n * beside them would be a second answer to a question nobody asked. The word is\n * the span since the host's own `lastUsedAt` (`ProjectSnapshot.usage`), and it\n * is drawn only while that record exists and parses: no data, no word — never a\n * `0`.\n * @param status - the row's status.\n * @param lastUsedAt - ISO timestamp of the server's most recent call.\n * @param t - translate seat; falls back to this module's English copy.\n * @param now - epoch milliseconds to measure against; `Date.now()` by default.\n * @returns the label, or undefined when this row shows none.\n */\nexport function idleNote(\n status: ServerStatus,\n lastUsedAt: string | undefined,\n t: Translate = translateOf(),\n now: number = Date.now(),\n): string | undefined {\n if (status !== 'idle' && status !== 'disabled') return undefined\n const span = idleOf(lastUsedAt, now)\n if (span === undefined) return undefined\n const key = span.unit === 'day' ? 'idleDay' : span.unit === 'hour' ? 'idleHour' : 'idleMinute'\n return t(key, { count: span.count })\n}\n\n/**\n * How often one tool was called, as its row writes it.\n *\n * The counters belong to the host's record of the tool's server, and there are\n * two of them: the project's, which is what proved the tool hot, and the reading\n * session's own share of it (F-34). The row leads with the session's figure —\n * the question a reader at one session asks — and names the project's when the\n * two disagree, because that disagreement is the whole point: tools are mounted\n * for the project and used inside a session. Three states are told apart: a\n * figure to print, a server the host recorded whose counter for this tool is\n * absent (`never called`), and no record at all, which draws nothing.\n * @param calls - the two readings, absent when the host published no record.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the label, or undefined when the row shows none.\n */\nexport function callsLabel(calls: ToolCalls | undefined, t: Translate = translateOf()): string | undefined {\n if (calls === undefined || !calls.recorded) return undefined\n // The session's own reading leads whenever the host splits its counters by\n // session; without a split the project total is the only figure there is.\n const lead = calls.split ? calls.session : calls.project\n const figure =\n lead === undefined ? t('callsNone') : lead === 1 ? t('callsOne') : t('callsMany', { count: lead })\n const project = calls.project\n // The project's figure rides along exactly while it adds something: it is\n // published, and the session's own reading does not already say it. Two numbers\n // that agree are one number, and `never called · 182 in the project` says what\n // \"never called\" alone would leave unsaid.\n const adds = project !== undefined && project !== lead\n return adds ? `${figure} · ${t('callsProject', { count: project })}` : figure\n}\n\n/**\n * The one `Retry` a failing server row carries.\n *\n * Two surfaces draw a server row — the errors disclosure's {@link serverRow} and\n * the tab's own {@link ServersBlock} — and both offer the same action: the host\n * route drops this project's failed mounts and re-mounts them. The button is\n * built here once, so its label, its hint and the `disabled` flag that keeps\n * every press still while one host action is in flight cannot drift apart\n * between them. A surface that hands no action down gets no button at all,\n * which is what makes a read-only panel read-only instead of drawing a dead\n * press.\n * @param t - translate seat.\n * @param onRetry - the project's retry, or undefined where nothing can be written.\n * @param busy - `true` while a host action is in flight.\n * @returns the button, or `null` where there is no action to press.\n */\nfunction retryButton(\n t: Translate,\n onRetry: (() => void) | undefined,\n busy: boolean | undefined,\n): ReactNode {\n return onRetry === undefined\n ? null\n : h(\n 'button',\n {\n style: STYLE.button,\n title: t('retryHint'),\n disabled: busy === true,\n onClick: onRetry,\n },\n t('retry'),\n )\n}\n\n/**\n * One server, as the tab draws it.\n *\n * The status is the dot, not a word: its colour comes from the shared\n * {@link STATUS_COLOR} table and its tooltip through {@link STATUS_HINT}, so the\n * row reads at a glance and still explains itself on hover. The transport and\n * the quiet states (`idle`, `disabled`) are chips, and the quiet rows are dimmed\n * rather than recoloured. A row the host reported a failure for carries its own\n * `Retry` — the host route is project-scoped, so it sends exactly the request\n * the toolbar's button sends — and its detail in a banner underneath, with the\n * coloured left rule the mockup uses for a failure.\n * @param row - the server row.\n * @param keyPrefix - prefix for the two element keys of this row.\n * @param options - the row action and the translate seat.\n * @returns the row and, when it has one, its detail banner.\n */\nexport function serverRow(\n row: ServerRow,\n keyPrefix: string,\n options: ServerRowOptions = {},\n): ReactNode[] {\n const t = translateOf(options.t)\n const quiet = row.status === 'idle' || row.status === 'disabled'\n // The host's detail line, translated when the row carries its wire code.\n const detail = rowDetail(row, options.hostT)\n // The span since the host's own `lastUsedAt`, drawn beside the quiet status\n // word and only there: `idle 3d` says how long a quiet server has been quiet,\n // which is a fact the status word alone cannot carry.\n const idle = idleNote(row.status, options.lastUsedAt, t)\n return [\n h(\n 'div',\n {\n style: quiet ? { ...STYLE.row, ...STYLE.rowQuiet } : STYLE.row,\n key: `${keyPrefix}#${row.name}`,\n title: detail ?? t(STATUS_HINT[row.status]),\n },\n h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[row.status] },\n 'aria-hidden': true,\n }),\n h('span', { style: STYLE.name }, row.name),\n row.transport === undefined\n ? null\n : h('span', { style: STYLE.tag }, shortTransport(row.transport)),\n // The quiet chip takes the mock's `.dim` tone (`docs/design/mockups/harness.html`),\n // one step below the transport chip beside it.\n quiet ? h('span', { style: { ...STYLE.tag, ...STYLE.tagQuiet } }, t(STATUS_KEYS[row.status])) : null,\n idle === undefined ? null : h('span', { style: STYLE.dim }, idle),\n h('span', { style: { flex: 1 } }),\n retryButton(t, row.status === 'error' ? options.onRetry : undefined, options.busy),\n ),\n // A quiet row's detail (\"not mounted yet — this session has not started a\n // turn\") is a fact about a *normal* state, and the mockup draws `idle` as a\n // chip with no note under it (`docs/design/mockups/harness.html`): a warning banner per\n // idle server turns a calm list into a wall of amber. The reason stays on\n // the row's own `title`, and the errors disclosure (error / conflict /\n // connecting only) is where the host's text is read out in full.\n row.detail === undefined || quiet\n ? null\n : h(\n 'div',\n {\n style:\n row.status === 'error'\n ? STYLE.banner\n : { ...STYLE.banner, ...STYLE.bannerWarn },\n key: `${keyPrefix}#${row.name}#detail`,\n },\n detail,\n ),\n ]\n}\n\nfunction countStatuses(rows: readonly ServerRow[]): Partial<Record<ServerStatus, number>> {\n const totals: Partial<Record<ServerStatus, number>> = {}\n for (const row of rows) totals[row.status] = (totals[row.status] ?? 0) + 1\n return totals\n}\n\n/** The statuses a summary line names, in the order it names them. */\nconst SUMMARY_ORDER = ['active', 'connecting', 'idle', 'error', 'conflict'] as const\n\n/**\n * The `{count}` template key of every status — a full `ServerStatus` record,\n * so a status the order above ever names without a template is a compile\n * error, not a raw token in the summary line.\n */\nconst SUMMARY_KEYS: Record<ServerStatus, LocaleKey> = {\n active: 'summaryActive',\n connecting: 'summaryConnecting',\n idle: 'summaryIdle',\n disabled: 'summaryDisabled',\n error: 'summaryError',\n conflict: 'summaryConflict',\n}\n\n/**\n * One line of status counts (`2 active, 1 idle`), every count a `{count}`\n * placeholder of its status's template so no language reads a concatenation.\n * @param totals - the counted rows.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the summary, or the `summaryNone` answer when nothing was counted.\n */\nfunction summarize(\n totals: Partial<Record<ServerStatus, number>>,\n t: Translate = fallbackTranslate,\n): string {\n const parts: string[] = []\n for (const status of SUMMARY_ORDER) {\n const count = totals[status]\n if (count !== undefined && count > 0) parts.push(t(SUMMARY_KEYS[status], { count }))\n }\n return parts.length === 0 ? t('summaryNone') : parts.join(', ')\n}\n\n/** Last path segment; used for every project and document label. */\nexport function basename(path: string): string {\n const parts = path.split('/').filter((part) => part !== '')\n return parts[parts.length - 1] ?? path\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * The tools side of the plugin's page in DSH's native Settings.\n *\n * The page has two pages of its own, because one plugin is one row of the\n * settings navigation: `Servers` is the declaration view this module never\n * touches, and `Tools` is the per-project policy the disclosure half of the\n * mockup lays out. Both live in the same `settings.section` registration — this\n * module adds the tab, it does not register a second navigation item.\n *\n * Tools answers a different question than the live surfaces: not \"what does the\n * model see right now\", but \"what will this project offer, and what is pinned\".\n * Everything on it is measured rather than invented: the server and tool counts\n * come from the host snapshot's rows and each session's `tools`, the pinned list\n * and the mode are the project's own `policy`, the per-server counters are\n * counted from the session's own offer by the registry's `mcp__<server>__`\n * prefix, the conflicts are the host's report, and the request preview lists the\n * names the session really offers with the token estimate the contract derives\n * from the serialized sizes. Nothing here reads `./demo.ts`, and no row invents\n * a value the host does not publish.\n *\n * @module dsh-project-mcp/client/settings-tools\n */\n\nimport { createElement as h } from 'react'\nimport type { ReactNode } from 'react'\nimport type {\n ConflictChoice,\n ProjectSnapshot,\n ServerConflict,\n SessionTools,\n ToolMode,\n ToolPolicy,\n} from '../types.ts'\nimport { policyOf } from './policy.ts'\nimport { STYLE } from './settings.ts'\nimport type { LocaleKey, Translate } from './settings.ts'\nimport {\n basename,\n callsLabel,\n serverOfToolName,\n serverPinPress,\n serverPinState,\n toolCounts,\n toolCalls,\n} from './view.ts'\nimport type { ToolCalls } from './view.ts'\nimport { byCalls } from './usage-view.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\n\n/**\n * A serialized size in tokens, by the contract's own reading: `chars / 4`.\n *\n * The estimate is printed only where a size is known: a session the host\n * published without `deferredChars` gets the hidden count and no estimate,\n * rather than an invented one.\n * @param chars - serialized size in characters.\n * @returns the estimate, rounded to a whole token.\n */\nexport function tokenEstimate(chars: number): number {\n return Math.round(chars / 4)\n}\n\n/**\n * The three values the mode switch offers, in the order the contract lists them.\n *\n * Straight from the frozen `ToolMode`, so the form cannot drift into the\n * mockup's `all-direct` spelling of the same state.\n */\nexport const TOOL_MODES: readonly ToolMode[] = ['disclosure', 'direct', 'off']\n\n/** Which of the plugin page's own pages is open. */\nexport type SettingsPageKey = 'servers' | 'tools'\n\n/** Page shown when nothing else was chosen, so the page never opens blank. */\nexport const DEFAULT_SETTINGS_PAGE: SettingsPageKey = 'servers'\n\n/** One page of the plugin's own settings page, in the switch's order. */\nexport interface SettingsPageTab {\n key: SettingsPageKey\n /** Dictionary key of the label; the switch resolves it through `t`. */\n labelKey: LocaleKey\n}\n\n/**\n * The two pages of our own settings page.\n *\n * `Servers` is what the plugin has shipped since the write path landed; `Tools`\n * is the disclosure policy, added next to it rather than as a second row of the\n * settings navigation.\n */\nexport const SETTINGS_PAGES: readonly SettingsPageTab[] = [\n { key: 'servers', labelKey: 'tabServers' },\n { key: 'tools', labelKey: 'tabTools' },\n]\n\n/** The `Servers` / `Tools` switch inside our own settings page. */\nexport function SettingsPageSwitch(props: {\n page: SettingsPageKey\n onChange: (page: SettingsPageKey) => void\n t: Translate\n}): ReactNode {\n const item = (tab: SettingsPageTab): ReactNode =>\n h(\n 'button',\n {\n key: tab.key,\n style:\n tab.key === props.page\n ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }\n : STYLE.segmentItem,\n 'aria-pressed': tab.key === props.page,\n onClick: () => props.onChange(tab.key),\n },\n props.t(tab.labelKey),\n )\n return h('div', { style: STYLE.segment }, SETTINGS_PAGES.map(item))\n}\n\n// ── the project table ─────────────────────────────────────────────────────────\n\n/** How many live sessions one project has; the table's \"seen\" column. */\nexport function liveSessions(project: ProjectSnapshot): number {\n return project.sessionIds.length\n}\n\n/**\n * The live snapshot of one project's first session, when the host published one.\n * @param project - project row of the settings page.\n * @returns that session's snapshot, or undefined when nothing is live.\n */\nexport function firstSession(project: ProjectSnapshot): ProjectSnapshot['sessions'][number] | undefined {\n return (project.sessions ?? [])[0]\n}\n\n/** The tools one project shows in the table, with their provenance. */\nexport interface ProjectToolCounts {\n /** Servers the project declares. */\n servers: number\n /** Tools mounted for the project, when the session published them. */\n tools: number | undefined\n /** Tools the session activated on demand. */\n disclosed: number\n}\n\n/**\n * Count one project's servers and tools.\n *\n * Both numbers are real: servers are `project.rows`, tools are the mounted total\n * of the first live session's `SessionTools`. A project whose sessions published\n * no offer has no tool count at all — the row shows a dash — because the count of\n * its *servers* is not the count of its tools.\n * @param project - project row of the settings page.\n * @returns the counts; `tools` is undefined when no session published an offer.\n */\nexport function projectToolCounts(project: ProjectSnapshot): ProjectToolCounts {\n const live = firstSession(project)?.tools\n return {\n servers: project.rows.length,\n tools: live?.mounted,\n disclosed: live === undefined ? 0 : toolCounts(live).disclosed,\n }\n}\n\n/** The policy row of one project: the host's own counts and the policy in force. */\nexport interface ProjectPolicyRow {\n /** Project root. */\n projectRoot: string\n /** Short label the table shows. */\n label: string\n /** Declared servers and mounted tools. */\n counts: ProjectToolCounts\n /** The policy in force, as the host published it. */\n policy: ToolPolicy\n}\n\n/**\n * One table row per project with a live session, in snapshot order.\n * @param projects - projects the host snapshot carries.\n * @returns the rows the table renders.\n */\nexport function projectPolicyRows(projects: readonly ProjectSnapshot[]): ProjectPolicyRow[] {\n return projects.map((project) => ({\n projectRoot: project.projectRoot,\n label: basename(project.projectRoot),\n counts: projectToolCounts(project),\n policy: policyOf(project),\n }))\n}\n\n/** What one mode value is called in the UI. */\nconst MODE_KEYS: Record<ToolMode, LocaleKey> = {\n disclosure: 'modeDisclosure',\n direct: 'modeDirect',\n off: 'modeOff',\n}\n\n/** The label of one mode value. */\nexport function modeLabel(mode: ToolMode, t: Translate): string {\n return t(MODE_KEYS[mode])\n}\n\n/**\n * The dense per-project overview: one row per project with a live session.\n *\n * The mode cell is the one interactive column: a mode is a value the host\n * stores, so it is written as soon as it is clicked (the page says so under the\n * form) and the button goes quiet while the answer is in flight.\n *\n * Seven columns did not fit the settings panel's content column on every window;\n * the five the host answers for do, and the table is still a scroll region\n * rather than a block that runs under the panel edge. Its headers stay on one\n * line, and the project name — the only free-form text in it — wraps inside its\n * cell instead of widening the table.\n */\nexport function ToolsProjectTable(props: {\n rows: readonly ProjectPolicyRow[]\n /** Roots the host is currently writing a mode or a pin for. */\n pending: ReadonlySet<string>\n onMode: (projectRoot: string, mode: ToolMode) => void\n t: Translate\n}): ReactNode {\n const { t } = props\n const th = { ...STYLE.th, whiteSpace: 'nowrap' as const }\n return h(\n 'div',\n { style: STYLE.tableScroll },\n h(\n 'table',\n { style: STYLE.table },\n h(\n 'thead',\n null,\n h(\n 'tr',\n null,\n h('th', { style: th }, t('project')),\n h('th', { style: th }, t('servers')),\n h('th', { style: th }, t('toolsCount')),\n h('th', { style: th }, t('pinned')),\n h('th', { style: th }, t('mode')),\n ),\n ),\n h(\n 'tbody',\n null,\n props.rows.map((row) =>\n h(\n 'tr',\n { key: row.projectRoot },\n h('td', { style: { ...STYLE.td, overflowWrap: 'anywhere' as const } }, row.label),\n h('td', { style: STYLE.td }, String(row.counts.servers)),\n h(\n 'td',\n { style: STYLE.td },\n row.counts.tools === undefined ? '—' : String(row.counts.tools),\n ),\n h('td', { style: STYLE.td }, String(row.policy.pins.length)),\n h(\n 'td',\n { style: STYLE.td },\n ModeSwitchRow({\n mode: row.policy.mode,\n busy: props.pending.has(row.projectRoot),\n onMode: (mode) => props.onMode(row.projectRoot, mode),\n t,\n }),\n ),\n ),\n ),\n ),\n ),\n )\n}\n\n// ── the tools tab ─────────────────────────────────────────────────────────────\n\n/** Props of the `Tools` page: the selected project and its host policy. */\nexport interface ToolsPageProps {\n /** The project the page shows; selected by the shared project picker. */\n project: ProjectSnapshot\n /** Every project with a live session, for the overview table above the form. */\n rows: readonly ProjectPolicyRow[]\n /** Switch one project's mode; the host stores it, so it is written at once. */\n onMode: (projectRoot: string, mode: ToolMode) => void\n /** Roots with a policy write in flight. */\n pending: ReadonlySet<string>\n /** Last refusal from a policy write, when the host did not take it. */\n modeError: string | undefined\n /** Wire companions of `modeError`, when the host coded the refusal (F-48). */\n modeErrorCode?: string | undefined\n /** Flat params of `modeErrorCode`. */\n modeErrorParams?: Record<string, string> | undefined\n /** Re-read the host snapshot now; the conflict report's own action. */\n onSync: () => void\n /** Pin or unpin one tool of one project; the host stores it at once. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight, per `projectRoot` + `tool`. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal from a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n /**\n * Choose which declaration of one contested name the project shows. The host\n * stores the answer and answers with the snapshot that already reflects it,\n * so this page draws the new state instead of guessing it.\n */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a choice write in flight, per `projectRoot` + name. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal from a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n t: Translate\n /** Host-namespace seat for the conflicts' coded messages (F-48). */\n hostT?: Translate | undefined\n}\n\n/**\n * The `Tools` page: the project table, then the form of the selected project.\n *\n * The page is a vertical list of setting rows rather than the mockup's split:\n * a policy form is a list of settings, which is what DSH's own settings pages\n * are, and the split's panes are too narrow for the sentences they had to hold.\n */\nexport function ToolsPage(props: ToolsPageProps): ReactNode {\n const { t } = props\n const policy = policyOf(props.project)\n return h(\n 'div',\n null,\n h(ToolsProjectTable, {\n rows: props.rows,\n pending: props.pending,\n onMode: props.onMode,\n t,\n }),\n props.modeError === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.noteError },\n // A coded refusal translates through the host seat; prose alone\n // renders exactly as it did before codes existed.\n `${t('modeRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.modeErrorCode, props.modeErrorParams, props.modeError)}`,\n ),\n h(ProjectForm, {\n project: props.project,\n policy,\n onMode: props.onMode,\n pending: props.pending.has(props.project.projectRoot),\n onSync: props.onSync,\n onPin: props.onPin,\n pinPending: props.pinPending,\n pinError: props.pinError,\n pinErrorCode: props.pinErrorCode,\n pinErrorParams: props.pinErrorParams,\n onChoice: props.onChoice,\n choicePending: props.choicePending,\n choiceError: props.choiceError,\n choiceErrorCode: props.choiceErrorCode,\n choiceErrorParams: props.choiceErrorParams,\n t,\n hostT: props.hostT,\n }),\n )\n}\n\n/**\n * The switch that stands for a whole server (F-44).\n *\n * It wears the control every per-name row below wears, and its reading is\n * {@link serverPinState}'s proportion: on while the project pins **every** name\n * this page lists for that server, off otherwise. A half-pinned server\n * therefore reads off, and that is the honest reading of the only store there\n * is — the pin list holds names, no rule about servers, and this page has no\n * third visual for \"some\". What the press does is said by the tooltip and is\n * never a loss: the set is completed when it is not complete and released only\n * when it is ({@link serverPinPress}).\n *\n * The names are **every** name the host published for that server: the offered\n * ones this page lists below, and the ones it kept hidden. A pin is what pulls a\n * hidden name into the request (that is what the tab's hidden tier does with its\n * own `Pin`), so a switch that stood for the server while skipping them would\n * leave the server half-pinned — and the row's own description already counts\n * them (`1 of 3 tools offered directly`).\n * @param props - the project, the server, the names that stand for it and the writer.\n * @returns the switch, inert while there is nothing to write to.\n */\nfunction serverPinSwitch(props: {\n projectRoot: string\n server: string\n /** Every name the host published for this server, hidden ones included. */\n names: readonly string[]\n /** The project's own pin list. */\n pins: readonly string[]\n /** `true` while a pin write of this server is in flight. */\n pending: boolean\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n t: Translate\n}): ReactNode {\n const { t } = props\n const all = serverPinState(props.names, props.pins) === 'all'\n const press = serverPinPress(props.names, props.pins)\n // `names` is never empty for a row that is drawn: the rows come from\n // `serverToolCounts`, and a server is in that list because it contributed at\n // least one name. A switch over nothing would not exist to be disabled.\n const disabled = props.onPin === undefined || props.pending\n return h(\n 'button',\n {\n type: 'button',\n style: all ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n 'aria-checked': all,\n 'aria-label': `${props.server} — ${all ? t('serverUnpin') : t('serverPin')}`,\n title: all ? t('serverUnpinHint') : t('serverPinHint'),\n disabled,\n onClick: () => {\n for (const name of press.names) props.onPin?.(props.projectRoot, name, press.pinned)\n },\n },\n h('span', { style: all ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob }),\n )\n}\n\n/**\n * The form of one project's policy: the setting rows — the mode, then one row\n * per server of the session — under the page's own note, then the pinned group\n * with the conflict report, the mounted tool list and the request preview as\n * full-width blocks.\n *\n * The server rows are the mockup's \"not to be touched\" field, made real: each\n * one names a server this session mounts and says, from the session's own offer,\n * how many of its tools the model is offered directly. A row that used to\n * promise a locked example service now counts the project's own servers.\n */\nexport function ProjectForm(props: {\n project: ProjectSnapshot\n /** The host's policy for that project: the mode and the pin list. */\n policy: ToolPolicy\n onMode: (projectRoot: string, mode: ToolMode) => void\n /** `true` while this project's mode is being written. */\n pending: boolean\n /** Re-read the host snapshot now; the conflict report's own action. */\n onSync: () => void\n /** Pin or unpin one tool of this project; the host stores it at once. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal from a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n /** Choose which declaration of one contested name this project shows. */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a choice write in flight. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal from a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n t: Translate\n /** Host-namespace seat for the conflicts' coded messages (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t, policy } = props\n const tools = firstSession(props.project)?.tools\n const servers = tools === undefined ? [] : serverToolCounts(tools)\n // The names this page lists, read once: the per-name list below works from\n // this set.\n const offered = offeredNames(tools)\n /**\n * Every name the host published for one server, offered and hidden alike.\n *\n * The per-name list below shows the offered half only, but a server's switch\n * speaks for the server: the hidden names are exactly the ones a pin pulls\n * into the request, and the row's own description counts them, so leaving them\n * out would make the switch quieter than the sentence beside it.\n * @param server - the `serverName` as the registry spells it in the prefix.\n * @returns the names, offered first, each once.\n */\n const mountedOf = (server: string): string[] => [\n ...new Set([\n ...offered.filter((name) => serverOfToolName(name) === server),\n ...(tools?.deferred ?? []).filter((name) => serverOfToolName(name) === server),\n ]),\n ]\n return h(\n 'div',\n null,\n // The mode is the host's own value: the write goes out on the click, so\n // the row carries the hint about that instead of a Save of its own. The\n // longer explanation rides the row's tooltip rather than a paragraph above\n // it — the mockup spends its lines on controls, not on prose.\n SettingRow({\n label: t('mode'),\n description: t('modeHint'),\n title: t('policyNote'),\n control: ModeSwitchRow({\n mode: policy.mode,\n busy: props.pending,\n onMode: (mode) => props.onMode(props.project.projectRoot, mode),\n t,\n }),\n last: servers.length === 0,\n }),\n // One row per server, and since F-44 the row is also where a whole server\n // gets pinned: the name keeps its place at the right edge and the switch\n // stands beside it, so the reading and the action share one line.\n ...servers.map((count, index) => {\n const names = mountedOf(count.server)\n return SettingRow({\n label: t('server'),\n description: serverOfferLabel(count, t),\n control: h(\n 'span',\n { style: STYLE.settingRowControl },\n h('span', { style: STYLE.muted }, count.server),\n serverPinSwitch({\n projectRoot: props.project.projectRoot,\n server: count.server,\n names,\n pins: policy.pins,\n pending: names.some((name) => props.pinPending?.has(name) === true),\n onPin: props.onPin,\n t,\n }),\n ),\n last: index === servers.length - 1,\n })\n }),\n h(\n 'div',\n { style: STYLE.settingGroup },\n h('div', { style: STYLE.settingGroupHead }, t('pinned')),\n // The pin list is the host's: names the user pinned by hand, in the order\n // they pinned them. No badge, because nothing here is invented — and the\n // list gets the whole width, so a long name cannot be clipped.\n h(\n 'div',\n { style: STYLE.tagList },\n policy.pins.length === 0\n ? h('span', { style: STYLE.hint }, t('pinListEmpty'))\n : policy.pins.map((name) => h('span', { key: name, style: STYLE.tag }, name)),\n ),\n // The conflict check is real: the report is the host's own\n // `ProjectSnapshot.conflicts`, drawn under the row, and the button asks\n // the host for a fresh snapshot rather than standing in for one. Both the\n // hint and the button carry the label \"Check conflicts\": the head is the\n // block's own title, and the button repeats it as the action.\n SettingRow({\n label: t('checkConflicts'),\n description: t('pinList'),\n title: t('checkConflictsHint'),\n control: h(\n 'button',\n { style: STYLE.button, title: t('checkConflictsHint'), onClick: props.onSync },\n t('checkConflicts'),\n ),\n last: true,\n }),\n ConflictReport({\n projectRoot: props.project.projectRoot,\n conflicts: props.project.conflicts ?? [],\n onChoice: props.onChoice,\n choicePending: props.choicePending,\n choiceError: props.choiceError,\n choiceErrorCode: props.choiceErrorCode,\n choiceErrorParams: props.choiceErrorParams,\n t,\n hostT: props.hostT,\n }),\n ),\n h(ToolList, {\n project: props.project,\n policy,\n onPin: props.onPin,\n pinPending: props.pinPending,\n pinError: props.pinError,\n pinErrorCode: props.pinErrorCode,\n pinErrorParams: props.pinErrorParams,\n t,\n hostT: props.hostT,\n }),\n h(RequestPreview, { project: props.project, policy, t }),\n )\n}\n\n/**\n * The host's conflict report for one project, always drawn.\n *\n * The report needs no click to appear: the host counts the conflicts when it\n * builds the snapshot, so hiding them behind a button would hide an answer the\n * page already holds. The empty state is a real answer too — \"no conflicts\" is\n * the good case, and the row above it says so instead of showing nothing.\n * @param props - the conflicts, in the host's order.\n * @returns one row per conflict, or the empty state.\n */\nexport function ConflictReport(props: {\n /** Project the names belong to; the choice is stored per project. */\n projectRoot: string\n conflicts: readonly ServerConflict[]\n /** Choose a declaration; absent leaves the cards read-only. */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a write in flight. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal from a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n t: Translate\n /**\n * Host-namespace seat for the conflicts' coded messages (F-48); without one\n * each card renders its payload's English, byte-identical to before codes.\n */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t } = props\n if (props.conflicts.length === 0) {\n return h('div', { style: { ...STYLE.hint, padding: '8px 0' } }, t('conflictsNone'))\n }\n return h(\n 'div',\n null,\n props.conflicts.map((conflict) =>\n // One conflict is one card, in the alarm tone: the mockups draw a conflict\n // as a note that reads as a warning, not as another table row.\n h(\n 'div',\n { key: conflict.server, style: STYLE.noteError },\n h('strong', null, conflict.server),\n ' ',\n h('span', { style: conflictTone(conflict.kind) }, conflictKindLabel(conflict.kind, t)),\n h(\n 'div',\n { style: STYLE.muted },\n resolveHost(props.hostT ?? hostTranslate(undefined), conflict.code, conflict.params, conflict.message),\n ),\n conflict.sources.length === 0\n ? null\n : h(\n 'div',\n { style: STYLE.hint },\n t('conflictSources', { sources: conflict.sources.join(' · ') }),\n ),\n ConflictChoiceRow({\n projectRoot: props.projectRoot,\n conflict,\n onChoice: props.onChoice,\n pending: props.choicePending?.has(choiceKey(props.projectRoot, conflict.server)) ?? false,\n t,\n }),\n ),\n ),\n props.choiceError === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.noteError },\n `${t('choiceRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.choiceErrorCode, props.choiceErrorParams, props.choiceError)}`,\n ),\n )\n}\n\n/**\n * The choice control of one conflict card: which of the declarations this\n * project shows.\n *\n * Drawn wherever a profile-level reservation meets a surface that can write the\n * answer. A duplicate declaration has no toggle on purpose: both copies live in\n * this project's own documents, and no rename of the winner brings the loser\n * back.\n *\n * The three answers are the host's own `ConflictChoice`, in its order. `profile`\n * and `native` need nothing but the name the conflict already carries; `local`\n * is the one that cannot be drawn without a worked-out alias, so a host that\n * published none loses that button alone — an alias-less project can still keep\n * the profile instance or mount its own declaration under the declared name.\n * @param props - the conflict, its project and the write surface.\n * @returns the row, or `null` when the conflict carries no choice.\n */\nfunction ConflictChoiceRow(props: {\n projectRoot: string\n conflict: ServerConflict\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n pending: boolean\n t: Translate\n}): ReactNode {\n const { conflict, t } = props\n const write = props.onChoice\n if (conflict.kind !== 'profile' || write === undefined) return null\n const choice = conflict.choice ?? 'profile'\n const button = (next: ConflictChoice, title: string, label: string): ReactNode =>\n h(\n 'button',\n {\n type: 'button',\n style: choice === next ? STYLE.choiceOn : STYLE.choiceOff,\n disabled: props.pending,\n 'aria-pressed': choice === next,\n title,\n onClick: () => write(props.projectRoot, conflict.server, next),\n },\n label,\n )\n const alias = conflict.alias\n return h(\n 'div',\n { style: STYLE.choiceRow },\n h('span', { style: STYLE.hint }, t('choiceLabel')),\n button('profile', t('choiceProfileHint'), t('conflictProfile')),\n // Only a `local` answer names the alias it would mount under, so the button\n // exists exactly where the host published one.\n alias === undefined\n ? null\n : button('local', t('choiceLocalHint', { alias }), t('choiceLocal', { alias })),\n button('native', t('choiceNativeHint'), t('choiceNative')),\n )\n}\n\n/** The key one contested name's write is tracked under: project + name. */\nexport function choiceKey(projectRoot: string, server: string): string {\n return `${projectRoot}\\u0000${server}`\n}\n\n/**\n * The chip rule an alarm about this kind of conflict wears.\n *\n * A profile-level reservation is the warning tone — the name is taken, nothing\n * is broken. A duplicate declaration inside one project is the error tone: only\n * one of the two can win, so a declaration the file states is being dropped.\n * @param kind - the host's own conflict kind.\n * @returns the chip style for that kind.\n */\nfunction conflictTone(kind: ServerConflict['kind']): Record<string, unknown> {\n return kind === 'profile' ? STYLE.tagWarn : STYLE.tagError\n}\n\n/** What one conflict kind is called in the UI. */\nconst CONFLICT_KEYS: Record<ServerConflict['kind'], LocaleKey> = {\n profile: 'conflictProfile',\n duplicate: 'conflictDuplicate',\n}\n\n/** The label of one conflict kind. */\nexport function conflictKindLabel(kind: ServerConflict['kind'], t: Translate): string {\n return t(CONFLICT_KEYS[kind])\n}\n\n/**\n * One setting row of the `Tools` page: the label and its description in the\n * text column, the control in the column on the right.\n *\n * The text column is the wide one and the one that wraps — `flex: 1` takes the\n * leftover width and `minWidth: 0` lets it shrink below its content instead of\n * pushing the control out of the panel. The control column is `flex: none`, so\n * it measures to its own content and never wraps. That is exactly the shape the\n * old three-pane grid got wrong: it put sentences in panes narrower than one of\n * their words, so they rendered as one-word-wide slivers.\n * @param props - label, optional description and the row's own control.\n * @returns the row element.\n */\nexport function SettingRow(props: {\n /** Bold text of the text column. */\n label: string\n /** Muted one-line description under the label, when the row has one. */\n description?: string\n /**\n * The longer explanation of the row, as a tooltip rather than a paragraph.\n *\n * The mockups keep a settings line to a label and a control; anything that\n * needs a sentence hangs it off the label it explains.\n */\n title?: string\n /** The control, sized to its content in the column on the right. */\n control: ReactNode\n /** `true` on the last row of a group, whose trailing separator is dropped. */\n last?: boolean\n}): ReactNode {\n return h(\n 'div',\n { style: props.last === true ? { ...STYLE.settingRow, ...STYLE.lastRow } : STYLE.settingRow },\n h(\n 'div',\n {\n style: STYLE.settingRowText,\n ...(props.title === undefined ? null : { title: props.title }),\n },\n h('div', { style: STYLE.settingRowLabel }, props.label),\n props.description === undefined\n ? null\n : h('div', { style: STYLE.settingRowDesc }, props.description),\n ),\n h('div', { style: STYLE.settingRowControl }, props.control),\n )\n}\n\n/**\n * The mode switch: `disclosure / direct / off`, the host's own three values.\n *\n * Unlike the mockup's segmented controls below it, this one writes through to\n * the host the moment it is clicked (the caller owns the request), so each\n * button stays disabled until the answer lands and the row re-reads the mode the\n * host actually stored.\n */\nexport function ModeSwitchRow(props: {\n mode: ToolMode\n busy: boolean\n onMode: (mode: ToolMode) => void\n t: Translate\n}): ReactNode {\n return h(\n 'span',\n { style: STYLE.segment },\n TOOL_MODES.map((mode) =>\n h(\n 'button',\n {\n key: mode,\n style:\n mode === props.mode\n ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }\n : STYLE.segmentItem,\n 'aria-pressed': mode === props.mode,\n disabled: props.busy,\n onClick: () => props.onMode(mode),\n },\n modeLabel(mode, props.t),\n ),\n ),\n )\n}\n\n// ── the session's own offer, counted per server ───────────────────────────────\n\n/** One server's share of a session's offer. */\nexport interface ServerToolCount {\n /** Server name, without the registry's `mcp__` prefix. */\n server: string\n /** Its tools the session offers the model right now. */\n offered: number\n /** Its tools mounted for the project but held back from this offer. */\n hidden: number\n /** `offered + hidden`. */\n total: number\n}\n\n/**\n * The names one session offers, in offer order: the durable baseline, then the\n * two on-demand tiers.\n *\n * Each name once: the tiers are not disjoint — a pinned or hot name can be\n * activated too — and both readers of this list count, so a repeat would be\n * counted twice (the per-server rows) or printed twice (the picker below).\n * @param tools - one session's offer, when the host published one.\n * @returns the public names, each once; empty without an offer.\n */\nexport function offeredNames(tools: SessionTools | undefined): string[] {\n if (tools === undefined) return []\n return [\n ...new Set([\n ...tools.baseline,\n ...tools.activated.map((tool) => tool.name),\n ...tools.context.map((tool) => tool.name),\n ]),\n ]\n}\n\n/**\n * The names this project's request would carry, in offer order: the host's pin\n * list first, then the session's own offer, each name once.\n *\n * Pins lead because that is where the request builder starts: a pinned name is\n * offered from the first step whatever the counters say. A pin the project no\n * longer mounts is kept — the declaration may come back — which is why the list\n * follows `policy.pins` rather than filtering it first.\n * @param tools - one session's tool offer.\n * @param policy - the project's policy, whose `pins` lead the list.\n * @returns the visible names, in request order.\n */\nexport function visibleToolNames(tools: SessionTools, policy: ToolPolicy): string[] {\n const seen = new Set<string>()\n const names: string[] = []\n for (const name of [...policy.pins, ...offeredNames(tools)]) {\n if (seen.has(name)) continue\n seen.add(name)\n names.push(name)\n }\n return names\n}\n\n/**\n * Count the session's offer per server, by the registry's `mcp__<server>__`\n * prefix (contract C6).\n *\n * `offered` and `hidden` are the session's own lists, so a name without the\n * prefix — a built-in, or one another owner contributes — belongs to no server\n * and is left out rather than filed under a made-up one. The sum of `total` is\n * therefore a lower bound on `SessionTools.mounted`, which stays the control.\n * @param tools - one session's tool offer.\n * @returns one entry per server, ordered by name.\n */\nexport function serverToolCounts(tools: SessionTools): ServerToolCount[] {\n const counts = new Map<string, ServerToolCount>()\n const bump = (name: string, tier: 'offered' | 'hidden'): void => {\n const server = serverOfToolName(name)\n if (server === undefined) return\n const entry = counts.get(server) ?? { server, offered: 0, hidden: 0, total: 0 }\n if (tier === 'offered') entry.offered += 1\n else entry.hidden += 1\n entry.total = entry.offered + entry.hidden\n counts.set(server, entry)\n }\n for (const name of offeredNames(tools)) bump(name, 'offered')\n for (const name of tools.deferred) bump(name, 'hidden')\n return [...counts.values()].sort((left, right) => left.server.localeCompare(right.server))\n}\n\n/**\n * What one server's counters mean in words: everything it mounts is offered\n * directly, or only part of it is.\n * @param count - one server's counters.\n * @param t - translate seat.\n * @returns the sentence the filter row carries.\n */\nexport function serverOfferLabel(count: ServerToolCount, t: Translate): string {\n return count.hidden === 0\n ? t('serverAllOffered', { count: count.offered })\n : t('serverPartlyOffered', { offered: count.offered, total: count.total })\n}\n\n/** One name and its switch: the picker's row. */\nfunction pinRow(\n name: string,\n pinned: boolean,\n pending: boolean,\n calls: ToolCalls | undefined,\n props: {\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n project: ProjectSnapshot\n t: Translate\n },\n): ReactNode {\n const { t } = props\n const disabled = props.onPin === undefined || pending\n const figure = callsLabel(calls, t)\n return h(\n 'div',\n { key: name, style: STYLE.listItem },\n h('span', { style: STYLE.muted }, name),\n figure === undefined ? null : h('span', { style: STYLE.hint }, figure),\n h('span', { style: { flex: 1 } }),\n h(\n 'button',\n {\n type: 'button',\n style: pinned ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n 'aria-checked': pinned,\n 'aria-label': name,\n title: pinned ? t('toolsUnpinHint') : t('toolsPinHint'),\n disabled,\n onClick: () => props.onPin?.(props.project.projectRoot, name, !pinned),\n },\n h('span', { style: pinned ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob }),\n ),\n )\n}\n\n/**\n * The project's mounted tools as a full-width block, with the pinned ones\n * marked.\n *\n * It lists the names the host actually offers — the pinned list first, then\n * whatever this session's own `tools` published — so a name on screen is a name\n * the project really mounts. The total in the head is the host's count of\n * mounted tools; a project whose session has published no offer yet shows a\n * dash and no rows rather than a number nobody measured.\n *\n * The block used to be the split's left pane, which is why it carried a\n * fixed-width rail and a right border; it is a card between two other blocks\n * now, so its rows are separated by the card's own rules instead.\n *\n * Since F-32 the rows are ordered by the host's own call counters and carry\n * that count, so the name worth pinning is the name at the top rather than the\n * one the session happened to list first.\n */\nexport function ToolList(props: {\n project: ProjectSnapshot\n policy: ToolPolicy\n /** Pin or unpin one tool of this project; absent leaves the switches inert. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal from a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n t: Translate\n /** Host-namespace seat for the refusal's coded message (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t } = props\n const counts = projectToolCounts(props.project)\n const live = firstSession(props.project)\n const tools = live?.tools\n const offered = offeredNames(tools)\n const pinnedNames = new Set(props.policy.pins)\n const pending = props.pinPending ?? new Set<string>()\n const rest = counts.tools === undefined ? 0 : Math.max(0, counts.tools - offered.length)\n return h(\n 'div',\n { style: STYLE.card },\n h('div', { style: STYLE.cardHead }, `${t('tabTools')} · ${counts.tools ?? '—'}`),\n offered.length === 0\n ? h(\n 'div',\n { style: STYLE.listItem },\n h('span', { style: STYLE.hint }, t('requestPreviewNoOffer')),\n )\n : [...offered]\n .sort(byCalls(props.project.usage, live?.id))\n .map((name) =>\n pinRow(\n name,\n pinnedNames.has(name),\n pending.has(name),\n toolCalls(name, props.project.usage, live?.id),\n props,\n ),\n ),\n rest > 0\n ? h(\n 'div',\n { style: { ...STYLE.listItem, ...STYLE.muted } },\n h('span', { style: STYLE.hint }, t('moreTools', { count: rest })),\n )\n : null,\n // The prefix is a fact of the registry, not a setting of this page: it is\n // stated once, under the names it explains, and is not a control.\n h(\n 'div',\n { style: { ...STYLE.listItem, ...STYLE.lastRow } },\n h('span', { style: STYLE.hint }, t('prefixFact')),\n ),\n props.pinError === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.noteError },\n `${t('pinRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.pinErrorCode, props.pinErrorParams, props.pinError)}`,\n ),\n )\n}\n\n/**\n * The request the policy would build, as far as the host publishes it: the names\n * this session offers, in request order, with the pinned ones marked.\n *\n * The names are real — the session's own `tools` plus the policy's pin list —\n * and the sizes are the contract's own (`visibleChars` / `deferredChars`), so\n * the token estimate is `Math.round(chars / 4)` and is printed only where a size\n * is known: a snapshot without `deferredChars` shows the hidden count and no\n * estimate at all, rather than an invented one. The mockup's `tools[] = 6` with\n * its five made-up lines and its invented savings went with the other\n * placeholders.\n *\n * It used to be the split's third column, where the widest line of the preview\n * was wider than the pane and collided with the form beside it.\n */\nexport function RequestPreview(props: {\n project: ProjectSnapshot\n policy: ToolPolicy\n t: Translate\n}): ReactNode {\n const { t } = props\n const tools = firstSession(props.project)?.tools\n if (tools === undefined) {\n return h(\n 'div',\n { style: STYLE.card },\n h('div', { style: STYLE.cardHead }, t('requestPreview')),\n h(\n 'div',\n { style: { ...STYLE.listItem, ...STYLE.lastRow } },\n h('span', { style: STYLE.hint }, t('requestPreviewNoOffer')),\n ),\n )\n }\n const names = visibleToolNames(tools, props.policy)\n const pinned = new Set(props.policy.pins)\n const footer =\n tools.deferredChars === undefined\n ? t('requestPreviewHidden', { count: tools.deferred.length })\n : t('requestPreviewSaved', {\n count: tools.deferred.length,\n tokens: tokenEstimate(tools.deferredChars),\n })\n return h(\n 'div',\n { style: STYLE.card },\n h(\n 'div',\n { style: STYLE.cardHead },\n t('requestPreview'),\n h('span', { style: STYLE.tag }, t('requestPreviewTools', { count: names.length })),\n tools.visibleChars === undefined\n ? null\n : h(\n 'span',\n { style: STYLE.tag },\n t('requestPreviewTokens', { tokens: tokenEstimate(tools.visibleChars) }),\n ),\n ),\n h(\n 'pre',\n { style: STYLE.json },\n names.map((name) =>\n h('div', { key: name }, pinned.has(name) ? `${name} ${t('pinTag')}` : name),\n ),\n h('div', { style: STYLE.muted }, footer),\n ),\n )\n}\n","/**\n * The plugin's page inside DSH's native Settings.\n *\n * A sidebar tab belongs to one conversation, so it deliberately shows **only**\n * that session's project. This page is the other half of the picture: every\n * project with a live session, one selected at a time, with two remembered\n * views — `Table` (a dense overview) and `By files` (the plugin's own model:\n * documents read in priority order, a later document overriding an earlier\n * entry) — plus the split editor.\n *\n * The editor writes, and only within the frozen contract of\n * `docs/design/contracts/write-path.md`: the form edits the parsed {@link EntrySnapshot}\n * the row carries, the JSON pane shows that entry against the snapshot as a\n * line diff, and a save goes through a confirmation that names the document,\n * the `.bak` copy and the format normalization. A row whose\n * {@link ServerRow.writeScope} is `readonly` keeps the old blocked rendering,\n * with `writeBlockedReason` on every control. Secrets stay out of the editor's\n * reach: a masked `env`/`headers` key submitted untouched carries `masked: true`\n * and no value, so the document keeps the secret the form never saw.\n *\n * Registration contract (DSH `settings.section`, kind `list`, scope\n * `root`, owner copy intentionally empty):\n *\n * ```ts\n * ctx.slots.inject('settings.section', () => ctx.slots.register({\n * name: 'settings.section', id, order, label: () => t('tab'), locale: NS,\n * inject: () => ({}),\n * }, SettingsTab))\n * ```\n *\n * `slots.inject` is not decoration: the slot is declared by the Plugins\n * settings section at runtime, and `slots.register` **throws** on an undeclared\n * slot. Data comes from the host over `/project-mcp/snapshot` (see\n * `src/ui.ts`), through the same poll path the sidebar tab uses.\n *\n * The DSH client packages (`@deepseek-ai/dsh-client-ui-slots`, `-locale`,\n * `-ui-settings`) are provided by the web shell and are not dependencies of\n * this package, so the contract is mirrored structurally here: the composed\n * props type is `PropsRuntime<'settings.section'> & PropsLocale<NS> &\n * InjectFace<SettingsTabInjected>`, which for this slot means \"no owner props,\n * the namespace-bound `t` seat, and the inject factory's members\".\n *\n * @module dsh-project-mcp/client/settings\n */\n\nimport { createElement as h, useCallback, useEffect, useRef, useState } from 'react'\nimport type { CSSProperties, ReactHTML, ReactNode } from 'react'\nimport { PACKAGE_NAME, ROUTE_ACTIONS, ROUTE_PREFIX } from '../shared.ts'\nimport type { SaveErrorCode, SaveRequest } from '../shared.ts'\nimport type {\n ConflictChoice,\n EntryField,\n EntrySnapshot,\n McpSnapshot,\n ProjectSnapshot,\n ServerRow,\n ServerStatus,\n ToolMode,\n} from '../types.ts'\nimport {\n DEFAULT_REFRESH_MS,\n STATUS_COLOR,\n STATUS_HINT,\n STATUS_KEYS,\n basename,\n browserStorage,\n emptyState,\n idleNote,\n rowDetail,\n serverCount,\n storeString,\n storedString,\n useSnapshot,\n} from './view.ts'\nimport type { PanelStorage } from './view.ts'\nimport { DEFAULT_SETTINGS_PAGE, SettingsPageSwitch, ToolsPage, choiceKey } from './settings-tools.ts'\nimport type { SettingsPageKey } from './settings-tools.ts'\nimport {\n conflictBody,\n operatorBody,\n pinBody,\n policyBody,\n postConflict,\n requestMode,\n requestPin,\n} from './policy.ts'\nimport type { PolicyRefusal } from './policy.ts'\nimport { projectPolicyRows } from './settings-tools.ts'\nimport { uiTranslate } from './locales/ui.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\n\n/** Locale namespace the page's copy is registered under. */\nexport const NS = 'settings.projectMcp'\n\n/**\n * The settings page's own English copy, half of the namespace's dictionary.\n *\n * Keys only; the language switch stays with the shell, which re-registers\n * nothing here — a second language is one more dictionary, not a code change.\n * `./locales/ui.ts` adds the panel's half for the one\n * `ctx.locale.register(NS, { zh, en, ru })` call the plugin makes.\n */\nexport const EN = {\n project: 'Project',\n projectsOne: '1 project with a live session',\n projectsMany: '{count} projects with live sessions',\n viewTable: 'Table',\n viewFiles: 'By files',\n sync: 'Sync',\n syncHint: 'Re-read the host snapshot now',\n server: 'Server',\n transport: 'Transport',\n status: 'Status',\n source: 'Source',\n on: 'On',\n servers: 'Servers',\n paneEntry: 'Entry',\n name: 'Name',\n detail: 'Detail',\n loading: 'Reading the host snapshot…',\n loadingHint: 'The page polls /project-mcp/snapshot as soon as it opens.',\n hostUnavailable: 'The page did not get an answer from the plugin host.',\n hostUnavailableHint:\n 'The host half serves {route}; it picks up changes only after a dsh web restart — check the log.',\n noSessions: 'No session is attached to a project yet.',\n noSessionsHint:\n 'Servers come up when a session starts working inside a project folder — nothing is mounted for a project without one.',\n noSessionsPaths: 'read: {paths}',\n noSessionsNoPaths:\n 'this deployment reads no MCP document — list the documents to read in the plugin config (`localFiles`, `globalFiles`)',\n noServers: 'This project declares no MCP servers.',\n noServersHint: 'Nothing is declared, so nothing is mounted for its sessions.',\n noServersNoPath: 'This deployment reads no project document, so there is nowhere to declare one.',\n documentUnknown: 'declaration document unknown',\n global: 'global',\n priority: 'priority {tier}/{total}',\n overrideFrom: '↳ overrides {name} from {from}',\n overrideUnpinned: '↳ overrides {name} declared in a lower-priority document',\n nameReason: 'Read-only: the server name is the declaration key the host reports.',\n statusReason: 'Read-only: the status comes from the running host, not from a document.',\n sourceReason: 'Read-only: the declaring document path comes from the host.',\n detailReason: 'Read-only: the host redacts this text and never includes arguments.',\n openToEdit: 'Read-only here: open the server to edit its entry.',\n rowActionsMore: '…',\n rowActionsHint: 'Open this entry in the editor',\n retry: 'Retry',\n retryHint: 'Retry this project’s failed mounts now',\n showJson: 'Show JSON',\n hideJson: 'Hide JSON',\n jsonPreview: 'snapshot JSON',\n jsonPreviewHint: 'Read from the host snapshot; the document on disk is not touched.',\n back: 'Back to the list',\n backHint: 'Return to the overview without changing anything',\n // Editor: the fields of the parsed entry.\n entryUnavailable: 'The host did not parse this entry, so there is nothing to edit.',\n commandField: 'Command',\n argsField: 'Args',\n cwdField: 'CWD',\n urlField: 'URL',\n envField: 'Env',\n headersField: 'Headers',\n enabledField: 'Enabled',\n timeoutField: 'Timeout',\n keyField: 'Key',\n valueField: 'Value',\n argsHint: 'One argument per line; every line is written verbatim.',\n envHint: 'One value per key; a key the form drops is removed from the entry.',\n headersHint: 'One value per header; a key the form drops is removed from the entry.',\n timeoutHint: 'Milliseconds; empty means the declaration sets no timeout.',\n enabledValue: 'enabled: {value}',\n absent: 'absent',\n maskedValue: '•••• unchanged — type to replace',\n valuePlaceholder: 'value',\n keyPlaceholder: 'KEY',\n credentialsNote:\n 'Comes from an external source — the project .env or the credentials file — not from this document: it is shown and written back untouched.',\n credentialValue: 'from the project .env or the credentials file',\n addKey: 'Add key',\n addKeyHint: 'Append an empty key; an unnamed key is not written.',\n removeKey: '✕',\n removeKeyHint: 'Drop this key; a dropped key is removed from the entry.',\n // Writing.\n editableNote:\n 'Editing {document}: Save asks for confirmation, keeps {backup} and rewrites the entry wholesale.',\n writeBlocked: 'Read-only: {reason}',\n writeBlockedUnknown: 'the host did not report why this document may not be written.',\n save: 'Save…',\n saveHint: 'Open the confirmation for this write',\n saveNoChange: 'No change to save yet.',\n saveUnavailable: 'The snapshot carries no declaring document or revision to write back to.',\n saveTimeoutInvalid: 'The timeout is not a whole number of milliseconds.',\n saving: 'Writing…',\n discard: 'Discard',\n discardHint: 'Restore every field from the snapshot and write nothing',\n discardReason: 'No change to restore yet.',\n unsaved: 'unsaved',\n jsonDiff: 'diff',\n jsonClean: 'no change',\n jsonUnavailable: 'no parsed entry',\n jsonInvalid: 'The JSON does not parse into an entry: {reason}',\n jsonEditHint: 'Edit the entry as the document declares it',\n saveJsonInvalid: 'Fix the JSON pane first: it does not parse into an entry.',\n footerWrite: '→ {document} · .bak copy · confirmation',\n footerReadonly: '→ {document} · read-only',\n confirmTitle: 'Write {document}?',\n confirmBackup: 'The current document is copied to {backup} first.',\n confirmFormat:\n 'The entry replaces mcpServers[{server}] wholesale. The document is re-serialized with two-space indentation and a trailing newline, so the indentation and the key order of the rest of the document are normalized.',\n confirmConsent:\n 'This is a global document: every project reads it, so the write needs explicit consent.',\n consentLabel: 'I understand this rewrites a global document shared by every project.',\n confirmWrite: 'Write the document',\n confirmWriteHint: 'Write the document after the checks above',\n confirmBlocked: 'Tick the consent box first: a global write without it is refused.',\n cancel: 'Cancel',\n saveOk: 'Saved: the document was written and re-read.',\n saveErrorInvalid:\n 'The host refused the entry: it is not one this plugin would mount. Nothing was written.',\n saveErrorBlocked:\n 'The document may not be written on this tier, or the consent is missing. Nothing was written.',\n saveErrorConflict: 'The document changed since this snapshot was taken. Nothing was written.',\n saveErrorNotFound: 'The document or the server is no longer there. Nothing was written.',\n saveErrorFailed: 'The write itself failed; the document is left as it was. Nothing was written.',\n hostMessage: 'The host said: {message}',\n reRead: 'Re-read',\n reReadHint: 'Refetch the host snapshot and rebuild the form from it',\n // Our own two pages, and the disclosure policy page next to `Servers`.\n tabServers: 'Servers',\n tabTools: 'Tools',\n policyNote: 'the mode this project follows, and the tools pinned for it',\n checkConflicts: 'Check conflicts',\n checkConflictsHint:\n 'the conflicting server names the host reports for this project, read from its snapshot; the button re-reads it now',\n conflictsNone: 'no conflicting server name in this project',\n conflictProfile: 'profile name',\n conflictDuplicate: 'duplicate declaration',\n conflictSources: 'declared in {sources}',\n choiceLabel: 'show',\n choiceLocal: 'this project\\u2019s copy as {alias}',\n choiceProfileHint: 'keep the profile instance\\u2019s tools exactly as they are',\n choiceLocalHint:\n 'mount this project\\u2019s own declaration beside the profile one, under the local name {alias}',\n choiceNative: 'this project\\u2019s declaration under its own name',\n choiceNativeHint:\n 'mount this project\\u2019s own declaration under the name it declares: it is the nearer one in this project, so it shadows the profile instance\\u2019s tools here while every other project keeps seeing them',\n choiceRefused: 'The host refused the choice:',\n toolsCount: 'tools',\n pinned: 'Pinned',\n mode: 'Mode',\n modeDisclosure: 'disclosure',\n modeDirect: 'all direct',\n modeOff: 'off',\n modeHint: 'written straight away, on the request the host assembles next',\n modeRefused: 'The host refused the mode:',\n pinRefused: 'The host refused the pin:',\n pinList: 'pinned · written by hand, offered in every request',\n pinListEmpty: 'no pins yet — switch one on in the tool list below',\n serverAllOffered: 'all {count} of its tools are offered directly',\n serverPartlyOffered: '{offered} of {total} tools offered directly',\n // The server-level pin (F-44): one switch for the whole server row, above the\n // per-name rows it stands for.\n serverPin: 'pin this server’s tools',\n serverPinHint: 'Pin every tool this server mounts — the hidden ones too — so every request carries them',\n serverUnpin: 'unpin this server’s tools',\n serverUnpinHint: 'Stop pinning the tools of this server',\n prefixFact: 'mcp__<server>__<tool>; the registry applies the prefix, not this page',\n pinTag: 'pin',\n moreTools: '… {count} more',\n requestPreview: 'request preview',\n requestPreviewTools: 'tools[] = {count}',\n requestPreviewTokens: '≈ {tokens} tokens',\n requestPreviewHidden: 'hidden {count}',\n requestPreviewSaved: 'hidden {count} · ≈ {tokens} tokens saved',\n requestPreviewNoOffer: 'no offer published by this session yet',\n // The host's own usage counters, the same six keys and the same words the\n // panel's table holds: the settings page draws its server rows and its pin\n // picker itself, and one namespace means one spelling of `never called`\n // (merged with the panel's half in `./locales/ui.ts`, panel last).\n callsOne: '1 call',\n callsMany: '{count} calls',\n callsNone: 'never called',\n idleDay: 'idle {count}d',\n idleHour: 'idle {count}h',\n idleMinute: 'idle {count}m',\n} satisfies Record<string, string>\n\n/** A dictionary key of this namespace. */\nexport type LocaleKey = keyof typeof EN\n\n/** Translate one key, with optional `{name}` template params (the DSH seat). */\nexport type Translate = (key: string, params?: Record<string, unknown>) => string\n\n/**\n * Bind the translate seat the framework injects, falling back to this module's\n * own English dictionary when the page renders outside a DSH shell (tests, or a\n * browser half newer than the host).\n * @param t - the `t` seat of the composed props, when the framework passes one.\n * @returns a translate function that always answers.\n */\nexport function translateOf(t?: Translate): Translate {\n return t ?? fallbackTranslate\n}\n\nfunction fallbackTranslate(key: string, params?: Record<string, unknown>): string {\n const template = (EN as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in params ? String(params[name]) : match,\n )\n}\n\n/**\n * Slot key the page contributes to.\n *\n * `settings.section` is the settings navigation itself: one entry per settings\n * page, rendered as the content column when it is selected. The plugin's page is\n * a page in its own right — it has a project selector, its own view switch and a\n * write path — not a detail tab of the plugin inventory, so it belongs here\n * rather than inside the Plugins section.\n */\nexport const SETTINGS_SLOT = 'settings.section'\n\n/** Section id inside the navigation: the package name, so the row reads like the plugin. */\nexport const SETTINGS_TAB_ID = PACKAGE_NAME\n\n/**\n * Navigation position. The in-box sections run from `0` (General) to `25`\n * (Archived sessions), and installed plugins fill the rows after them; a page\n * about this plugin's own project data belongs at the end of that list.\n */\nexport const SETTINGS_TAB_ORDER = 900\n\n/** Options a `list` slot accepts for one registration. */\nexport interface SlotRegistration<Slot extends string = string> {\n name: Slot\n id: string\n order: number\n /** The shell re-reads this per render, so a language switch needs no re-register. */\n label?: () => string\n locale: string\n /** The registrant's business face; empty while the page reads the host over HTTP. */\n inject?: () => Record<string, never>\n}\n\n/** Options the settings page registers with; the slot it may claim is fixed. */\nexport type SettingsTabRegistration = SlotRegistration<typeof SETTINGS_SLOT>\n\n/** Injected business face of the settings tab. Nothing yet: the page fetches. */\nexport type SettingsTabInjected = Record<never, never>\n\n/**\n * Composed component props, mirroring\n * `PropsRuntime<'settings.section'> & PropsLocale<NS> & InjectFace<SettingsTabInjected>`:\n * the slot's owner passes no props, the framework contributes the\n * namespace-bound `t` seat, and the inject face's members arrive flattened.\n *\n * `t` is optional so the page still renders its own English copy outside a DSH\n * shell, which is also what the no-DOM view tests rely on.\n */\nexport interface SettingsTabProps {\n t?: Translate\n /**\n * The `projectMcp.host` seat, injected by {@link registerSettingsTab} from\n * the locale service the framework's own `t` cannot reach: `t` is bound to\n * the UI namespace, while host messages resolve through their own. Absent in\n * tests and outside a shell — the resolver then falls back to the payload's\n * English message.\n */\n hostT?: Translate | undefined\n}\n\n/**\n * The two client services the settings contribution needs. Both are optional in\n * a composition, which is exactly why registration goes through `ctx.inject`\n * rather than a module-level `inject` list: dropping either one must not take\n * the sidebar tab down with it.\n */\nexport interface SlotLocale {\n register(namespace: string, dictionaries: Record<string, Record<string, string>>): () => void\n bind(namespace: string): Translate\n /**\n * Add a language the shell does not ship, so dictionaries registered under\n * its id resolve. Optional: a shell whose locale service predates the method\n * must not break this plugin's boot — its keys then fall back to English.\n */\n addLanguage?(input: { id: string; label: string; fallback: string }): () => void\n}\n\n/**\n * The slot service, as a registrant uses it.\n *\n * `register`'s component seat is the slots package's own generic (a component of\n * the slot's composed props), which this package mirrors structurally: each\n * registrant supplies the props type it reads, so the settings page keeps its\n * `SettingsTabProps` and nothing else has to share it.\n */\nexport interface SlotSlots<Slot extends string = string> {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(\n options: SlotRegistration<Slot>,\n component: (props: Props) => ReactNode,\n ): unknown\n}\n\n/**\n * The two client services a contribution needs. Both are optional in a\n * composition, which is exactly why registration goes through `ctx.inject`\n * rather than a module-level `inject` list: dropping either one must not take\n * the sidebar tab down with it.\n */\nexport interface SettingsSlotServices {\n effect(execute: () => unknown, label?: string): unknown\n locale: SlotLocale\n slots: SlotSlots<typeof SETTINGS_SLOT>\n}\n\n/**\n * Contribute the page to the Plugins settings section.\n *\n * Two steps, because the slot is declared by the section at runtime:\n * `slots.inject` waits for the declaration (and re-registers after a collapse,\n * so a settings-section reload does not leave the tab missing), and the callback\n * calls `slots.register`, which would throw if the slot were not declared yet.\n * @param services - the injected `slots` and `locale` services.\n * @param component - the page to register; the real one by default. The\n * design-only render mode passes its fixture-fed page (`./design.ts`) so the\n * slot, the id and the order stay a single implementation.\n */\nexport function registerSettingsTab(\n services: SettingsSlotServices,\n component: (props: SettingsTabProps) => ReactNode = SettingsTab,\n): void {\n // The one translator both seats share: the bound namespace answers first,\n // the merged English table answers a key the active language lacks, and the\n // raw key shows only when even English has nothing for it. The slot keeps\n // `locale: NS` so the framework's own seat stays consistent.\n const t = uiTranslate(services.locale)\n // The second namespace's seat: the framework binds `t` to `NS` only, so the\n // host messages' translator is bound here and handed to the page as a prop.\n const hostT = hostTranslate(services.locale)\n services.slots.inject(SETTINGS_SLOT, () =>\n services.slots.register(\n {\n name: SETTINGS_SLOT,\n id: SETTINGS_TAB_ID,\n order: SETTINGS_TAB_ORDER,\n label: () => t('tab'),\n locale: NS,\n inject: () => ({}),\n },\n (props: SettingsTabProps) => component({ ...props, hostT }),\n ),\n )\n}\n\n/** Which overview the page shows; the choice is remembered. */\nexport type SettingsView = 'table' | 'files'\n\n/** View shown when nothing valid is persisted. */\nexport const DEFAULT_SETTINGS_VIEW: SettingsView = 'table'\n\n/**\n * `localStorage` key the page persists its view under.\n *\n * The settings page has no `pluginSettings` blob of its own — that helper\n * belongs to a sidebar tab descriptor — so the view is a browser-local\n * preference rather than a synced one.\n */\nexport const SETTINGS_VIEW_STORAGE_KEY = `${PACKAGE_NAME}:settings-view`\n\n/**\n * Read the persisted view.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored view, or {@link DEFAULT_SETTINGS_VIEW}.\n */\nexport function settingsViewOf(storage: PanelStorage | undefined = browserStorage()): SettingsView {\n return storedString(SETTINGS_VIEW_STORAGE_KEY, storage) === 'files'\n ? 'files'\n : DEFAULT_SETTINGS_VIEW\n}\n\n/**\n * Persist the view; hostile storage only costs the choice at the next reload.\n * @param view - view to store.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function persistSettingsView(\n view: SettingsView,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n storeString(SETTINGS_VIEW_STORAGE_KEY, view, storage)\n}\n\n/**\n * The project the page shows.\n *\n * The page is the one surface that lists every project with a live session, but\n * it renders exactly one project's rows at a time: an unknown or stale\n * selection falls back to the first project, never to a mix.\n * @param snapshot - host snapshot, or undefined before the first poll lands.\n * @param projectRoot - the selected project root, when known.\n * @returns the selected project, or undefined while there is none.\n */\nexport function selectedProject(\n snapshot: McpSnapshot | undefined,\n projectRoot: string | undefined,\n): ProjectSnapshot | undefined {\n if (snapshot === undefined || snapshot.projects.length === 0) return undefined\n if (projectRoot !== undefined) {\n const match = snapshot.projects.find((project) => project.projectRoot === projectRoot)\n if (match !== undefined) return match\n }\n return snapshot.projects[0]\n}\n\n/**\n * Display label of a declaring document: relative to the project root, or\n * home-shortened when it is a global document.\n * @param source - absolute document path.\n * @param projectRoot - the project the document belongs to.\n * @returns the label shown on a card or in the Source column.\n */\nexport function documentLabel(source: string, projectRoot: string): string {\n if (source.startsWith(`${projectRoot}/`)) return source.slice(projectRoot.length + 1)\n return source.replace(/^(\\/Users\\/[^/]+|\\/home\\/[^/]+)/, '~')\n}\n\n/**\n * Where one declaring document sits in the read order of its project.\n *\n * The order is the host's to publish (`ProjectSnapshot.files`): global documents\n * first, then the project's own, so a tier is the 1-based place in that list and\n * `total` is how many it holds — a deployment that reads one document prints\n * `priority 1/1` instead of a `3` it cannot have. A host older than the field\n * reports nothing, and then the shipped names answer: the global documents, then\n * `<project>/.kimi-code/mcp.json`, then `<project>/.dsh/mcp.json`. A document\n * outside either table has no priority, and the panel says nothing rather than\n * inventing one.\n */\nexport interface DocumentPriority {\n /** 1-based place in the read order of this project. */\n readonly tier: number\n /** How many documents that read order holds. */\n readonly total: number\n /** True for a global document, read before the project's own. */\n readonly global: boolean\n}\n\n/** Documents this version reads when the host reports none — the shipped names. */\nconst SHIPPED_LOCAL_FILES = ['.kimi-code/mcp.json', '.dsh/mcp.json'] as const\n\n/** The one project document this version ships with, for a host that says none. */\nconst DEFAULT_LOCAL_SPECS = ['.dsh/mcp.json'] as const\n\n/**\n * Priority of a declaring document, per {@link DocumentPriority}.\n * @param source - absolute document path, or `''` when the host reported none.\n * @param project - the project the document belongs to.\n * @returns the tier, or `undefined` when the document is not one this project reads.\n */\nexport function documentPriority(source: string, project: ProjectSnapshot): DocumentPriority | undefined {\n if (source === '') return undefined\n const files = project.files\n if (files !== undefined) {\n const index = files.findIndex((file) => file.path === source)\n const file = files[index]\n if (file === undefined) return undefined\n return { tier: index + 1, total: files.length, global: file.scope === 'global' }\n }\n const projectRoot = project.projectRoot\n if (!source.startsWith(`${projectRoot}/`)) {\n return /(\\.dsh|\\.kimi-code)\\/mcp\\.json$/.test(source)\n ? { tier: 1, total: SHIPPED_LOCAL_FILES.length + 1, global: true }\n : undefined\n }\n const index = SHIPPED_LOCAL_FILES.findIndex((relative) => source === `${projectRoot}/${relative}`)\n return index < 0 ? undefined : { tier: index + 2, total: SHIPPED_LOCAL_FILES.length + 1, global: false }\n}\n\n/** A spec that already names where it lives, so the panel prints it as written. */\nfunction isRootedSpec(spec: string): boolean {\n return spec.startsWith('/') || spec.startsWith('~') || spec.startsWith('$') || /^[A-Za-z]:[\\\\/]/.test(spec)\n}\n\n/**\n * Documents of the deployment itself, written the way a person would write them\n * in the config: `<project>/…` for a local spec, `~/…` for a relative global one.\n * A host older than `sources` reported nothing, and then this version's shipped\n * names answer — the same ones its own default reads.\n */\nfunction deploymentDocuments(snapshot: McpSnapshot): string[] {\n const sources = snapshot.sources\n if (sources === undefined) return DEFAULT_LOCAL_SPECS.map((relative) => `<project>/${relative}`)\n return [\n ...sources.global.map((spec) => (isRootedSpec(spec) ? spec : `~/${spec}`)),\n ...sources.local.map((spec) => (isRootedSpec(spec) ? spec : `<project>/${spec}`)),\n ]\n}\n\n/**\n * The `read: …` code line under an empty state, said from the config rather than\n * from a file name baked into this bundle.\n */\nfunction readPaths(snapshot: McpSnapshot, t: Translate): string {\n const documents = deploymentDocuments(snapshot)\n return documents.length === 0 ? t('noSessionsNoPaths') : t('noSessionsPaths', { paths: documents.join(' · ') })\n}\n\n/** One overridden declaration, as the host's merge warning reports it. */\nexport interface OverrideNote {\n /** `serverName` that was declared in more than one document. */\n name: string\n /**\n * The overridden document, when the snapshot pins it; `undefined` when more\n * than one lower-priority document could have carried the losing entry.\n */\n from: string | undefined\n}\n\n/** One card of the \"By files\" view: a document and the servers it declares. */\nexport interface DocumentGroup {\n /** Absolute document path, or `''` when the host reported no source. */\n source: string\n /** Path relative to the project (or `~`-shortened); `''` when source is `''`. */\n label: string\n /** Where the document sits in the read order, per {@link documentPriority}. */\n priority: DocumentPriority | undefined\n /** The surviving rows that this document declares. */\n rows: ServerRow[]\n /** Declarations of this document's servers that a later document replaced. */\n overrides: OverrideNote[]\n}\n\n/**\n * Group a project's rows per declaring document, in priority order.\n *\n * The plugin's native model is the document, not the server: a document read\n * later overrides an earlier entry with the same `serverName`, so the earlier\n * declaration is a property of the file that won. The host reports the\n * overridden *name* in a merge warning (`project.issues`) and the winner's\n * document in the row's `source`; this function pairs the two. Which earlier\n * document carried the losing entry is only knowable when a single\n * lower-priority document is in the picture, so {@link OverrideNote.from} stays\n * `undefined` otherwise and the view says so instead of guessing.\n * @param project - one project from the host snapshot.\n * @returns one group per declaring document, lowest priority first.\n */\nexport function fileGroups(project: ProjectSnapshot): DocumentGroup[] {\n const groups: DocumentGroup[] = []\n for (const row of project.rows) {\n const source = row.source ?? ''\n let group = groups.find((candidate) => candidate.source === source)\n if (group === undefined) {\n group = {\n source,\n label: source === '' ? '' : documentLabel(source, project.projectRoot),\n priority: source === '' ? undefined : documentPriority(source, project),\n rows: [],\n overrides: [],\n }\n groups.push(group)\n }\n group.rows.push(row)\n }\n // Stable in modern engines: documents keep their first-appearance order inside\n // one tier, and documents the read order does not know come last.\n groups.sort((left, right) => (left.priority?.tier ?? Number.MAX_SAFE_INTEGER) - (right.priority?.tier ?? Number.MAX_SAFE_INTEGER))\n for (const issue of project.issues) {\n // The merge warning is recognised by its wire code, never by its prose:\n // the client translates the payload, so an English string-match would both\n // miss under another language and misread a translated message.\n if (issue.server === undefined || issue.code !== 'parse.server.multiDocument') continue\n const winnerIndex = groups.findIndex((group) =>\n group.rows.some((row) => row.name === issue.server),\n )\n if (winnerIndex < 0) continue\n const winner = groups[winnerIndex]\n if (winner === undefined) continue\n const earlier = groups\n .slice(0, winnerIndex)\n .filter(\n (group) =>\n group.priority === undefined ||\n winner.priority === undefined ||\n group.priority.tier < winner.priority.tier,\n )\n winner.overrides.push({\n name: issue.server,\n from: earlier.length === 1 ? earlier[0]?.label : undefined,\n })\n }\n return groups\n}\n\n/** The `1 project …` / `3 projects …` toolbar summary. */\nfunction liveProjectCount(count: number, t: Translate): string {\n return count === 1 ? t('projectsOne') : t('projectsMany', { count })\n}\n\n// ── styles ────────────────────────────────────────────────────────────────────\n// Same vocabulary as `view.ts`: only the DSH alias layer's own custom\n// properties, each with the fallback a non-DSH page needs.\n\nconst BORDER = '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))'\nconst BORDER_L2 = '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.4))'\n\n/**\n * The longest a line of copy is allowed to run before it wraps.\n *\n * The settings panel is a modal `min(800px, 100vw - 48px)` wide, so a hint laid\n * out at full width runs to ~110 characters and the eye loses the line. The\n * mockups cap their prose at 74–84ch for the same reason; this is the cap the\n * page's own copy uses.\n */\nconst COPY_COLUMN = '72ch'\n\nexport const STYLE = {\n root: {\n display: 'flex',\n flexDirection: 'column',\n height: '100%',\n minHeight: 0,\n color: 'inherit',\n } satisfies CSSProperties,\n bar: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n padding: '6px 8px',\n borderBottom: BORDER,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n muted: { opacity: 0.9, fontSize: '0.9em' } satisfies CSSProperties,\n title: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n marginRight: 4,\n } satisfies CSSProperties,\n body: { flex: 1, minHeight: 0, overflow: 'auto', padding: '2px 2px 18px' } satisfies CSSProperties,\n segment: {\n display: 'flex',\n gap: 2,\n border: BORDER,\n borderRadius: 6,\n padding: 1,\n } satisfies CSSProperties,\n segmentItem: {\n padding: '1px 8px',\n border: 'none',\n borderRadius: 4,\n background: 'transparent',\n color: 'inherit',\n opacity: 0.65,\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.9em',\n } satisfies CSSProperties,\n segmentItemActive: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n opacity: 1,\n } satisfies CSSProperties,\n button: {\n padding: '2px 8px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n buttonPrimary: {\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid transparent',\n background: 'var(--dsw-alias-button-primary-fill, currentColor)',\n color: 'var(--dsw-alias-label-primary-foreground, inherit)',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n select: {\n border: BORDER,\n borderRadius: 4,\n padding: '2px 4px',\n background: 'var(--dsw-alias-bg-layer-2, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.9em',\n } satisfies CSSProperties,\n card: {\n border: BORDER,\n borderRadius: 7,\n marginBottom: 7,\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n overflow: 'hidden',\n } satisfies CSSProperties,\n cardHead: {\n display: 'flex',\n alignItems: 'center',\n gap: 7,\n padding: '6px 9px',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n background: 'var(--dsw-alias-bg-layer-2, transparent)',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n cardPath: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n fontSize: '0.9em',\n } satisfies CSSProperties,\n tag: {\n opacity: 0.75,\n fontSize: '0.8em',\n border: BORDER,\n borderRadius: 4,\n padding: '0 5px',\n color: 'var(--dsw-alias-label-secondary, inherit)',\n whiteSpace: 'nowrap',\n } satisfies CSSProperties,\n /** The `warn` chip of the mockups: the same rule, in the warning tone. */\n tagWarn: {\n opacity: 1,\n borderColor: 'var(--dsw-alias-state-warn-label, #b45309)',\n color: 'var(--dsw-alias-state-warn-label, #b45309)',\n } satisfies CSSProperties,\n /**\n * The choice control of a conflict card: the label, then the two answers side\n * by side. Four pixels apart like the mockups' own switch, and one row that\n * wraps rather than a column, because a long local name widens its button.\n */\n choiceRow: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n flexWrap: 'wrap',\n marginTop: 6,\n } satisfies CSSProperties,\n /** One answer of that control, while it is the one in force. */\n choiceOn: {\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid var(--dsw-alias-state-warn-label, #b45309)',\n background: 'var(--dsw-alias-bg-layer-2, rgba(127, 127, 127, 0.08))',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n /** One answer of that control, while the other one is in force. */\n choiceOff: {\n padding: '2px 8px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'var(--dsw-alias-label-secondary, inherit)',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n /** The `error` chip of the mockups, for the conflicts the host reports. */\n tagError: {\n opacity: 1,\n borderColor: 'var(--dsw-alias-state-error-primary, #ec1313)',\n color: 'var(--dsw-alias-state-error-primary, #ec1313)',\n } satisfies CSSProperties,\n row: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n padding: '5px 9px',\n borderTop: BORDER,\n } satisfies CSSProperties,\n dot: {\n width: 8,\n height: 8,\n borderRadius: '50%',\n display: 'inline-block',\n flex: 'none',\n alignSelf: 'center',\n } satisfies CSSProperties,\n serverButton: {\n padding: 0,\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n textAlign: 'left',\n } satisfies CSSProperties,\n serverButtonActive: {\n color: 'var(--dsw-alias-state-business-primary, inherit)',\n } satisfies CSSProperties,\n overrideNote: {\n padding: '3px 8px 3px 22px',\n borderTop: BORDER,\n opacity: 0.75,\n fontSize: '0.85em',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n } satisfies CSSProperties,\n note: {\n marginTop: 8,\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-warn-primary, #f59e0b)',\n background: 'var(--dsw-alias-state-warn-tertiary, transparent)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n maxWidth: COPY_COLUMN,\n // The failing-mount notes reuse this style and carry a multi-line detail.\n whiteSpace: 'pre-wrap',\n } satisfies CSSProperties,\n table: { width: '100%', borderCollapse: 'collapse' } satisfies CSSProperties,\n th: {\n textAlign: 'left',\n fontWeight: 500,\n fontSize: '0.75em',\n letterSpacing: '0.06em',\n textTransform: 'uppercase',\n // A header cell is a label, not prose: letting it wrap turns a column into a\n // one-word sliver at the panel's width.\n whiteSpace: 'nowrap',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n padding: '0 8px 5px 0',\n } satisfies CSSProperties,\n td: {\n padding: '6px 8px 6px 0',\n borderTop: BORDER,\n verticalAlign: 'baseline',\n // A cell is a value, not a heading: without this the browser's own `th`/`td`\n // default would render every name in the table bolder than the mockups do.\n fontWeight: 400,\n } satisfies CSSProperties,\n /** The editor's own checkboxes: a real input, so it only needs the reset. */\n switch: { margin: 0 } satisfies CSSProperties,\n /** The On column: the mockups' switch, drawn from the tokens they name. */\n switchOn: {\n display: 'inline-flex',\n alignItems: 'center',\n width: 26,\n height: 15,\n borderRadius: 8,\n padding: 0,\n border: 'none',\n background: 'var(--dsw-alias-state-business-primary, var(--dsw-alias-state-success-primary, #22c55e))',\n cursor: 'pointer',\n verticalAlign: '-2px',\n } satisfies CSSProperties,\n switchOff: { background: 'var(--dsw-alias-border-l3, #d0d3d8)' } satisfies CSSProperties,\n /** The knob inside {@link STYLE.switchOn}, pushed right when the row is on. */\n switchKnob: {\n width: 11,\n height: 11,\n borderRadius: '50%',\n background: 'var(--dsw-alias-label-primary-foreground, #ffffff)',\n marginLeft: 2,\n pointerEvents: 'none',\n } satisfies CSSProperties,\n switchKnobOn: { marginLeft: 13 } satisfies CSSProperties,\n // The vertical setting rows the `Tools` page is built from — the shape DSH's\n // own settings pages use (one row per setting: text column left, control\n // right, rule under). The `split` / `pane*` styles below belong to the entry\n // editor, whose three panes are deliberately not reused by a policy form:\n // its panes are far too narrow for a sentence, so the copy has nowhere to go\n // but a one-word-wide sliver.\n /** One setting row: label and description left, control right, rule under. */\n settingRow: {\n display: 'flex',\n alignItems: 'center',\n gap: 16,\n padding: '16px 0',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n /** The last row of a group or a block, which carries no trailing rule. */\n lastRow: { borderBottom: 'none' } satisfies CSSProperties,\n /** The row's text column: the wide one, and the one copy wraps in. */\n settingRowText: {\n flex: 1,\n minWidth: 0,\n display: 'flex',\n flexDirection: 'column',\n gap: 3,\n } satisfies CSSProperties,\n settingRowLabel: { fontWeight: 600 } satisfies CSSProperties,\n settingRowDesc: {\n fontSize: '0.85em',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n /** The control column: sized to its content, never the column that wraps. */\n settingRowControl: {\n flex: 'none',\n display: 'inline-flex',\n alignItems: 'center',\n gap: 6,\n } satisfies CSSProperties,\n /** A titled group of rows below the first one. */\n settingGroup: { marginTop: 16 } satisfies CSSProperties,\n settingGroupHead: {\n fontSize: '0.75em',\n letterSpacing: '0.06em',\n textTransform: 'uppercase',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n marginBottom: 6,\n } satisfies CSSProperties,\n /** The pinned names: chips that wrap across the row, not a column of their own. */\n tagList: {\n display: 'flex',\n flexWrap: 'wrap',\n alignItems: 'center',\n gap: 4,\n } satisfies CSSProperties,\n /** A table too wide for the panel scrolls instead of colliding with it. */\n tableScroll: { maxWidth: '100%', overflowX: 'auto' } satisfies CSSProperties,\n split: {\n display: 'flex',\n alignItems: 'stretch',\n minHeight: 260,\n border: BORDER,\n borderRadius: 7,\n overflow: 'hidden',\n } satisfies CSSProperties,\n /** Laid on top of {@link STYLE.split} while the panes stack. */\n splitNarrow: { flexDirection: 'column' } satisfies CSSProperties,\n splitBar: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n marginBottom: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n splitFooter: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n marginTop: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n paneList: {\n flex: '1 1 168px',\n minWidth: 0,\n borderRight: BORDER,\n overflow: 'auto',\n } satisfies CSSProperties,\n /** The server list stacked: full width, its rule on the bottom edge. */\n paneListNarrow: {\n flex: 'none',\n width: '100%',\n maxHeight: 180,\n borderRight: 'none',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n paneHead: {\n padding: '5px 8px',\n fontSize: '0.75em',\n letterSpacing: '0.06em',\n textTransform: 'uppercase',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n listItem: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n padding: '4px 8px',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n listItemActive: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n } satisfies CSSProperties,\n /**\n * The right column: the entry's form, and the JSON body under it.\n *\n * The JSON used to be a third column beside the form, which made both narrow\n * and put the entry in two places at once. Under the form it is the same entry\n * — the form's fields on top, the document body below — and the list keeps the\n * only fixed width.\n */\n paneColumn: {\n flex: '1 1 240px',\n minWidth: 0,\n display: 'flex',\n flexDirection: 'column',\n } satisfies CSSProperties,\n /** The form on top of the column: its own height, its rule on the bottom edge. */\n paneForm: {\n flex: 'none',\n minWidth: 0,\n padding: '8px 10px',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n /** The column stacked: full width, no rules left over from the row. */\n paneColumnNarrow: {\n flex: 'none',\n width: '100%',\n } satisfies CSSProperties,\n paneFormNarrow: {\n width: '100%',\n } satisfies CSSProperties,\n paneJson: {\n flex: '1 1 auto',\n minWidth: 0,\n display: 'flex',\n flexDirection: 'column',\n background: 'var(--dsw-alias-markdown-code-block, transparent)',\n } satisfies CSSProperties,\n /** The JSON pane stacked: full width, its own height under the form. */\n paneJsonNarrow: {\n flex: 'none',\n width: '100%',\n minHeight: 200,\n } satisfies CSSProperties,\n json: {\n margin: 0,\n padding: '8px 10px',\n fontSize: '0.8em',\n whiteSpace: 'pre',\n overflowX: 'auto',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n } satisfies CSSProperties,\n /**\n * The editable body: the pane's own `pre`, as a control.\n *\n * `pre-wrap` rather than `pre`: the pane is a column of the settings panel and\n * a long `args` line would otherwise scroll sideways inside it. `resize` is on\n * because the entry is read as a whole and a wrapped line is not always the\n * shape someone wants.\n */\n jsonArea: {\n flex: '1 1 auto',\n minHeight: 160,\n margin: 0,\n padding: '8px 10px',\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.8em',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n lineHeight: '1.5',\n whiteSpace: 'pre-wrap',\n overflowWrap: 'anywhere',\n overflowY: 'auto',\n resize: 'vertical',\n boxSizing: 'border-box',\n width: '100%',\n } satisfies CSSProperties,\n field: {\n display: 'grid',\n gridTemplateColumns: '90px 1fr',\n gap: '5px 9px',\n alignItems: 'center',\n marginBottom: 4,\n } satisfies CSSProperties,\n fieldLabel: {\n fontSize: '0.75em',\n letterSpacing: '0.05em',\n textTransform: 'uppercase',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n } satisfies CSSProperties,\n input: {\n border: BORDER,\n borderRadius: 4,\n padding: '2px 6px',\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.85em',\n minWidth: 0,\n } satisfies CSSProperties,\n /**\n * The read-only Detail row. A mount detail is a multi-line diagnostic, and an\n * `<input>` collapses its line breaks — the operator would lose exactly the\n * structure that makes the message readable.\n */\n fieldText: {\n border: BORDER,\n borderRadius: 4,\n padding: '2px 6px',\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.85em',\n minWidth: 0,\n whiteSpace: 'pre-wrap',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldHint: {\n margin: '-2px 0 6px 99px',\n fontSize: '0.8em',\n opacity: 0.6,\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldGroup: {\n display: 'grid',\n gridTemplateColumns: '90px 1fr',\n gap: '4px 9px',\n alignItems: 'start',\n marginBottom: 5,\n } satisfies CSSProperties,\n fieldRow: { display: 'flex', gap: 4, alignItems: 'center', marginBottom: 3 } satisfies CSSProperties,\n fieldKey: {\n flex: 'none',\n minWidth: 90,\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n fontSize: '0.8em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n iconButton: {\n flex: 'none',\n padding: '1px 5px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.8em',\n } satisfies CSSProperties,\n confirm: {\n marginTop: 6,\n padding: '7px 9px',\n border: BORDER,\n borderRadius: 6,\n background: 'var(--dsw-alias-bg-layer-2, transparent)',\n display: 'flex',\n flexDirection: 'column',\n gap: 4,\n } satisfies CSSProperties,\n noteOk: {\n marginTop: 8,\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-success-primary, #22c55e)',\n background: 'var(--dsw-alias-state-success-tertiary, transparent)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n noteError: {\n marginTop: 8,\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',\n background: 'var(--dsw-alias-interactive-bg-hover-danger, var(--dsw-alias-state-error-tertiary, transparent))',\n borderRadius: '0 5px 5px 0',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n maxWidth: COPY_COLUMN,\n } satisfies CSSProperties,\n errorState: { padding: '10px 12px' } satisfies CSSProperties,\n stateTitle: { opacity: 0.9, marginBottom: 4 } satisfies CSSProperties,\n /** Muted one-liner under a row or a card: a short label, never a paragraph. */\n hint: {\n opacity: 0.6,\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n maxWidth: COPY_COLUMN,\n } satisfies CSSProperties,\n codeLine: {\n margin: '6px auto 0',\n maxWidth: 560,\n padding: '5px 8px',\n border: BORDER,\n borderRadius: 5,\n background: 'var(--dsw-alias-markdown-code-block, transparent)',\n color: 'var(--dsw-alias-link, inherit)',\n fontSize: '0.8em',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n textAlign: 'left',\n } satisfies CSSProperties,\n} as const\n\n// ── layout adaptivity ─────────────────────────────────────────────────────────\n\n/**\n * The query the page stacks its split editor's panes on.\n *\n * The editor lives inside DSH's settings panel, not in the viewport: the panel\n * is `min(800px, 100vw - 48px)` wide, its navigation rail is 188px and its\n * options column pads 24px per side, so the page is given `min(564px, 100vw -\n * 284px)`. Three panes need all 564px of that, which is why they are flexible;\n * a viewport below 848px starts shrinking the panel itself, and three panes\n * there are slivers. The query sits at that break, so the panes stack whenever\n * the settings panel is not at its full 800px width.\n */\nexport const NARROW_SETTINGS_QUERY = '(max-width: 850px)'\n\n/** Just enough of `MediaQueryList` for the detector, so tests need no DOM. */\nexport interface MediaQueryLike {\n /** `true` while the query matches the current viewport. */\n matches: boolean\n /** Optional, so a test double can drive the flag by hand. */\n addEventListener?(type: 'change', listener: () => void): void\n /** Optional, for the same reason. */\n removeEventListener?(type: 'change', listener: () => void): void\n}\n\n/** One `matchMedia` query, as the detector asks for it. */\nexport type MediaQueryMatcher = (query: string) => MediaQueryLike\n\n/**\n * The browser's media-query matcher, or undefined when this half runs without\n * one — a non-browser host, or a policy that blocks the property.\n * @returns a matcher bound to the host, or undefined.\n */\nexport function browserMatchMedia(): MediaQueryMatcher | undefined {\n try {\n const host = globalThis as { matchMedia?: MediaQueryMatcher }\n if (typeof host.matchMedia !== 'function') return undefined\n const match = host.matchMedia\n return (query) => match.call(host, query)\n } catch {\n // Reading the property itself throws when a policy blocks it.\n return undefined\n }\n}\n\n/**\n * Resolve the narrow layout against a media-query matcher.\n * @param match - the browser's matcher, or undefined outside a browser.\n * @returns `true` when the panes must stack; `false` without a matcher.\n */\nexport function narrowSettingsLayout(match: MediaQueryMatcher | undefined): boolean {\n return match?.(NARROW_SETTINGS_QUERY).matches === true\n}\n\n/**\n * The narrow flag the page renders with, tracked across viewport resizes.\n *\n * Only the shell reads the media query: everything below it takes the flag as a\n * prop, which is what lets the no-DOM tests render both layouts.\n * @returns `true` while the viewport is at or below {@link NARROW_SETTINGS_QUERY}.\n */\nexport function useNarrowSettings(): boolean {\n const [narrow, setNarrow] = useState(() => narrowSettingsLayout(browserMatchMedia()))\n useEffect(() => {\n const match = browserMatchMedia()\n if (match === undefined) return undefined\n const list = match(NARROW_SETTINGS_QUERY)\n const sync = (): void => setNarrow(list.matches === true)\n sync()\n list.addEventListener?.('change', sync)\n return () => list.removeEventListener?.('change', sync)\n }, [])\n return narrow\n}\n\n// ── entry draft ───────────────────────────────────────────────────────────────\n\n/**\n * One `env`/`headers` row as the editor holds it.\n *\n * The row is the key plus what the input shows, never a copy of the declared\n * value: a masked key the user did not touch carries no value at all, which is\n * exactly what {@link draftEntry} has to submit for it.\n */\nexport interface FieldDraft {\n /** Key exactly as the document declares it, or the key being typed. */\n key: string\n /** What the value input shows; empty for a masked key until it is replaced. */\n text: string\n /** `true` when the host withheld the declared value as a secret. */\n masked: boolean\n /** `true` when the key resolves through the credentials file, not the document. */\n fromCredentials: boolean\n /** `true` once the user typed into a masked input, even back to empty. */\n replaced: boolean\n /** `true` for a row the user added; only its key is still editable. */\n added: boolean\n}\n\n/**\n * The form state of one open row.\n *\n * Optional entry fields hold exactly what the snapshot reported — `undefined`\n * means the document declares nothing — so an untouched draft rebuilds the\n * declared entry field for field and the editor opens clean instead of\n * announcing a change the user never made.\n */\nexport interface EntryDraft {\n /** Server the draft belongs to; a draft built for another row is ignored. */\n server: string\n /** `documentRevision` the draft was built from. */\n revision: string | undefined\n transport: 'stdio' | 'streamable-http'\n command: string | undefined\n args: readonly string[] | undefined\n cwd: string | undefined\n url: string | undefined\n /** `stdio`: declared environment, with the masked keys among them. */\n env: FieldDraft[]\n /** `true` when the declaration carried an `env`, so an emptied list still writes one. */\n envDeclared: boolean\n /** `streamable-http`: declared headers, with the masked keys among them. */\n headers: FieldDraft[]\n /** `true` when the declaration carried `headers`. */\n headersDeclared: boolean\n /** `enabled` exactly as declared: `undefined` means the document sets nothing. */\n enabled: boolean | undefined\n /** Milliseconds as typed; `''` means the declaration sets no timeout. */\n connectTimeoutMs: string\n /** Declared keys the editor never presents, written back untouched. */\n extra: Readonly<Record<string, unknown>>\n}\n\n/** Build the editable rows of one `env`/`headers` list. */\nexport function fieldDrafts(fields: readonly EntryField[] | undefined): FieldDraft[] {\n return (fields ?? []).map((field) => ({\n key: field.key,\n text: field.value ?? '',\n masked: field.masked === true,\n fromCredentials: field.fromCredentials === true,\n replaced: false,\n added: false,\n }))\n}\n\n/**\n * The draft the editor opens on: the snapshot's own entry, field for field.\n * @param row - the row being edited.\n * @returns the draft, or undefined when the host did not parse the entry.\n */\nexport function draftOf(row: ServerRow): EntryDraft | undefined {\n const entry = row.entry\n if (entry === undefined) return undefined\n return {\n server: row.name,\n revision: row.documentRevision,\n transport: entry.transport,\n command: entry.command,\n args: entry.args,\n cwd: entry.cwd,\n url: entry.url,\n env: fieldDrafts(entry.env),\n envDeclared: entry.env !== undefined,\n headers: fieldDrafts(entry.headers),\n headersDeclared: entry.headers !== undefined,\n enabled: entry.enabled,\n connectTimeoutMs: entry.connectTimeoutMs === undefined ? '' : String(entry.connectTimeoutMs),\n extra: entry.extra ?? {},\n }\n}\n\n/**\n * The draft actually shown: the stored one while it still belongs to this row\n * and this document revision, otherwise a fresh one.\n *\n * A background poll that re-reads a changed document therefore drops a stale\n * edit instead of writing it back on the snapshot's revision: the save would be\n * refused as `conflict` anyway.\n * @param row - the row being edited.\n * @param stored - the draft the shell still holds, if any.\n * @returns the draft to render, or undefined when there is nothing to edit.\n */\nexport function activeDraft(row: ServerRow, stored: EntryDraft | undefined): EntryDraft | undefined {\n const fresh = draftOf(row)\n if (fresh === undefined) return undefined\n if (stored === undefined || stored.server !== row.name || stored.revision !== row.documentRevision) {\n return fresh\n }\n return stored\n}\n\n/** One declared key as the save request carries it; undefined when it is not ours to write. */\nfunction fieldOf(row: FieldDraft): EntryField | undefined {\n if (row.key === '') return undefined\n // A key the credentials file answers is not editable, but it must still be\n // submitted: the host replaces the whole `env`/`headers` object with what this\n // request carries, so a dropped key is a key deleted from the document — the\n // reference to the credential would vanish on any unrelated edit. The host\n // writes the declared text back for a `fromCredentials` field and never a value\n // from here.\n if (row.fromCredentials) return { key: row.key, masked: true, fromCredentials: true }\n // Untouched and masked: no value at all, so the document keeps its secret.\n if (row.masked && !row.replaced) return { key: row.key, masked: true }\n return { key: row.key, value: row.text }\n}\n\nfunction fieldsOf(rows: readonly FieldDraft[]): EntryField[] {\n const fields: EntryField[] = []\n for (const row of rows) {\n const field = fieldOf(row)\n if (field !== undefined) fields.push(field)\n }\n return fields\n}\n\n/** The timeout as typed, or undefined when the field is empty or not a duration. */\nexport function timeoutOf(text: string): number | undefined {\n if (text.trim() === '') return undefined\n const value = Number(text)\n return Number.isInteger(value) && value >= 0 ? value : undefined\n}\n\n/** `true` when the timeout field holds something that is not a duration. */\nexport function timeoutInvalid(text: string): boolean {\n return text.trim() !== '' && timeoutOf(text) === undefined\n}\n\n/**\n * The entry a save writes: the whole declaration, rebuilt from the draft.\n *\n * Everything the editor presents is taken from the draft; `extra` rides along\n * untouched, because a save replaces `mcpServers[server]` wholesale and dropping\n * the keys the form never showed would delete configuration.\n * @param draft - the open row's form state.\n * @returns the entry body of a {@link SaveRequest}.\n */\nexport function draftEntry(draft: EntryDraft): EntrySnapshot {\n const env = fieldsOf(draft.env)\n const headers = fieldsOf(draft.headers)\n const timeout = timeoutOf(draft.connectTimeoutMs)\n const body: EntrySnapshot =\n draft.transport === 'stdio'\n ? {\n transport: 'stdio',\n ...(draft.command === undefined ? {} : { command: draft.command }),\n ...(draft.args === undefined ? {} : { args: draft.args }),\n ...(draft.cwd === undefined ? {} : { cwd: draft.cwd }),\n ...(env.length === 0 && !draft.envDeclared ? {} : { env }),\n }\n : {\n transport: 'streamable-http',\n ...(draft.url === undefined ? {} : { url: draft.url }),\n ...(headers.length === 0 && !draft.headersDeclared ? {} : { headers }),\n }\n return {\n ...body,\n ...(draft.enabled === undefined ? {} : { enabled: draft.enabled }),\n ...(timeout === undefined ? {} : { connectTimeoutMs: timeout }),\n ...(Object.keys(draft.extra).length === 0 ? {} : { extra: draft.extra }),\n }\n}\n\n/**\n * The save request for one row, or undefined when the snapshot does not carry\n * what a write needs (the row has no declaring document or no revision).\n */\nexport function saveRequestOf(\n project: ProjectSnapshot,\n row: ServerRow,\n entry: EntrySnapshot,\n consent: boolean,\n): SaveRequest | undefined {\n if (row.source === undefined || row.documentRevision === undefined) return undefined\n return {\n projectRoot: project.projectRoot,\n server: row.name,\n document: row.source,\n revision: row.documentRevision,\n ...(row.writeScope === 'global' ? { consent } : {}),\n entry,\n }\n}\n\n// ── the JSON pane's diff ──────────────────────────────────────────────────────\n\n/** One line of the JSON pane: shared context, or one side of a change. */\nexport interface DiffLine {\n kind: 'context' | 'removed' | 'added'\n text: string\n}\n\n/**\n * Line diff between two pretty-printed entries.\n *\n * A plain longest-common-subsequence walk: entries are small, and a faithful\n * diff is what makes the pane show the edit instead of a copy of the snapshot.\n * @param before - the declared entry, line by line.\n * @param after - the entry the draft would write.\n * @returns every line of both sides, in reading order.\n */\nexport function diffLines(before: readonly string[], after: readonly string[]): DiffLine[] {\n const table: number[][] = Array.from({ length: before.length + 1 }, () =>\n new Array<number>(after.length + 1).fill(0),\n )\n for (let i = before.length - 1; i >= 0; i -= 1) {\n for (let j = after.length - 1; j >= 0; j -= 1) {\n const row = table[i]\n const next = table[i + 1]\n if (row === undefined || next === undefined) continue\n row[j] =\n before[i] === after[j]\n ? (next[j + 1] ?? 0) + 1\n : Math.max(next[j] ?? 0, row[j + 1] ?? 0)\n }\n }\n const lines: DiffLine[] = []\n let i = 0\n let j = 0\n while (i < before.length && j < after.length) {\n const left = before[i] ?? ''\n const right = after[j] ?? ''\n if (left === right) {\n lines.push({ kind: 'context', text: left })\n i += 1\n j += 1\n } else if ((table[i + 1]?.[j] ?? 0) >= (table[i]?.[j + 1] ?? 0)) {\n lines.push({ kind: 'removed', text: left })\n i += 1\n } else {\n lines.push({ kind: 'added', text: right })\n j += 1\n }\n }\n for (; i < before.length; i += 1) lines.push({ kind: 'removed', text: before[i] ?? '' })\n for (; j < after.length; j += 1) lines.push({ kind: 'added', text: after[j] ?? '' })\n return lines\n}\n\n/**\n * The entry in the shape the document holds it: the keys the form never showed\n * sit beside the parsed ones instead of under `extra`, and the keys that resolve\n * through the credentials file are gone, because the document does not declare\n * them at all.\n *\n * Both sides of the diff go through this, so an untouched draft compares equal\n * to the snapshot however the host bucketed the unparsed and credential keys.\n */\nexport function entryBody(entry: EntrySnapshot): Record<string, unknown> {\n const body: Record<string, unknown> = { transport: entry.transport }\n if (entry.command !== undefined) body.command = entry.command\n if (entry.args !== undefined) body.args = entry.args\n if (entry.cwd !== undefined) body.cwd = entry.cwd\n const env = documentFields(entry.env)\n if (env !== undefined) body.env = env\n if (entry.url !== undefined) body.url = entry.url\n const headers = documentFields(entry.headers)\n if (headers !== undefined) body.headers = headers\n if (entry.enabled !== undefined) body.enabled = entry.enabled\n if (entry.connectTimeoutMs !== undefined) body.connectTimeoutMs = entry.connectTimeoutMs\n for (const [key, value] of Object.entries(entry.extra ?? {})) body[key] = value\n return body\n}\n\n/** A declared list without the keys that only exist in the credentials file. */\nfunction documentFields(fields: readonly EntryField[] | undefined): EntryField[] | undefined {\n return fields?.filter((field) => field.fromCredentials !== true)\n}\n\n/** The declared entry against the entry the draft would write, line by line. */\nexport function entryDiff(declared: EntrySnapshot | undefined, edited: EntrySnapshot): DiffLine[] {\n const before = declared === undefined ? [] : JSON.stringify(entryBody(declared), null, 2).split('\\n')\n return diffLines(before, JSON.stringify(entryBody(edited), null, 2).split('\\n'))\n}\n\n/** `true` when the draft would write something other than the declared entry. */\nexport function entryDirty(declared: EntrySnapshot | undefined, edited: EntrySnapshot): boolean {\n return entryDiff(declared, edited).some((line) => line.kind !== 'context')\n}\n\n/**\n * One `env`/`headers` list as the document holds it: a flat object of strings.\n *\n * The snapshot's own shape is a list of `{ key, value }` — that is what a diff\n * compares and what the JSON preview prints — while a document declares an\n * object. The pane edits the document, so this is the shape it shows.\n * @param fields - the draft's rows.\n * @returns the object; a key with no value (a secret the panel is not shown) and\n * a key answered outside the document are both left out, because neither has a\n * value the pane could print.\n */\nfunction recordFields(fields: readonly FieldDraft[]): Record<string, string> {\n const record: Record<string, string> = {}\n for (const field of fields) {\n if (field.key === '' || field.text === '' || field.fromCredentials === true) continue\n record[field.key] = field.text\n }\n return record\n}\n\n/**\n * One draft as its document declares it: the shape a person writes in `mcp.json`.\n *\n * The keys a document cannot carry are the same ones {@link entryBody} drops: a\n * secret the panel is not shown has no value to print, and a key answered by the\n * project's `.env` or the credentials file is not in the document at all. Both\n * are kept by {@link draftFromJson} when the pane's text omits them, so editing\n * the body never erases one by accident.\n * @param draft - the entry the form and the pane edit.\n * @returns the declaration object the host would write.\n */\nexport function documentBody(draft: EntryDraft): Record<string, unknown> {\n const body: Record<string, unknown> = { transport: draft.transport }\n if (draft.command !== undefined) body.command = draft.command\n if (draft.args !== undefined) body.args = draft.args\n if (draft.cwd !== undefined) body.cwd = draft.cwd\n if (draft.envDeclared) body.env = recordFields(draft.env)\n if (draft.url !== undefined) body.url = draft.url\n if (draft.headersDeclared) body.headers = recordFields(draft.headers)\n if (draft.enabled !== undefined) body.enabled = draft.enabled\n if (draft.connectTimeoutMs !== '') body.connectTimeoutMs = Number(draft.connectTimeoutMs)\n for (const [key, value] of Object.entries(draft.extra)) body[key] = value\n return body\n}\n\n/** The entry as the JSON pane shows and writes it: the document's own body. */\nexport function jsonBodyOf(draft: EntryDraft): string {\n return `${JSON.stringify(documentBody(draft), null, 2)}\\n`\n}\n\n/** One edit of the JSON pane: the draft it parses into, or why it does not. */\nexport type JsonDraftAnswer = { draft: EntryDraft } | { error: string }\n\n/** A string field, or `undefined` when the document sets nothing. */\nfunction jsonString(body: Record<string, unknown>, key: string): string | undefined | false {\n const value = body[key]\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : false\n}\n\n/** One `env`/`headers` pair of the parsed body, or `false` for a value that is not text. */\nfunction jsonFields(value: unknown, path: string): EntryField[] | undefined | false {\n if (value === undefined) return undefined\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const fields: EntryField[] = []\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (typeof entry !== 'string') return false\n void path\n fields.push({ key, value: entry })\n }\n return fields\n}\n\n/**\n * Read one JSON edit back into a draft.\n *\n * This is the inverse of {@link entryBody}, and it is deliberately the same\n * shape the form edits: whatever the pane parses becomes the draft the form\n * renders and the confirmation compares, so both entries edit one value.\n *\n * Two things the document cannot express are preserved rather than dropped:\n * keys answered outside it (the project's `.env` or the credentials file) are\n * not part of the body the pane shows, so a hand edit that omits them keeps the\n * ones the draft already had. Unknown keys travel in `extra` exactly as written,\n * because a save replaces the entry wholesale.\n * @param text - the pane's text.\n * @param base - the draft the pane opened on: its server, revision and the keys\n * the document does not carry.\n * @returns the parsed draft, or the first field that does not parse.\n */\nexport function draftFromJson(text: string, base: EntryDraft): JsonDraftAnswer {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch (error) {\n return { error: error instanceof Error ? error.message : String(error) }\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return { error: 'not an object' }\n }\n const body = value as Record<string, unknown>\n const transport = body.transport\n if (transport !== 'stdio' && transport !== 'streamable-http') return { error: 'transport' }\n\n const command = jsonString(body, 'command')\n if (command === false) return { error: 'command' }\n const cwd = jsonString(body, 'cwd')\n if (cwd === false) return { error: 'cwd' }\n const url = jsonString(body, 'url')\n if (url === false) return { error: 'url' }\n\n let args: readonly string[] | undefined\n if (body.args !== undefined) {\n if (!Array.isArray(body.args)) return { error: 'args' }\n const lines: string[] = []\n for (const [index, entry] of body.args.entries()) {\n if (typeof entry !== 'string') return { error: `args[${index}]` }\n lines.push(entry)\n }\n args = lines\n }\n\n const env = jsonFields(body.env, 'env')\n if (env === false) return { error: 'env' }\n const headers = jsonFields(body.headers, 'headers')\n if (headers === false) return { error: 'headers' }\n\n const enabled = body.enabled\n if (enabled !== undefined && typeof enabled !== 'boolean') return { error: 'enabled' }\n const timeout = body.connectTimeoutMs\n if (timeout !== undefined && (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout < 0)) {\n return { error: 'connectTimeoutMs' }\n }\n\n const known = new Set([\n 'transport',\n 'command',\n 'args',\n 'cwd',\n 'env',\n 'headers',\n 'url',\n 'enabled',\n 'connectTimeoutMs',\n ])\n const extra: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(body)) {\n if (!known.has(key)) extra[key] = entry\n }\n\n /**\n * The parsed list, plus the keys the pane cannot show a value for.\n *\n * Both are keys the document holds and the pane's body does not print: a key\n * answered outside the document, and a secret whose value the host withholds.\n * The pane's text omitting them is \"unchanged\", not \"deleted\" — a save removes\n * a key when the draft drops it, and only the form's own row can do that.\n */\n const carryUnshown = (\n parsed: EntryField[] | undefined,\n was: readonly FieldDraft[],\n ): FieldDraft[] => {\n const text1 = (parsed ?? []).map((field) => ({\n key: field.key,\n text: field.value ?? '',\n masked: false,\n fromCredentials: false,\n replaced: false,\n added: false,\n }))\n const carried = new Set(text1.map((field) => field.key))\n for (const field of was) {\n const unshown = field.fromCredentials === true || (field.masked === true && field.text === '')\n if (unshown && !carried.has(field.key)) text1.push(field)\n }\n return text1\n }\n\n return {\n draft: {\n server: base.server,\n revision: base.revision,\n // Every field above is narrowed to its real type by its own `false` check.\n transport,\n command,\n args,\n cwd,\n url,\n env: carryUnshown(env, base.env),\n envDeclared: env !== undefined,\n headers: carryUnshown(headers, base.headers),\n headersDeclared: headers !== undefined,\n enabled: enabled as boolean | undefined,\n connectTimeoutMs: timeout === undefined ? '' : String(timeout),\n extra,\n },\n }\n}\n\n// ── saving ────────────────────────────────────────────────────────────────────\n\n/** What the host answered to a save: written, or one of the frozen error codes. */\nexport type SaveAnswer =\n | { readonly ok: true }\n | {\n readonly ok: false\n readonly code: SaveErrorCode\n readonly message: string\n /**\n * Wire code of `message` (`projectMcp.host` namespace), when the host\n * coded the refusal (F-48); `saveNotice` resolves it through the host\n * seat and an answer without it keeps the `hostMessage` wrapper.\n */\n readonly messageCode?: string | undefined\n /** Flat params of {@link SaveAnswer}'s messageCode, when it has any. */\n readonly messageParams?: Record<string, string> | undefined\n }\n\n/** The sentence each frozen {@link SaveErrorCode} gets; the keys live in {@link EN}. */\nconst SAVE_ERROR_KEYS: Record<SaveErrorCode, LocaleKey> = {\n invalid: 'saveErrorInvalid',\n blocked: 'saveErrorBlocked',\n conflict: 'saveErrorConflict',\n 'not-found': 'saveErrorNotFound',\n failed: 'saveErrorFailed',\n}\n\nconst SAVE_ERROR_CODES = Object.keys(SAVE_ERROR_KEYS) as SaveErrorCode[]\n\nfunction codeOf(code: string | undefined): SaveErrorCode {\n return SAVE_ERROR_CODES.find((known) => known === code) ?? 'failed'\n}\n\n/** The shape of the `{ ok, value | error }` envelope every host route answers with. */\ninterface SaveEnvelope {\n ok?: boolean\n error?: { code?: string; message?: string; messageCode?: string; messageParams?: Record<string, string> }\n}\n\n/**\n * `POST` one save and unwrap the envelope.\n *\n * Unlike the snapshot poll this never throws: every failure is one of the five\n * frozen codes, and `invalid` keeps the host's own text — the only place the\n * parser's reason reaches the user.\n * @param request - the entry, the document and the revision it was built from.\n * @returns the host's answer, normalized to {@link SaveAnswer}.\n */\nexport async function postSave(request: SaveRequest): Promise<SaveAnswer> {\n try {\n const response = await fetch(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.save}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(request),\n })\n const payload = (await response.json()) as SaveEnvelope\n if (payload.ok === true) return { ok: true }\n return {\n ok: false,\n code: codeOf(payload.error?.code),\n message: payload.error?.message ?? `request failed (${response.status})`,\n // The coded companions are optional on the wire: an old host's refusal\n // has none, and the notice falls back to the message.\n ...(typeof payload.error?.messageCode === 'string'\n ? { messageCode: payload.error.messageCode, messageParams: payload.error.messageParams }\n : {}),\n }\n } catch (error) {\n return { ok: false, code: 'failed', message: error instanceof Error ? error.message : String(error) }\n }\n}\n\n/** One save answer, as a sentence, plus what the notice has to offer. */\nexport interface SaveNotice {\n /** The sentence to show, one locale key per code. */\n text: string\n /** `true` when the document was written. */\n written: boolean\n /**\n * The host's own sentence, ready to render; only `invalid` shows it. A\n * coded refusal is resolved through the host seat and stands alone (F-48);\n * an uncoded one keeps the `hostMessage` wrapper it always had.\n */\n detail: string | undefined\n /** `true` when the page offers the re-read action that `conflict` asks for. */\n reRead: boolean\n}\n\n/**\n * Turn a save answer into the sentence the page shows.\n * @param answer - the host's answer, normalized by {@link postSave}.\n * @param t - the UI-namespace seat.\n * @param hostT - the `projectMcp.host` seat for a coded refusal's message;\n * absent — or a seat that does not know the code — the payload's English\n * message answers, never the raw code.\n */\nexport function saveNotice(answer: SaveAnswer, t: Translate, hostT?: Translate | undefined): SaveNotice {\n if (answer.ok) return { text: t('saveOk'), written: true, detail: undefined, reRead: false }\n return {\n text: t(SAVE_ERROR_KEYS[answer.code]),\n written: false,\n detail:\n answer.code !== 'invalid'\n ? undefined\n : answer.messageCode === undefined\n ? t('hostMessage', { message: answer.message })\n : resolveHost(hostT ?? hostTranslate(undefined), answer.messageCode, answer.messageParams, answer.message),\n reRead: answer.code === 'conflict',\n }\n}\n\n// ── form controls ─────────────────────────────────────────────────────────────\n\n/**\n * One control that feeds the save request.\n *\n * Enabled while the row may be written; when the tier is `readonly` it renders\n * disabled with the row's own `writeBlockedReason`. The internal `data-write`\n * marker lets the no-DOM tests find every such control without a rendered\n * document.\n */\nfunction formControl<T extends keyof ReactHTML>(\n kind: T,\n props: Record<string, unknown>,\n editable: boolean,\n reason: string,\n children?: ReactNode,\n): ReactNode {\n const marked: Record<string, unknown> = {\n ...props,\n title: reason,\n 'data-write': true,\n ...(editable ? {} : { disabled: true }),\n }\n return h(kind, marked as never, children)\n}\n\n/** A field the host owns: shown, never editable, with the reason why. */\nfunction hostField(label: string, value: string, reason: string): ReactNode {\n return h(\n 'div',\n { style: STYLE.field, key: label },\n h('span', { style: STYLE.fieldLabel }, label),\n h('input', {\n style: STYLE.input,\n value,\n readOnly: true,\n disabled: true,\n title: reason,\n 'aria-label': label,\n 'data-read': true,\n }),\n )\n}\n\n/**\n * The same host-owned row for a value that carries line breaks — the mount\n * detail. It keeps the label, the read-only marker and the reason tooltip, but\n * renders pre-wrapped text so the diagnostic's structure survives.\n */\nfunction hostDetailField(label: string, value: string, reason: string): ReactNode {\n return h(\n 'div',\n { style: STYLE.field, key: label },\n h('span', { style: STYLE.fieldLabel }, label),\n h(\n 'div',\n {\n style: STYLE.fieldText,\n title: reason,\n 'aria-label': label,\n 'data-read': true,\n },\n value,\n ),\n )\n}\n\n/** One editable text field of the parsed entry. */\nfunction textField(\n label: string,\n value: string,\n editable: boolean,\n reason: string,\n onChange: (value: string) => void,\n hint?: string,\n): ReactNode {\n return h(\n 'div',\n { key: label },\n h(\n 'div',\n { style: STYLE.field },\n h('span', { style: STYLE.fieldLabel }, label),\n formControl(\n 'input',\n {\n style: STYLE.input,\n value,\n readOnly: !editable,\n 'aria-label': label,\n ...(editable\n ? { onChange: (event: { target: { value: string } }) => onChange(event.target.value) }\n : {}),\n },\n editable,\n reason,\n ),\n ),\n hint === undefined ? null : h('div', { style: STYLE.fieldHint }, hint),\n )\n}\n\n/** Reproduce one `env`/`headers` list as key/value rows plus an add button. */\nfunction fieldList(\n label: string,\n rows: readonly FieldDraft[],\n editable: boolean,\n reason: string,\n t: Translate,\n hint: string,\n onChange: (rows: FieldDraft[]) => void,\n): ReactNode {\n return h(\n 'div',\n { style: STYLE.fieldGroup, key: label },\n h('span', { style: STYLE.fieldLabel }, label),\n h(\n 'div',\n null,\n rows.length === 0 ? h('div', { style: STYLE.hint }, hint) : null,\n rows.map((row, index) =>\n h(\n 'div',\n { key: `${row.key}#${index}` },\n h(\n 'div',\n { style: STYLE.fieldRow },\n row.added\n ? formControl(\n 'input',\n {\n style: STYLE.input,\n value: row.key,\n placeholder: t('keyPlaceholder'),\n 'aria-label': t('keyField'),\n ...(editable\n ? {\n onChange: (event: { target: { value: string } }) =>\n onChange(replaceRow(rows, index, { key: event.target.value })),\n }\n : {}),\n },\n editable,\n reason,\n )\n : h('span', { style: STYLE.fieldKey, title: row.key }, row.key),\n row.fromCredentials\n ? h('input', {\n style: STYLE.input,\n value: row.text,\n readOnly: true,\n disabled: true,\n title: t('credentialsNote'),\n placeholder: t('credentialValue'),\n 'aria-label': `${row.key} — ${t('credentialsNote')}`,\n 'data-read': true,\n })\n : formControl(\n 'input',\n {\n style: STYLE.input,\n value: row.text,\n placeholder:\n row.masked && !row.replaced ? t('maskedValue') : t('valuePlaceholder'),\n 'aria-label': `${row.key} ${t('valueField')}`,\n ...(editable\n ? {\n onChange: (event: { target: { value: string } }) =>\n onChange(\n replaceRow(rows, index, {\n // A masked input becomes a replacement on the first\n // keystroke, even when the user clears it back to empty.\n text: event.target.value,\n replaced: row.masked ? true : row.replaced,\n }),\n ),\n }\n : {}),\n },\n editable,\n reason,\n ),\n row.fromCredentials || !editable\n ? null\n : h(\n 'button',\n {\n style: STYLE.iconButton,\n title: t('removeKeyHint'),\n 'aria-label': `${t('removeKey')} ${row.key}`,\n onClick: () => onChange(rows.filter((_entry, at) => at !== index)),\n },\n t('removeKey'),\n ),\n ),\n row.fromCredentials ? h('div', { style: STYLE.fieldHint }, t('credentialsNote')) : null,\n ),\n ),\n h(\n 'button',\n {\n style: { ...STYLE.button, fontSize: '0.8em' },\n disabled: !editable,\n title: editable ? t('addKeyHint') : reason,\n onClick: () =>\n onChange([\n ...rows,\n {\n key: '',\n text: '',\n masked: false,\n fromCredentials: false,\n replaced: false,\n added: true,\n },\n ]),\n },\n t('addKey'),\n ),\n ),\n )\n}\n\n/** One row of a key/value list, replaced by key change or a typed value. */\nfunction replaceRow(\n rows: readonly FieldDraft[],\n index: number,\n patch: Partial<FieldDraft>,\n): FieldDraft[] {\n return rows.map((row, at) => (at === index ? { ...row, ...patch } : row))\n}\n\n/** The JSON pane's lines, coloured by side of the change. */\n/**\n * The reason a disabled control carries: the host's payload resolved through\n * the host namespace (a known code translates; an unknown one falls back to\n * the payload's own English, never the raw code), or the page's fallback when\n * the host reported no reason at all.\n */\nfunction blockedReason(row: ServerRow, t: Translate, hostT?: Translate | undefined): string {\n if (row.writeBlockedReason === undefined) return t('writeBlockedUnknown')\n return resolveHost(hostT ?? hostTranslate(undefined), row.blockedCode, row.blockedParams, row.writeBlockedReason)\n}\n\n/** `true` when the row's declaring document may be rewritten at all. */\nfunction writable(row: ServerRow): boolean {\n return row.writeScope !== undefined && row.writeScope !== 'readonly'\n}\n\n// ── the page ──────────────────────────────────────────────────────────────────\n\n/**\n * Everything the page renders, as plain props — the tests drive this directly.\n *\n * The editor props ride along from {@link EditorProps}: the shell owns the draft\n * and the confirmation state, the page is a function of them.\n */\nexport interface SettingsPageProps extends Omit<EditorProps, 'project' | 'row'> {\n /** Host snapshot, or undefined before the first poll lands. */\n snapshot: McpSnapshot | undefined\n /** Last fetch failure, when the host did not answer. */\n error: string | undefined\n /** True while a host action is in flight. */\n busy: boolean\n view: SettingsView\n onView: (view: SettingsView) => void\n /** Which page of this plugin's own settings page is open. */\n page: SettingsPageKey\n onPage: (page: SettingsPageKey) => void\n /** Selected project root; a stale value falls back to the first project. */\n selectedRoot: string | undefined\n onSelectProject: (projectRoot: string) => void\n /** Selected server name; opens the split editor. */\n selectedServer: string | undefined\n onSync: () => void\n /** Retry every failed mount of the selected project. */\n onRetry: () => void\n /** `true` while the table view also shows the snapshot's own JSON. */\n json: boolean\n onJson: (next: boolean) => void\n /** Switch one project's mode; written straight through to the host. */\n onMode: (projectRoot: string, mode: ToolMode) => void\n /** Roots with a mode write in flight. */\n modePending: ReadonlySet<string>\n /** Last refusal of a mode write, when the host did not take it. */\n modeError: string | undefined\n /** Wire companions of `modeError`, when the host coded the refusal (F-48). */\n modeErrorCode?: string | undefined\n /** Flat params of `modeErrorCode`. */\n modeErrorParams?: Record<string, string> | undefined\n /** Pin or unpin one tool of one project; the host stores it at once. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal of a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n /** Choose which declaration of one contested name the project shows. */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a choice write in flight, per `projectRoot` + name. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal of a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n}\n\n/**\n * The registered component: wire the host poll, the remembered view and the\n * editor's own state into the pure page. Kept thin on purpose — everything below\n * this line is a plain function of its props, which is what the no-DOM tests\n * exercise.\n */\nexport function SettingsTab(props: SettingsTabProps): ReactNode {\n const t = translateOf(props.t)\n const { snapshot, error, busy, run, reload } = useSnapshot(true, DEFAULT_REFRESH_MS)\n const [view, setView] = useState<SettingsView>(() => settingsViewOf())\n const [page, setPage] = useState<SettingsPageKey>(DEFAULT_SETTINGS_PAGE)\n const [selectedRoot, setSelectedRoot] = useState<string | undefined>(undefined)\n const [selectedServer, setSelectedServer] = useState<string | undefined>(undefined)\n const [modePending, setModePending] = useState<ReadonlySet<string>>(() => new Set())\n // Each refusal is the host's whole answer — prose plus the F-48 wire code\n // and its params — so the render site resolves the coded message through\n // the host seat and an old host's prose renders exactly as before.\n const [modeRefusal, setModeRefusal] = useState<PolicyRefusal | undefined>(undefined)\n // The other half of the policy: one row of the tool list disables while its own\n // pin is in flight, and the host's refusal is shown rather than reverted.\n const [pinPending, setPinPending] = useState<ReadonlySet<string>>(() => new Set())\n const [pinRefusal, setPinRefusal] = useState<PolicyRefusal | undefined>(undefined)\n // The durable answer to a name two declarations fight over: which of them the\n // project shows. One card disables while its own write is in flight.\n const [choicePending, setChoicePending] = useState<ReadonlySet<string>>(() => new Set())\n const [choiceRefusal, setChoiceRefusal] = useState<PolicyRefusal | undefined>(undefined)\n // The editor's own state: the draft the user is building, the confirmation\n // step, the consent a global write needs, and the last answer from the host.\n const [stored, setStored] = useState<EntryDraft | undefined>(undefined)\n /**\n * The JSON pane's parse error, held here rather than in the pane.\n *\n * The pane owns the text, but Save is decided here: a document must never be\n * written from text the pane could not read, so a failed parse blocks the\n * confirmation until the text parses again.\n */\n const [jsonError, setJsonError] = useState<string | undefined>(undefined)\n const [confirming, setConfirming] = useState(false)\n const [consent, setConsent] = useState(false)\n const [saveState, setSaveState] = useState<SaveAnswer | undefined>(undefined)\n const [saving, setSaving] = useState(false)\n // The one place the media query is read; the page below takes the flag as a prop.\n const narrow = useNarrowSettings()\n const resetEditor = useCallback((): void => {\n setStored(undefined)\n setConfirming(false)\n setConsent(false)\n setSaveState(undefined)\n setSaving(false)\n setJsonError(undefined)\n }, [])\n const chooseView = useCallback((next: SettingsView): void => {\n setView(next)\n persistSettingsView(next)\n }, [])\n const chooseProject = useCallback(\n (projectRoot: string): void => {\n setSelectedRoot(projectRoot)\n setSelectedServer(undefined)\n resetEditor()\n },\n [resetEditor],\n )\n const chooseServer = useCallback(\n (name: string | undefined): void => {\n setSelectedServer(name)\n resetEditor()\n },\n [resetEditor],\n )\n // Both operator actions act on the selected project and ask for the whole\n // snapshot back: this page lists every project, so a narrowed answer would\n // empty it, while the action itself must not start a server for a project the\n // user is not looking at. The toolbar's button and every broken row's own\n // `Retry` send exactly the same request.\n const sync = useCallback((): void => {\n void run(\n ROUTE_ACTIONS.sync,\n operatorBody(selectedProject(snapshot, selectedRoot)?.projectRoot, true),\n )\n }, [snapshot, selectedRoot, run])\n const retry = useCallback((): void => {\n void run(\n ROUTE_ACTIONS.retry,\n operatorBody(selectedProject(snapshot, selectedRoot)?.projectRoot, true),\n )\n }, [snapshot, selectedRoot, run])\n const [json, setJson] = useState(false)\n const chooseJson = useCallback((next: boolean): void => setJson(next), [])\n /**\n * Write one project's mode. The switch is not a draft: the host reads the mode\n * on each request assembly, so the answer of this call is the only source of\n * truth and a refusal is shown rather than silently reverted.\n */\n const onMode = useCallback(\n (projectRoot: string, mode: ToolMode): void => {\n setModeRefusal(undefined)\n void requestMode(policyBody(projectRoot, mode), {\n onStart: (root) => setModePending((previous) => new Set(previous).add(root)),\n onSettled: (root) =>\n setModePending((previous) => {\n const next = new Set(previous)\n next.delete(root)\n return next\n }),\n onRefused: (message, messageCode, messageParams) => setModeRefusal({ message, messageCode, messageParams }),\n })\n },\n [],\n )\n const onPin = useCallback((projectRoot: string, tool: string, pinned: boolean): void => {\n setPinRefusal(undefined)\n void requestPin(pinBody(projectRoot, tool, pinned), {\n onStart: (name) => setPinPending((previous) => new Set(previous).add(name)),\n onSettled: (name) =>\n setPinPending((previous) => {\n const next = new Set(previous)\n next.delete(name)\n return next\n }),\n onRefused: (message, messageCode, messageParams) => setPinRefusal({ message, messageCode, messageParams }),\n })\n }, [])\n const onChoice = useCallback(\n (projectRoot: string, server: string, choice: ConflictChoice): void => {\n setChoiceRefusal(undefined)\n const key = choiceKey(projectRoot, server)\n const settle = (): void =>\n setChoicePending((previous) => {\n const next = new Set(previous)\n next.delete(key)\n return next\n })\n setChoicePending((previous) => new Set(previous).add(key))\n void postConflict(conflictBody(projectRoot, server, choice))\n .then((answer) => {\n if (!answer.ok) {\n setChoiceRefusal({\n message: answer.message,\n messageCode: answer.messageCode,\n messageParams: answer.messageParams,\n })\n }\n })\n .finally(settle)\n },\n [],\n )\n const project = selectedProject(snapshot, selectedRoot)\n const row = project?.rows.find((entry) => entry.name === selectedServer)\n const draft = row === undefined ? undefined : activeDraft(row, stored)\n const onDraft = useCallback((next: EntryDraft): void => {\n setStored(next)\n // The form re-derives the pane's text from this draft, so whatever the pane\n // failed to parse is no longer what is on screen.\n setJsonError(undefined)\n }, [])\n const onJsonEdit = useCallback(\n (next: EntryDraft | undefined, error: string | undefined): void => {\n setJsonError(error)\n if (next !== undefined) setStored(next)\n },\n [],\n )\n const onDiscard = useCallback((): void => {\n setStored(undefined)\n setConfirming(false)\n setSaveState(undefined)\n }, [])\n const onAskSave = useCallback((): void => {\n setSaveState(undefined)\n setConfirming(true)\n }, [])\n const onCancelSave = useCallback((): void => setConfirming(false), [])\n const onConsent = useCallback((next: boolean): void => setConsent(next), [])\n const onReRead = useCallback((): void => {\n setStored(undefined)\n setConfirming(false)\n setSaveState(undefined)\n void reload()\n }, [reload])\n const onConfirmSave = useCallback((): void => {\n if (project === undefined || row === undefined || draft === undefined) return\n // Belt and braces with the disabled confirm button: a global write without\n // the explicit consent is never sent.\n if (row.writeScope === 'global' && !consent) return\n const request = saveRequestOf(project, row, draftEntry(draft), consent)\n if (request === undefined) return\n setSaving(true)\n void postSave(request).then((answer) => {\n setSaving(false)\n setConfirming(false)\n setSaveState(answer)\n if (!answer.ok) return\n // The write landed: drop the draft and pull the fresh snapshot the host\n // re-read after the save.\n setStored(undefined)\n setConsent(false)\n void reload()\n })\n }, [project, row, draft, consent, run, reload])\n return h(SettingsPage, {\n snapshot,\n error,\n busy,\n view,\n onView: chooseView,\n page,\n onPage: setPage,\n onMode,\n modePending,\n modeError: modeRefusal?.message,\n modeErrorCode: modeRefusal?.messageCode,\n modeErrorParams: modeRefusal?.messageParams,\n onPin,\n pinPending,\n pinError: pinRefusal?.message,\n pinErrorCode: pinRefusal?.messageCode,\n pinErrorParams: pinRefusal?.messageParams,\n onChoice,\n choicePending,\n choiceError: choiceRefusal?.message,\n choiceErrorCode: choiceRefusal?.messageCode,\n choiceErrorParams: choiceRefusal?.messageParams,\n selectedRoot,\n onSelectProject: chooseProject,\n selectedServer,\n onSelectServer: chooseServer,\n onSync: sync,\n onRetry: retry,\n json,\n onJson: chooseJson,\n draft,\n confirming,\n consent,\n saveState,\n saving,\n onDraft,\n onJsonEdit,\n jsonError,\n onDiscard,\n onAskSave,\n onCancelSave,\n onConsent,\n onConfirmSave,\n onReRead,\n narrow,\n t,\n hostT: props.hostT,\n })\n}\n\n/**\n * The page: toolbar, then one state body. Exported so every state — before the\n * first poll, no live project, no declared server, a failed fetch — is asserted\n * without a DOM.\n * @param props - see {@link SettingsPageProps}.\n * @returns the page element tree.\n */\nexport function SettingsPage(props: SettingsPageProps): ReactNode {\n const t = props.t\n const projects = props.snapshot?.projects ?? []\n return h(\n 'div',\n { style: STYLE.root },\n h(\n 'div',\n { style: STYLE.bar },\n projects.length === 0\n ? null\n : h(ProjectSelector, {\n projects,\n selected: props.selectedRoot,\n onSelect: props.onSelectProject,\n t,\n }),\n projects.length === 0\n ? null\n : h('span', { style: STYLE.muted }, liveProjectCount(projects.length, t)),\n h('span', { style: { flex: 1 } }),\n h(SettingsPageSwitch, { page: props.page, onChange: props.onPage, t }),\n // The view switch, the JSON reading and the way out of it belong to the\n // server page: `Tools` is one policy form, not a second way to read the\n // same documents, so it keeps the toolbar it shares and drops the rest.\n props.page === 'tools' ? null : h(ViewSwitch, { view: props.view, onChange: props.onView, t }),\n props.page === 'tools' || props.view !== 'table'\n ? null\n : h(\n 'button',\n {\n style: STYLE.button,\n 'aria-pressed': props.json,\n title: props.json ? t('hideJson') : t('showJson'),\n onClick: () => props.onJson(!props.json),\n },\n props.json ? t('hideJson') : t('showJson'),\n ),\n h(\n 'button',\n {\n style: STYLE.button,\n disabled: props.busy,\n title: t('syncHint'),\n onClick: props.onSync,\n },\n t('sync'),\n ),\n ),\n // A poll that fails after data has landed keeps the page: the rows stay, and\n // the failure is reported above them instead of replacing them.\n props.error === undefined || props.snapshot === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.note },\n `${t('hostUnavailable')} `,\n h('span', { style: STYLE.hint }, props.error),\n ),\n h('div', { style: STYLE.body }, settingsBody(props)),\n )\n}\n\n/**\n * The body below the toolbar: exactly one branch per situation, and every empty\n * branch names what is missing instead of showing an empty box.\n * @param props - see {@link SettingsPageProps}.\n * @returns the element tree below the toolbar.\n */\nexport function settingsBody(props: SettingsPageProps): ReactNode {\n const t = props.t\n // The error state only when there is nothing to show; a later failure is\n // reported by the page above the rows it kept.\n if (props.error !== undefined && props.snapshot === undefined) {\n return h(\n 'div',\n { style: STYLE.errorState },\n h('div', { style: STYLE.stateTitle }, t('hostUnavailable')),\n h('div', { style: STYLE.hint }, t('hostUnavailableHint', { route: `${ROUTE_PREFIX}/snapshot` })),\n h('div', { style: STYLE.hint }, props.error),\n )\n }\n if (props.snapshot === undefined) {\n return h(\n 'div',\n { style: STYLE.errorState },\n emptyState(t('loading'), t('loadingHint')),\n )\n }\n const projects = props.snapshot.projects\n if (projects.length === 0) {\n return withCodeLine(t('noSessions'), t('noSessionsHint'), readPaths(props.snapshot, t))\n }\n const project = selectedProject(props.snapshot, props.selectedRoot)\n if (project === undefined) return null\n if (props.page === 'tools') {\n return h(ToolsPage, {\n project,\n rows: projectPolicyRows(projects),\n onMode: props.onMode,\n pending: props.modePending,\n modeError: props.modeError,\n modeErrorCode: props.modeErrorCode,\n modeErrorParams: props.modeErrorParams,\n onSync: props.onSync,\n onPin: props.onPin,\n pinPending: props.pinPending,\n pinError: props.pinError,\n pinErrorCode: props.pinErrorCode,\n pinErrorParams: props.pinErrorParams,\n onChoice: props.onChoice,\n choicePending: props.choicePending,\n choiceError: props.choiceError,\n choiceErrorCode: props.choiceErrorCode,\n choiceErrorParams: props.choiceErrorParams,\n t,\n hostT: props.hostT,\n })\n }\n const row = project.rows.find((entry) => entry.name === props.selectedServer)\n if (row !== undefined) {\n return h(EditorSplit, {\n project,\n row,\n onSelectServer: props.onSelectServer,\n draft: props.draft,\n confirming: props.confirming,\n consent: props.consent,\n saveState: props.saveState,\n saving: props.saving,\n onDraft: props.onDraft,\n onJsonEdit: props.onJsonEdit,\n jsonError: props.jsonError,\n onDiscard: props.onDiscard,\n onAskSave: props.onAskSave,\n onCancelSave: props.onCancelSave,\n onConsent: props.onConsent,\n onConfirmSave: props.onConfirmSave,\n onReRead: props.onReRead,\n narrow: props.narrow,\n t,\n hostT: props.hostT,\n })\n }\n if (project.rows.length === 0) {\n // Where to declare one: this project's own documents, as configured. An\n // empty list is the honest answer \"nowhere\", not a file name this bundle\n // would otherwise invent.\n const documents = (project.files ?? [])\n .filter((file) => file.scope === 'project')\n .map((file) => file.path)\n return documents.length === 0\n ? emptyState(t('noServers'), t('noServersNoPath'))\n : withCodeLine(t('noServers'), t('noServersHint'), documents.join(' · '))\n }\n return props.view === 'files'\n ? h(FileCards, {\n project,\n selectedServer: props.selectedServer,\n onSelectServer: props.onSelectServer,\n t,\n hostT: props.hostT,\n })\n : h(\n 'div',\n null,\n h(ServerTable, {\n project,\n selectedServer: props.selectedServer,\n onSelectServer: props.onSelectServer,\n onRetry: props.onRetry,\n busy: props.busy,\n t,\n hostT: props.hostT,\n }),\n // The table keeps the failure banners it renders; the JSON reading is an\n // extra, below them, and only while the toolbar's toggle is on.\n props.json ? h(JsonPreview, { project, t }) : null,\n )\n}\n\n/** A centred empty state followed by the path or command that fixes it. */\nfunction withCodeLine(title: string, hint: string, code: string): ReactNode {\n return h('div', null, emptyState(title, hint), h('div', { style: STYLE.codeLine }, code))\n}\n\n/** The `Table` / `By files` switch. Not a write: it only changes this page. */\nexport function ViewSwitch(props: {\n view: SettingsView\n onChange: (view: SettingsView) => void\n t: Translate\n}): ReactNode {\n const item = (value: SettingsView, label: string): ReactNode =>\n h(\n 'button',\n {\n key: value,\n style:\n value === props.view\n ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }\n : STYLE.segmentItem,\n 'aria-pressed': value === props.view,\n onClick: () => props.onChange(value),\n },\n label,\n )\n return h(\n 'div',\n { style: STYLE.segment },\n item('table', props.t('viewTable')),\n item('files', props.t('viewFiles')),\n )\n}\n\n/**\n * Project picker. The only seat on this page where another project is visible,\n * and it only ever selects which single project's rows the body renders.\n */\nexport function ProjectSelector(props: {\n projects: readonly ProjectSnapshot[]\n selected: string | undefined\n onSelect: (projectRoot: string) => void\n t: Translate\n}): ReactNode {\n const value =\n props.selected !== undefined &&\n props.projects.some((project) => project.projectRoot === props.selected)\n ? props.selected\n : (props.projects[0]?.projectRoot ?? '')\n return h(\n 'label',\n { style: STYLE.muted },\n `${props.t('project')}: `,\n h(\n 'select',\n {\n style: STYLE.select,\n value,\n title: value,\n onChange: (event: { target: { value: string } }) => props.onSelect(event.target.value),\n },\n props.projects.map((project) =>\n h(\n 'option',\n { key: project.projectRoot, value: project.projectRoot },\n basename(project.projectRoot),\n ),\n ),\n ),\n )\n}\n\n/** The dense overview: one row per declared server of the selected project. */\n/**\n * The table's status cell: the host's word for the row, in the colour of that\n * status, and — for a quiet row the host counted — how long it has been unused.\n *\n * The figure comes from the host's own `usage[server].lastUsedAt`; a row the\n * counters never recorded has nothing to print, and the cell stays the word it\n * has always been rather than saying `idle 0m`.\n */\nfunction statusCell(row: ServerRow, project: ProjectSnapshot, t: Translate): ReactNode {\n const idle = idleNote(row.status, project.usage?.[row.name]?.lastUsedAt, t)\n return h(\n 'td',\n { style: { ...STYLE.td, color: STATUS_COLOR[row.status] } },\n t(STATUS_KEYS[row.status]),\n idle === undefined ? null : h('span', { style: STYLE.hint }, ` ${idle}`),\n )\n}\n\nexport function ServerTable(props: {\n project: ProjectSnapshot\n selectedServer?: string | undefined\n onSelectServer: (name: string | undefined) => void\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight, so the row buttons stay still. */\n busy?: boolean | undefined\n t: Translate\n /** The host namespace's seat, for the rows' coded blocked reasons. */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = props.t\n return h(\n 'div',\n { style: STYLE.tableScroll },\n h(\n 'table',\n { style: STYLE.table },\n h(\n 'thead',\n null,\n h(\n 'tr',\n null,\n h('th', { style: STYLE.th }, t('server')),\n h('th', { style: STYLE.th }, t('transport')),\n h('th', { style: STYLE.th }, t('status')),\n h('th', { style: STYLE.th }, t('source')),\n h('th', { style: STYLE.th }, t('on')),\n h('th', { style: STYLE.th }, ''),\n ),\n ),\n h(\n 'tbody',\n null,\n props.project.rows.map((row) =>\n h(\n 'tr',\n { key: row.name },\n h(\n 'td',\n { style: STYLE.td },\n statusDot(row.status, t),\n ' ',\n serverButton(row, row.name === props.selectedServer, props.onSelectServer, t, props.hostT),\n ),\n h('td', { style: STYLE.td }, h('span', { style: STYLE.muted }, row.transport ?? '—')),\n statusCell(row, props.project, t),\n h('td', { style: STYLE.td }, sourceLabel(row, props.project, t)),\n h('td', { style: STYLE.td }, enabledSwitch(row, t, props.hostT)),\n h('td', { style: STYLE.td }, rowAction(row, props, t)),\n ),\n ),\n ),\n ),\n ...props.project.rows\n .filter((row) => row.status === 'error' && row.detail !== undefined)\n .map((row) =>\n h(\n 'div',\n { style: STYLE.note, key: `detail-${row.name}` },\n h('strong', null, row.name),\n // The row passed the filter, so its detail is present; the seat\n // translates it when the host sent the wire code (F-48).\n ` — ${rowDetail(row, props.hostT) ?? ''}`,\n ),\n ),\n )\n}\n\n/**\n * The table's last cell: the one action the row has.\n *\n * A broken row offers a real `Retry` — the host route is project-scoped, so it\n * sends the request the toolbar's own button sends. Every other row offers `…`,\n * which opens the entry in the split editor: on this surface a row is read-only,\n * so the only thing left to do with it is go and edit it. Both labels are keys;\n * neither control writes anything itself.\n * @param row - the server row.\n * @param props - the table's own props, for the action and the busy flag.\n * @param t - translate seat.\n * @returns the cell's content.\n */\nfunction rowAction(\n row: ServerRow,\n props: {\n onSelectServer: (name: string | undefined) => void\n onRetry?: (() => void) | undefined\n busy?: boolean | undefined\n },\n t: Translate,\n): ReactNode {\n if (row.status === 'error' && props.onRetry !== undefined) {\n return h(\n 'button',\n {\n style: STYLE.button,\n title: t('retryHint'),\n disabled: props.busy === true,\n onClick: props.onRetry,\n },\n t('retry'),\n )\n }\n return h(\n 'button',\n {\n style: STYLE.button,\n title: t('rowActionsHint'),\n onClick: () => props.onSelectServer(row.name),\n },\n t('rowActionsMore'),\n )\n}\n\n/**\n * The snapshot's own reading of a project's entries, as JSON.\n *\n * Built from the parsed entries the host published, not from the document on\n * disk: the page never reads a file, and this preview must not imply it does. A\n * row the host did not parse has no entry and is left out rather than invented.\n * @param project - the selected project.\n * @returns the two-space JSON body the preview prints.\n */\nexport function projectJson(project: ProjectSnapshot): string {\n const servers: Record<string, unknown> = {}\n for (const row of project.rows) {\n if (row.entry === undefined) continue\n servers[row.name] = entryBody(row.entry)\n }\n return JSON.stringify({ mcpServers: servers }, null, 2)\n}\n\n/**\n * The table view's optional JSON pane: the snapshot's entries, read-only.\n *\n * @param props - the project and the translate seat.\n * @returns the titled code block.\n */\nexport function JsonPreview(props: { project: ProjectSnapshot; t: Translate }): ReactNode {\n return h(\n 'div',\n null,\n h('div', { style: STYLE.paneHead }, props.t('jsonPreview')),\n h('div', { style: STYLE.hint }, props.t('jsonPreviewHint')),\n h('pre', { style: STYLE.json }, projectJson(props.project)),\n )\n}\n\n/** The \"By files\" overview: one card per declaring document, in priority order. */\nexport function FileCards(props: {\n project: ProjectSnapshot\n selectedServer?: string | undefined\n onSelectServer: (name: string | undefined) => void\n t: Translate\n /** The host namespace's seat, for the rows' coded blocked reasons. */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = props.t\n return h(\n 'div',\n null,\n fileGroups(props.project).map((group) =>\n h(\n 'div',\n { key: group.source, style: STYLE.card },\n h(\n 'div',\n { style: STYLE.cardHead },\n h(\n 'span',\n { style: STYLE.cardPath },\n group.source === '' ? t('documentUnknown') : group.label,\n ),\n group.priority?.global === true ? h('span', { style: STYLE.tag }, t('global')) : null,\n group.priority === undefined\n ? null\n : h('span', { style: STYLE.tag }, t('priority', { tier: group.priority.tier, total: group.priority.total })),\n h('span', { style: { flex: 1 } }),\n h('span', { style: STYLE.muted }, serverCount(group.rows.length, t)),\n ),\n group.rows.map((row) =>\n h(\n 'div',\n { key: row.name, style: STYLE.row },\n statusDot(row.status, t),\n serverButton(row, row.name === props.selectedServer, props.onSelectServer, t, props.hostT),\n row.transport === undefined\n ? null\n : h('span', { style: STYLE.tag }, row.transport),\n // The status carries the row's tone here too: the document view is\n // the same rows as the table, read by document instead of by column.\n h('span', { style: { ...STYLE.muted, color: STATUS_COLOR[row.status] } }, t(STATUS_KEYS[row.status])),\n h('span', { style: { flex: 1 } }),\n enabledSwitch(row, t, props.hostT),\n ),\n ),\n group.overrides.map((note, index) =>\n h(\n 'div',\n { key: `${note.name}#${index}`, style: STYLE.overrideNote },\n note.from === undefined\n ? t('overrideUnpinned', { name: note.name })\n : t('overrideFrom', { name: note.name, from: note.from }),\n ),\n ),\n ),\n ),\n )\n}\n\n/** Everything the split editor renders, as plain props. */\nexport interface EditorProps {\n /** Project the row belongs to; its root rides in the save request. */\n project: ProjectSnapshot\n /** The row being edited. */\n row: ServerRow\n /** Called with the server to open, or undefined to go back to the overview. */\n onSelectServer: (name: string | undefined) => void\n /**\n * The open row's form state, already resolved through {@link activeDraft} by\n * the shell: the stored draft while it still matches the row's revision, a\n * fresh one otherwise. Undefined when the host did not parse the entry.\n */\n draft: EntryDraft | undefined\n /** True while the confirmation step is open. */\n confirming: boolean\n /** Consent checkbox state; only `global` rows read it. */\n consent: boolean\n /** Last save answer, when one has landed. */\n saveState: SaveAnswer | undefined\n /** True while the save request is in flight. */\n saving: boolean\n /** The JSON pane's parse error, when the last edit did not parse. */\n jsonError?: string | undefined\n /** Report one JSON edit: a parsed draft, or the reason it did not parse. */\n onJsonEdit?: ((draft: EntryDraft | undefined, error: string | undefined) => void) | undefined\n onDraft: (draft: EntryDraft) => void\n onDiscard: () => void\n /** Open the confirmation step; writes nothing on its own. */\n onAskSave: () => void\n onCancelSave: () => void\n onConsent: (consent: boolean) => void\n /** Write the document: the only control that reaches the host. */\n onConfirmSave: () => void\n /** Refetch the snapshot after a `conflict`. */\n onReRead: () => void\n /**\n * Stack the three panes instead of laying them in a row. The shell passes\n * {@link useNarrowSettings}'s flag; the tests pass it by hand, which is why\n * the editor itself never reads the media query. Defaults to `false`.\n */\n narrow?: boolean | undefined\n t: Translate\n /**\n * The `projectMcp.host` seat for the host's coded messages (the blocked\n * reason is the first channel). Optional: absent outside a shell and in\n * tests, where the payload's English message renders exactly as before.\n */\n hostT?: Translate | undefined\n}\n\n/**\n * One pane's rule for the current layout.\n * @param base - the pane's side-by-side rule.\n * @param stacked - the overrides for the stacked layout.\n * @param narrow - `true` while the panes render stacked.\n * @returns the style object the pane renders with.\n */\nfunction paneStyle(\n base: CSSProperties,\n stacked: CSSProperties,\n narrow: boolean,\n): CSSProperties {\n return narrow ? { ...base, ...stacked } : base\n}\n\n/**\n * The entry as JSON, editable: the pane under the form.\n *\n * One value, two views: the text is what the pane last showed or the user typed,\n * and every keystroke is parsed back into the shell's draft through\n * {@link draftFromJson}. A parse that fails leaves the draft alone and reports\n * the reason upward — the shell blocks Save on it, so a document can never be\n * written from text the pane could not read. The text re-syncs only when the\n * draft changes from somewhere else (the form above, another server): the draft\n * the pane itself produced is the one it already shows.\n * @param props - the draft, the write scope, the pane's own label and the\n * shell's error line.\n * @returns the editable body; its head belongs to the editor, which reads\n * whether the body differs from the snapshot.\n */\nexport function JsonPane(props: {\n /** The draft the form and the pane both edit. */\n draft: EntryDraft\n /** `true` while the declaring document may be written. */\n editable: boolean\n /** Why it may not be written, when it may not. */\n reason: string\n /** The pane head's label: the document, and whether it differs from the snapshot. */\n label: string\n /** The parse error the shell holds, when the last edit did not parse. */\n error: string | undefined\n /** Report one edit: a parsed draft, or the reason it did not parse. */\n onJson?: ((draft: EntryDraft | undefined, error: string | undefined) => void) | undefined\n t: Translate\n}): ReactNode {\n const t = props.t\n const [text, setText] = useState(() => jsonBodyOf(props.draft))\n /** The draft this pane produced last, so its own echo does not overwrite the text. */\n const adopted = useRef<EntryDraft | undefined>(props.draft)\n useEffect(() => {\n if (props.draft === adopted.current) return\n adopted.current = props.draft\n setText(jsonBodyOf(props.draft))\n }, [props.draft])\n const change = (next: string): void => {\n setText(next)\n const answer = draftFromJson(next, props.draft)\n if ('error' in answer) {\n props.onJson?.(undefined, answer.error)\n return\n }\n adopted.current = answer.draft\n props.onJson?.(answer.draft, undefined)\n }\n return h(\n 'div',\n null,\n h('textarea', {\n style: props.editable ? STYLE.jsonArea : { ...STYLE.jsonArea, opacity: 0.75 },\n value: text,\n readOnly: !props.editable,\n spellCheck: false,\n 'aria-label': props.label,\n // The same marking the form's controls carry: this is a write control of\n // the document, and on a tier that may not be written it is disabled with\n // the host's own reason as its title.\n 'data-write': true,\n title: props.editable ? t('jsonEditHint') : props.reason,\n ...(props.editable ? {} : { disabled: true }),\n onChange: (event: { target: { value: string } }) => change(event.target.value),\n }),\n props.error === undefined\n ? null\n : h('div', { style: STYLE.noteError }, t('jsonInvalid', { reason: props.error })),\n )\n}\n\n/**\n * The split editor: the project's servers on the left, and the entry on the\n * right — its fields, and the document body under them.\n *\n * One entry, two editors: the form's fields and the JSON pane both write the same\n * draft, and the pane parses every keystroke back into it. That is the one thing\n * the pane cannot delegate: text the pane cannot read leaves the draft alone and\n * blocks the write (the shell holds the reason), so a document is never saved\n * from something nobody parsed. A `readonly` tier keeps every control disabled\n * with `writeBlockedReason`. Nothing reaches the host before the confirmation\n * step: Save only opens it, and the confirm button inside it is the write. The\n * list and the entry column share the width they are given until `narrow` says\n * there is too little of it, and then everything stacks.\n */\nexport function EditorSplit(props: EditorProps): ReactNode {\n const t = props.t\n const narrow = props.narrow === true\n const { project, row } = props\n const { draft } = props\n const declared = row.entry\n const edited = draft === undefined ? undefined : draftEntry(draft)\n const dirty = declared !== undefined && edited !== undefined && entryDirty(declared, edited)\n const parsed = draft !== undefined && edited !== undefined\n const editable = parsed && writable(row)\n const reason = blockedReason(row, t, props.hostT)\n const timeoutBad = draft !== undefined && timeoutInvalid(draft.connectTimeoutMs)\n const request = edited === undefined ? undefined : saveRequestOf(project, row, edited, props.consent)\n const jsonBad = props.jsonError !== undefined\n const saveEnabled =\n !props.saving && editable && dirty && !timeoutBad && !jsonBad && request !== undefined\n // The Save control is never silently dead: whatever disables it is its title.\n const saveReason = ((): string => {\n if (!parsed) return t('entryUnavailable')\n if (jsonBad) return t('saveJsonInvalid')\n if (!writable(row)) return reason\n if (timeoutBad) return t('saveTimeoutInvalid')\n if (request === undefined) return t('saveUnavailable')\n if (props.saving) return t('saving')\n if (!dirty) return t('saveNoChange')\n return t('saveHint')\n })()\n const global = row.writeScope === 'global'\n const confirmReady = !props.saving && (!global || props.consent)\n const source = row.source\n const label = source === undefined ? t('documentUnknown') : documentLabel(source, project.projectRoot)\n const backup = source === undefined ? undefined : `${source}.bak`\n const backupLabel =\n backup === undefined ? t('documentUnknown') : documentLabel(backup, project.projectRoot)\n const state = !parsed\n ? t('entryUnavailable')\n : writable(row)\n ? t('editableNote', { document: label, backup: backupLabel })\n : t('writeBlocked', { reason })\n return h(\n 'div',\n null,\n h(\n 'div',\n { style: STYLE.splitBar },\n h(\n 'button',\n {\n style: STYLE.button,\n title: t('backHint'),\n onClick: () => props.onSelectServer(undefined),\n },\n `‹ ${t('back')}`,\n ),\n h('span', { style: STYLE.hint, title: source ?? project.projectRoot }, state),\n ),\n h(\n 'div',\n { style: paneStyle(STYLE.split, STYLE.splitNarrow, narrow) },\n h(\n 'div',\n {\n style: paneStyle(STYLE.paneList, STYLE.paneListNarrow, narrow),\n 'data-pane': 'list',\n },\n h('div', { style: STYLE.paneHead }, t('servers')),\n project.rows.map((entry) =>\n h(\n 'div',\n {\n key: entry.name,\n style:\n entry.name === row.name\n ? { ...STYLE.listItem, ...STYLE.listItemActive }\n : STYLE.listItem,\n },\n statusDot(entry.status, t),\n serverButton(entry, entry.name === row.name, props.onSelectServer, t, props.hostT),\n ),\n ),\n ),\n h(\n 'div',\n { style: paneStyle(STYLE.paneColumn, STYLE.paneColumnNarrow, narrow) },\n h(\n 'div',\n {\n style: paneStyle(STYLE.paneForm, STYLE.paneFormNarrow, narrow),\n 'data-pane': 'form',\n },\n // The form's own head: the pane below it holds the same entry in the\n // shape the document keeps, and the list is every declared server.\n h('div', { style: STYLE.paneHead }, t('paneEntry')),\n hostField(t('name'), row.name, t('nameReason')),\n ...(draft === undefined\n ? []\n : draftFields(draft, declared, editable, reason, t, props.onDraft)),\n hostField(t('status'), t(STATUS_KEYS[row.status]), t('statusReason')),\n hostField(t('source'), source ?? t('documentUnknown'), t('sourceReason')),\n hostDetailField(t('detail'), rowDetail(row, props.hostT) ?? '—', t('detailReason')),\n ),\n h(\n 'div',\n {\n style: paneStyle(STYLE.paneJson, STYLE.paneJsonNarrow, narrow),\n 'data-pane': 'json',\n },\n h(\n 'div',\n { style: STYLE.paneHead },\n draft === undefined || edited === undefined\n ? label\n : `${label} · ${dirty ? t('jsonDiff') : t('jsonClean')}`,\n ),\n draft === undefined || declared === undefined || edited === undefined\n ? h('div', { style: STYLE.json }, t('jsonUnavailable'))\n : h(JsonPane, {\n draft,\n editable,\n reason,\n label,\n error: props.jsonError,\n onJson: props.onJsonEdit,\n t,\n }),\n ),\n ),\n ),\n h(\n 'div',\n null,\n h(\n 'div',\n { style: STYLE.splitFooter },\n formControl(\n 'button',\n { style: STYLE.buttonPrimary, onClick: props.onAskSave },\n saveEnabled,\n saveReason,\n t('save'),\n ),\n h(\n 'button',\n {\n style: STYLE.button,\n disabled: !dirty,\n title: dirty ? t('discardHint') : t('discardReason'),\n onClick: props.onDiscard,\n },\n t('discard'),\n ),\n dirty ? h('span', { style: STYLE.tag }, t('unsaved')) : null,\n h('span', { style: { flex: 1 } }),\n h(\n 'span',\n {\n style: STYLE.hint,\n title: source ?? project.projectRoot,\n },\n t(writable(row) ? 'footerWrite' : 'footerReadonly', { document: label }),\n ),\n ),\n props.confirming\n ? confirmation({\n label,\n backupLabel,\n server: row.name,\n global,\n consent: props.consent,\n ready: confirmReady,\n saving: props.saving,\n t,\n onConsent: props.onConsent,\n onConfirm: props.onConfirmSave,\n onCancel: props.onCancelSave,\n })\n : null,\n props.saveState === undefined ? null : noticeBlock(props.saveState, t, props.onReRead, props.hostT),\n ),\n )\n}\n\n/** The entry's own fields, for the transport the draft currently declares. */\nfunction draftFields(\n draft: EntryDraft,\n declared: EntrySnapshot | undefined,\n editable: boolean,\n reason: string,\n t: Translate,\n onDraft: (draft: EntryDraft) => void,\n): ReactNode[] {\n const clearable = (value: string): string | undefined => (value === '' ? undefined : value)\n const transport = transportField(draft, editable, reason, t, onDraft)\n if (draft.transport === 'streamable-http') {\n return [\n transport,\n textField(t('urlField'), draft.url ?? '', editable, reason, (value) =>\n onDraft({ ...draft, url: clearable(value) }),\n ),\n fieldList(t('headersField'), draft.headers, editable, reason, t, t('headersHint'), (headers) =>\n onDraft({ ...draft, headers }),\n ),\n ...commonFields(draft, declared, editable, reason, t, onDraft),\n ]\n }\n return [\n transport,\n textField(t('commandField'), draft.command ?? '', editable, reason, (value) =>\n onDraft({ ...draft, command: clearable(value) }),\n ),\n textField(\n t('argsField'),\n (draft.args ?? []).join('\\n'),\n editable,\n reason,\n (value) => onDraft({ ...draft, args: value === '' ? undefined : value.split('\\n') }),\n t('argsHint'),\n ),\n textField(t('cwdField'), draft.cwd ?? '', editable, reason, (value) =>\n onDraft({ ...draft, cwd: clearable(value) }),\n ),\n fieldList(t('envField'), draft.env, editable, reason, t, t('envHint'), (env) =>\n onDraft({ ...draft, env }),\n ),\n ...commonFields(draft, declared, editable, reason, t, onDraft),\n ]\n}\n\n/** Fields both transports carry: `enabled` and the connect timeout. */\nfunction commonFields(\n draft: EntryDraft,\n declared: EntrySnapshot | undefined,\n editable: boolean,\n reason: string,\n t: Translate,\n onDraft: (draft: EntryDraft) => void,\n): ReactNode[] {\n const value = draft.enabled === undefined ? t('absent') : String(draft.enabled)\n return [\n h(\n 'div',\n { style: STYLE.field, key: 'enabled' },\n h('span', { style: STYLE.fieldLabel }, t('enabledField')),\n h(\n 'label',\n { style: { display: 'flex', alignItems: 'center', gap: 6 } },\n formControl(\n 'input',\n {\n type: 'checkbox',\n checked: draft.enabled !== false,\n style: STYLE.switch,\n 'aria-label': t('enabledField'),\n ...(editable\n ? {\n onChange: (event: { target: { checked: boolean } }) =>\n onDraft({\n ...draft,\n enabled: event.target.checked ? (declared?.enabled === true ? true : undefined) : false,\n }),\n }\n : {}),\n },\n editable,\n reason,\n ),\n h('span', { style: STYLE.hint }, t('enabledValue', { value })),\n ),\n ),\n textField(\n t('timeoutField'),\n draft.connectTimeoutMs,\n editable,\n reason,\n (value) => onDraft({ ...draft, connectTimeoutMs: value }),\n timeoutInvalid(draft.connectTimeoutMs) ? t('saveTimeoutInvalid') : t('timeoutHint'),\n ),\n ]\n}\n\n/** The confirmation step: what is written where, and the consent it may need. */\nfunction confirmation(props: {\n label: string\n backupLabel: string\n server: string\n global: boolean\n consent: boolean\n ready: boolean\n saving: boolean\n t: Translate\n onConsent: (consent: boolean) => void\n onConfirm: () => void\n onCancel: () => void\n}): ReactNode {\n const { t } = props\n return h(\n 'div',\n { style: STYLE.confirm },\n h('div', { style: STYLE.stateTitle }, t('confirmTitle', { document: props.label })),\n h('div', { style: STYLE.hint }, t('confirmBackup', { backup: props.backupLabel })),\n h('div', { style: STYLE.hint }, t('confirmFormat', { server: props.server })),\n props.global ? h('div', { style: STYLE.hint }, t('confirmConsent')) : null,\n props.global\n ? h(\n 'label',\n { style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: '0.85em' } },\n h('input', {\n type: 'checkbox',\n checked: props.consent,\n style: STYLE.switch,\n 'aria-label': t('consentLabel'),\n onChange: (event: { target: { checked: boolean } }) =>\n props.onConsent(event.target.checked),\n }),\n t('consentLabel'),\n )\n : null,\n h(\n 'div',\n { style: STYLE.splitFooter },\n formControl(\n 'button',\n { style: STYLE.buttonPrimary, onClick: props.onConfirm },\n props.ready,\n props.ready ? t('confirmWriteHint') : props.saving ? t('saving') : t('confirmBlocked'),\n t('confirmWrite'),\n ),\n h('button', { style: STYLE.button, onClick: props.onCancel }, t('cancel')),\n ),\n )\n}\n\n/** The sentence the last save answer gets, plus the actions it offers. */\nfunction noticeBlock(answer: SaveAnswer, t: Translate, onReRead: () => void, hostT?: Translate | undefined): ReactNode {\n const notice = saveNotice(answer, t, hostT)\n return h(\n 'div',\n { style: notice.written ? STYLE.noteOk : STYLE.noteError },\n notice.text,\n // The detail arrives ready to render: saveNotice applied the hostMessage\n // wrapper to an uncoded answer and the host seat to a coded one.\n notice.detail === undefined ? null : h('div', { style: STYLE.hint }, notice.detail),\n notice.reRead\n ? h('button', { style: STYLE.button, title: t('reReadHint'), onClick: onReRead }, t('reRead'))\n : null,\n )\n}\n\n/** The transport field: the two transports the host maps. */\nfunction transportField(\n draft: EntryDraft,\n editable: boolean,\n reason: string,\n t: Translate,\n onDraft: (draft: EntryDraft) => void,\n): ReactNode {\n return h(\n 'div',\n { style: STYLE.field, key: 'transport' },\n h('span', { style: STYLE.fieldLabel }, t('transport')),\n formControl(\n 'select',\n {\n style: STYLE.input,\n value: draft.transport,\n 'aria-label': t('transport'),\n ...(editable\n ? {\n onChange: (event: { target: { value: string } }) =>\n onDraft({\n ...draft,\n transport: event.target.value === 'streamable-http' ? 'streamable-http' : 'stdio',\n }),\n }\n : {}),\n },\n editable,\n reason,\n ['stdio', 'streamable-http'].map((option) => h('option', { key: option, value: option }, option)),\n ),\n )\n}\n\n/** The Source column: the declaring document, or the project root fallback. */\nfunction sourceLabel(row: ServerRow, project: ProjectSnapshot, t: Translate): ReactNode {\n const label =\n row.source === undefined ? t('documentUnknown') : documentLabel(row.source, project.projectRoot)\n return h('span', { style: { ...STYLE.muted, fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)' }, title: row.source ?? project.projectRoot }, label)\n}\n\n/** The row's `enabled` switch: the table edits nothing, so it opens the editor. */\nfunction enabledSwitch(row: ServerRow, t: Translate, hostT?: Translate | undefined): ReactNode {\n // The mockups draw the On column as their switch, not as a checkbox: the two\n // live states are the same fact (`enabled: false` is what `disabled` means),\n // and the switch is the shape the rest of the page's controls use. It is not\n // an editor either way — the click that opens the entry is the row's own.\n const on = row.status !== 'disabled'\n return formControl(\n 'button',\n {\n type: 'button',\n style: on ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n 'aria-checked': on,\n 'aria-label': t('on'),\n },\n false,\n writable(row) ? t('openToEdit') : blockedReason(row, t, hostT),\n h('span', {\n style: on ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob,\n 'aria-hidden': true,\n }),\n )\n}\n\n/** A status dot; the colour and the wording both come from the shared vocabulary. */\nfunction statusDot(status: ServerStatus, t: Translate): ReactNode {\n return h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[status] },\n title: t(STATUS_HINT[status]),\n 'aria-hidden': true,\n })\n}\n\n/** A server name that selects it; selection is not a write. */\nfunction serverButton(\n row: ServerRow,\n selected: boolean,\n onSelect: (name: string | undefined) => void,\n t: Translate,\n hostT?: Translate | undefined,\n): ReactNode {\n return h(\n 'button',\n {\n style: selected\n ? { ...STYLE.serverButton, ...STYLE.serverButtonActive }\n : STYLE.serverButton,\n title: rowDetail(row, hostT) ?? t(STATUS_HINT[row.status]),\n onClick: () => onSelect(selected ? undefined : row.name),\n },\n row.name,\n )\n}\n","/**\n * The plugin's own configuration card (F-54): a `plugins.bundle.config` entry\n * that edits the volatile configuration the host serves over `configForms`.\n *\n * The card is deliberately thin: the host owns the schema, the revision dance\n * and the write path; this module renders the eighteen volatile fields as two\n * groups of setting rows, commits valid edits through `form.set`, and offers a\n * per-field reset (`form.unset`) only for fields the user layer overrides.\n *\n * Two host facts are mirrored here on purpose, because host code must never\n * enter the client bundle: the volatile-field defaults (`src/index.ts`\n * `DEFAULTS`, module-private and host-side) and the local-prefix rule\n * (`src/naming.ts` `isValidLocalPrefix`). Both mirrors carry a comment at the\n * copy.\n */\n\nimport { createElement as h, useMemo, useState, useSyncExternalStore } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { PACKAGE_NAME } from '../shared.ts'\n// settings.ts owns the locale namespace and the row/switch styles. Both are\n// read inside function bodies only, never at module scope: `locales/ui.ts`\n// imports this module while settings.ts imports `locales/ui.ts`, so a value\n// read here during evaluation could land inside settings.ts's TDZ window.\nimport { NS, STYLE } from './settings.ts'\n\n// ---------------------------------------------------------------------------\n// Local faces — the vendored contracts, so the client never imports host types\n// ---------------------------------------------------------------------------\n\n/** The slice of `ConfigForm`'s snapshot the card reads. */\nexport interface ConfigFormSnapshotLike {\n readonly status: 'loading' | 'ready' | 'unavailable'\n readonly value: Record<string, unknown> | undefined\n /** The user layer of the layered configuration; a field's PRESENCE marks an override. */\n readonly user: unknown\n readonly writable: boolean\n}\n\n/** The slice of the host's `ConfigForm` service object the card uses. */\nexport interface ConfigFormLike {\n getSnapshot(): ConfigFormSnapshotLike\n subscribe(listener: () => void): () => void\n set(field: string, value: unknown): Promise<boolean>\n unset(field: string): Promise<boolean>\n}\n\n/** The slice of the `configForms` service the registration block uses. */\nexport interface ConfigFormsLike {\n get<T>(namespace: string): ConfigFormLike\n whileServed(\n namespaces: readonly string[],\n register: (served: ReadonlySet<string>) => () => void,\n ): () => void\n}\n\n/**\n * The props the slot contract declares for `plugins.bundle.config`\n * (`PluginConfigViewProps`), with `form` widened to `unknown`: this\n * registration injects a factory under `form`, but the contract also lets an\n * owner pass its own page form, and a card must survive every shape quietly.\n */\nexport interface PluginConfigViewPropsLike {\n readonly view: 'summary' | 'page'\n readonly form?: unknown\n readonly t?: Translate\n}\n\n// ---------------------------------------------------------------------------\n// English dictionary (zh/ru live in `./locales/ui.ts`, which merges this table)\n// ---------------------------------------------------------------------------\n\nexport const EN = {\n configSummary: 'Edit this plugin’s activation and runtime configuration',\n configGroupActivation: 'Activation',\n configGroupRuntime: 'Runtime',\n configLoading: 'Loading the configuration…',\n configUnavailable: 'The host does not serve this plugin’s configuration to this client.',\n configReadOnly: 'This client keeps its preferences process-local, so these values are read-only here.',\n configOverridden: 'overridden',\n configReset: 'Reset',\n configResetHint: 'Clear this override and inherit the default',\n configInvalidInteger: 'Enter a whole number ≥ {min}',\n configInvalidRange: 'Enter a whole number between {min} and {max}',\n configInvalidPrefix: 'Up to {max} characters: letters, digits, “_” or “-”',\n // The Activation group: the tool-activation surface of `src/activation.ts`.\n configActivationEnabled: 'Tool activation',\n configActivationEnabledHint: 'Offer MCP tools progressively — counters, disclosure and the search gate',\n configActivationSeeded: 'Seeded tools',\n configActivationSeededHint: 'Tools offered from the first step, before any counter accrues; 0 seeds none',\n configActivationMinCalls: 'Calls to pin',\n configActivationMinCallsHint: 'Calls after which the counters pin a tool directly',\n configToolIdleMs: 'Tool idle timeout (ms)',\n configToolIdleMsHint: 'A tool unused for this long drops back out of the request',\n configGuidanceEnabled: 'System-prompt guidance',\n configGuidanceEnabledHint: 'Inject the plugin’s operating notes into the session prompt',\n configActivationAutoLimit: 'Auto-activation limit',\n configActivationAutoLimitHint: 'Most tools the counters may add on their own (0–50)',\n configActivationAutoStickySteps: 'Sticky steps',\n configActivationAutoStickyStepsHint: 'Steps a just-used tool stays pinned regardless of counters (0–20)',\n configActivationToolBudgetChars: 'Tool budget (chars)',\n configActivationToolBudgetCharsHint: 'Character budget for the tool schemas one request carries (≥ 1000)',\n // The Runtime group: mounting, precedence and timeouts.\n configAllowGlobalWrite: 'Global writes',\n configAllowGlobalWriteHint: 'Allow saving into the user-level (~/.dsh) configuration',\n configEnvFiles: '.env files',\n configEnvFilesHint: 'Load .env files for server environment variables',\n configLazy: 'Lazy mounting',\n configLazyHint: 'Start project servers on the session’s first step, not at boot',\n configLocalPrefix: 'Local prefix',\n configLocalPrefixHint: 'Prefix for local tool names — up to 5 characters of A–Z, 0–9, _ or -; empty disables it',\n configProfileWins: 'Profile wins',\n configProfileWinsHint: 'Profile-level servers override project declarations of the same name',\n configConnectTimeoutMs: 'Connect timeout (ms)',\n configConnectTimeoutMsHint: 'How long starting one server may take',\n configToolCallTimeoutMs: 'Call timeout (ms)',\n configToolCallTimeoutMsHint: 'How long one tool call may take',\n configIdleTimeoutMs: 'Server idle timeout (ms)',\n configIdleTimeoutMsHint: 'A server idle for this long is stopped',\n configDebounceMs: 'Watch debounce (ms)',\n configDebounceMsHint: 'Quiet period before a config change triggers a rescan',\n configActivationWaitMs: 'Activation wait (ms)',\n configActivationWaitMsHint: 'How long the first step may wait for lazy servers',\n} satisfies Record<string, string>\n\n/** A dictionary key of this module's half of the namespace. */\nexport type LocaleKey = keyof typeof EN\n\n/** Translate one key, with optional `{name}` template params (the DSH seat). */\nexport type Translate = (key: string, params?: Record<string, unknown>) => string\n\n/**\n * Bind the translate seat the framework injects, falling back to this module's\n * own English dictionary when the card renders outside a DSH shell (tests, or\n * a browser half newer than the host).\n * @param t - the `t` seat of the composed props, when the framework passes one.\n * @returns a translate function that always answers.\n */\nexport function translateOf(t?: Translate): Translate {\n return t ?? fallbackTranslate\n}\n\nfunction fallbackTranslate(key: string, params?: Record<string, unknown>): string {\n const template = (EN as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in params ? String(params[name]) : match,\n )\n}\n\n// ---------------------------------------------------------------------------\n// The volatile fields — a mirror of the host table, with the card's own bounds\n// ---------------------------------------------------------------------------\n\n/** The eighteen keys of `VOLATILE_CONFIG_KEYS` (`src/index.ts`), redeclared. */\nexport type VolatileConfigKey =\n | 'activationEnabled'\n | 'activationSeeded'\n | 'activationMinCalls'\n | 'toolIdleMs'\n | 'guidanceEnabled'\n | 'activationAutoLimit'\n | 'activationAutoStickySteps'\n | 'activationToolBudgetChars'\n | 'allowGlobalWrite'\n | 'envFiles'\n | 'lazy'\n | 'localPrefix'\n | 'profileWins'\n | 'connectTimeoutMs'\n | 'toolCallTimeoutMs'\n | 'idleTimeoutMs'\n | 'debounceMs'\n | 'activationWaitMs'\n\n/**\n * The defaults the card displays when the served snapshot has no value for a\n * field. Mirror of the host's module-private `DEFAULTS` (`src/index.ts`) and\n * the activation constants (`src/activation.ts`): the host table cannot cross\n * into the client bundle, so the copy lives here and the schema's own defaults\n * remain the source of truth at write time.\n */\nexport const CONFIG_DEFAULTS: Record<VolatileConfigKey, boolean | number | string> = {\n activationEnabled: true,\n activationSeeded: 8,\n activationMinCalls: 5,\n toolIdleMs: 1_800_000,\n guidanceEnabled: true,\n activationAutoLimit: 12,\n activationAutoStickySteps: 2,\n activationToolBudgetChars: 40_000,\n allowGlobalWrite: false,\n envFiles: true,\n lazy: true,\n localPrefix: '',\n profileWins: true,\n connectTimeoutMs: 60_000,\n toolCallTimeoutMs: 60_000,\n idleTimeoutMs: 300_000,\n debounceMs: 300,\n activationWaitMs: 2_000,\n}\n\n/**\n * The local-prefix rule, mirrored from `src/naming.ts` (`MAX_LOCAL_PREFIX_LENGTH`\n * and `PREFIX_SHAPE`, in `isValidLocalPrefix`): empty disables the prefix,\n * otherwise at most five characters of letters, digits, `_` or `-`.\n */\nconst LOCAL_PREFIX_MAX = 5\nconst LOCAL_PREFIX_SHAPE = /^[A-Za-z0-9_-]+$/\n\n/** Client-side replica of the host's `isValidLocalPrefix`; see the note above. */\nexport function isValidLocalPrefix(value: string): boolean {\n if (value === '') return true\n return value.length <= LOCAL_PREFIX_MAX && LOCAL_PREFIX_SHAPE.test(value)\n}\n\n/** One editable field: how it is grouped, edited and bounded. */\ninterface FieldDef {\n readonly key: VolatileConfigKey\n readonly kind: 'boolean' | 'integer' | 'text'\n readonly min?: number\n readonly max?: number\n readonly label: LocaleKey\n readonly hint: LocaleKey\n}\n\nconst ACTIVATION_FIELDS: readonly FieldDef[] = [\n { key: 'activationEnabled', kind: 'boolean', label: 'configActivationEnabled', hint: 'configActivationEnabledHint' },\n { key: 'activationSeeded', kind: 'integer', min: 0, label: 'configActivationSeeded', hint: 'configActivationSeededHint' },\n { key: 'activationMinCalls', kind: 'integer', min: 1, label: 'configActivationMinCalls', hint: 'configActivationMinCallsHint' },\n { key: 'toolIdleMs', kind: 'integer', min: 0, label: 'configToolIdleMs', hint: 'configToolIdleMsHint' },\n { key: 'guidanceEnabled', kind: 'boolean', label: 'configGuidanceEnabled', hint: 'configGuidanceEnabledHint' },\n { key: 'activationAutoLimit', kind: 'integer', min: 0, max: 50, label: 'configActivationAutoLimit', hint: 'configActivationAutoLimitHint' },\n { key: 'activationAutoStickySteps', kind: 'integer', min: 0, max: 20, label: 'configActivationAutoStickySteps', hint: 'configActivationAutoStickyStepsHint' },\n { key: 'activationToolBudgetChars', kind: 'integer', min: 1000, label: 'configActivationToolBudgetChars', hint: 'configActivationToolBudgetCharsHint' },\n]\n\nconst RUNTIME_FIELDS: readonly FieldDef[] = [\n { key: 'allowGlobalWrite', kind: 'boolean', label: 'configAllowGlobalWrite', hint: 'configAllowGlobalWriteHint' },\n { key: 'envFiles', kind: 'boolean', label: 'configEnvFiles', hint: 'configEnvFilesHint' },\n { key: 'lazy', kind: 'boolean', label: 'configLazy', hint: 'configLazyHint' },\n { key: 'localPrefix', kind: 'text', label: 'configLocalPrefix', hint: 'configLocalPrefixHint' },\n { key: 'profileWins', kind: 'boolean', label: 'configProfileWins', hint: 'configProfileWinsHint' },\n { key: 'connectTimeoutMs', kind: 'integer', min: 0, label: 'configConnectTimeoutMs', hint: 'configConnectTimeoutMsHint' },\n { key: 'toolCallTimeoutMs', kind: 'integer', min: 0, label: 'configToolCallTimeoutMs', hint: 'configToolCallTimeoutMsHint' },\n { key: 'idleTimeoutMs', kind: 'integer', min: 0, label: 'configIdleTimeoutMs', hint: 'configIdleTimeoutMsHint' },\n { key: 'debounceMs', kind: 'integer', min: 0, label: 'configDebounceMs', hint: 'configDebounceMsHint' },\n { key: 'activationWaitMs', kind: 'integer', min: 0, label: 'configActivationWaitMs', hint: 'configActivationWaitMsHint' },\n]\n\n// ---------------------------------------------------------------------------\n// The card\n// ---------------------------------------------------------------------------\n\nconst QUIET: CSSProperties = {\n fontSize: '0.85em',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n}\n\nconst OVERRIDDEN_CHIP: CSSProperties = {\n marginLeft: 8,\n padding: '0 6px',\n borderRadius: 8,\n border: '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.4))',\n fontSize: '0.75em',\n fontWeight: 400,\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n verticalAlign: '1px',\n}\n\nconst RESET_BUTTON: CSSProperties = {\n border: 'none',\n background: 'none',\n padding: 0,\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.85em',\n color: 'var(--dsw-alias-state-business-primary, #2563eb)',\n}\n\nconst INPUT_WIDTH: CSSProperties = { width: 96 }\n\nconst INPUT_INVALID: CSSProperties = {\n borderColor: 'var(--dsw-alias-state-error-primary, #ef4444)',\n}\n\nconst INVALID_NOTE: CSSProperties = {\n fontSize: '0.8em',\n color: 'var(--dsw-alias-state-error-primary, #ef4444)',\n}\n\n/** The snapshot used while there is no form at all: the unavailable note. */\nconst NO_FORM_SNAPSHOT: ConfigFormSnapshotLike = {\n status: 'unavailable',\n value: undefined,\n user: undefined,\n writable: false,\n}\n\nconst noFormSnapshot = (): ConfigFormSnapshotLike => NO_FORM_SNAPSHOT\nconst subscribeNone = (): (() => void) => () => undefined\n\n/** The memoized store pair `useSyncExternalStore` needs, plus the form itself. */\ninterface FormSource {\n readonly form: ConfigFormLike\n readonly subscribe: (listener: () => void) => () => void\n readonly getSnapshot: () => ConfigFormSnapshotLike\n}\n\n/**\n * Resolve the `form` prop into a store the card can subscribe to. The\n * registration injects a factory (`() => forms.get(ns)`); a direct\n * `ConfigForm`-shaped object is accepted as well. Anything else — an absent\n * prop, a factory that throws, an owner-provided page form the card cannot\n * write through — resolves to `null`, and the card renders its quiet\n * unavailable note instead of failing.\n */\nfunction formSourceOf(raw: unknown): FormSource | null {\n let candidate: unknown = raw\n if (typeof candidate === 'function') {\n try {\n candidate = (candidate as () => unknown)()\n } catch {\n return null\n }\n }\n if (candidate === null || typeof candidate !== 'object') return null\n const form = candidate as ConfigFormLike\n if (\n typeof form.getSnapshot !== 'function' ||\n typeof form.subscribe !== 'function' ||\n typeof form.set !== 'function' ||\n typeof form.unset !== 'function'\n ) {\n return null\n }\n return {\n form,\n subscribe: (listener) => form.subscribe(listener),\n getSnapshot: () => form.getSnapshot(),\n }\n}\n\n/** A field is overridden when it is PRESENT in the user layer, whatever its value. */\nfunction hasOverride(user: unknown, field: string): boolean {\n return typeof user === 'object' && user !== null && Object.prototype.hasOwnProperty.call(user, field)\n}\n\n/** The displayed value: the served one, falling back to the mirrored default. */\nfunction fieldValue(def: FieldDef, snapshot: ConfigFormSnapshotLike): boolean | number | string {\n const raw = snapshot.value?.[def.key]\n const fallback = CONFIG_DEFAULTS[def.key]\n if (def.kind === 'boolean') return typeof raw === 'boolean' ? raw : (fallback as boolean)\n if (def.kind === 'integer') {\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : (fallback as number)\n }\n return typeof raw === 'string' ? raw : (fallback as string)\n}\n\n/** Parse a draft into a bounded whole number; `undefined` means \"do not write\". */\nfunction parseInteger(raw: string, min: number, max: number | undefined): number | undefined {\n const trimmed = raw.trim()\n if (!/^-?\\d+$/.test(trimmed)) return undefined\n const parsed = Number(trimmed)\n if (!Number.isSafeInteger(parsed) || parsed < min || (max !== undefined && parsed > max)) return undefined\n return parsed\n}\n\n/**\n * The plugin's configuration card. `view: 'summary'` is the one-liner the\n * contract allows an owner to ask for; the Plugins page today only ever asks\n * for `'page'`, which is the full two-group form.\n */\nexport function PluginConfigCard(props: PluginConfigViewPropsLike): ReactNode {\n const t = translateOf(props.t)\n // The injected face is cached per entry, so `props.form` is stable and this\n // memo resolves the factory exactly once per entry.\n const source = useMemo(() => formSourceOf(props.form), [props.form])\n const snapshot = useSyncExternalStore(\n source === null ? subscribeNone : source.subscribe,\n source === null ? noFormSnapshot : source.getSnapshot,\n )\n if (props.view === 'summary') {\n return h('div', { style: QUIET }, t('configSummary'))\n }\n if (source === null || snapshot.status === 'unavailable') {\n return h('div', { style: QUIET }, t('configUnavailable'))\n }\n if (snapshot.status === 'loading') {\n return h('div', { style: QUIET }, t('configLoading'))\n }\n const disabled = !snapshot.writable\n return h(\n 'div',\n null,\n disabled ? h('div', { style: { ...QUIET, marginBottom: 8 } }, t('configReadOnly')) : null,\n fieldGroup('activation', 'configGroupActivation', ACTIVATION_FIELDS, snapshot, source.form, t, disabled),\n fieldGroup('runtime', 'configGroupRuntime', RUNTIME_FIELDS, snapshot, source.form, t, disabled),\n )\n}\n\n/** One titled group of setting rows, in the shape DSH's own settings pages use. */\nfunction fieldGroup(\n group: string,\n titleKey: LocaleKey,\n fields: readonly FieldDef[],\n snapshot: ConfigFormSnapshotLike,\n form: ConfigFormLike,\n t: Translate,\n disabled: boolean,\n): ReactNode {\n return h(\n 'section',\n { key: group, style: group === 'activation' ? undefined : STYLE.settingGroup },\n h('div', { style: STYLE.settingGroupHead }, t(titleKey)),\n fields.map((def, index) =>\n h(FieldRow, {\n key: def.key,\n def,\n snapshot,\n form,\n t,\n disabled,\n last: index === fields.length - 1,\n }),\n ),\n )\n}\n\ninterface FieldRowProps {\n readonly def: FieldDef\n readonly snapshot: ConfigFormSnapshotLike\n readonly form: ConfigFormLike\n readonly t: Translate\n readonly disabled: boolean\n readonly last: boolean\n}\n\n/** One setting row: label and hint left, control right, reset when overridden. */\nfunction FieldRow(props: FieldRowProps): ReactNode {\n const { def, snapshot, form, t, disabled, last } = props\n const overridden = hasOverride(snapshot.user, def.key)\n const value = fieldValue(def, snapshot)\n const label = t(def.label)\n const control =\n def.kind === 'boolean'\n ? h(BooleanControl, {\n label,\n value: value as boolean,\n disabled,\n onToggle: (next: boolean) => void form.set(def.key, next),\n })\n : def.kind === 'integer'\n ? h(IntegerControl, {\n label,\n value: value as number,\n disabled,\n min: def.min ?? 0,\n max: def.max,\n t,\n onCommit: (next: number) => void form.set(def.key, next),\n })\n : h(TextControl, {\n label,\n value: value as string,\n disabled,\n t,\n onCommit: (next: string) => void form.set(def.key, next),\n })\n return h(\n 'div',\n { style: last ? { ...STYLE.settingRow, ...STYLE.lastRow } : STYLE.settingRow },\n h(\n 'div',\n { style: STYLE.settingRowText },\n h(\n 'span',\n { style: STYLE.settingRowLabel },\n label,\n overridden ? h('span', { style: OVERRIDDEN_CHIP }, t('configOverridden')) : null,\n ),\n h('span', { style: STYLE.settingRowDesc }, t(def.hint)),\n ),\n h(\n 'div',\n { style: STYLE.settingRowControl },\n control,\n overridden\n ? h(\n 'button',\n {\n type: 'button',\n style: RESET_BUTTON,\n disabled,\n title: t('configResetHint'),\n 'aria-label': `${t('configReset')}: ${label}`,\n onClick: () => void form.unset(def.key),\n },\n t('configReset'),\n )\n : null,\n ),\n )\n}\n\ninterface BooleanControlProps {\n readonly label: string\n readonly value: boolean\n readonly disabled: boolean\n readonly onToggle: (next: boolean) => void\n}\n\n/** The settings pages' sliding switch, bound to one boolean field. */\nfunction BooleanControl(props: BooleanControlProps): ReactNode {\n return h(\n 'button',\n {\n type: 'button',\n role: 'switch',\n 'aria-checked': props.value,\n 'aria-label': props.label,\n disabled: props.disabled,\n style: props.value ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n onClick: () => props.onToggle(!props.value),\n },\n h('span', {\n style: props.value ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob,\n 'aria-hidden': true,\n }),\n )\n}\n\ninterface IntegerControlProps {\n readonly label: string\n readonly value: number\n readonly disabled: boolean\n readonly min: number\n readonly max: number | undefined\n readonly t: Translate\n readonly onCommit: (next: number) => void\n}\n\n/**\n * A bounded whole-number input. The draft is local; only a dirty draft commits,\n * on blur or Enter — a blur with no edit writes nothing. An invalid draft\n * never reaches `form.set` — it marks the control and explains the bound\n * instead. Escape abandons the draft.\n */\nfunction IntegerControl(props: IntegerControlProps): ReactNode {\n const [draft, setDraft] = useState<string | undefined>(undefined)\n const [invalid, setInvalid] = useState(false)\n const invalidText =\n props.max === undefined\n ? props.t('configInvalidInteger', { min: props.min })\n : props.t('configInvalidRange', { min: props.min, max: props.max })\n const commit = (raw: string): void => {\n const parsed = parseInteger(raw, props.min, props.max)\n if (parsed === undefined) {\n setInvalid(true)\n return\n }\n setInvalid(false)\n setDraft(undefined)\n props.onCommit(parsed)\n }\n return h(\n 'span',\n { style: { display: 'inline-flex', flexDirection: 'column', gap: 2 } },\n h('input', {\n type: 'number',\n inputMode: 'numeric',\n step: 1,\n min: props.min,\n ...(props.max === undefined ? {} : { max: props.max }),\n style: invalid ? { ...STYLE.input, ...INPUT_WIDTH, ...INPUT_INVALID } : { ...STYLE.input, ...INPUT_WIDTH },\n value: draft ?? String(props.value),\n disabled: props.disabled,\n 'aria-label': props.label,\n 'aria-invalid': invalid || undefined,\n onChange: (event: { target: { value: string } }) => {\n setDraft(String(event.target.value))\n if (invalid) setInvalid(false)\n },\n onBlur: () => {\n // Commit only a dirty draft: a blur with no edit must not write the\n // displayed snapshot value (it would pin a phantom override), and the\n // Enter path clears the draft, so an Enter-then-blur no-ops instead of\n // committing the stale value the input fell back to.\n if (draft !== undefined) commit(draft)\n },\n onKeyDown: (event: { key: string }) => {\n if (event.key === 'Enter') {\n if (draft !== undefined) commit(draft)\n } else if (event.key === 'Escape') {\n setDraft(undefined)\n setInvalid(false)\n }\n },\n }),\n invalid ? h('span', { role: 'alert', style: INVALID_NOTE }, invalidText) : null,\n )\n}\n\ninterface TextControlProps {\n readonly label: string\n readonly value: string\n readonly disabled: boolean\n readonly t: Translate\n readonly onCommit: (next: string) => void\n}\n\n/** The local-prefix input: same commit discipline as the numbers, prefix rule. */\nfunction TextControl(props: TextControlProps): ReactNode {\n const [draft, setDraft] = useState<string | undefined>(undefined)\n const [invalid, setInvalid] = useState(false)\n const commit = (raw: string): void => {\n if (!isValidLocalPrefix(raw)) {\n setInvalid(true)\n return\n }\n setInvalid(false)\n setDraft(undefined)\n props.onCommit(raw)\n }\n return h(\n 'span',\n { style: { display: 'inline-flex', flexDirection: 'column', gap: 2 } },\n h('input', {\n type: 'text',\n maxLength: LOCAL_PREFIX_MAX,\n style: invalid ? { ...STYLE.input, ...INPUT_WIDTH, ...INPUT_INVALID } : { ...STYLE.input, ...INPUT_WIDTH },\n value: draft ?? props.value,\n placeholder: '—',\n disabled: props.disabled,\n 'aria-label': props.label,\n 'aria-invalid': invalid || undefined,\n onChange: (event: { target: { value: string } }) => {\n setDraft(String(event.target.value))\n if (invalid) setInvalid(false)\n },\n onBlur: () => {\n // Same commit discipline as the number input: dirty drafts only.\n if (draft !== undefined) commit(draft)\n },\n onKeyDown: (event: { key: string }) => {\n if (event.key === 'Enter') {\n if (draft !== undefined) commit(draft)\n } else if (event.key === 'Escape') {\n setDraft(undefined)\n setInvalid(false)\n }\n },\n }),\n invalid\n ? h('span', { role: 'alert', style: INVALID_NOTE }, props.t('configInvalidPrefix', { max: LOCAL_PREFIX_MAX }))\n : null,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Registration — the `plugins.bundle.config` entry, parked on the configForms\n// service so the card appears exactly when the host serves the namespace\n// ---------------------------------------------------------------------------\n\nconst PLUGIN_CONFIG_SLOT = 'plugins.bundle.config'\nconst PRIMARY_CONFIG_NS = 'dsh-project-mcp'\nconst LEGACY_CONFIG_NS = 'project-mcp'\n\n/** The slot-services slice the registration needs, mirroring settings.ts. */\nexport interface PluginConfigSlotServices {\n effect(execute: () => unknown, label?: string): unknown\n slots: {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(\n options: {\n name: string\n key: string\n locale: string\n inject: () => Record<string, unknown>\n },\n component: (props: Props) => ReactNode,\n ): unknown\n }\n configForms: ConfigFormsLike\n}\n\n/**\n * Register the card on the Plugins page.\n *\n * The keyed slot's options are exactly `{ name, key, locale, inject }` — the\n * `id`/`order`/`label` options of list slots do not exist here. `whileServed`\n * watches both config namespaces and prefers the plugin's own; the register\n * callback fires once, when the first watched namespace becomes served (there\n * is no re-fire while any of them stays served), and its returned disposer —\n * the one `slots.inject` hands back — runs when the last one disappears.\n */\nexport function registerPluginConfigCard(services: PluginConfigSlotServices): void {\n const forms = services.configForms\n services.effect(\n () =>\n forms.whileServed([PRIMARY_CONFIG_NS, LEGACY_CONFIG_NS], (served) => {\n const ns = served.has(PRIMARY_CONFIG_NS) ? PRIMARY_CONFIG_NS : LEGACY_CONFIG_NS\n // `slots.inject` keeps registration a no-op on a composition whose\n // slots registry does not declare the slot (an older host) — the card\n // is simply absent there, nothing throws.\n const dispose = services.slots.inject(PLUGIN_CONFIG_SLOT, () =>\n services.slots.register(\n {\n name: PLUGIN_CONFIG_SLOT,\n key: PACKAGE_NAME,\n locale: NS,\n inject: () => ({ form: () => forms.get(ns) }),\n },\n (props: PluginConfigViewPropsLike) => h(PluginConfigCard, props),\n ),\n )\n return typeof dispose === 'function' ? (dispose as () => void) : (): void => undefined\n }),\n 'project-mcp: plugin config card',\n )\n}\n","/**\n * Every word the plugin's client half shows a person, in the three languages it\n * ships. The tables in `view.ts` and `settings.ts` stay where they are — they are\n * the runtime's English fallback and their key types are what makes a missing\n * translation a compile error here:\n *\n * `en` is the merge of both halves (`settings.ts` first, the panel last — the\n * order the runtime registration registers it), `UiKey` is the union of both key\n * types, and all three tables are declared `Record<UiKey, string>` — as an\n * annotated object literal, so the compiler reads every key of the union off the\n * literal itself and a key that exists in one language and not another does not\n * build.\n *\n * Composed here rather than at the registration site, so the merge sits at the\n * source of the two halves and is read against their own key types. That is a\n * preference, not the gate: the gate is whichever form a table is written in,\n * and both forms the translation tasks use — the annotated literal above and\n * `{ … } satisfies Record<UiKey, string>` — reject a short table the same way\n * (probed: identical `TS2740`, `… and 266 more`).\n *\n * The `zh` and `ru` tables are authored by the maintainers, not by a native\n * speaker, and are pending review: see the release notes for 0.2.0.\n *\n * @module src/client/locales/ui\n */\n\nimport { EN as configEn } from '../plugin-config.ts'\nimport type { LocaleKey as PluginConfigLocaleKey } from '../plugin-config.ts'\nimport { EN, NS } from '../settings.ts'\nimport type { LocaleKey as SettingsLocaleKey } from '../settings.ts'\nimport type { TabLocale } from '../tab-locale.ts'\nimport { en as viewEn } from '../view.ts'\nimport type { LocaleKey as ViewLocaleKey, Translate } from '../view.ts'\n\n/** Every key the `settings.projectMcp` namespace carries. */\nexport type UiKey = ViewLocaleKey | SettingsLocaleKey | PluginConfigLocaleKey\n\n/**\n * The merged English table, built on first read rather than at module\n * evaluation. `settings.ts` imports this module for {@link uiTranslate} while\n * this module imports `EN` from `settings.ts`, so which of the two evaluates\n * first depends on the entry point — and a spread of the not-yet-initialized\n * half would silently drop every settings key from the fallback. Deferring the\n * merge past module evaluation keeps the table complete in either order.\n */\nlet english: Record<UiKey, string> | undefined\nfunction mergedEnglish(): Record<UiKey, string> {\n return (english ??= { ...EN, ...viewEn, ...configEn })\n}\n\n/** English, and the runtime fallback for any language that lacks a key. */\nexport const en: Record<UiKey, string> = new Proxy({} as Record<UiKey, string>, {\n get: (_target, property) => Reflect.get(mergedEnglish(), property),\n has: (_target, property) => Reflect.has(mergedEnglish(), property),\n ownKeys: () => Reflect.ownKeys(mergedEnglish()),\n getOwnPropertyDescriptor: (_target, property) =>\n Object.getOwnPropertyDescriptor(mergedEnglish(), property),\n})\n\n/**\n * Chinese, complete across the namespace: every key of `UiKey` is written out\n * below — the view half (the tab and its blocks) first, then the settings half\n * in `settings.ts` order — so the `Record<UiKey, string>` annotation itself\n * proves completeness. Its key order is the canonical one for future\n * additions.\n */\nexport const zh: Record<UiKey, string> = {\n // The tab itself: its label in the sidebar and the line under it.\n tab: '项目 MCP',\n tabDescription: '各项目声明的 MCP 服务器,以及为其会话挂载的内容',\n sync: '同步',\n retryFailed: '重试失败项',\n // Tool presentation: the tab's tools block and the settings page's Tools rows.\n toolsSeeModel: '模型所见',\n toolsPinned: '已置顶',\n toolsByCounters: '按计数器',\n toolsDisclosed: '已披露',\n toolsHidden: '已隐藏',\n toolsNotMounted: '暂无可隐藏的工具',\n toolsNotMountedHint:\n '惰性挂载:项目的服务器在会话的第一步才启动,因此工具目录在此之前为空',\n toolsNotMountedCode: 'tools[] = built-ins only · mcp__* not registered yet',\n // The declared servers of this session, on the tools block: the reason an\n // apparently empty catalog is empty.\n toolsServers: '服务器',\n toolsServersUp: '{up}/{total} 运行中',\n toolsGroupPinned: '已置顶 · 始终在请求中',\n toolsGroupCounters: '由计数器提供',\n toolsGroupDisclosed: '由模型披露 · 直至会话结束',\n toolsGroupHidden: '已隐藏',\n toolsPin: '置顶',\n toolsPinHint: '让此工具保留在此项目的每次请求中',\n toolsUnpin: '取消置顶',\n toolsUnpinHint: '取消在此项目的每次请求中置顶此工具',\n toolsHide: '隐藏',\n toolsHideHint: '放弃此次披露,不再提供此工具',\n toolsHiddenVia: '模型只能通过 mcp_search_tools 使用',\n // The tools block's own filter (F-43): the counter chips above the list stop\n // being a reading and become the tier switch, and a query narrows by name.\n toolsFilterPlaceholder: '按名称过滤…',\n toolsFilterLabel: '按注册表名过滤此会话的工具',\n toolsFilterTier: '只显示此层级;再按一次显示全部层级',\n toolsFilterClear: '清除',\n toolsFilterClearHint: '显示全部层级并清空查询',\n toolsFilterShown: '显示 {shown}/{total}',\n toolsFilterNone: '此会话没有符合过滤条件的工具。',\n // The server-level pin (F-44): one press for a whole server's names, since a\n // server is how the hidden tier and the settings page both group them.\n toolsPinAll: '全部置顶',\n toolsPinAllHint: '在每次请求中置顶此服务器的所有隐藏工具',\n // The other direction of the same press, said by both surfaces when the set\n // is already wholly pinned.\n toolsUnpinAll: '全部取消置顶',\n toolsUnpinAllHint: '取消置顶此服务器的所有隐藏工具',\n // The same press on the pinned tier, where the names it releases are the ones\n // the user pinned rather than the ones the host hid.\n toolsUnpinServerHint: '取消置顶此服务器的所有工具',\n toolsBudget: '{used}/{total} 字符 · ≈ {tokens} token',\n toolsBudgetExhausted: '预算已用尽:后续披露将被拒绝并说明原因',\n toolsBudgetFree: '腾出预算空间,或在项目设置中置顶此工具',\n toolsBudgetGateOff: '披露门控已关闭:所有已挂载的工具都会进入请求',\n toolsBudgetBreakdown: '{used}/{total}({percent}%)',\n toolsModeOff: '此项目的 MCP 工具已关闭',\n toolsModeOffCounters: '已挂载 {mounted} 个 · 均未提供',\n toolsModeOffHint:\n '此项目的工具都不会提供给模型。在「工具」页将模式设为「披露」即可重新提供。',\n toolsModeDirect: '全部直接:所有已挂载的工具都会进入请求',\n toolsPresentationOwner: '另一个插件正在主导请求的呈现',\n toolsOtherOwner: '其他呈现所有者',\n toolsDemo: '演示',\n toolsStep: '第 {step} 步',\n // The host's own usage counters: how often one tool was called, and how\n // long one server has gone unused.\n callsOne: '1 次调用',\n callsMany: '{count} 次调用',\n callsNone: '从未调用',\n callsProject: '项目中 {count} 次',\n idleDay: '闲置 {count} 天',\n idleHour: '闲置 {count} 小时',\n idleMinute: '闲置 {count} 分钟',\n // One tool row's detail block (F-56): the serving server with its state, the\n // tier as a sentence, the two counter readings, then the host's own answer\n // about the definition. The header keeps the name, the clock and the step, and the\n // body prints them again in its fact line: that is what the contract's own probe reads\n // out of the open disclosure (`contracts/surfaces.md` §1.5).\n toolServer: '服务器 {server}',\n toolServerState: '{server} · {state}',\n toolTierPinned: '已置顶 — 始终在请求中',\n toolTierSession: '由本次会话提供',\n toolTierContext: '由上下文排序提供',\n showTool: '显示此工具的服务器、说明、字段及其提供方式',\n hideTool: '隐藏此工具的详细信息',\n toolCallsSession: '本次会话 {count} 次',\n toolLoading: '正在从宿主读取此定义…',\n toolFailed: '宿主没有对此定义作答',\n toolFieldsLabel: '接受',\n toolFieldRequiredHint: '必填字段',\n toolReasonBudget: '未提供:{chars} 字符,超出 {budget} 字符的预算',\n toolReasonChars: '{chars} 字符',\n toolReasonBudgetOnly: '{budget} 字符的预算',\n toolReasonUsed: '已提供 {used}',\n toolReason: '未提供',\n // The errors and logs blocks, under their own disclosures: the event ring is\n // the plugin's own, one project at a time.\n errorsSection: '问题',\n showErrors: '显示需要查看的服务器',\n hideErrors: '隐藏需要查看的服务器',\n logsSection: '日志',\n showLogs: '显示此项目的事件',\n hideLogs: '隐藏此项目的事件',\n logsThisSession: '本会话',\n logsAllSessions: '全部会话',\n logsAllLevels: '全部级别',\n logsErrorsOnly: '错误',\n logsLevelInfo: 'info',\n logsLevelUp: 'up',\n logsLevelWarn: 'warn',\n logsLevelError: 'error',\n logsClear: '清除',\n logsClearHint: '隐藏目前已记录的所有事件;新事件仍会出现',\n logsEmptyTitle: '暂无事件',\n logsEmptyHint:\n '项目的服务器会在会话的第一步启动,或在你按下「同步」时启动;挂载、启动和停止都会显示在这里。',\n logsNoErrorsTitle: '没有错误',\n logsNoErrorsHint:\n '本项目的事件环中存有其他事件;把级别过滤器切到「全部级别」即可查看。',\n logsMore: '显示更早',\n logsMoreHint: '加载比当前屏幕上更早的事件',\n logsShown: '显示 {shown}/{total}',\n logsProjectCount: '本项目 {count} 条',\n logsLoading: '正在加载更早的事件…',\n logsLoadFailed: '无法读取更早的事件',\n // The tab's own states, in the same table for the same reason.\n noSession: '此标签页没有关联会话。',\n noSessionHint: '面板读取的是它所在会话的项目。',\n noProject: '此会话的文件夹还不在任何项目内。',\n noProjectHint:\n '宿主会从此会话的 cwd 向上查找 .git · .dsh · .kimi-code · package.json · *.sln。',\n nothingNeedsAttention: '无需关注。',\n noServersDeclared: '此项目未声明任何 MCP 服务器。',\n noServersDeclaredHint: '添加 {documents}。',\n noServersDeclaredUnknown: '请向项目添加一份 MCP 文档。',\n noServersDeclaredNowhere:\n '此部署不读取任何项目文档,因此无处声明——请在插件配置(`localFiles`)中列出一个。',\n // Surface A's own header and the vocabulary its rows are built from. The\n // segment bar is gone (F-26): the toolbar names the project and carries one\n // phrase on its right edge, and every count a mode segment used to badge lives\n // on the block it describes.\n thisSession: '本会话',\n noProjectLabel: '无项目',\n retry: '重试',\n retryHint: '立即重试此项目失败的挂载',\n sessionsSection: '会话',\n // The `sessions` section is the project's *disagreement* view: its chip counts\n // the sessions whose own reading differs from the merged rows, not the\n // sessions that exist.\n differsOne: '1 个会话不一致',\n differsMany: '{count} 个会话不一致',\n sessionsOne: '1 个会话',\n sessionsMany: '{count} 个会话',\n serversOne: '1 个服务器',\n serversMany: '{count} 个服务器',\n mergedAcrossSessions: '跨会话合并',\n release: '释放',\n nothingDeclared: '无声明',\n showSessions: '显示此项目的会话',\n hideSessions: '隐藏此项目的会话',\n showSession: '显示此会话的服务器',\n hideSession: '隐藏此会话的服务器',\n mountedPerProject: '按项目挂载',\n projectsCount: '{count} 个项目',\n nothingMounted: '尚未挂载任何内容。',\n // The status vocabulary (F-47): the word a row wears and the one-line\n // explanation its tooltip carries.\n statusActive: '运行中',\n statusConnecting: '连接中',\n statusConflict: '冲突',\n statusError: '错误',\n statusIdle: '闲置',\n statusDisabled: '已禁用',\n statusHintActive: '已挂载,其工具在本会话中可见',\n statusHintConnecting: '已挂载,尚未发布任何工具',\n statusHintIdle: '已声明但未挂载——将在下一轮挂载',\n statusHintDisabled: '以 enabled: false 声明',\n statusHintConflict: '同名 serverName 已被配置文件级实例占用',\n statusHintError: '查看详情',\n // The status line of a project or session: one template per status, the\n // count always a `{count}` placeholder.\n summaryActive: '{count} 个运行中',\n summaryConnecting: '{count} 个连接中',\n summaryIdle: '{count} 个闲置',\n summaryDisabled: '{count} 个已禁用',\n summaryError: '{count} 个错误',\n summaryConflict: '{count} 个冲突',\n summaryNone: '无声明',\n close: '关闭',\n // The frame-wide toasts (F-47): one keyed line per lifecycle moment, and the\n // quieter line weaving the project around the fact behind it.\n toastUp: '{server} 已启动',\n toastFailed: '{server} 失败',\n toastReleased: '{server} 已释放',\n toastDetail: '{project} · {detail}',\n // The poll interval's row in the tab's settings panel.\n refreshTitle: '刷新间隔',\n refreshDesc: '面板重新读取宿主快照的频率',\n // The tab's actions menu: the row that opens the settings popup.\n settingsMenuItem: '面板设置…',\n // The design stand's own tab title and description.\n designTitle: '项目 MCP · 设计 ({variant})',\n designDesc: '设计模式:{variant} 夹具,背后没有宿主',\n // Settings half, in `settings.ts` order: the overview table, its states and\n // the read-only reasons of its rows.\n project: '项目',\n projectsOne: '1 个项目有活动会话',\n projectsMany: '{count} 个项目有活动会话',\n viewTable: '表格',\n viewFiles: '按文件',\n syncHint: '立即重新读取宿主快照',\n server: '服务器',\n transport: '传输',\n status: '状态',\n source: '来源',\n on: '开',\n servers: '服务器',\n paneEntry: '条目',\n name: '名称',\n detail: '详情',\n loading: '正在读取宿主快照…',\n loadingHint: '页面一打开就会轮询 /project-mcp/snapshot。',\n hostUnavailable: '页面没有收到插件宿主的应答。',\n hostUnavailableHint:\n '宿主侧提供 {route};它只在 dsh web 重启后才拾取变更——请查看日志。',\n noSessions: '还没有会话关联到任何项目。',\n noSessionsHint:\n '当会话开始在项目文件夹内工作时服务器才会启动——没有会话的项目不会挂载任何内容。',\n noSessionsPaths: '读取:{paths}',\n noSessionsNoPaths:\n '此部署不读取任何 MCP 文档——请在插件配置(`localFiles`、`globalFiles`)中列出要读取的文档',\n noServers: '此项目未声明任何 MCP 服务器。',\n noServersHint: '没有任何声明,因此不会为其会话挂载任何内容。',\n noServersNoPath: '此部署不读取任何项目文档,因此无处声明。',\n documentUnknown: '声明文档未知',\n global: '全局',\n priority: '优先级 {tier}/{total}',\n overrideFrom: '↳ 覆盖来自 {from} 的 {name}',\n overrideUnpinned: '↳ 覆盖在更低优先级文档中声明的 {name}',\n nameReason: '只读:服务器名是宿主报告的声明键。',\n statusReason: '只读:状态来自运行中的宿主,而非文档。',\n sourceReason: '只读:声明文档的路径来自宿主。',\n detailReason: '只读:宿主会隐去这段文本,且从不包含参数。',\n openToEdit: '此处只读:打开服务器以编辑其条目。',\n rowActionsMore: '…',\n rowActionsHint: '在编辑器中打开此条目',\n showJson: '显示 JSON',\n hideJson: '隐藏 JSON',\n jsonPreview: '快照 JSON',\n jsonPreviewHint: '读取自宿主快照;磁盘上的文档不会被触碰。',\n back: '返回列表',\n backHint: '返回概览,不做任何更改',\n // Editor: the fields of the parsed entry.\n entryUnavailable: '宿主未能解析此条目,因此没有可编辑的内容。',\n commandField: '命令',\n argsField: '参数',\n cwdField: 'CWD',\n urlField: 'URL',\n envField: 'Env',\n headersField: '请求头',\n enabledField: '启用',\n timeoutField: '超时',\n keyField: '键',\n valueField: '值',\n argsHint: '每行一个参数;每一行都原样写入。',\n envHint: '每个键一个值;表单中删去的键会从条目中移除。',\n headersHint: '每个请求头一个值;表单中删去的键会从条目中移除。',\n timeoutHint: '毫秒;留空表示声明不设置超时。',\n enabledValue: '启用:{value}',\n absent: '未设置',\n maskedValue: '•••• 未更改——输入以替换',\n valuePlaceholder: '值',\n keyPlaceholder: 'KEY',\n credentialsNote:\n '来自外部来源——项目的 .env 或凭据文件——而非此文档:它会被原样显示并原样写回。',\n credentialValue: '来自项目的 .env 或凭据文件',\n addKey: '添加键',\n addKeyHint: '追加一个空键;未命名的键不会被写入。',\n removeKey: '✕',\n removeKeyHint: '删去此键;被删去的键会从条目中移除。',\n // Writing.\n editableNote:\n '正在编辑 {document}:「保存」会要求确认、先备份到 {backup} 并整体重写该条目。',\n writeBlocked: '只读:{reason}',\n writeBlockedUnknown: '宿主未报告此文档为何不可写入。',\n save: '保存…',\n saveHint: '打开此次写入的确认',\n saveNoChange: '还没有可保存的更改。',\n saveUnavailable: '快照没有携带可写回的声明文档或修订版本。',\n saveTimeoutInvalid: '超时不是以毫秒为单位的整数。',\n saving: '正在写入…',\n discard: '放弃',\n discardHint: '从快照恢复所有字段,不写入任何内容',\n discardReason: '还没有可恢复的更改。',\n unsaved: '未保存',\n jsonDiff: 'diff',\n jsonClean: '无更改',\n jsonUnavailable: '无已解析的条目',\n jsonInvalid: 'JSON 无法解析为条目:{reason}',\n jsonEditHint: '按文档声明的形式编辑条目',\n saveJsonInvalid: '请先修复 JSON 窗格:它无法解析为条目。',\n footerWrite: '→ {document} · .bak 副本 · 确认',\n footerReadonly: '→ {document} · 只读',\n confirmTitle: '写入 {document}?',\n confirmBackup: '当前文档会先被复制到 {backup}。',\n confirmFormat:\n '该条目会整体替换 mcpServers[{server}]。文档将以两空格缩进和末尾换行重新序列化,因此文档其余部分的缩进和键顺序会被规范化。',\n confirmConsent:\n '这是一个全局文档:每个项目都会读取它,因此写入需要明确同意。',\n consentLabel: '我理解这会重写一个所有项目共享的全局文档。',\n confirmWrite: '写入文档',\n confirmWriteHint: '通过上述检查后写入文档',\n confirmBlocked: '请先勾选同意框:没有它的全局写入会被拒绝。',\n cancel: '取消',\n saveOk: '已保存:文档已写入并重新读取。',\n saveErrorInvalid:\n '宿主拒绝了该条目:它不是此插件会挂载的条目。未写入任何内容。',\n saveErrorBlocked:\n '此层级不允许写入该文档,或缺少同意。未写入任何内容。',\n saveErrorConflict: '自此快照取得以来文档已更改。未写入任何内容。',\n saveErrorNotFound: '文档或服务器已不存在。未写入任何内容。',\n saveErrorFailed: '写入本身失败;文档保持原样。未写入任何内容。',\n hostMessage: '宿主返回:{message}',\n reRead: '重新读取',\n reReadHint: '重新获取宿主快照并据此重建表单',\n // Our own two pages, and the disclosure policy page next to `Servers`.\n tabServers: '服务器',\n tabTools: '工具',\n policyNote: '此项目遵循的模式,以及为它置顶的工具',\n checkConflicts: '检查冲突',\n checkConflictsHint:\n '宿主为此项目报告的冲突服务器名读取自其快照;此按钮会立即重新读取快照',\n conflictsNone: '此项目没有冲突的服务器名',\n conflictProfile: '配置文件级名称',\n conflictDuplicate: '重复声明',\n conflictSources: '声明于 {sources}',\n choiceLabel: '显示',\n choiceLocal: '此项目的副本,作为 {alias}',\n choiceProfileHint: '保持配置文件实例的工具原样不变',\n choiceLocalHint:\n '将此项目自己的声明挂载在配置文件声明旁边,使用本地名 {alias}',\n choiceNative: '此项目的声明,使用其自身名称',\n choiceNativeHint:\n '将此项目自己的声明按其声明的名称挂载:它在此项目中更近,因此在此它会遮蔽配置文件实例的工具,而其他所有项目仍照常看到它们',\n choiceRefused: '宿主拒绝了该选择:',\n toolsCount: '工具',\n pinned: '已置顶',\n mode: '模式',\n modeDisclosure: '披露',\n modeDirect: '全部直接',\n modeOff: 'off',\n modeHint: '立即写入,在宿主组装的下一个请求上生效',\n modeRefused: '宿主拒绝了该模式:',\n pinRefused: '宿主拒绝了该置顶:',\n pinList: '已置顶 · 手写维护,在每次请求中提供',\n pinListEmpty: '还没有置顶——在下方工具列表中开启一个',\n serverAllOffered: '其全部 {count} 个工具都直接提供',\n serverPartlyOffered: '{total} 个工具中 {offered} 个直接提供',\n // The server-level pin (F-44): one switch for the whole server row, above the\n // per-name rows it stands for.\n serverPin: '置顶此服务器的工具',\n serverPinHint: '置顶此服务器挂载的每个工具——包括隐藏的——让每个请求都携带它们',\n serverUnpin: '取消置顶此服务器的工具',\n serverUnpinHint: '停止置顶此服务器的工具',\n prefixFact: 'mcp__<server>__<tool>;前缀由注册表添加,而非本页',\n pinTag: 'pin',\n moreTools: '… 还有 {count} 个',\n requestPreview: '请求预览',\n requestPreviewTools: 'tools[] = {count}',\n requestPreviewTokens: '≈ {tokens} token',\n requestPreviewHidden: '已隐藏 {count} 个',\n requestPreviewSaved: '已隐藏 {count} 个 · 节省 ≈ {tokens} token',\n requestPreviewNoOffer: '此会话尚未向模型提供任何工具',\n // The plugin's own configuration card (F-54), the newest keys last.\n configSummary: '编辑本插件的激活与运行时配置',\n configGroupActivation: '激活',\n configGroupRuntime: '运行时',\n configLoading: '正在加载配置…',\n configUnavailable: '宿主未向此客户端提供本插件的配置。',\n configReadOnly: '此客户端的偏好为进程内有效,因此此处这些值为只读。',\n configOverridden: '已覆盖',\n configReset: '重置',\n configResetHint: '清除此覆盖,恢复默认值',\n configInvalidInteger: '请输入 ≥ {min} 的整数',\n configInvalidRange: '请输入 {min} 到 {max} 之间的整数',\n configInvalidPrefix: '最多 {max} 个字符:字母、数字、“_” 或 “-”',\n configActivationEnabled: '工具激活',\n configActivationEnabledHint: '渐进式提供 MCP 工具——计数、披露与搜索门控',\n configActivationSeeded: '预置工具数',\n configActivationSeededHint: '在计数累计之前,从第一步就提供的工具数;0 表示不预置',\n configActivationMinCalls: '固定所需调用次数',\n configActivationMinCallsHint: '计数器在调用达到此次数后直接固定该工具',\n configToolIdleMs: '工具闲置超时(毫秒)',\n configToolIdleMsHint: '工具超过此时长未使用将从请求中移除',\n configGuidanceEnabled: '系统提示指引',\n configGuidanceEnabledHint: '将本插件的使用说明注入会话提示',\n configActivationAutoLimit: '自动激活上限',\n configActivationAutoLimitHint: '计数器最多可自行加入的工具数(0–50)',\n configActivationAutoStickySteps: '黏滞步数',\n configActivationAutoStickyStepsHint: '刚使用过的工具无论计数如何都保持固定的步数(0–20)',\n configActivationToolBudgetChars: '工具预算(字符)',\n configActivationToolBudgetCharsHint: '单次请求携带的工具模式字符预算(≥ 1000)',\n configAllowGlobalWrite: '允许全局写入',\n configAllowGlobalWriteHint: '允许保存到用户级(~/.dsh)配置',\n configEnvFiles: '.env 文件',\n configEnvFilesHint: '为服务器环境变量加载 .env 文件',\n configLazy: '惰性挂载',\n configLazyHint: '在会话的第一步启动项目服务器,而非启动时',\n configLocalPrefix: '本地前缀',\n configLocalPrefixHint: '本地工具名前缀——最多 5 个字符,仅限 A–Z、0–9、_ 或 -;留空则禁用',\n configProfileWins: '配置档优先',\n configProfileWinsHint: '同名服务器以配置档级覆盖项目声明',\n configConnectTimeoutMs: '连接超时(毫秒)',\n configConnectTimeoutMsHint: '启动单个服务器允许的最长时长',\n configToolCallTimeoutMs: '调用超时(毫秒)',\n configToolCallTimeoutMsHint: '单次工具调用允许的最长时长',\n configIdleTimeoutMs: '服务器闲置超时(毫秒)',\n configIdleTimeoutMsHint: '服务器闲置超过此时长将被停止',\n configDebounceMs: '监听去抖(毫秒)',\n configDebounceMsHint: '配置变更触发重新扫描前的静默时长',\n configActivationWaitMs: '激活等待(毫秒)',\n configActivationWaitMsHint: '第一步等待惰性服务器就绪的最长时长',\n}\n\n/**\n * Russian, complete across the namespace: every key of `UiKey` is written out\n * below, so the `Record<UiKey, string>` annotation itself proves completeness.\n */\nexport const ru: Record<UiKey, string> = {\n // The tab itself: its label in the sidebar and the line under it.\n tab: 'MCP проекта',\n tabDescription:\n 'MCP-серверы, которые объявляет проект, и что смонтировано для его сессий',\n sync: 'Синхронизировать',\n retryFailed: 'Повторить неудачные',\n // Tool presentation: the tab's tools block and the settings page's Tools rows.\n toolsSeeModel: 'что видит модель',\n toolsPinned: 'закреплённые',\n toolsByCounters: 'по счётчикам',\n toolsDisclosed: 'раскрытые',\n toolsHidden: 'скрытые',\n toolsNotMounted: 'Пока скрывать нечего',\n toolsNotMountedHint:\n 'ленивое монтирование: серверы проекта поднимаются на первом шаге сессии, поэтому каталог пока пуст',\n toolsNotMountedCode: 'tools[] = built-ins only · mcp__* not registered yet',\n // The declared servers of this session, on the tools block.\n toolsServers: 'Серверы',\n toolsServersUp: '{up}/{total} работают',\n toolsGroupPinned: 'закреплённые · всегда в запросе',\n toolsGroupCounters: 'предлагаются счётчиками',\n toolsGroupDisclosed: 'раскрыты моделью · до конца сессии',\n toolsGroupHidden: 'скрытые',\n toolsPin: 'Закрепить',\n toolsPinHint: 'Держать этот инструмент в каждом запросе проекта',\n toolsUnpin: 'Открепить',\n toolsUnpinHint: 'Больше не закреплять этот инструмент в запросах проекта',\n toolsHide: 'Скрыть',\n toolsHideHint: 'Снять это раскрытие и перестать предлагать инструмент',\n toolsHiddenVia: 'доступен модели только через mcp_search_tools',\n // The tools block's own filter: the tier switch and the name query.\n toolsFilterPlaceholder: 'фильтр по имени…',\n toolsFilterLabel: 'фильтр инструментов сессии по имени в реестре',\n toolsFilterTier: 'Показать только этот уровень; ещё раз — все уровни',\n toolsFilterClear: 'Сбросить',\n toolsFilterClearHint: 'Показать все уровни и убрать запрос',\n toolsFilterShown: 'показано {shown} из {total}',\n toolsFilterNone: 'Ни один инструмент сессии не подходит под фильтр.',\n // The server-level pin: one press for a whole server's names.\n toolsPinAll: 'Закрепить все',\n toolsPinAllHint: 'Закрепить каждый скрытый инструмент этого сервера в каждом запросе',\n // The other direction of the same press.\n toolsUnpinAll: 'Открепить все',\n toolsUnpinAllHint: 'Открепить все скрытые инструменты этого сервера',\n // The same press on the pinned tier.\n toolsUnpinServerHint: 'Открепить все инструменты этого сервера',\n toolsBudget: '{used} симв. из {total} · ≈ {tokens} токенов',\n toolsBudgetExhausted: 'бюджет исчерпан: дальнейшие раскрытия отклоняются с указанием причины',\n toolsBudgetFree: 'освободите место в бюджете или закрепите инструмент в настройках проекта',\n toolsBudgetGateOff: 'контроль раскрытий выключен: каждый смонтированный инструмент попадает в запрос',\n toolsBudgetBreakdown: '{used} из {total} ({percent}%)',\n toolsModeOff: 'MCP-инструменты этого проекта выключены',\n toolsModeOffCounters: 'смонтировано: {mounted} · не предлагаются',\n toolsModeOffHint:\n 'Ничто из этого проекта не предлагается модели. Включите режим «Раскрытие» на странице инструментов, чтобы снова их предлагать.',\n toolsModeDirect: 'ничего не откладывается: каждый смонтированный инструмент попадает в запрос',\n toolsPresentationOwner: 'Другой плагин формирует запрос',\n toolsOtherOwner: 'Другой владелец представления',\n toolsDemo: 'демо',\n toolsStep: 'шаг {step}',\n // The host's own usage counters: how often one tool was called, and how\n // long one server has gone unused.\n callsOne: '1 вызов',\n callsMany: 'вызовов: {count}',\n callsNone: 'ни разу не вызывался',\n callsProject: '{count} в проекте',\n idleDay: 'простой {count}д',\n idleHour: 'простой {count}ч',\n idleMinute: 'простой {count}мин',\n // One tool row's detail block (F-56): the serving server with its state, the\n // tier as a sentence, the two counter readings, then the host's own answer\n // about the definition. The header keeps the name, the clock and the step, and the\n // body prints them again in its fact line: that is what the contract's own probe reads\n // out of the open disclosure (`contracts/surfaces.md` §1.5).\n toolServer: 'сервер {server}',\n toolServerState: '{server} · {state}',\n toolTierPinned: 'закреплён — всегда в запросе',\n toolTierSession: 'предложен этой сессией',\n toolTierContext: 'предложен ранжированием контекста',\n showTool: 'показать сервер инструмента, описание, поля и способ предложения',\n hideTool: 'скрыть подробности инструмента',\n toolCallsSession: '{count} в этой сессии',\n toolLoading: 'читаем это определение у хоста…',\n toolFailed: 'хост не ответил на это определение',\n toolFieldsLabel: 'принимает',\n toolFieldRequiredHint: 'обязательное поле',\n toolReasonBudget: 'не предложен: {chars} символов при бюджете {budget}',\n toolReasonChars: '{chars} символов',\n toolReasonBudgetOnly: 'бюджет {budget} символов',\n toolReasonUsed: 'уже предложено {used}',\n toolReason: 'не предложен',\n // The errors and logs blocks, under their own disclosures.\n errorsSection: 'Проблемы',\n showErrors: 'показать серверы, требующие внимания',\n hideErrors: 'скрыть серверы, требующие внимания',\n logsSection: 'Журнал',\n showLogs: 'показать события проекта',\n hideLogs: 'скрыть события проекта',\n logsThisSession: 'эта сессия',\n logsAllSessions: 'все сессии',\n logsAllLevels: 'все уровни',\n logsErrorsOnly: 'ошибки',\n logsLevelInfo: 'info',\n logsLevelUp: 'up',\n logsLevelWarn: 'warn',\n logsLevelError: 'error',\n logsClear: 'Очистить',\n logsClearHint: 'Скрыть все записанные события; новые всё равно появятся',\n logsEmptyTitle: 'Событий пока нет',\n logsEmptyHint:\n 'Серверы проекта поднимаются на первом шаге сессии или при нажатии «Синхронизировать»; монтирование, запуск и остановка появятся здесь.',\n logsNoErrorsTitle: 'Ошибок нет',\n logsNoErrorsHint:\n 'Кольцо проекта содержит другие события; переключите фильтр уровней на «все уровни», чтобы их увидеть.',\n logsMore: 'Показать более ранние',\n logsMoreHint: 'Загрузить события старше показанных',\n logsShown: 'показано {shown} из {total}',\n logsProjectCount: '{count} в этом проекте',\n logsLoading: 'загрузка старых событий…',\n logsLoadFailed: 'старые события не удалось прочитать',\n // The tab's own states.\n noSession: 'К этой вкладке не привязана сессия.',\n noSessionHint: 'Панель читает проект сессии, в которой открыта.',\n noProject: 'Папка этой сессии пока не входит в проект.',\n noProjectHint:\n 'Хост поднимается от cwd сессии в поисках .git · .dsh · .kimi-code · package.json · *.sln.',\n nothingNeedsAttention: 'Внимания не требуется.',\n noServersDeclared: 'Этот проект не объявляет MCP-серверы.',\n noServersDeclaredHint: 'Добавьте {documents}.',\n noServersDeclaredUnknown: 'Добавьте в проект MCP-документ.',\n noServersDeclaredNowhere:\n 'Эта установка не читает документы проекта, так что объявлять некуда — укажите один в конфигурации плагина (`localFiles`).',\n // Surface A's own header and the vocabulary its rows are built from.\n thisSession: 'эта сессия',\n noProjectLabel: 'нет проекта',\n retry: 'Повторить',\n retryHint: 'Повторить неудачные монтирования проекта сейчас',\n sessionsSection: 'сессии',\n // The `sessions` section is the project's *disagreement* view.\n differsOne: '1 расходится',\n differsMany: '{count} расходятся',\n sessionsOne: '1 сессия',\n sessionsMany: 'сессий: {count}',\n serversOne: '1 сервер',\n serversMany: 'серверов: {count}',\n mergedAcrossSessions: 'объединено между сессиями',\n release: 'Освободить',\n nothingDeclared: 'ничего не объявлено',\n showSessions: 'показать сессии этого проекта',\n hideSessions: 'скрыть сессии этого проекта',\n showSession: 'показать серверы этой сессии',\n hideSession: 'скрыть серверы этой сессии',\n mountedPerProject: 'Смонтировано по проектам',\n projectsCount: '{count} проект(ов)',\n nothingMounted: 'Пока ничего не смонтировано.',\n // The status vocabulary (F-47): the word a row wears and the one-line\n // explanation its tooltip carries.\n statusActive: 'активен',\n statusConnecting: 'подключается',\n statusConflict: 'конфликт',\n statusError: 'ошибка',\n statusIdle: 'простой',\n statusDisabled: 'отключён',\n statusHintActive: 'смонтирован, его инструменты видны в этой сессии',\n statusHintConnecting: 'смонтирован, инструменты ещё не опубликованы',\n statusHintIdle: 'объявлен, но не смонтирован — смонтируется на следующем шаге',\n statusHintDisabled: 'объявлен с enabled: false',\n statusHintConflict: 'то же имя serverName занято экземпляром уровня профиля',\n statusHintError: 'см. подробности',\n // The status line of a project or session: one template per status, the\n // count always a `{count}` placeholder. The counted forms are the genitive\n // plural or an invariant construction — the documented 2–4 compromise.\n summaryActive: '{count} активных',\n summaryConnecting: '{count} подключающихся',\n summaryIdle: '{count} в простое',\n summaryDisabled: '{count} отключено',\n summaryError: '{count} с ошибкой',\n summaryConflict: '{count} в конфликте',\n summaryNone: 'ничего не объявлено',\n close: 'Закрыть',\n // The frame-wide toasts (F-47): one keyed line per lifecycle moment, and the\n // quieter line weaving the project around the fact behind it.\n toastUp: '{server} поднят',\n toastFailed: '{server}: сбой',\n toastReleased: '{server} освобождён',\n toastDetail: '{project} · {detail}',\n // The poll interval's row in the tab's settings panel.\n refreshTitle: 'Интервал обновления',\n refreshDesc: 'Как часто панель перечитывает снимок хоста',\n // The tab's actions menu: the row that opens the settings popup.\n settingsMenuItem: 'Настройки панели…',\n // The design stand's own tab title and description.\n designTitle: 'MCP проекта · дизайн ({variant})',\n designDesc: 'режим дизайна: фикстура {variant}, хоста за ней нет',\n // Settings half, in `settings.ts` order: the overview table, its states and\n // the read-only reasons of its rows.\n project: 'Проект',\n projectsOne: '1 проект с активной сессией',\n projectsMany: 'проектов с активными сессиями: {count}',\n viewTable: 'Таблица',\n viewFiles: 'По файлам',\n syncHint: 'Перечитать снимок хоста сейчас',\n server: 'Сервер',\n transport: 'Транспорт',\n status: 'Статус',\n source: 'Источник',\n on: 'Вкл',\n servers: 'Серверы',\n paneEntry: 'Запись',\n name: 'Имя',\n detail: 'Подробности',\n loading: 'Чтение снимка хоста…',\n loadingHint: 'Страница опрашивает /project-mcp/snapshot сразу после открытия.',\n hostUnavailable: 'Страница не получила ответа от хоста плагина.',\n hostUnavailableHint:\n 'Хостовая половина обслуживает {route}; изменения она подхватывает только после перезапуска dsh web — проверьте журнал.',\n noSessions: 'К проекту пока не привязана ни одна сессия.',\n noSessionsHint:\n 'Серверы поднимаются, когда сессия начинает работать в папке проекта, — без сессии для проекта ничего не монтируется.',\n noSessionsPaths: 'читаются: {paths}',\n noSessionsNoPaths:\n 'эта установка не читает ни одного MCP-документа — перечислите документы для чтения в конфигурации плагина (`localFiles`, `globalFiles`)',\n noServers: 'Этот проект не объявляет MCP-серверы.',\n noServersHint: 'Ничего не объявлено, поэтому для его сессий ничего не монтируется.',\n noServersNoPath: 'Эта установка не читает документы проекта, так что объявлять некуда.',\n documentUnknown: 'документ объявления неизвестен',\n global: 'глобальный',\n priority: 'приоритет {tier}/{total}',\n overrideFrom: '↳ переопределяет {name} из {from}',\n overrideUnpinned: '↳ переопределяет {name}, объявленное в документе с более низким приоритетом',\n nameReason: 'Только чтение: имя сервера — ключ объявления, который сообщает хост.',\n statusReason: 'Только чтение: статус приходит от работающего хоста, а не из документа.',\n sourceReason: 'Только чтение: путь объявляющего документа приходит от хоста.',\n detailReason: 'Только чтение: хост скрывает этот текст и никогда не включает аргументы.',\n openToEdit: 'Здесь только чтение: откройте сервер, чтобы изменить его запись.',\n rowActionsMore: '…',\n rowActionsHint: 'Открыть эту запись в редакторе',\n showJson: 'Показать JSON',\n hideJson: 'Скрыть JSON',\n jsonPreview: 'JSON снимка',\n jsonPreviewHint: 'Читается из снимка хоста; документ на диске не затрагивается.',\n back: 'Назад к списку',\n backHint: 'Вернуться к обзору, ничего не меняя',\n // Editor: the fields of the parsed entry.\n entryUnavailable: 'Хост не смог разобрать эту запись, так что редактировать нечего.',\n commandField: 'Команда',\n argsField: 'Аргументы',\n cwdField: 'CWD',\n urlField: 'URL',\n envField: 'Env',\n headersField: 'Заголовки',\n enabledField: 'Включён',\n timeoutField: 'Таймаут',\n keyField: 'Ключ',\n valueField: 'Значение',\n argsHint: 'Один аргумент на строку; каждая строка записывается как есть.',\n envHint: 'Одно значение на ключ; ключ, убранный в форме, удаляется из записи.',\n headersHint: 'Одно значение на заголовок; заголовок, убранный в форме, удаляется из записи.',\n timeoutHint: 'Миллисекунды; пусто — объявление не задаёт таймаут.',\n enabledValue: 'включён: {value}',\n absent: 'отсутствует',\n maskedValue: '•••• без изменений — введите текст, чтобы заменить',\n valuePlaceholder: 'значение',\n keyPlaceholder: 'KEY',\n credentialsNote:\n 'Приходит из внешнего источника — из .env проекта или файла учётных данных, — а не из этого документа: показывается и записывается обратно без изменений.',\n credentialValue: 'из .env проекта или файла учётных данных',\n addKey: 'Добавить ключ',\n addKeyHint: 'Добавить пустой ключ; безымянный ключ не записывается.',\n removeKey: '✕',\n removeKeyHint: 'Убрать этот ключ; убранный ключ удаляется из записи.',\n // Writing.\n editableNote:\n 'Редактируется {document}: «Сохранить» попросит подтверждение, сохранит резервную копию в {backup} и перезапишет запись целиком.',\n writeBlocked: 'Только чтение: {reason}',\n writeBlockedUnknown: 'хост не сообщил, почему этот документ нельзя записывать.',\n save: 'Сохранить…',\n saveHint: 'Открыть подтверждение этой записи',\n saveNoChange: 'Пока нечего сохранять.',\n saveUnavailable: 'В снимке нет ни объявляющего документа, ни ревизии, в которую можно было бы записать.',\n saveTimeoutInvalid: 'Таймаут — не целое число миллисекунд.',\n saving: 'Запись…',\n discard: 'Отменить',\n discardHint: 'Восстановить все поля из снимка и ничего не записывать',\n discardReason: 'Пока нечего восстанавливать.',\n unsaved: 'не сохранено',\n jsonDiff: 'diff',\n jsonClean: 'нет изменений',\n jsonUnavailable: 'нет разобранной записи',\n jsonInvalid: 'JSON не разбирается в запись: {reason}',\n jsonEditHint: 'Редактировать запись в том виде, в каком её объявляет документ',\n saveJsonInvalid: 'Сначала исправьте панель JSON: она не разбирается в запись.',\n footerWrite: '→ {document} · копия .bak · подтверждение',\n footerReadonly: '→ {document} · только чтение',\n confirmTitle: 'Записать {document}?',\n confirmBackup: 'Сначала текущий документ копируется в {backup}.',\n confirmFormat:\n 'Запись заменяет mcpServers[{server}] целиком. Документ сериализуется заново с отступом в два пробела и завершающим переводом строки, поэтому отступы и порядок ключей в остальной части документа нормализуются.',\n confirmConsent:\n 'Это глобальный документ: его читает каждый проект, поэтому запись требует явного согласия.',\n consentLabel: 'Я понимаю, что это перезапишет глобальный документ, общий для всех проектов.',\n confirmWrite: 'Записать документ',\n confirmWriteHint: 'Записать документ после проверок выше',\n confirmBlocked: 'Сначала отметьте согласие: глобальная запись без него отклоняется.',\n cancel: 'Отмена',\n saveOk: 'Сохранено: документ записан и перечитан.',\n saveErrorInvalid:\n 'Хост отклонил запись: этот плагин не стал бы монтировать такую. Ничего не записано.',\n saveErrorBlocked:\n 'Документ нельзя записать на этом уровне, либо нет согласия. Ничего не записано.',\n saveErrorConflict: 'Документ изменился с момента снятия этого снимка. Ничего не записано.',\n saveErrorNotFound: 'Документа или сервера больше нет. Ничего не записано.',\n saveErrorFailed: 'Сама запись не удалась; документ оставлен как был. Ничего не записано.',\n hostMessage: 'Хост ответил: {message}',\n reRead: 'Перечитать',\n reReadHint: 'Заново запросить снимок хоста и перестроить по нему форму',\n // Our own two pages, and the disclosure policy page next to `Servers`.\n tabServers: 'Серверы',\n tabTools: 'Инструменты',\n policyNote: 'режим, которому следует проект, и закреплённые для него инструменты',\n checkConflicts: 'Проверить конфликты',\n checkConflictsHint:\n 'конфликтующие имена серверов, которые хост сообщает для этого проекта, читаются из его снимка; кнопка перечитывает его сейчас',\n conflictsNone: 'в этом проекте нет конфликтующих имён серверов',\n conflictProfile: 'имя из профиля',\n conflictDuplicate: 'дубликат объявления',\n conflictSources: 'объявлено в {sources}',\n choiceLabel: 'показать',\n choiceLocal: 'копию этого проекта как {alias}',\n choiceProfileHint: 'оставить инструменты экземпляра профиля как есть',\n choiceLocalHint:\n 'смонтировать собственное объявление этого проекта рядом с профильным, под локальным именем {alias}',\n choiceNative: 'объявление этого проекта под его собственным именем',\n choiceNativeHint:\n 'смонтировать собственное объявление этого проекта под именем, которое оно объявляет: в этом проекте оно ближе, поэтому здесь оно затеняет инструменты экземпляра профиля, а все остальные проекты продолжают их видеть',\n choiceRefused: 'Хост отклонил выбор:',\n toolsCount: 'инструменты',\n pinned: 'Закреплённые',\n mode: 'Режим',\n modeDisclosure: 'раскрытие',\n modeDirect: 'все напрямую',\n modeOff: 'off',\n modeHint: 'записывается сразу, в следующий запрос, который соберёт хост',\n modeRefused: 'Хост отклонил режим:',\n pinRefused: 'Хост отклонил закрепление:',\n pinList: 'закреплённые · записаны вручную, предлагаются в каждом запросе',\n pinListEmpty: 'закреплений пока нет — включите одно в списке инструментов ниже',\n serverAllOffered: 'все {count} его инструментов предлагаются напрямую',\n serverPartlyOffered: '{offered} из {total} инструментов предлагаются напрямую',\n // The server-level pin (F-44): one switch for the whole server row, above the\n // per-name rows it stands for.\n serverPin: 'закрепить инструменты этого сервера',\n serverPinHint: 'Закрепить каждый инструмент, который монтирует этот сервер, — и скрытые тоже, — чтобы их нёс каждый запрос',\n serverUnpin: 'открепить инструменты этого сервера',\n serverUnpinHint: 'Перестать закреплять инструменты этого сервера',\n prefixFact: 'mcp__<server>__<tool>; префикс добавляет реестр, а не эта страница',\n pinTag: 'pin',\n moreTools: '… ещё {count}',\n requestPreview: 'предпросмотр запроса',\n requestPreviewTools: 'tools[] = {count}',\n requestPreviewTokens: '≈ {tokens} токенов',\n requestPreviewHidden: 'скрыто {count}',\n requestPreviewSaved: 'скрыто {count} · сэкономлено ≈ {tokens} токенов',\n requestPreviewNoOffer: 'эта сессия пока ничего не предложила',\n // The plugin's own configuration card (F-54), the newest keys last.\n configSummary: 'Настройка активации и параметров времени выполнения плагина',\n configGroupActivation: 'Активация',\n configGroupRuntime: 'Время выполнения',\n configLoading: 'Загрузка конфигурации…',\n configUnavailable: 'Хост не предоставляет конфигурацию этого плагина данному клиенту.',\n configReadOnly: 'Этот клиент хранит настройки в пределах процесса, поэтому здесь эти значения доступны только для чтения.',\n configOverridden: 'переопределено',\n configReset: 'Сбросить',\n configResetHint: 'Убрать переопределение и вернуть значение по умолчанию',\n configInvalidInteger: 'Введите целое число ≥ {min}',\n configInvalidRange: 'Введите целое число от {min} до {max}',\n configInvalidPrefix: 'Не более {max} символов: буквы, цифры, «_» или «-»',\n configActivationEnabled: 'Активация инструментов',\n configActivationEnabledHint: 'Постепенно предлагать MCP-инструменты — счётчики, раскрытие и поисковый шлюз',\n configActivationSeeded: 'Предустановленные инструменты',\n configActivationSeededHint: 'Инструменты, предлагаемые с первого шага, до накопления счётчиков; 0 — не предлагать',\n configActivationMinCalls: 'Вызовов до закрепления',\n configActivationMinCallsHint: 'После стольких вызовов счётчики закрепляют инструмент напрямую',\n configToolIdleMs: 'Тайм-аут простоя инструмента (мс)',\n configToolIdleMsHint: 'Инструмент, не использованный за это время, исключается из запроса',\n configGuidanceEnabled: 'Подсказки в системном промпте',\n configGuidanceEnabledHint: 'Добавлять рабочие заметки плагина в промпт сессии',\n configActivationAutoLimit: 'Лимит автоактивации',\n configActivationAutoLimitHint: 'Максимум инструментов, которые счётчики могут добавить сами (0–50)',\n configActivationAutoStickySteps: 'Шагов закрепления',\n configActivationAutoStickyStepsHint: 'Сколько шагов только что использованный инструмент остаётся закреплённым независимо от счётчиков (0–20)',\n configActivationToolBudgetChars: 'Бюджет инструментов (символы)',\n configActivationToolBudgetCharsHint: 'Бюджет в символах на схемы инструментов в одном запросе (≥ 1000)',\n configAllowGlobalWrite: 'Глобальная запись',\n configAllowGlobalWriteHint: 'Разрешить сохранение в пользовательскую (~/.dsh) конфигурацию',\n configEnvFiles: 'Файлы .env',\n configEnvFilesHint: 'Загружать .env-файлы для переменных окружения серверов',\n configLazy: 'Ленивое монтирование',\n configLazyHint: 'Запускать серверы проекта на первом шаге сессии, а не при загрузке',\n configLocalPrefix: 'Локальный префикс',\n configLocalPrefixHint: 'Префикс имён локальных инструментов — до 5 символов: A–Z, 0–9, _ или -; пусто — отключён',\n configProfileWins: 'Профиль приоритетнее',\n configProfileWinsHint: 'Серверы уровня профиля переопределяют одноимённые объявления проекта',\n configConnectTimeoutMs: 'Тайм-аут подключения (мс)',\n configConnectTimeoutMsHint: 'Сколько может длиться запуск одного сервера',\n configToolCallTimeoutMs: 'Тайм-аут вызова (мс)',\n configToolCallTimeoutMsHint: 'Сколько может длиться один вызов инструмента',\n configIdleTimeoutMs: 'Тайм-аут простоя сервера (мс)',\n configIdleTimeoutMsHint: 'Сервер, простаивающий дольше этого срока, останавливается',\n configDebounceMs: 'Антидребезг наблюдения (мс)',\n configDebounceMsHint: 'Пауза перед тем, как изменение конфигурации запустит повторное сканирование',\n configActivationWaitMs: 'Ожидание активации (мс)',\n configActivationWaitMsHint: 'Сколько первый шаг может ждать ленивые серверы',\n}\n\n/** English text for a key, with `{name}` placeholders substituted. */\nexport function uiFallback(key: string, params?: Record<string, unknown>): string {\n const template = (en as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/gu, (whole, name: string) =>\n name in params ? String(params[name]) : whole,\n )\n}\n\n/**\n * A translator bound to this namespace that never shows a raw key when English\n * knows it.\n *\n * Both translate seats route through here — the sidebar tab's `tabTranslate`\n * and the settings page's label — so the fallback is one code path: the bound\n * seat answers first, and when it can only echo the key (the active language's\n * dictionary lacks it) the merged English table of this module answers instead.\n * A key even English lacks renders as itself — a documented last resort, made\n * unreachable by construction (compile-time completeness of the three tables,\n * plus the parity spec), not by hiding the branch.\n * @param locale - the shell's locale service, when there is one.\n * @returns a translate function that always answers.\n */\nexport function uiTranslate(locale: TabLocale | undefined): Translate {\n if (locale === undefined) return uiFallback\n let bound: Translate\n try {\n bound = locale.bind(NS) as Translate\n } catch {\n // A service that refuses the namespace leaves the surface its own English.\n return uiFallback\n }\n return (key, params) => {\n const text = bound(key, params)\n return text === key ? uiFallback(key, params) : text\n }\n}\n","/**\n * The translate seat of the sidebar tab.\n *\n * The native Settings page registers through `settings.section` / `slots`,\n * which hands its component the framework's own `t` seat. The tab has neither:\n * it is created by the sidebar service, so its\n * panel used to render the module's English dictionary while the rest of the\n * shell followed the language preference.\n *\n * The tab's translator is built here, out of the one locale face the shell\n * publishes on the client context (`ctx.get('locale')` — the DSH `LocaleRuntime`\n * every dictionary registers into): the component binds the plugin's namespace\n * to it, subscribes to the locale snapshot, and repaints on a language switch.\n * The same namespace is registered from `./index.ts` with the merged\n * three-language dictionary, so a key the shell translates wins, and the\n * fallback inside {@link uiTranslate} is only the last resort for a composition\n * without a locale service — a test, or a browser half newer than the host.\n *\n * @module dsh-project-mcp/client/tab-locale\n */\n\nimport { useEffect, useState } from 'react'\nimport { uiTranslate } from './locales/ui.ts'\nimport type { Translate } from './view.ts'\n\n/**\n * The slice of the client locale service the tab needs, mirrored structurally.\n *\n * The DSH client packages are provided by the web shell and are not dependencies\n * of this one, so the seat is bound by shape rather than by import — the same\n * reason the settings page mirrors its slot services. `subscribe` is optional:\n * a service that publishes no snapshot never notifies, and the tab then renders\n * whatever language it was opened in.\n */\nexport interface TabLocale {\n /** Bind one namespace to a translate function that follows the active locale. */\n bind(namespace: string): Translate\n /** Subscribe to locale changes (a language switch or a late registration). */\n subscribe?(listener: () => void): () => void\n}\n\n/**\n * The locale service out of the client context, when the composition has one.\n *\n * The read goes through `ctx.get`, never through a property: Cordis throws\n * `cannot get property \"locale\" without inject` for a service this fiber did not\n * declare, and that throw takes the whole web client boot down with it. A\n * composition without a locale service answers `undefined`, and the tab keeps\n * its own English table.\n * @param ctx - the client context `apply` was called with.\n * @returns the locale service, or undefined when there is none.\n */\nexport function localeServiceOf(ctx: unknown): TabLocale | undefined {\n if (ctx === null || typeof ctx !== 'object') return undefined\n const get = (ctx as { get?: unknown }).get\n if (typeof get !== 'function') return undefined\n const candidate = (get as (name: string) => unknown).call(ctx, 'locale')\n if (candidate === null || typeof candidate !== 'object') return undefined\n return typeof (candidate as Partial<TabLocale>).bind === 'function'\n ? (candidate as TabLocale)\n : undefined\n}\n\n/**\n * The tab's translator, bound to the shell's locale service.\n *\n * A thin delegate to {@link uiTranslate}, the one translator both seats share:\n * the bound namespace answers first, the merged English table answers a key\n * the active language lacks, and the raw key shows only when even English has\n * nothing for it.\n * @param locale - the locale service, when there is one.\n * @returns a translate function that always answers.\n */\nexport function tabTranslate(locale: TabLocale | undefined): Translate {\n return uiTranslate(locale)\n}\n\n/**\n * The tab's translator as a hook: bound once, re-bound when the language\n * changes.\n *\n * The tab component is the one surface of this plugin rendered outside the slot\n * framework, so it is the one place a repaint has to be asked for explicitly.\n * @param locale - the locale service, when there is one.\n * @returns the translate seat the panel renders through.\n */\nexport function useTabTranslate(locale: TabLocale | undefined): Translate {\n const [seat, setSeat] = useState<Translate>(() => tabTranslate(locale))\n useEffect(() => {\n setSeat(tabTranslate(locale))\n return locale?.subscribe?.(() => setSeat(tabTranslate(locale)))\n }, [locale])\n return seat\n}\n","/**\n * The plugin's tab in DSH's **own** right sidebar, and the settings it carries.\n *\n * The panel used to be a tab of `dsh-better-sidebar`, a third-party registry\n * that re-exports DSH's right sidebar with its own descriptor API (and with its\n * own builtin tabs, its own `+` menu and its own side card settings). This module\n * speaks to the shipped surface directly, so the plugin depends on nothing\n * outside the harness:\n *\n * - the type itself goes into `sidebarRightTabs` (stage one: what the type *is* —\n * its id, its kind, and one guide entry, which is the only way a user can open\n * a page type at all);\n * - its body and its chip title go into the keyed `sidebar.right.pane.tab` /\n * `sidebar.right.pane.tab.title` seats under that same id, which is what the\n * sidebar dispatches on for every tab of the kind;\n * - the chip's actions menu gains one row (`sidebar.right.tab.menu.item`) that\n * opens the plugin's settings, and the settings themselves render as an entry\n * of the frame-wide `shell.overlay` layer — because a menu item that acts must\n * dismiss the menu it was pressed in, and the popup cannot live inside the row\n * that opened it. One store drives both halves.\n *\n * The DSH client packages are provided by the web shell and are not dependencies\n * of this package, so each of those contracts is **mirrored structurally** here —\n * the choice `./settings.ts` and `./tab-locale.ts` already make for\n * `settings.section` and the locale service. Nothing in this module imports a\n * `@deepseek-ai/dsh-client-*` package; the slot keys and the service name are\n * the only names it needs from the checkout, and they are dialled as strings.\n *\n * What the port changes for a user: the tab is listed by the shell's own guide\n * page instead of the sidebar's `+` menu, and the side card's plugin settings\n * page is gone — the poll interval and the per-project release panel now sit\n * behind the row this module adds to the tab's actions menu.\n *\n * @module dsh-project-mcp/client/sidebar-tab\n */\n\nimport { createElement as h, useEffect, useState } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { PACKAGE_NAME, TAB_ID } from '../shared.ts'\nimport { hostTranslate } from './locales/host.ts'\nimport { tabTranslate, useTabTranslate } from './tab-locale.ts'\nimport type { TabLocale } from './tab-locale.ts'\nimport type { RefreshStore, Translate } from './view.ts'\n\n/** Type discriminator of the panel's page: what `openTab` names and what the sidebar dispatches on. */\nexport const TAB_KIND = 'project-mcp'\n\n/** Keyed seat a tab type registers its body under. */\nexport const TAB_SLOT = 'sidebar.right.pane.tab'\n\n/** Keyed seat the same type registers its chip title under. */\nexport const TAB_TITLE_SLOT = 'sidebar.right.pane.tab.title'\n\n/** List seat a tab type adds its own entries to: the actions menu of the chip. */\nexport const TAB_MENU_SLOT = 'sidebar.right.tab.menu.item'\n\n/** Frame-wide floating layer the settings popup renders into. */\nexport const SETTINGS_DIALOG_SLOT = 'shell.overlay'\n\n/** Registration id of the actions-menu row, unique within that menu. */\nexport const TAB_MENU_ID = `${PACKAGE_NAME}:settings`\n\n/** Position of the row among the menu's entries, after the kit's own close item. */\nexport const TAB_MENU_ORDER = 60\n\n/** Registration id of the settings popup in the floating layer. */\nexport const SETTINGS_DIALOG_ID = `${PACKAGE_NAME}:settings-dialog`\n\n/** Position of the popup among the layer's entries, after the toast stack. */\nexport const SETTINGS_DIALOG_ORDER = 61\n\n/** Identity of the type's guide entry: the box the guide page offers to open a tab. */\nexport const TAB_GUIDE_ENTRY_ID = 'servers'\n\n/** Position of the guide entry among every registered type's entries; the tab's own descriptor order. */\nexport const TAB_GUIDE_ORDER = 55\n\n/**\n * One box the guide page offers, contributed by the type it opens.\n *\n * `title` and `description` are thunks read on every render, so a language\n * switch needs no re-registration — the rule the old descriptor's own copy\n * followed. A guide that lists too many entries drops descriptions and shows\n * titles alone, so the title has to stand on its own.\n */\nexport interface SidebarRightGuideEntry {\n readonly id: string\n readonly order: number\n readonly title: () => string\n readonly description?: (() => string) | undefined\n}\n\n/**\n * Stage one of a tab type: what it is, and nothing per-tab.\n *\n * `patterns` is omitted on purpose — the panel is a *page* type, opened by kind\n * (from the guide page, or from another surface's `openTab`), not a viewer that\n * claims an address. `multiple` is omitted too: one project panel per pane is\n * what `single: true` meant in the sidebar the tab came from.\n */\nexport interface SidebarRightTabDefinition {\n readonly id: string\n readonly kind: string\n /** Defaults to `extension` in the shipped registry: a type from outside the product. */\n readonly priority?: 'extension' | 'builtin' | 'fallback' | undefined\n /** Chip text captured when a tab opens. */\n readonly title: (address: string) => string\n readonly guide?: readonly SidebarRightGuideEntry[] | undefined\n}\n\n/** The registry service (stage one), as a registrant uses it. */\nexport interface SidebarRightTabsService {\n /** Register one type; the returned disposer removes it and is idempotent. */\n register(definition: SidebarRightTabDefinition): () => void\n}\n\n/** Live tab information the framework binds for a body: the presentation and the record. */\nexport interface SidebarTabInfo {\n readonly tab: {\n /** Only a tab on screen is visible: a docked body requires expansion and selection, a float survives a collapse. */\n readonly visible: boolean\n }\n}\n\n/**\n * The framework's own props for a `sidebar.right.pane.tab` body.\n *\n * `sessionId` is the slot's session scope; `useTabInfo` is the slot-owned hook\n * the framework injects (declared as `inject.hooks.tabInfo` in the slot map and\n * delivered flattened under that `use…` name). Both are optional here because a\n * composition — or a test — may hand the body neither, and this module falls\n * back rather than throwing.\n */\nexport interface SidebarTabFrameworkProps {\n readonly sessionId?: string | undefined\n readonly useTabInfo?: (() => SidebarTabInfo) | undefined\n}\n\n/** Owner share of one actions-menu occurrence: the menu's own dismiss seat. */\nexport interface SidebarTabMenuOwnerProps {\n readonly dismiss?: (() => void) | undefined\n}\n\n/**\n * Options one `slots.register` accepts, as far as this module uses them.\n *\n * `key` addresses a keyed seat; `id` and `order` place a list entry.\n */\nexport interface SidebarTabSlotOptions {\n name: string\n key?: string | undefined\n id?: string | undefined\n order?: number | undefined\n}\n\n/** The slot service, as this module's registrants use it. */\nexport interface SidebarTabSlots {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(options: SidebarTabSlotOptions, component: (props: Props) => ReactNode): unknown\n}\n\n/** The client services the tab's registration needs; each may be absent from a composition. */\nexport interface SidebarTabServices {\n effect(execute: () => unknown, label?: string): unknown\n slots: SidebarTabSlots\n sidebarRightTabs: SidebarRightTabsService\n}\n\n/** The tab body's props: the framework's own, plus the seats this module binds. */\nexport interface SidebarTabBodyProps {\n /** The session the tab belongs to — the panel shows that session's project only. */\n sessionId: string | undefined\n /** Whether the tab is on screen; an off-screen panel stops polling. */\n visible: boolean\n /** The poll interval, followed live so a change in the settings popup reaches the panel. */\n refreshMs: number\n t: Translate\n hostT: Translate\n}\n\n/** The settings popup's content, with the seats it needs. */\nexport interface SidebarSettingsProps {\n refreshMs: number\n /** Write a new interval; the popup's own row is the only writer. */\n onRefreshMs: (value: number) => void\n onClose: () => void\n t: Translate\n hostT: Translate\n}\n\n/**\n * Whether the settings popup is on screen, and how the menu row reaches it.\n *\n * The row and the popup are not in one tree: an actions-menu item that acts must\n * dismiss the menu, so the row cannot render the popup itself — it opens this\n * store, the menu closes, and the popup's own entry in the floating layer renders\n * from the same value. It is a store rather than a state setter because exactly\n * one side opens and the other subscribes.\n */\nexport interface SettingsDialogStore {\n isOpen(): boolean\n open(): void\n close(): void\n subscribe(listener: () => void): () => void\n}\n\n/**\n * Build a {@link SettingsDialogStore}, closed.\n * @returns the store the menu row and the popup share.\n */\nexport function createSettingsDialogStore(): SettingsDialogStore {\n let open = false\n const listeners = new Set<() => void>()\n const publish = (next: boolean): void => {\n if (next === open) return\n open = next\n for (const listener of listeners) listener()\n }\n return {\n isOpen: () => open,\n open: () => publish(true),\n close: () => publish(false),\n subscribe: (listener: () => void): (() => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\n/** Run one render when `open` flips, so a closed popup draws nothing at all. */\nfunction useSettingsOpen(store: SettingsDialogStore): boolean {\n const [open, setOpen] = useState(() => store.isOpen())\n useEffect(() => store.subscribe(() => setOpen(store.isOpen())), [store])\n return open\n}\n\n/** Follow the interval store so both the body and the popup re-render on a change. */\nfunction useRefreshMs(store: RefreshStore): number {\n const [value, setValue] = useState(() => store.get())\n useEffect(() => store.subscribe(() => setValue(store.get())), [store])\n return value\n}\n\n/** Copy the type publishes to the guide page; overridable so the design stand can name its picture. */\nexport interface SidebarTabCopy {\n title: () => string\n description: () => string\n}\n\n/** What {@link registerSidebarTab} wires up; the product and the design stand differ only here. */\nexport interface RegisterSidebarTabOptions {\n /** The shell's locale service, when the composition has one. */\n locale: TabLocale | undefined\n /** The poll interval shared by the body and the popup. */\n refresh: RefreshStore\n /** The tab body. */\n body: (props: SidebarTabBodyProps) => ReactNode\n /** The popup's content. */\n settings: (props: SidebarSettingsProps) => ReactNode\n /** The guide page's copy for this type; the product's own by default. */\n copy?: SidebarTabCopy | undefined\n}\n\n/** Nothing on screen when no tab information arrives: the frame renders every entry, hidden or not. */\nconst ALWAYS_VISIBLE: SidebarTabInfo = { tab: { visible: true } }\n\nfunction useAlwaysVisible(): SidebarTabInfo {\n return ALWAYS_VISIBLE\n}\n\n/**\n * Register the panel as a tab type of DSH's own right sidebar.\n *\n * Five registrations, all disposed with the fiber: the type in the registry, its\n * body and its chip title under their keyed seats, the settings row in the chip's\n * actions menu, and the settings popup in the frame-wide floating layer. A\n * composition that lacks any of the services keeps the surfaces it has — the\n * settings page, the toasts and the host half never depend on this module.\n * @param services - the injected `slots` registry, the right-sidebar tab registry, and `effect`.\n * @param options - the two surfaces to draw, the interval they share, and the guide copy.\n */\nexport function registerSidebarTab(\n services: SidebarTabServices,\n options: RegisterSidebarTabOptions,\n): void {\n const t = tabTranslate(options.locale)\n const copy: SidebarTabCopy = options.copy ?? {\n title: () => t('tab'),\n description: () => t('tabDescription'),\n }\n const store = createSettingsDialogStore()\n\n services.effect(\n () =>\n services.sidebarRightTabs.register({\n id: TAB_ID,\n kind: TAB_KIND,\n title: () => copy.title(),\n guide: [\n {\n id: TAB_GUIDE_ENTRY_ID,\n order: TAB_GUIDE_ORDER,\n title: () => copy.title(),\n description: () => copy.description(),\n },\n ],\n }),\n 'dsh-project-mcp: sidebar tab type',\n )\n\n services.slots.inject(TAB_SLOT, () =>\n services.slots.register({ name: TAB_SLOT, key: TAB_ID }, (props: SidebarTabFrameworkProps) =>\n h(TabBody, { framework: props, locale: options.locale, refresh: options.refresh, body: options.body }),\n ),\n )\n\n // The chip's title is re-read here on every render, which is what makes the\n // tab's own label follow a language switch. The registry's `title` thunk above\n // only covers the moment a tab opens: a record keeps the text it was minted\n // with until this seat overrides it.\n services.slots.inject(TAB_TITLE_SLOT, () =>\n services.slots.register({ name: TAB_TITLE_SLOT, key: TAB_ID }, () => h(TabChipTitle, { copy })),\n )\n\n services.slots.inject(TAB_MENU_SLOT, () =>\n services.slots.register(\n { name: TAB_MENU_SLOT, id: TAB_MENU_ID, order: TAB_MENU_ORDER },\n (props: SidebarTabMenuOwnerProps) =>\n h(MenuRow, { locale: options.locale, store, dismiss: props.dismiss }),\n ),\n )\n\n services.slots.inject(SETTINGS_DIALOG_SLOT, () =>\n services.slots.register(\n { name: SETTINGS_DIALOG_SLOT, id: SETTINGS_DIALOG_ID, order: SETTINGS_DIALOG_ORDER },\n () =>\n h(SettingsDialog, {\n locale: options.locale,\n store,\n refresh: options.refresh,\n settings: options.settings,\n }),\n ),\n )\n}\n\n/**\n * The tab body: the framework's props, the two translate seats and the live\n * interval, handed to the surface the entry supplied.\n * @param props - the framework's share plus the registration's own options.\n * @returns the panel element tree.\n */\nexport function TabBody(props: {\n framework: SidebarTabFrameworkProps\n locale: TabLocale | undefined\n refresh: RefreshStore\n body: (props: SidebarTabBodyProps) => ReactNode\n}): ReactNode {\n const t = useTabTranslate(props.locale)\n const hostT = hostTranslate(props.locale)\n const refreshMs = useRefreshMs(props.refresh)\n // Called unconditionally — the framework injects this hook for the seat. A\n // composition that somehow hands none is drawn as an on-screen tab rather than\n // as an error: `visible` only paces the panel's own polling.\n const info = (props.framework.useTabInfo ?? useAlwaysVisible)()\n // An element, not a bare call: the body is a component of its own, so its\n // hooks belong to its own fiber rather than to this adapter's.\n return h(props.body, {\n sessionId: props.framework.sessionId,\n visible: info.tab.visible,\n refreshMs,\n t,\n hostT,\n })\n}\n\n/**\n * The chip's title: the type's own name, read through the entry's copy thunk on\n * every render.\n *\n * The registry captures a title when a tab opens, and a record keeps that text\n * until this seat replaces it — so without this registration an open tab would\n * keep whatever language it was opened in. The component takes nothing from the\n * tab: the panel's label is the same for every occurrence.\n * @param props - the type's copy.\n * @returns the title text.\n */\nexport function TabChipTitle(props: { copy: SidebarTabCopy }): ReactNode {\n return props.copy.title()\n}\n\n/**\n * The row this plugin adds to a tab chip's actions menu.\n *\n * It dismisses the menu first — the contract for an item that acts, and the\n * reason the popup is not drawn here: the menu unmounts on dismiss, so a popup\n * inside the item would go with it. The row reads the plugin's own dictionary and\n * follows the language like every other surface.\n * @param props - the locale seat, the store the popup subscribes to, and the menu's dismiss seat.\n * @returns the menu item.\n */\nexport function MenuRow(props: {\n locale: TabLocale | undefined\n store: SettingsDialogStore\n dismiss?: (() => void) | undefined\n}): ReactNode {\n const t = useTabTranslate(props.locale)\n return h(\n 'button',\n {\n type: 'button',\n role: 'menuitem',\n style: STYLE.menuItem,\n onClick: () => {\n props.dismiss?.()\n props.store.open()\n },\n },\n t('settingsMenuItem'),\n )\n}\n\n/**\n * The settings popup: the tab's own settings, rendered as an entry of the\n * frame-wide floating layer.\n *\n * Nothing is drawn while the popup is closed, so the layer holds an empty cell\n * and the frame's click-through is untouched. The backdrop is the entry's own\n * element, which is what makes the layer's `pointer-events: auto` rule apply to\n * it.\n * @param props - the locale seat, the open/closed store, the interval and the content.\n * @returns the backdrop with the popup card, or `null` while it is closed.\n */\nexport function SettingsDialog(props: {\n locale: TabLocale | undefined\n store: SettingsDialogStore\n refresh: RefreshStore\n settings: (props: SidebarSettingsProps) => ReactNode\n}): ReactNode {\n const t = useTabTranslate(props.locale)\n const hostT = hostTranslate(props.locale)\n const refreshMs = useRefreshMs(props.refresh)\n const open = useSettingsOpen(props.store)\n if (!open) return null\n const close = (): void => props.store.close()\n return h(\n 'div',\n { style: STYLE.backdrop, onClick: close },\n h(\n 'div',\n {\n style: STYLE.dialog,\n role: 'dialog',\n 'aria-modal': true,\n 'aria-label': t('settingsMenuItem'),\n // A press inside the card must not reach the backdrop's close.\n onClick: (event: { stopPropagation: () => void }) => event.stopPropagation(),\n },\n // An element too: the popup's content is a component with hooks of its\n // own — the panel polls, and a bare call would fold them into this frame.\n h(props.settings, {\n refreshMs,\n onRefreshMs: (value: number) => props.refresh.set(value),\n onClose: close,\n t,\n hostT,\n }),\n ),\n )\n}\n\n/**\n * The entries' own style.\n *\n * The popup is deliberately not the panel's `STYLE`: it draws a menu row and a\n * frame-wide card, and neither is part of the tab's surface contract. The tokens\n * are the same alias variables every other surface uses, so the card follows the\n * theme — including the design stand's, which renders the same components.\n */\nconst STYLE = {\n /**\n * The menu row. The kit's own items are hashed CSS the plugin cannot borrow,\n * so the row is drawn the way the plugin draws every other control: an inline\n * style over the alias tokens, matching the kit's item in size and weight.\n */\n menuItem: {\n display: 'block',\n width: '100%',\n padding: '4px 10px',\n border: 'none',\n borderRadius: 4,\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n textAlign: 'left',\n cursor: 'pointer',\n } satisfies CSSProperties,\n /** The layer spans the frame, so the backdrop does too; the card is centred over the whole application. */\n backdrop: {\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: 'rgba(0, 0, 0, 0.4)',\n } satisfies CSSProperties,\n /**\n * The card, which scrolls its own content: the panel lists every project with\n * a live session, and a project with many servers is taller than any window.\n */\n dialog: {\n maxWidth: 'min(560px, 92vw)',\n maxHeight: '80vh',\n overflowY: 'auto',\n borderRadius: 8,\n border: '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))',\n background: 'var(--dsw-alias-bg-layer-2, #1f1f22)',\n color: 'var(--dsw-alias-label-primary, inherit)',\n boxShadow: '0 12px 32px rgba(0, 0, 0, 0.45)',\n } satisfies CSSProperties,\n} as const\n","/**\n * `dsh-project-mcp`, frame-wide toasts: one banner per MCP server that comes\n * up, fails, or is released — announced wherever the user is, rather than only\n * inside the sidebar tab's «Logs» mode.\n *\n * The seat is `shell.overlay` (`kind: 'list'`, `scope: 'root'`), DSH's\n * frame-wide floating layer: additive, owned by no feature, and click-through\n * until an entry opts into pointer events. Its catalog names a toast stack as\n * one of the things that belong there, so this module adds an entry **beside**\n * the shipped ones and declares no slot of its own. The composer dock that\n * F-05 removed is not coming back: nothing here paints into a surface this\n * plugin does not own.\n *\n * The source is the host's status channel, `GET /project-mcp/events` (see\n * `createEventStream` in `src/ui.ts`), the same stream the sidebar panel falls\n * back from polling to. A toast is not a second source of truth: every frame\n * carries the whole snapshot, and this module only diffs the picture it already\n * had for {@link ServerRow.status} transitions, so a missed frame costs one\n * banner rather than a wrong one.\n *\n * What a toast cannot say: a **stall** is not a lifecycle transition in the\n * snapshot — the row stays `connecting` and only its `detail` wording changes —\n * so stalls stay in the «Logs» tab and in the DSH log instead of becoming\n * banners.\n *\n * A draft carries dictionary keys and parameters, never a finished sentence:\n * the stack resolves them at render through the tab's translate seat\n * (`useTabTranslate`), so a language switch repaints the banners already on\n * screen instead of freezing the language of whatever the store holds (F-47).\n *\n * @module dsh-project-mcp/client/toasts\n */\n\nimport { createElement as h, useEffect, useState } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { ROUTE_ACTIONS, ROUTE_PREFIX } from '../shared.ts'\nimport type { McpSnapshot, ServerRow, SnapshotChange } from '../types.ts'\nimport type { UiKey } from './locales/ui.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\nimport { useTabTranslate } from './tab-locale.ts'\nimport type { TabLocale } from './tab-locale.ts'\nimport { STATUS_COLOR, STATUS_HINT, basename, translateOf } from './view.ts'\nimport type { Translate } from './view.ts'\n\n/** Slot the stack registers into: DSH's frame-wide floating layer. */\nexport const TOASTS_SLOT = 'shell.overlay'\n\n/** Registration id, unique among the layer's entries, and the cell it owns. */\nexport const TOASTS_ID = 'dsh-project-mcp:toasts'\n\n/** Position among the layer's entries, ascending. */\nexport const TOASTS_ORDER = 60\n\n/** Full-opacity hold before a banner starts to fade, matching DSH's own toast. */\nexport const TOAST_HOLD_MS = 3_000\n\n/** Fade duration, matching the `transition` the banner carries. */\nexport const TOAST_FADE_MS = 1_000\n\n/**\n * Banners kept on screen at once.\n *\n * A pass can start every server of a project in one go, and a stack taller than\n * the window is a stack nobody reads: the newest {@link MAX_TOASTS} are kept\n * and older ones drop, the same way a notification centre ages out its tail.\n */\nexport const MAX_TOASTS = 3\n\n/** Which lifecycle moment a banner reports. */\nexport type ToastLevel =\n /** The server reached `active`: mounted, its tools are visible. */\n | 'up'\n /** The server landed in `error`: the entry or its mount failed. */\n | 'error'\n /** An active server went back to `idle`: its mounts were dropped. */\n | 'released'\n\n/** One banner before the store stamps it with an identity. */\nexport interface ToastDraft {\n readonly level: ToastLevel\n /** `serverName` the transition belongs to. */\n readonly server: string\n /** Basename of the project root, so a banner fits on one line. */\n readonly project: string\n /**\n * Dictionary key of the one line — what happened to the server — resolved\n * through the seat at render, so a stored banner follows a language switch.\n */\n readonly textKey: UiKey\n /** Parameters of that line (`{server}`). */\n readonly textParams?: Record<string, unknown> | undefined\n /**\n * Dictionary key of the fact the quieter line explains — a status hint —\n * with the project woven around it (`toastDetail`). Absent, the quieter line\n * is just {@link ToastDraft.detail}, a language-neutral string.\n */\n readonly detailKey?: UiKey | undefined\n /**\n * The host's own fact sentence, shown instead of the keyed hint when the row\n * carries one; when {@link ToastDraft.detailKey} is absent, the whole\n * quieter line (the project basename).\n */\n readonly detail?: string | undefined\n /**\n * Wire companions of {@link ToastDraft.detail} (F-48): the row's\n * `detailCode`/`detailParams`, carried through so the quieter line resolves\n * through the host namespace at render and falls back to the prose when the\n * code is absent or unknown.\n */\n readonly detailCode?: string | undefined\n /** Flat params of {@link ToastDraft.detailCode}. */\n readonly detailParams?: Record<string, string> | undefined\n}\n\n/** One banner on screen. */\nexport interface Toast extends ToastDraft {\n /** Identity the store mints; also the React key and the dismiss handle. */\n readonly id: number\n}\n\n/**\n * The stack's own state.\n *\n * A plain observable rather than React state, because the writer is the status\n * channel and the reader is the slot entry: they are not in one component tree,\n * and only the store has to survive the slot re-registering.\n */\nexport interface ToastStore {\n /** Current banners, newest first. */\n getSnapshot(): readonly Toast[]\n /** Listen for changes; returns the unsubscribe. */\n subscribe(listener: () => void): () => void\n /** Add one banner, dropping the tail beyond the limit. */\n push(draft: ToastDraft): void\n /** Retire one banner; an unknown id is a no-op. */\n dismiss(id: number): void\n}\n\n/**\n * Build one stack's store.\n * @param limit - banners kept at once; defaults to {@link MAX_TOASTS}.\n * @returns the store the entry renders from.\n */\nexport function createToastStore(limit: number = MAX_TOASTS): ToastStore {\n let toasts: readonly Toast[] = []\n let minted = 0\n const listeners = new Set<() => void>()\n /** Publish one new array: the snapshot identity is what React compares. */\n const publish = (next: readonly Toast[]): void => {\n toasts = next\n for (const listener of [...listeners]) listener()\n }\n return {\n getSnapshot: () => toasts,\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n push(draft) {\n minted += 1\n publish([{ ...draft, id: minted }, ...toasts].slice(0, Math.max(0, limit)))\n },\n dismiss(id) {\n const next = toasts.filter((toast) => toast.id !== id)\n if (next.length !== toasts.length) publish(next)\n },\n }\n}\n\n/** Identity of one row across frames: a server name is unique per project. */\nfunction keyOf(row: ServerRow): string {\n return `${row.projectRoot}\\u0000${row.name}`\n}\n\n/**\n * Every row of one picture, keyed by project and server.\n * @param snapshot - a picture.\n * @returns the keyed rows.\n */\nfunction rowsOf(snapshot: McpSnapshot): Map<string, ServerRow> {\n const rows = new Map<string, ServerRow>()\n for (const project of snapshot.projects) {\n for (const row of project.rows) rows.set(keyOf(row), row)\n }\n return rows\n}\n\n/** The banner one row's new state earns, when it earns one. */\nfunction transitionToast(was: ServerRow | undefined, row: ServerRow): ToastDraft | undefined {\n const project = basename(row.projectRoot)\n if (row.status === 'active') {\n return {\n level: 'up',\n server: row.name,\n project,\n textKey: 'toastUp',\n textParams: { server: row.name },\n detail: project,\n }\n }\n if (row.status === 'error') {\n return {\n level: 'error',\n server: row.name,\n project,\n textKey: 'toastFailed',\n textParams: { server: row.name },\n detailKey: STATUS_HINT.error,\n detail: row.detail,\n ...(row.detailCode === undefined ? {} : { detailCode: row.detailCode }),\n ...(row.detailParams === undefined ? {} : { detailParams: row.detailParams }),\n }\n }\n // Only an active server *loses* mounts; `idle` reached from `connecting` or\n // `disabled` is a picture of a server that never came up, not a release.\n if (row.status === 'idle' && was?.status === 'active') {\n return {\n level: 'released',\n server: row.name,\n project,\n textKey: 'toastReleased',\n textParams: { server: row.name },\n detailKey: STATUS_HINT.idle,\n }\n }\n return undefined\n}\n\n/**\n * The banners two consecutive pictures earn.\n *\n * Read from status alone, and only when the status actually changed: a rescan\n * that re-derives the same rows announces nothing, and a row that moves between\n * two non-terminal states (`idle → connecting` on the next turn's lazy mount)\n * is not a lifecycle moment worth a banner.\n * @param previous - the picture already applied; `undefined` makes `next` the baseline.\n * @param next - the picture a `change` frame just delivered.\n * @returns banners, oldest transition first; empty for a baseline or a quiet frame.\n */\nexport function serverTransitions(previous: McpSnapshot | undefined, next: McpSnapshot): ToastDraft[] {\n if (previous === undefined) return []\n const before = rowsOf(previous)\n const drafts: ToastDraft[] = []\n for (const [key, row] of rowsOf(next)) {\n const was = before.get(key)\n if (was?.status === row.status) continue\n const draft = transitionToast(was, row)\n if (draft !== undefined) drafts.push(draft)\n }\n return drafts\n}\n\n/**\n * Read one frame's payload.\n *\n * A frame this plugin cannot read is dropped, not guessed at: the stream is\n * whole-picture, so the next frame is a complete answer, and a half-parsed\n * snapshot would produce phantom transitions.\n * @param data - `MessageEvent.data` of a `hello`/`change` frame.\n * @returns the change, or `undefined` when the payload is not one.\n */\nexport function parseChange(data: unknown): SnapshotChange | undefined {\n if (typeof data !== 'string') return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return undefined\n }\n if (parsed === null || typeof parsed !== 'object') return undefined\n const { revision, snapshot } = parsed as { revision?: unknown; snapshot?: unknown }\n if (typeof revision !== 'number') return undefined\n if (snapshot === null || typeof snapshot !== 'object') return undefined\n if (!Array.isArray((snapshot as { projects?: unknown }).projects)) return undefined\n return { revision, snapshot: snapshot as McpSnapshot }\n}\n\n/** The part of `EventSource` this module uses, so a test can hand it a stand-in. */\nexport interface FollowSource {\n addEventListener(type: string, listener: (event: Event) => void): void\n close(): void\n}\n\n/**\n * How the channel is opened.\n *\n * A seam for tests: the channel is the one thing in this module that talks to\n * the browser, so a test hands it a stand-in rather than patching a global, and\n * the default is the only place that reaches for `EventSource`.\n */\nexport type OpenSource = (url: string) => FollowSource | undefined\n\n/** Open the status channel, or nothing in an environment without `EventSource`. */\nfunction defaultOpen(url: string): FollowSource | undefined {\n return typeof EventSource === 'undefined' ? undefined : new EventSource(url)\n}\n\n/**\n * Follow the host's status channel and raise one banner per transition.\n *\n * The stream carries two frame kinds: `hello` is the picture as it is — on\n * open and on every reconnect the browser's `EventSource` performs — and\n * `change` is one announced change. `hello` only resets the baseline, so a page\n * load, a dropped connection and a late join never read as twenty servers\n * starting at once. A frame whose revision is not newer than the last applied\n * one is repeated or replayed, and is ignored for the same reason.\n * @param store - the stack to push banners into.\n * @param open - channel factory; defaults to a real `EventSource`.\n * @returns the disposer that closes the channel.\n */\nexport function followServers(store: ToastStore, open: OpenSource = defaultOpen): () => void {\n const source = open(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.events}`)\n if (source === undefined) return () => undefined\n let previous: McpSnapshot | undefined\n let revision = Number.NEGATIVE_INFINITY\n /** Apply one frame's picture; `raise` is false for the baseline `hello`. */\n const apply = (event: Event, raise: boolean): void => {\n const change = parseChange((event as MessageEvent).data)\n if (change === undefined || change.revision <= revision) return\n if (raise) {\n for (const draft of serverTransitions(previous, change.snapshot)) store.push(draft)\n }\n previous = change.snapshot\n revision = change.revision\n }\n source.addEventListener('hello', (event) => apply(event, false))\n source.addEventListener('change', (event) => apply(event, true))\n return () => source.close()\n}\n\n/** The slot service, as this registrant uses it; mirrored structurally, not imported. */\nexport interface ToastSlots {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(\n options: { name: string; id: string; order: number },\n component: (props: Props) => ReactNode,\n ): () => void\n}\n\n/**\n * The one client service the stack needs.\n *\n * It is optional in a composition — a shell without the floating layer simply\n * has no banners — which is why registration goes through `ctx.inject` rather\n * than a module-level `inject` list: a composition without `slots` must keep\n * the sidebar tab and the settings page, and must not leave this entry pending.\n * The locale service is the tab's own seat: with it, a language switch repaints\n * the banners on screen; without it, the stack renders its English fallback.\n */\nexport interface ToastsServices {\n slots: ToastSlots\n /** The shell's locale service, when the composition has one. */\n locale?: TabLocale | undefined\n}\n\n/**\n * Contribute the stack to the frame's floating layer.\n *\n * `slots.register` throws on a duplicate list id, so the entry and the channel\n * are installed behind one disposer and that disposer is returned to\n * `slots.inject`: a second run — the layer's declaration collapsing and coming\n * back, or an HMR reload — tears the first activation down before the second\n * registers, instead of throwing away the whole entry or following the channel\n * twice.\n * @param services - the injected `slots` service, and the locale seat.\n */\nexport function registerToasts(services: ToastsServices): void {\n const store = createToastStore()\n /** The live activation, so a repeat of the injection can never leave two. */\n let stop: (() => void) | undefined\n services.slots.inject(TOASTS_SLOT, () => {\n stop?.()\n const entry = services.slots.register({ name: TOASTS_SLOT, id: TOASTS_ID, order: TOASTS_ORDER }, () =>\n h(ToastStack, { store, locale: services.locale }),\n )\n const channel = followServers(store)\n stop = () => {\n channel()\n entry()\n stop = undefined\n }\n return stop\n })\n}\n\n/** The tones a banner's dot takes, from the panel's own status palette. */\nconst LEVEL_COLOR: Record<ToastLevel, string> = {\n up: STATUS_COLOR.active,\n error: STATUS_COLOR.error,\n released: STATUS_COLOR.idle,\n}\n\n/**\n * The stack's own styles.\n *\n * The banner mirrors DSH's shipped `Toast` (`ui-primitives`): the same alias\n * variables, radius, padding and type, so a banner reads as a shell surface\n * rather than a plugin's own invention. The difference is placement — that\n * toast portals to the body and centers itself on the viewport, while this one\n * is an entry of the floating layer, which spans the frame and already sits\n * above every column.\n */\nconst STYLE = {\n stack: {\n position: 'absolute',\n top: 12,\n left: '50%',\n transform: 'translateX(-50%)',\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n gap: 8,\n // Same bound as one banner: the frame's center is where a long failure\n // sentence would otherwise size itself against half the window.\n maxWidth: 'min(640px, calc(100vw - 48px))',\n // Announcements never intercept clicks: the layer is click-through until an\n // entry opts in, and this entry opts back out for its whole subtree.\n pointerEvents: 'none',\n } satisfies CSSProperties,\n banner: {\n display: 'flex',\n alignItems: 'center',\n gap: 10,\n width: 'max-content',\n maxWidth: 'min(640px, calc(100vw - 48px))',\n padding: '12px 16px',\n borderRadius: 14,\n background: 'var(--dsw-alias-button-contrast-fill, rgba(20, 22, 26, 0.92))',\n color: 'var(--dsw-alias-label-primary-inverted, #fff)',\n fontSize: 14,\n lineHeight: '22px',\n boxShadow: 'var(--dsw-shadow-lv3, 0 8px 24px rgba(0, 0, 0, 0.28))',\n transition: `opacity ${TOAST_FADE_MS}ms ease`,\n } satisfies CSSProperties,\n /** The tail of a banner's life: it is already retired, only the fade is left. */\n fading: { opacity: 0 } satisfies CSSProperties,\n dot: {\n flex: 'none',\n width: 8,\n height: 8,\n borderRadius: 999,\n } satisfies CSSProperties,\n body: { minWidth: 0 } satisfies CSSProperties,\n detail: { opacity: 0.75, fontSize: 12, lineHeight: '18px' } satisfies CSSProperties,\n} as const\n\n/** Read one banner off the store and follow it while the entry is mounted. */\nfunction useToasts(store: ToastStore): readonly Toast[] {\n const [toasts, setToasts] = useState<readonly Toast[]>(store.getSnapshot())\n useEffect(() => store.subscribe(() => setToasts(store.getSnapshot())), [store])\n return toasts\n}\n\n/**\n * The stack the floating layer renders.\n *\n * Nothing is rendered while there is nothing to say, so the layer holds no\n * empty box between banners. The live-region role is on the stack rather than\n * on a banner, because a banner mounts and unmounts on its own timer. The\n * translate seat is bound here: drafts carry keys, and `useTabTranslate`\n * re-reads them when the shell's language changes, so the banners on screen\n * repaint without the store re-deriving anything.\n * @param props.store - the stack's state.\n * @param props.locale - the shell's locale service, when there is one.\n * @returns the banners, newest first, or `null`.\n */\nexport function ToastStack(props: { store: ToastStore; locale?: TabLocale | undefined }): ReactNode {\n const toasts = useToasts(props.store)\n const t = useTabTranslate(props.locale)\n // The host namespace beside the UI one: a banner whose row carried a coded\n // detail (F-48) resolves it through this seat, and the repaint still rides\n // on `t`'s re-bind.\n const hostT = hostTranslate(props.locale)\n if (toasts.length === 0) return null\n return h(\n 'div',\n { style: STYLE.stack, role: 'status', 'aria-live': 'polite' },\n toasts.map((toast) => h(ToastRow, { key: toast.id, toast, store: props.store, t, hostT })),\n )\n}\n\n/**\n * The quieter line of one banner, resolved through the seat at render time.\n *\n * A keyed fact is a status hint the project is woven around (`toastDetail`);\n * the host's own detail sentence wins over the hint when the row carries one;\n * a draft with no key at all shows its language-neutral line as it is. A coded\n * detail (F-48) resolves through the host seat first and falls back to its\n * prose when the code is absent or unknown, so an uncoded banner reads exactly\n * as before.\n * @param toast - the banner to read.\n * @param t - the translate seat.\n * @param hostT - the host-namespace seat; the echo seat answers without one.\n * @returns the line, or `undefined` when the banner has none.\n */\nfunction detailLine(toast: ToastDraft, t: Translate, hostT: Translate): string | undefined {\n if (toast.detailKey === undefined) {\n if (toast.detail === undefined && toast.detailCode === undefined) return undefined\n return resolveHost(hostT, toast.detailCode, toast.detailParams, toast.detail)\n }\n const fact =\n toast.detailCode === undefined\n ? toast.detail ?? t(toast.detailKey)\n : resolveHost(hostT, toast.detailCode, toast.detailParams, toast.detail ?? t(toast.detailKey))\n return t('toastDetail', { project: toast.project, detail: fact })\n}\n\n/**\n * One banner: full opacity for {@link TOAST_HOLD_MS}, then a fade of\n * {@link TOAST_FADE_MS}, then retired from the store.\n *\n * Two timers rather than one, because the fade is a real transition the user\n * sees; a single timer would drop the banner from full opacity to nothing.\n * @param props.toast - the banner to draw.\n * @param props.store - the stack it belongs to, so it can retire itself.\n * @param props.t - the translate seat the stack bound; the panel's English\n * fallback answers without one.\n * @returns the banner element.\n */\nexport function ToastRow(props: {\n toast: Toast\n store: ToastStore\n t?: Translate | undefined\n /** Host-namespace seat for a coded detail (F-48); the echo seat answers without one. */\n hostT?: Translate | undefined\n}): ReactNode {\n const [fading, setFading] = useState(false)\n const { store, toast } = props\n const t = translateOf(props.t)\n const detail = detailLine(toast, t, props.hostT ?? hostTranslate(undefined))\n useEffect(() => {\n const hold = setTimeout(() => setFading(true), TOAST_HOLD_MS)\n return () => clearTimeout(hold)\n }, [])\n useEffect(() => {\n if (!fading) return\n const fade = setTimeout(() => store.dismiss(props.toast.id), TOAST_FADE_MS)\n return () => clearTimeout(fade)\n }, [fading, store, props.toast.id])\n return h(\n 'div',\n { style: fading ? { ...STYLE.banner, ...STYLE.fading } : STYLE.banner },\n h('span', { style: { ...STYLE.dot, background: LEVEL_COLOR[toast.level] } }),\n h(\n 'span',\n { style: STYLE.body },\n h('div', null, t(toast.textKey, toast.textParams)),\n detail === undefined ? null : h('div', { style: STYLE.detail }, detail),\n ),\n )\n}\n","/**\n * The pictures the design surfaces draw.\n *\n * `./design.ts` mounts the three browser surfaces with **no host half at all**:\n * nothing is mounted, no route is called, and the sidebar tab, its settings\n * popover and the settings page are rendered from the fixtures below. That keeps\n * the interface reviewable on a machine with no live project and no MCP server,\n * which is the whole point of the mode.\n *\n * Every field here is the shape the host really publishes (`src/types.ts`), and\n * the `full` picture is the same one the parity gate feeds the live panel\n * (`scripts/design-parity.mjs`): seven servers covering all four status tones, a\n * session that disagrees with its project, a failure with its detail, four\n * events in the ring and a tool offer with pinned, disclosed and hidden names.\n * The other pictures isolate one state each, so a designer can look at it alone.\n *\n * @module dsh-project-mcp/client/design-fixtures\n */\n\nimport type {\n LogEvent,\n McpSnapshot,\n ProjectSnapshot,\n ServerRow,\n ServerStatus,\n ServerUsage,\n SessionSnapshot,\n SessionTools,\n ToolFacts,\n ToolPolicy,\n} from '../types.ts'\nimport type { ToastDraft } from './toasts.ts'\nimport { STATUS_HINT, seedToolFacts } from './view.ts'\n\n/** Session the fixtures belong to; `shortSessionId` renders it as `8fce1c`. */\nexport const DESIGN_SESSION = 'session-8fce1c-4a3f-4d0b-9c11-2f6a7b8c9d10'\n\n/** Neutral placeholder project, as the repository's conventions require. */\nexport const DESIGN_PROJECT_ROOT = '/example/service'\n\n/** The declaring document of every fixture row. */\nexport const DESIGN_DOCUMENT = `${DESIGN_PROJECT_ROOT}/.dsh/mcp.json`\n\n/** The detail a failed mount carries: three facts, no advice (`F-03`). */\nexport const DESIGN_FAILURE =\n `no tool appeared within 60.2s; endpoint stdio docker; declared in ${DESIGN_DOCUMENT}`\n\n/** How long the quiet fixture server has been unused, as the stand shows it. */\nconst DESIGN_IDLE_MS = 3 * 24 * 60 * 60 * 1000\n\n/**\n * The host's usage counters for the picture (`ProjectSnapshot.usage`).\n *\n * The three states the panel can draw are all here, because a stand that shows\n * only the happy one hides the rule that matters: `tglider` has counts for both\n * its tools, `grafana-local` has a record whose `tools` came back empty — the\n * row prints `never called` rather than a zero nobody counted — and every other\n * server has no record at all, so its rows carry no figure. `graph` is quiet\n * with a three-day-old date, which is the one row that draws `idle 3d`; the\n * figure is computed at module load so the stand always shows the same reading.\n *\n * The split is the other half of the rule (F-34): this session called\n * `workspace` 3 times while the project counted 182, so the row shows both, and\n * it never called `catalog`, so that row reads `never called · 96 in the\n * project`. A project whose host publishes no split draws one number, which is\n * what the other pictures show.\n */\nexport const DESIGN_USAGE: Record<string, ServerUsage> = {\n tglider: {\n calls: 182,\n errors: 0,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS / 3).toISOString(),\n tools: { workspace: 182, catalog: 96 },\n sessions: {\n [DESIGN_SESSION]: {\n calls: 3,\n errors: 0,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS / 3).toISOString(),\n tools: { workspace: 3 },\n },\n },\n },\n 'grafana-local': {\n calls: 0,\n errors: 0,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS).toISOString(),\n tools: {},\n },\n context7: {\n calls: 12,\n errors: 1,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS * 2).toISOString(),\n tools: { docs: 12 },\n },\n}\n\n/**\n * The definitions the stand's own host publishes (F-56).\n *\n * The body of an opened row is answered by `GET tool`, a route the stand has no\n * host behind: without these records every open row of the design surfaces would\n * sit on a read that never lands. The records are the picture's own — they agree\n * with {@link DESIGN_USAGE} (`workspace` was called, `catalog` never) and with\n * {@link designTools} — so the stand draws the real body: a description, a field\n * list with one required field and one nested object drawn as its type, and the\n * reason a deferred name is not in the request.\n *\n * They are seeded into the panel's own cache ({@link designProject} calls\n * {@link seedDesignToolFacts}), not branched on inside the row: `view.ts` has no\n * code path that knows whether an answer came from a socket, and the stand must\n * render the product's body rather than a second drawing of it.\n */\nexport const DESIGN_TOOL_FACTS: Record<string, ToolFacts> = {\n 'mcp__tglider__workspace': {\n name: 'mcp__tglider__workspace',\n description:\n 'Workspace overview: changed symbols, diagnostics and the files that carry them, as one page.',\n fields: [\n {\n name: 'path',\n type: 'string',\n required: true,\n description: 'Directory to read, relative to the project root.',\n },\n {\n name: 'depth',\n type: 'number',\n required: false,\n description: 'How deep the dependency walk may go.',\n },\n {\n // An object field is drawn as its own type and not expanded: the panel\n // lists what a call takes, it does not mirror the schema.\n name: 'filters',\n type: 'object',\n required: false,\n description: 'Per-file overrides; the server documents their shape.',\n },\n ],\n },\n // No fields at all, so the stand also shows the rule that an empty group draws\n // no heading rather than an empty list under it.\n 'mcp__tglider__catalog': {\n name: 'mcp__tglider__catalog',\n description: 'Every tool the server declares, with the size of each definition.',\n fields: [],\n },\n 'mcp__grafana-local__query': {\n name: 'mcp__grafana-local__query',\n description: 'Run one PromQL query against a dashboard’s data source.',\n fields: [\n { name: 'query', type: 'string', required: true, description: 'The PromQL expression.' },\n { name: 'range', type: 'string', required: false },\n ],\n },\n 'mcp__context7__docs': {\n name: 'mcp__context7__docs',\n description: 'Documentation pages for one library, ranked by the question asked.',\n fields: [],\n },\n 'mcp__playwright__navigate': {\n name: 'mcp__playwright__navigate',\n description: 'Open a URL in the browser and wait for the page to settle.',\n fields: [{ name: 'url', type: 'string', required: true, description: 'Absolute URL to open.' }],\n // Every figure is one the picture's own host measured, which is the whole\n // point of the reason line: the panel prints no size it computed itself.\n reason: { kind: 'budget', chars: 1_240, budget: 8_000, used: 6_900 },\n },\n 'mcp__rider__open': {\n name: 'mcp__rider__open',\n description: 'Open one file in the IDE at a line.',\n fields: [{ name: 'path', type: 'string', required: true }],\n reason: { kind: 'budget', chars: 640, budget: 8_000 },\n },\n}\n\n/**\n * Publish the picture's definitions into the panel's cache.\n *\n * Idempotent and cheap: called from {@link designProject}, which every design\n * surface renders through, so a fixture body is always seeded before the first\n * row can be opened. Seeding the same record twice is the same record.\n */\nexport function seedDesignToolFacts(): void {\n for (const [name, facts] of Object.entries(DESIGN_TOOL_FACTS)) seedToolFacts(name, facts)\n}\n\n/** One lifecycle event, as the ring stores it. */\nfunction event(\n at: number,\n level: LogEvent['level'],\n server: string,\n message: string,\n detail?: string,\n): LogEvent {\n return detail === undefined\n ? { at, level, projectRoot: DESIGN_PROJECT_ROOT, sessionId: DESIGN_SESSION, server, message }\n : { at, level, projectRoot: DESIGN_PROJECT_ROOT, sessionId: DESIGN_SESSION, server, message, detail }\n}\n\n/** The four events the `full` picture holds, oldest first. */\nexport const DESIGN_EVENTS: readonly LogEvent[] = [\n event(1_789_000_000_000, 'info', 'tglider', `mounting for session ${DESIGN_SESSION} (trigger: turn)`),\n event(1_789_000_001_000, 'up', 'tglider', `is up — tools visible to session ${DESIGN_SESSION} after 812ms`),\n event(1_789_000_002_000, 'warn', 'grafana-local', 'unmounting — the session went idle (it ran for 8m 03s)'),\n event(1_789_000_003_000, 'error', 'gateway', 'no tool appeared in 4m 27s', `endpoint: stdio docker · declared in ${DESIGN_DOCUMENT}`),\n]\n\n/** The one event the `tools-absent` picture holds: a declaration waiting for a turn. */\nexport const DESIGN_PENDING_EVENT: readonly LogEvent[] = [\n event(1_789_000_030_000, 'info', 'tglider', 'declared, waiting for the session’s first step'),\n]\n\n/** One row of a picture. */\nfunction row(\n name: string,\n status: ServerStatus,\n transport: 'stdio' | 'streamable-http',\n detail?: string,\n): ServerRow {\n return detail === undefined\n ? { name, status, projectRoot: DESIGN_PROJECT_ROOT, source: DESIGN_DOCUMENT, transport }\n : { name, status, projectRoot: DESIGN_PROJECT_ROOT, source: DESIGN_DOCUMENT, transport, detail }\n}\n\n/**\n * Every picture the design mode can draw.\n *\n * `full` is the default and the one the docs' own mock (`mockups/harness.html`)\n * mirrors; the rest isolate a single state so it can be reviewed on its own.\n */\nexport type DesignVariant =\n /** All states at once: four tones, a disagreement, a failure, a full tool offer. */\n | 'full'\n /** The quiet project: sessions agree, nothing failed, the ring is empty. */\n | 'quiet'\n /** The project declares nothing. */\n | 'empty'\n /** The session declares one server and the host published no offer yet. */\n | 'tools-absent'\n /** The tools page is switched off for this project. */\n | 'off'\n /** Nothing is deferred: every mounted tool goes into the request. */\n | 'direct'\n /** The session's folder is not inside a project. */\n | 'no-project'\n /** No session is attached to the tab. */\n | 'no-session'\n\n/** The variants, in the order the docs present them. */\nexport const DESIGN_VARIANTS: readonly DesignVariant[] = [\n 'full',\n 'quiet',\n 'empty',\n 'tools-absent',\n 'off',\n 'direct',\n 'no-project',\n 'no-session',\n]\n\n/** Narrow `unknown` to a variant, so a stored string can never switch the mode blind. */\nexport function isDesignVariant(value: unknown): value is DesignVariant {\n return typeof value === 'string' && (DESIGN_VARIANTS as readonly string[]).includes(value)\n}\n\n/** The merged rows of the project, per picture. */\nfunction mergedRows(variant: DesignVariant): ServerRow[] {\n switch (variant) {\n case 'full':\n return [\n row('tglider', 'active', 'streamable-http'),\n row('grafana-local', 'active', 'streamable-http'),\n row('gateway', 'error', 'stdio', DESIGN_FAILURE),\n row('playwright', 'connecting', 'stdio'),\n row('context7', 'conflict', 'streamable-http', 'the name is taken by a live profile-level instance'),\n row('rider', 'idle', 'stdio', 'not mounted yet — this session has not started a turn (lazy mounting is on)'),\n row('legacy-gh', 'disabled', 'stdio'),\n ]\n case 'quiet':\n case 'off':\n return [row('tglider', 'active', 'streamable-http'), row('grafana-local', 'active', 'streamable-http')]\n case 'direct':\n return [row('tglider', 'active', 'streamable-http')]\n case 'tools-absent':\n return [row('tglider', 'idle', 'streamable-http', 'not mounted yet — this session has not started a turn (lazy mounting is on)')]\n case 'empty':\n case 'no-project':\n case 'no-session':\n return []\n }\n}\n\n/**\n * This session's own rows.\n *\n * The `full` picture is the one the panel's project-first view exists for: the\n * project merges `grafana-local` as `active`, while this session — whose ring\n * says it went idle — reads it as `idle`. Every other picture agrees with its\n * project, so the panel draws no `sessions` section at all.\n */\nfunction sessionOwnRows(variant: DesignVariant): ServerRow[] {\n const rows = mergedRows(variant)\n if (variant !== 'full') return rows\n return rows.map((entry) =>\n entry.name === 'grafana-local' ? { ...entry, status: 'idle' as const } : entry,\n )\n}\n\n/** The tool policy in force for the picture. */\nexport function designPolicy(variant: DesignVariant): ToolPolicy {\n switch (variant) {\n case 'off':\n return { mode: 'off', pins: [] }\n case 'direct':\n return { mode: 'direct', pins: ['mcp__tglider__workspace'] }\n case 'quiet':\n return { mode: 'disclosure', pins: ['mcp__tglider__workspace', 'mcp__grafana-local__query'] }\n default:\n return { mode: 'disclosure', pins: ['mcp__tglider__workspace'] }\n }\n}\n\n/**\n * One session's tool offer, or `undefined` for the pictures where the host has\n * published none.\n *\n * `undefined` is the host's only \"not mounted yet\" signal, and it is a different\n * state from an offer whose counters are real zeroes — the panel prints two\n * different blocks for the two.\n */\nexport function designTools(variant: DesignVariant): SessionTools | undefined {\n const base = { sessionId: DESIGN_SESSION, mounted: 5, budgetChars: 20_000, deferring: false }\n switch (variant) {\n case 'full':\n return {\n ...base,\n baseline: ['mcp__tglider__workspace', 'mcp__tglider__catalog'],\n activated: [{ name: 'mcp__grafana-local__query', via: 'session', at: 1_789_000_004_000, step: 3 }],\n context: [{ name: 'mcp__context7__docs', via: 'context' }],\n deferred: ['mcp__playwright__navigate', 'mcp__rider__open'],\n surfaceChars: 12_800,\n visibleChars: 4_200,\n deferredChars: 8_600,\n deferring: true,\n }\n case 'quiet':\n return {\n ...base,\n mounted: 2,\n baseline: ['mcp__tglider__workspace', 'mcp__grafana-local__query'],\n activated: [],\n context: [],\n deferred: [],\n surfaceChars: 6_400,\n visibleChars: 6_400,\n deferredChars: 0,\n }\n case 'off':\n return {\n ...base,\n mounted: 1,\n baseline: [],\n activated: [],\n context: [],\n deferred: ['mcp__tglider__workspace'],\n surfaceChars: 3_200,\n visibleChars: 0,\n deferredChars: 3_200,\n }\n case 'direct':\n return {\n ...base,\n mounted: 1,\n baseline: ['mcp__tglider__workspace'],\n activated: [],\n context: [],\n deferred: [],\n surfaceChars: 3_200,\n visibleChars: 3_200,\n deferredChars: 0,\n }\n case 'empty':\n case 'tools-absent':\n case 'no-project':\n case 'no-session':\n return undefined\n }\n}\n\n/** One session of the picture, or `undefined` when the picture has no session. */\nfunction sessionOf(variant: DesignVariant): SessionSnapshot[] {\n if (variant === 'no-project' || variant === 'no-session') return []\n const rows = sessionOwnRows(variant)\n const tools = designTools(variant)\n const logs = variant === 'full' ? DESIGN_EVENTS : variant === 'tools-absent' ? DESIGN_PENDING_EVENT : []\n const session: SessionSnapshot = {\n id: DESIGN_SESSION,\n rows,\n issues: [],\n logCount: logs.length,\n ...(tools === undefined ? {} : { tools }),\n }\n return [session]\n}\n\n/**\n * The one project of the picture, or `undefined` for the two that resolve to\n * none — a folder that is not inside a project, and a tab with no session at\n * all (the panel reads the project of the session it is open in, so neither\n * resolves).\n */\nexport function designProject(variant: DesignVariant): ProjectSnapshot | undefined {\n if (variant === 'no-project' || variant === 'no-session') return undefined\n // The stand's own host answers (F-56): an opened row reads the definitions\n // from the cache the product reads, seeded here because there is no route.\n seedDesignToolFacts()\n const rows = mergedRows(variant)\n const logs = variant === 'full' ? DESIGN_EVENTS : variant === 'tools-absent' ? DESIGN_PENDING_EVENT : []\n const sessions = sessionOf(variant)\n return {\n projectRoot: DESIGN_PROJECT_ROOT,\n policy: designPolicy(variant),\n sessionIds: [DESIGN_SESSION],\n // The read order of this deployment, as the host publishes it: the fixture\n // project is declared in the DSH document, and no global document is read.\n files: [{ path: DESIGN_DOCUMENT, scope: 'project' }],\n rows,\n issues: [],\n sessions,\n conflicts: [],\n ...(logs.length === 0 ? {} : { logs, logCount: logs.length }),\n // The counters belong to the two pictures that publish a tool offer: a\n // project the host never counted (every other picture) draws no figures at\n // all, which is a state worth being able to look at.\n ...(variant === 'full' || variant === 'quiet' ? { usage: DESIGN_USAGE } : {}),\n }\n}\n\n/** The whole picture, in the envelope's own shape. */\nexport function designPicture(variant: DesignVariant): McpSnapshot {\n const project = designProject(variant)\n return {\n ready: true,\n projects: project === undefined ? [] : [project],\n sources: { local: ['.dsh/mcp.json'], global: [] },\n watchedFiles: project === undefined ? [] : [DESIGN_DOCUMENT],\n }\n}\n\n/**\n * The session id the tab should read for this picture.\n *\n * `no-session` is the state the shell itself can be in — a tab with no session\n * attached — and the one the panel answers with its own empty state.\n * @param variant - the picture on screen.\n * @returns the fixture session id, or `undefined` for `no-session`.\n */\nexport function designSessionId(variant: DesignVariant): string | undefined {\n return variant === 'no-session' ? undefined : DESIGN_SESSION\n}\n\n/**\n * The banners the design toast stack shows, one per lifecycle moment. Keyed\n * like the real drafts (`src/client/toasts.ts`), so the stand repaints its\n * banners in the shell's active language the same way the product does.\n */\nexport const DESIGN_TOASTS: readonly ToastDraft[] = [\n {\n level: 'up',\n server: 'playwright',\n project: 'service',\n textKey: 'toastUp',\n textParams: { server: 'playwright' },\n detail: 'service',\n },\n {\n level: 'error',\n server: 'gateway',\n project: 'service',\n textKey: 'toastFailed',\n textParams: { server: 'gateway' },\n detailKey: STATUS_HINT.error,\n detail: DESIGN_FAILURE,\n },\n {\n level: 'released',\n server: 'rider',\n project: 'service',\n textKey: 'toastReleased',\n textParams: { server: 'rider' },\n detailKey: STATUS_HINT.idle,\n },\n]\n","/**\n * Design-only render mode: the browser half drawn from fixtures.\n *\n * This module exists so the interface can be reviewed **as the shell renders\n * it** on a machine where nothing is mounted: no project, no MCP server, no host\n * route. When the design flag is set (see {@link DESIGN_FLAG_KEY}) `./index.ts`\n * registers *these* surfaces instead of the real ones, and every one of them\n * renders the same components the product renders — `PanelHeader`, `tabBody`,\n * `SettingsPage`, `ProjectBlock`, `ToastStack` — fed from `./design-fixtures.ts`.\n *\n * What the mode is not: it is not a second UI. There is no markup here that the\n * real surfaces do not also produce; the only thing it swaps is where the\n * picture comes from. The host half is untouched, so a profile that has this\n * flag set still mounts whatever the project declares — the *drawing* is a\n * fixture, the *runtime* is real.\n *\n * Turning it on, from the web client's own console:\n *\n * ```js\n * localStorage.setItem('dsh-project-mcp:design', 'full') // or quiet | empty | …\n * location.reload() // back to the product\n * localStorage.removeItem('dsh-project-mcp:design')\n * ```\n *\n * @module dsh-project-mcp/client/design\n */\n\nimport { createElement as h, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { en, ru, zh } from './locales/ui.ts'\nimport { NS_HOST, en as hostEn, ru as hostRu, zh as hostZh, hostTranslate } from './locales/host.ts'\nimport { registerSidebarTab } from './sidebar-tab.ts'\nimport type { SidebarSettingsProps, SidebarTabBodyProps, SidebarTabServices } from './sidebar-tab.ts'\nimport {\n DEFAULT_SETTINGS_VIEW,\n NS,\n SETTINGS_TAB_ID,\n SETTINGS_TAB_ORDER,\n SettingsPage,\n registerSettingsTab,\n useNarrowSettings,\n} from './settings.ts'\nimport type { SettingsSlotServices, SettingsTabProps, SettingsView } from './settings.ts'\nimport { DEFAULT_SETTINGS_PAGE } from './settings-tools.ts'\nimport type { SettingsPageKey } from './settings-tools.ts'\nimport { localeServiceOf, tabTranslate, useTabTranslate } from './tab-locale.ts'\nimport type { TabLocale } from './tab-locale.ts'\nimport { TOASTS_ID, TOASTS_ORDER, TOASTS_SLOT, ToastStack, createToastStore } from './toasts.ts'\nimport type { ToastsServices } from './toasts.ts'\nimport {\n PanelHeader,\n ProjectBlock,\n RefreshRow,\n STYLE,\n browserStorage,\n createRefreshStore,\n sessionLogCount,\n statusGroups,\n storedString,\n tabBody,\n translateOf,\n} from './view.ts'\nimport type { PanelStorage, Translate } from './view.ts'\nimport {\n DESIGN_TOASTS,\n designPicture,\n designPolicy,\n designProject,\n designSessionId,\n isDesignVariant,\n} from './design-fixtures.ts'\nimport type { DesignVariant } from './design-fixtures.ts'\n\n/**\n * Where the design mode is asked for.\n *\n * A browser-local preference rather than a build flag, for the same reason the\n * panel's own view and filters are: it must be switchable without a rebuild, and\n * it must be readable by the bundle that is already loaded.\n */\nexport const DESIGN_FLAG_KEY = 'dsh-project-mcp:design'\n\n/** Values that mean \"on\" without naming a picture. */\nconst DESIGN_FLAG_ALIASES: readonly string[] = ['on', 'true', 'yes', '1']\n\n/** How often the fixture stack repeats its three banners. */\nconst DESIGN_TOAST_ROTATE_MS = 2_500\n\n/** A set that never changes, for the read-only props of the fixture settings page. */\nconst NO_PENDING: ReadonlySet<string> = new Set()\n\n/** Do nothing: the fixture surfaces have no host to call. */\nfunction noop(): void {\n // Intentionally empty: a design surface answers no route.\n}\n\n/**\n * The picture the flag asks for.\n *\n * The flag holds a variant name (`full`, `quiet`, …) or one of the plain \"on\"\n * spellings, which mean the all-states picture. Anything else — including a\n * value from a newer build — leaves the mode **off**, so a typo can never swap\n * the real interface for a fixture.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the variant, or undefined when the mode is off.\n */\nexport function designVariantOf(storage?: PanelStorage): DesignVariant | undefined {\n const value = storedString(DESIGN_FLAG_KEY, storage)\n if (value === undefined) return undefined\n if (DESIGN_FLAG_ALIASES.includes(value)) return 'full'\n return isDesignVariant(value) ? value : undefined\n}\n\n/**\n * `true` when the flag names a picture the mode can draw.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns whether the design surfaces should be registered instead of the real ones.\n */\nexport function designModeEnabled(storage?: PanelStorage): boolean {\n return designVariantOf(storage) !== undefined\n}\n\n/**\n * The sidebar tab, drawn from a picture.\n *\n * The same two elements the real panel renders, in the same order: the toolbar\n * and the one body of the single surface. Nothing here fetches, so nothing here\n * needs the shell to be connected.\n * @param props - the picture, the tab's session and the translate seat.\n * @returns the panel element tree.\n */\nexport function DesignPanel(props: {\n variant: DesignVariant\n sessionId: string | undefined\n t?: Translate | undefined\n /** Host-namespace seat for the fixtures' coded events (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const project = designProject(props.variant)\n const sessionId = designSessionId(props.variant)\n const groups = project === undefined ? [] : statusGroups(project.rows)\n const session = (project?.sessions ?? []).find((entry) => entry.id === sessionId)\n return h(\n 'div',\n { style: STYLE.root },\n h(PanelHeader, {\n project,\n sessions: project?.sessionIds.length ?? 0,\n busy: false,\n onSync: noop,\n t,\n }),\n h(\n 'div',\n { style: STYLE.body },\n tabBody({\n project,\n sessionId,\n groups,\n busy: false,\n policy: project === undefined ? undefined : designPolicy(props.variant),\n onRelease: noop,\n sessionLogCount: sessionLogCount(session),\n t,\n hostT: props.hostT,\n }),\n ),\n )\n}\n\n/**\n * The tab's own settings popup, drawn from a picture.\n *\n * Same shape as `ProjectMcpSettings`: the poll-interval row first, then the bar\n * that names the surface, counts the projects and offers `Sync`/`Close`, and a\n * body rendering one `ProjectBlock` per project — the product's own components,\n * fed here. The row is shared with the product rather than redrawn, so the two\n * cannot drift on the control this port moved into the popup.\n * @param props - the picture, the interval, the close seat and the translate seats.\n * @returns the popup element tree.\n */\nexport function DesignPopup(props: {\n variant: DesignVariant\n refreshMs: number\n onRefreshMs?: ((value: number) => void) | undefined\n onClose?: (() => void) | undefined\n t?: Translate | undefined\n /** Host-namespace seat for the fixtures' coded payload fields (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const projects = designPicture(props.variant).projects\n return h(\n 'div',\n { style: STYLE.root },\n h(\n 'div',\n { style: STYLE.bar },\n h('span', { style: STYLE.name }, t('mountedPerProject')),\n h('span', { style: STYLE.muted }, t('projectsCount', { count: projects.length })),\n h('span', { style: { flex: 1 } }),\n h('button', { style: STYLE.button, onClick: noop }, t('sync')),\n props.onClose === undefined\n ? null\n : h('button', { style: STYLE.button, onClick: () => props.onClose?.() }, t('close')),\n ),\n h(RefreshRow, { refreshMs: props.refreshMs, onRefreshMs: props.onRefreshMs, t }),\n h(\n 'div',\n { style: STYLE.body },\n projects.length === 0\n ? h('div', { style: { ...STYLE.muted, padding: 8 } }, t('nothingMounted'))\n : projects.map((project) =>\n h(ProjectBlock, {\n key: project.projectRoot,\n project,\n busy: false,\n onRelease: noop,\n t: props.t,\n hostT: props.hostT,\n }),\n ),\n ),\n )\n}\n\n/**\n * The native Settings page, drawn from a picture.\n *\n * `SettingsPage` is a pure function of its props, so the design mode supplies\n * the state the real `SettingsTab` owns — view, page, selection, JSON — and the\n * fixture snapshot, and lets the page render itself. The editor's write path is\n * the one thing the mode does not simulate: there is no host to write to, so the\n * draft stays empty and `Save…` never becomes live.\n * @param props - the picture and the translate seat.\n * @returns the settings page element tree.\n */\nexport function DesignSettingsTab(props: {\n variant: DesignVariant\n t?: Translate | undefined\n /** The host namespace's seat, forwarded to the page like the product does. */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const [view, setView] = useState<SettingsView>(DEFAULT_SETTINGS_VIEW)\n const [page, setPage] = useState<SettingsPageKey>(DEFAULT_SETTINGS_PAGE)\n const [selectedServer, setSelectedServer] = useState<string | undefined>(undefined)\n const [json, setJson] = useState(false)\n const narrow = useNarrowSettings()\n const snapshot = designPicture(props.variant)\n const project = snapshot.projects[0]\n return h(SettingsPage, {\n snapshot,\n error: undefined,\n busy: false,\n view,\n onView: setView,\n page,\n onPage: setPage,\n onMode: noop,\n modePending: NO_PENDING,\n modeError: undefined,\n selectedRoot: project?.projectRoot,\n onSelectProject: noop,\n selectedServer,\n onSelectServer: setSelectedServer,\n onSync: noop,\n onRetry: noop,\n json,\n onJson: setJson,\n draft: undefined,\n confirming: false,\n consent: false,\n saveState: undefined,\n saving: false,\n onDraft: noop,\n onDiscard: noop,\n onAskSave: noop,\n onCancelSave: noop,\n onConsent: noop,\n onConfirmSave: noop,\n onReRead: noop,\n narrow,\n t,\n hostT: props.hostT,\n })\n}\n\n/**\n * The tab body the entry hands to {@link registerSidebarTab}.\n *\n * The entry already bound both translate seats, so the adapter only forwards the\n * framework's own session and the fixture the mode was started with — the\n * product's own adapter (`LocalizedPanel` in `./index.ts`) does the same with the\n * real panel.\n * @param props - the body's props, seats included.\n * @returns the fixture panel.\n */\nexport function LocalizedDesignPanel(props: SidebarTabBodyProps & { variant?: DesignVariant }): ReactNode {\n const variant = props.variant ?? 'full'\n return h(DesignPanel, { variant, sessionId: props.sessionId, t: props.t, hostT: props.hostT })\n}\n\n/**\n * The settings popup's fixture content.\n *\n * Same chrome as the product's popup — the poll-interval row first, then the\n * per-project blocks — with the stand's fixtures behind it. The interval row is\n * the shared {@link RefreshRow}, so the stand cannot drift from the product on\n * the control the port moved here.\n * @param props - the popup's props, seats included, plus the fixture variant.\n * @returns the fixture popup.\n */\nexport function LocalizedDesignPopup(props: SidebarSettingsProps & { variant?: DesignVariant }): ReactNode {\n const variant = props.variant ?? 'full'\n return h(DesignPopup, {\n variant,\n refreshMs: props.refreshMs,\n onRefreshMs: props.onRefreshMs,\n onClose: props.onClose,\n t: props.t,\n hostT: props.hostT,\n })\n}\n\n\n/**\n * The frame-wide toast stack, repeating its three fixture banners.\n *\n * The product's stack reads a status channel; here the store is filled directly\n * from {@link DESIGN_TOASTS} and refilled on a timer, because a banner lives\n * three seconds and a design surface has to still be on screen when someone\n * looks at it.\n * @param services - the injected `slots` service, and the locale seat.\n */\nexport function registerDesignToasts(services: ToastsServices): void {\n const store = createToastStore()\n services.slots.inject(TOASTS_SLOT, () => {\n const entry = services.slots.register(\n { name: TOASTS_SLOT, id: TOASTS_ID, order: TOASTS_ORDER },\n () => h(ToastStack, { store, locale: services.locale }),\n )\n let index = 0\n const push = (): void => {\n const draft = DESIGN_TOASTS[index % DESIGN_TOASTS.length]\n index += 1\n if (draft !== undefined) store.push(draft)\n }\n push()\n const timer = setInterval(push, DESIGN_TOAST_ROTATE_MS)\n return () => {\n clearInterval(timer)\n entry()\n }\n })\n}\n\n/**\n * Register the fixture surfaces on the browser half.\n *\n * Mirrors `apply`'s own wiring exactly — the tab behind the right sidebar's\n * settings page behind `slots` + `locale`, the toasts behind `slots` alone — so\n * the design mode is a drop-in replacement for the real one and a composition\n * missing a service behaves the same way in both.\n * @param ctx - client root context.\n * @param variant - the picture to draw; read from the flag when omitted.\n */\nexport function registerDesignSurfaces(\n ctx: Context,\n variant: DesignVariant = designVariantOf(browserStorage()) ?? 'full',\n): void {\n const locale = localeServiceOf(ctx)\n const t = tabTranslate(locale)\n\n // The same four seats the product registers, from the fixtures: the stand has\n // to draw the surface the port produced — a right-sidebar tab, one actions-menu\n // row and the popup in the frame-wide floating layer — or it would be comparing\n // the product against a surface that no longer exists.\n ctx.inject(['slots', 'sidebarRightTabs'], (scope) => {\n registerSidebarTab(scope as unknown as SidebarTabServices, {\n locale,\n // The stand reads and writes the same browser-local interval the product\n // does, so the row a designer presses there behaves exactly like the row\n // the product shows.\n refresh: createRefreshStore(),\n body: (props) =>\n h(LocalizedDesignPanel, { ...props, variant }),\n settings: (props) =>\n h(LocalizedDesignPopup, { ...props, variant }),\n copy: {\n title: () => t('designTitle', { variant }),\n description: () => t('designDesc', { variant }),\n },\n })\n })\n\n ctx.inject(['slots', 'locale'], (scope) => {\n const services = scope as unknown as SettingsSlotServices\n // The same one call with all three tables as the product entry. No\n // `addLanguage` of its own: `apply()` returns early in design mode, so\n // the entry — the only place that names Russian to the shell — never runs\n // in this mode. The registration alone is still valid: its `ru` keys are\n // simply unused, and anything unresolved falls back to English.\n services.effect(\n () => services.locale.register(NS, { zh, en, ru }),\n 'dsh-project-mcp: design settings dictionary',\n )\n services.effect(\n // The host-code namespace, beside the UI one as in the product entry.\n () => services.locale.register(NS_HOST, { zh: hostZh, en: hostEn, ru: hostRu }),\n 'dsh-project-mcp: design host dictionary',\n )\n registerSettingsTab(services, (props: SettingsTabProps) =>\n h(DesignSettingsTab, { variant, t: props.t, hostT: props.hostT }),\n )\n })\n\n ctx.inject(['slots', 'locale'], (scope) => {\n registerDesignToasts(scope as unknown as ToastsServices)\n })\n}\n","/**\n * `dsh-project-mcp`, browser half: a DSH right-sidebar tab that shows which MCP\n * servers each project declares and what is currently mounted for its sessions,\n * its own settings popup in the tab chip's actions menu, a page in DSH's native\n * Settings listing every project with a live session, and a frame-wide toast\n * stack for the servers that come up, fail or are released.\n *\n * The tab is a type of DSH's own right sidebar (`./sidebar-tab.ts`, which mirrors\n * the shipped contract structurally), and the popup is an entry of the frame-wide\n * floating layer. The other three seats are the browser-shell slots\n * `settings.section`, `plugins.bundle.config` and `shell.overlay`. Every seat\n * exists in the browser half only. The host half publishes the same data over\n * `/project-mcp/*` (see `src/ui.ts`), so this module never imports host code at\n * runtime.\n *\n * @module dsh-project-mcp/client\n */\n\nimport { createElement } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { PACKAGE_NAME } from '../shared.ts'\nimport { designModeEnabled, registerDesignSurfaces } from './design.ts'\nimport { en, ru, zh } from './locales/ui.ts'\nimport { NS_HOST, en as hostEn, ru as hostRu, zh as hostZh } from './locales/host.ts'\nimport { registerPluginConfigCard } from './plugin-config.ts'\nimport type { PluginConfigSlotServices } from './plugin-config.ts'\nimport { NS, registerSettingsTab } from './settings.ts'\nimport type { SettingsSlotServices } from './settings.ts'\nimport { localeServiceOf } from './tab-locale.ts'\nimport { registerSidebarTab } from './sidebar-tab.ts'\nimport type { SidebarSettingsProps, SidebarTabBodyProps, SidebarTabServices } from './sidebar-tab.ts'\nimport { registerToasts } from './toasts.ts'\nimport type { ToastsServices } from './toasts.ts'\nimport { ProjectMcpPanel, ProjectMcpSettings, createRefreshStore } from './view.ts'\n\n/** Plugin name: matches the package name and the host half. */\nexport const name = PACKAGE_NAME\n\n/**\n * Register the surfaces, each behind the services it actually needs.\n *\n * No module-level dependency is declared, because every one of them is optional:\n * a module-level `inject` would leave this entry **pending** for good in a\n * composition without the right sidebar, and DSH's web boot audit refuses to\n * start while an entry is pending. `ctx.inject(name, …)` waits for the same\n * services without gating the entry, so a composition without the sidebar keeps\n * the native Settings page, the config card and the toast stack.\n *\n * A service this fiber did not declare must never be read as a property: Cordis\n * throws `cannot get property \"…\" without inject`, and that throw fails the\n * entry, which takes the whole web client boot down. Optional reads go through\n * {@link Context.get}.\n */\nexport const inject: string[] = []\n\n/**\n * Register the browser half's surfaces. Every registration returns a disposer and\n * Cordis runs them on fiber disposal, which is what keeps HMR and plugin\n * disabling free of \"already registered\" failures.\n * @param ctx - client root context.\n */\nexport function apply(ctx: Context): void {\n // The design-only render mode: when the flag names a picture, the four\n // surfaces below are registered from fixtures instead (`./design.ts`). It is a\n // replacement, never an addition — two registrations of one tab type id would\n // fight over the same sidebar cell. The flag is a browser-local preference, so\n // the product and the fixture mode are one bundle apart, not one build apart.\n if (designModeEnabled()) {\n registerDesignSurfaces(ctx)\n return\n }\n\n // The plugin's own translate seat: the slots below are registered without a\n // locale namespace of their own, because the plugin registers its dictionaries\n // itself and wants the tab to repaint on a language switch either way. The\n // shell's locale service is read with `ctx.get` — this fiber does not declare\n // it — and without one the seat falls back to the merged English table\n // composed in ./locales/ui.ts.\n const locale = localeServiceOf(ctx)\n\n // The panel's poll interval, shared by the tab it paces and the popup that\n // changes it. One store for both, because the two are not in one tree.\n const refresh = createRefreshStore()\n\n // The sidebar tab, its chip's settings row and the settings popup itself:\n // `./sidebar-tab.ts` holds the structural contract of DSH's own right sidebar\n // and registers all four seats behind the services they need. `ctx.inject`\n // parks this callback until the slot registry and the tab registry exist, so a\n // composition without a right sidebar still boots everything below.\n ctx.inject(['slots', 'sidebarRightTabs'], (scope) => {\n registerSidebarTab(scope as unknown as SidebarTabServices, {\n locale,\n refresh,\n body: LocalizedPanel,\n settings: LocalizedSettings,\n })\n })\n\n // The native Settings page. `ctx.inject` runs this callback only once both\n // services exist and unloads it when either goes away: a composition without\n // the web settings shell keeps the sidebar tab above and the toast stack\n // below, it just has no page to add.\n ctx.inject(['slots', 'locale'], (scope) => {\n const services = scope as unknown as SettingsSlotServices\n // The shell ships only `zh` and `en`: Russian is added at runtime, and the\n // add must precede the dictionary registration that uses it. `addLanguage`\n // is read optionally — a shell whose locale service predates the method\n // must still boot, with `ru` keys simply falling back to English.\n services.effect(\n () => services.locale.addLanguage?.({ id: 'ru', label: 'Русский', fallback: 'en' }),\n 'dsh-project-mcp: ru language',\n )\n services.effect(\n // One namespace for the whole plugin, one call carrying all three\n // languages: the runtime throws when the same (namespace, locale) pair is\n // registered twice, so three calls are not an option. The tables are the\n // complete ones from ./locales/ui.ts — `en` is the merge of the panel's\n // and the settings page's halves, composed there.\n () => services.locale.register(NS, { zh, en, ru }),\n 'dsh-project-mcp: settings dictionaries',\n )\n services.effect(\n // The second namespace, beside the first: the host's coded messages\n // (F-48). Same one-call shape — a duplicate (namespace, locale) pair\n // throws, so the three languages ride a single registration.\n () => services.locale.register(NS_HOST, { zh: hostZh, en: hostEn, ru: hostRu }),\n 'dsh-project-mcp: host dictionaries',\n )\n registerSettingsTab(services)\n })\n\n // The plugin's own configuration card on the Plugins page (F-54), in an\n // inject of its own: `configForms` is optional (DSH before the service's\n // introduction, or a composition without it), and the settings tab above must\n // not depend on it. `locale` rides along because the card declares the\n // plugin's namespace — the dictionaries themselves stay registered by the\n // settings block, whose inject list is a subset of this one's.\n ctx.inject(['slots', 'locale', 'configForms'], (scope) => {\n const services = scope as unknown as PluginConfigSlotServices\n const forms = services.configForms\n // A service that predates `get`/`whileServed` leaves the card absent\n // rather than failing the entry — the same rule the whole file follows.\n if (typeof forms?.get !== 'function' || typeof forms.whileServed !== 'function') return\n registerPluginConfigCard(services)\n })\n\n // The frame-wide toast stack, in its own inject: a composition without the\n // sidebar still floats banners, and one without the slot registry keeps every\n // other surface. The locale service rides along so a language switch repaints\n // the banners on screen; `shell.overlay` is declared by the layout frame, so\n // `registerToasts` waits for it through `slots.inject` and simply has nothing\n // to register in a shell without a frame.\n ctx.inject(['slots', 'locale'], (scope) => {\n registerToasts(scope as unknown as ToastsServices)\n })\n}\n\n/**\n * The sidebar panel.\n *\n * `./sidebar-tab.ts` already bound the two translate seats — the UI namespace and\n * the host-message one — before calling this, so the adapter has nothing left to\n * do but name the component and let React render it as an element rather than as\n * a bare call.\n * @param props - the body's props, seats included.\n * @returns the panel element.\n */\nexport function LocalizedPanel(props: SidebarTabBodyProps): ReactNode {\n return createElement(ProjectMcpPanel, {\n visible: props.visible,\n sessionId: props.sessionId,\n refreshMs: props.refreshMs,\n t: props.t,\n hostT: props.hostT,\n })\n}\n\n/**\n * The settings popup's content, with the same two seats.\n *\n * The popup is an entry of the frame-wide floating layer, so its chrome has to\n * repaint on a language switch exactly like the tab's: the seats are bound per\n * render by `./sidebar-tab.ts`, and this adapter only names the component.\n * @param props - the popup's props, seats included.\n * @returns the settings panel element.\n */\nexport function LocalizedSettings(props: SidebarSettingsProps): ReactNode {\n return createElement(ProjectMcpSettings, {\n refreshMs: props.refreshMs,\n onRef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F;EACA,SAAS,aAID,SAAS,OAAO,SAAS,SAAS;GAAE,IAAIM;GAAQ,IAAIC;GAAQ,IAAIC;EAAO,CAAC,GAC9E,oCACF;EACA,oBAAoB,QAAQ;CAC9B,CAAC;CAQD,IAAI,OAAO;EAAC;EAAS;EAAU;CAAa,IAAI,UAAU;EACxD,MAAM,WAAW;EACjB,MAAM,QAAQ,SAAS;EAGvB,IAAI,OAAO,OAAO,QAAQ,cAAc,OAAO,MAAM,gBAAgB,YAAY;EACjF,yBAAyB,QAAQ;CACnC,CAAC;CAQD,IAAI,OAAO,CAAC,SAAS,QAAQ,IAAI,UAAU;EACzC,eAAe,KAAkC;CACnD,CAAC;AACH;;;;;;;;;;;AAYA,SAAgB,eAAe,OAAuC;CACpE,QAAA,GAAOC,MAAAA,cAAAA,CAAc,iBAAiB;EACpC,SAAS,MAAM;EACf,WAAW,MAAM;EACjB,WAAW,MAAM;EACjB,GAAG,MAAM;EACT,OAAO,MAAM;CACf,CAAC;AACH;;;;;;;;;;AAWA,SAAgB,kBAAkB,OAAwC;CACxE,QAAA,GAAOA,MAAAA,cAAAA,CAAc,oBAAoB;EACvC,WAAW,MAAM;EACjB,aAAa,MAAM;EACnB,SAAS,MAAM;EACf,GAAG,MAAM;EACT,OAAO,MAAM;CACf,CAAC;AACH"}
1
+ {"version":3,"file":"client.js","names":["en","zh","ru","en","translateOf","fallbackTranslate","BORDER","STYLE","useState","useCallback","h","h","STYLE","EN","translateOf","fallbackTranslate","STYLE","useState","h","useCallback","useRef","useMemo","useSyncExternalStore","h","STYLE","useState","EN","viewEn","configEn","useState","useState","h","STYLE","h","useState","translateOf","translateOf","h","STYLE","useState","hostZh","hostEn","hostRu","hostZh","hostEn","hostRu","createElement"],"sources":["../src/shared.ts","../src/client/locales/host.ts","../src/types.ts","../src/client/policy.ts","../src/client/usage-view.ts","../src/client/view.ts","../src/client/settings-tools.ts","../src/client/settings.ts","../src/client/plugin-config.ts","../src/client/locales/ui.ts","../src/client/tab-locale.ts","../src/client/sidebar-tab.ts","../src/client/toasts.ts","../src/client/design-fixtures.ts","../src/client/design.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Contract shared by the host half and the browser half of the panel.\n *\n * Import-free on purpose: the client bundle must not pull host code in, and the\n * right sidebar exists only in the browser half, so the two halves meet at these\n * routes over HTTP.\n *\n * @module dsh-project-mcp/shared\n */\n\nimport type { ConflictChoice, EntrySnapshot, ToolMode } from './types.ts'\n\n/** Route prefix the host serves and the sidebar panel fetches. */\nexport const ROUTE_PREFIX = '/project-mcp'\n\n/** Sidebar tab id; also the `SidebarTab.type` the panel opens as. */\nexport const TAB_ID = 'dsh-project-mcp:servers'\n\n/** Plugin name, shared by both halves. */\nexport const PACKAGE_NAME = 'dsh-project-mcp'\n\n/** Actions the host serves under {@link ROUTE_PREFIX}, and the panel fetches. */\nexport const ROUTE_ACTIONS = {\n /** `GET`: the current snapshot. */\n snapshot: 'snapshot',\n /** `POST`: ask for a rescan; answers as soon as the request is accepted. */\n sync: 'sync',\n /** `POST`: drop this project's failed mounts and re-mount them; answers once they are dropped. */\n retry: 'retry',\n /** `GET`: the status channel — one pushed frame per change, held open. */\n events: 'events',\n /** `GET`: one page of a project's log ring, oldest first, for \"show older\". */\n logs: 'logs',\n /**\n * `GET`: one tool's detail — its description, its accepted fields, its\n * measured size and the reason it is not offered — read once per opened row\n * so that neither the snapshot nor a change frame carries it.\n */\n tool: 'tool',\n /** `POST`: release this session's mounts. */\n release: 'release',\n /** `POST`: write one edited entry back to its declaring document. */\n save: 'save',\n /** `POST`: pin or unpin one tool of one project. */\n pin: 'pin',\n /** `POST`: set one project's tool mode. */\n policy: 'policy',\n /** `POST`: choose which declaration of a contested `serverName` shows. */\n conflict: 'conflict',\n} as const\n\n/**\n * One operator request: the body of `POST sync` and `POST retry`.\n *\n * `projectRoot` scopes the action, so a surface that shows one project never\n * starts or restarts a server for another. `full` is the answer shape: a\n * single-project surface leaves it out and gets that project's slice back, while\n * a surface that lists every project — the settings page — asks for the whole\n * snapshot, since narrowing would empty the list it renders.\n */\nexport interface OperatorRequest {\n /** Project the action applies to; omitted covers every project. */\n readonly projectRoot?: string\n /** Answer with the whole snapshot rather than `projectRoot`'s slice. */\n readonly full?: boolean\n}\n\n/** Pin or unpin one tool of one project. */\nexport interface PinRequest {\n /** Project root the tool belongs to. */\n readonly projectRoot: string\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly tool: string\n /** `true` pins it, `false` unpins it. */\n readonly pinned: boolean\n}\n\n/** Set one project's tool mode. Pins travel in their own request. */\nexport interface PolicyRequest {\n /** Project root the mode applies to. */\n readonly projectRoot: string\n /** The mode to store. */\n readonly mode: ToolMode\n}\n\n/**\n * Choose which declaration of one contested `serverName` a project shows.\n *\n * The name stays the profile's either way; the answer decides whether the\n * project's own entry mounts beside it under a local namespace. The name is\n * carried as declared — the sanitized `mcpServers` key — because that is what\n * the conflict report names, and the local name is the plugin's to compute.\n */\nexport interface ConflictRequest {\n /** Project root the name belongs to. */\n readonly projectRoot: string\n /** Contested `serverName`, as the project declared it. */\n readonly server: string\n /** The declaration to show. */\n readonly choice: ConflictChoice\n}\n\n/**\n * One entry a save writes.\n *\n * The panel submits the {@link EntrySnapshot} it was given, with the fields the\n * user changed. A masked `env`/`headers` key submitted without a `value` keeps\n * whatever the document declares for it; a key the submission omits is removed.\n */\nexport interface SaveRequest {\n /** Project root the edited row belongs to. */\n readonly projectRoot: string\n /** `serverName` being edited. */\n readonly server: string\n /** Absolute path of the document the entry came from. */\n readonly document: string\n /** `documentRevision` the edit was built from; a mismatch refuses the write. */\n readonly revision: string\n /** `true` acknowledges a write to the global tier; required only there. */\n readonly consent?: boolean\n /** The entry body to write. */\n readonly entry: EntrySnapshot\n}\n\n/** Error codes a save answers with, each with its own sentence in the panel. */\nexport type SaveErrorCode =\n /** The entry is not one this plugin would mount; nothing was written. */\n | 'invalid'\n /** The document may not be written: profile, `<DSH_HOME>`, or no consent. */\n | 'blocked'\n /** The document changed since the snapshot was taken; nothing was written. */\n | 'conflict'\n /** The document or the server is no longer there. */\n | 'not-found'\n /** The write itself failed; the document is left as it was. */\n | 'failed'","/**\n * The `projectMcp.host` namespace: the wire contract for every message the\n * plugin's host half produces that a human can read (F-48).\n *\n * Host messages travel as `{ code, params, message }` — a dotted, stable code\n * plus its flat params for translation, and the English `message` always\n * present as the fallback. The keys below are the contract: a code, once\n * shipped, is never renamed, and rewording happens in dictionary values only.\n * That is why this namespace is separate from `settings.projectMcp`, whose\n * camelCase copy is reworded freely.\n *\n * The tables are declared `Record<HostCode, string>`, so the compiler reads\n * every code of the union off each literal and a table that lacks one does not\n * build — the same gate F-46 put on the UI namespace. The `en` values\n * duplicate the emission-time English messages on purpose: intentional\n * redundancy across a wire, not drift (the table serves the harness's own\n * fallback chain, the payload's `message` field serves old clients and the\n * resolver's last step). `tests/host-resolve.spec.ts` asserts the two are\n * byte-identical where a test can see both.\n *\n * The `zh` and `ru` tables reuse the F-46 terminology of `./ui.ts`\n * (deployment → 部署 / установка, document → 文档 / документ) and,\n * like it, are maintainer-authored and pending review.\n *\n * @module src/client/locales/host\n */\n\nimport type { TabLocale } from '../tab-locale.ts'\nimport type { Translate } from '../view.ts'\n\n/** Locale namespace the host's coded messages are registered under. */\nexport const NS_HOST = 'projectMcp.host'\n\n/**\n * Every wire code the host half can emit. The union grows per task of F-48;\n * the tables below are what force per-commit completeness. Each code carries a\n * one-line comment naming the channel that emits it.\n */\nexport type HostCode =\n | 'write.blocked.notConfigured'\n | 'write.blocked.notWritable'\n | 'write.blocked.globalDisabled'\n // The parse channel (Task 2): parseDocument's diagnostics, plus the runtime's\n // multi-document merge warning — the code the client compares, never the prose.\n | 'parse.json.invalid'\n | 'parse.doc.notObject'\n | 'parse.server.duplicateName'\n | 'parse.server.badName'\n | 'parse.server.renamedName'\n | 'parse.server.multiDocument'\n | 'parse.entry.notObject'\n | 'parse.entry.badType'\n | 'parse.entry.typeUnknown'\n | 'parse.entry.noCommand'\n | 'parse.entry.badArgs'\n | 'parse.entry.badEnv'\n | 'parse.entry.badCwd'\n | 'parse.entry.noUrl'\n | 'parse.entry.badHeaders'\n | 'parse.ref.empty'\n | 'parse.ref.inputUnset'\n | 'parse.ref.varUnset'\n | 'parse.ref.failedInKey'\n // The lifecycle channel (Task 3): the five logLifecycle events, the two\n // sharing phrases `mount.starting` nests two-level, the twelve unmount\n // reasons `unmounting` nests, and the four idle row details.\n | 'mount.starting'\n | 'mount.sharingShared'\n | 'mount.sharingForwarded'\n | 'mount.failed'\n | 'mount.failedDetail'\n | 'mount.up'\n | 'mount.stalled'\n | 'mount.stalledDetail'\n | 'unmounting'\n | 'unmount.reason.operatorRetry'\n | 'unmount.reason.unloading'\n | 'unmount.reason.sessionGone'\n | 'unmount.reason.sessionUnlisted'\n | 'unmount.reason.sessionMoved'\n | 'unmount.reason.sessionIdle'\n | 'unmount.reason.operatorReleased'\n | 'unmount.reason.profileShown'\n | 'unmount.reason.undeclared'\n | 'unmount.reason.nameChanged'\n | 'unmount.reason.declarationChanged'\n | 'unmount.reason.nothingMountable'\n | 'idle.lazy'\n | 'idle.disabled'\n | 'idle.releasedInactive'\n | 'idle.releasedRequest'\n // The conflict channel (Task 4): the two shapes of the profile-conflict\n // report, the duplicate-document report, the two readings of a shadowed\n // row's detail, and the presentation owner's note.\n | 'conflict.profile'\n | 'conflict.profileAlias'\n | 'conflict.documents'\n | 'conflict.profileDetail'\n | 'conflict.profileAliasDetail'\n | 'present.ownerNote'\n // The save channel (Task 5): every refusal of saveEntry and of the three\n // policy writes (setPin/setPolicy/setConflictChoice). The five\n // SaveErrorCodes stay the HTTP-status axis — these code the messages.\n | 'save.noPolicyStore'\n | 'save.noLiveSession'\n | 'save.unknownMode'\n | 'save.unknownChoice'\n | 'save.serverNotDeclared'\n | 'save.noDeclaringDocument'\n | 'save.notWritable'\n | 'save.needsConsent'\n | 'save.globalDisabled'\n | 'save.declaredElsewhere'\n | 'save.documentGone'\n | 'save.documentChanged'\n | 'save.invalidJson'\n | 'save.noMcpServers'\n | 'save.noLongerDeclared'\n | 'save.entryNotParsed'\n | 'save.writeFailed'\n // The trio applyEntry (src/write.ts) throws as WriteDocError and the save\n // path reuses beside its `invalid` refusal.\n | 'write.doc.invalidJson'\n | 'write.doc.notObject'\n | 'write.doc.noMcpServers'\n\n/**\n * English. Byte-identical to the literals `writeScopeFor` (`src/write.ts`)\n * emits as `reason` — the harness's own fallback chain ends here, one step\n * before the resolver falls back to the payload's `message`.\n */\nexport const en: Record<HostCode, string> = {\n // writeScopeFor: the document is none the deployment reads, and none is configured to write.\n 'write.blocked.notConfigured':\n '{document} is not a document this deployment reads, and it configures none to write',\n // writeScopeFor: the document is not among the deployment's MCP documents; {writable} lists them.\n 'write.blocked.notWritable':\n \"{document} is not one of this deployment's MCP documents; only {writable} can be written\",\n // writeScopeFor: a global-tier document with the deployment's allowGlobalWrite off.\n 'write.blocked.globalDisabled':\n 'writing the global tier is disabled by this deployment (allowGlobalWrite: false); {document} stays read-only here',\n // parseDocument: the document's text is not JSON at all.\n 'parse.json.invalid': 'invalid JSON: {error}',\n // parseDocument: no `mcpServers`/`servers` map and not a flat server map either.\n 'parse.doc.notObject': 'expected an object with an \"mcpServers\" object',\n // parseDocument: two keys sanitize to one serverName inside one document.\n 'parse.server.duplicateName': 'serverName \"{name}\" is declared twice in this document',\n // sanitizeName: nothing of the key survives slugification.\n 'parse.server.badName': '\"{key}\" cannot be converted into a valid serverName ({pattern})',\n // sanitizeName: the key mounts under its slug instead.\n 'parse.server.renamedName': 'serverName \"{key}\" is not a valid mcp-client name; using \"{slug}\"',\n // The runtime's merge pass: a later document overrode this name's earlier declaration.\n 'parse.server.multiDocument':\n 'serverName \"{name}\" was declared in more than one document; the highest-priority definition wins',\n // toEntry: the entry's value is not an object.\n 'parse.entry.notObject': 'entry must be an object',\n // toEntry: a `type`/`transport` that is not a string.\n 'parse.entry.badType': '\"type\" must be a string',\n // toEntry: a `type` outside the four known transports.\n 'parse.entry.typeUnknown': '\"type\" must be one of \"stdio\", \"http\", \"streamable-http\" or \"sse\"',\n // buildStdioEntry: no command to run.\n 'parse.entry.noCommand': 'stdio servers require a \"command\"',\n // buildStdioEntry: `args` present but not a string array.\n 'parse.entry.badArgs': '\"args\" must be an array of strings',\n // buildStdioEntry: `env` present but not a string map.\n 'parse.entry.badEnv': '\"env\" must be an object of strings',\n // buildStdioEntry: `cwd` present but not a string.\n 'parse.entry.badCwd': '\"cwd\" must be a string',\n // buildHttpEntry: no url to connect to.\n 'parse.entry.noUrl': 'http servers require a \"url\"',\n // buildHttpEntry: `headers` present but not a string map.\n 'parse.entry.badHeaders': '\"headers\" must be an object of strings',\n // resolveRef: `${input:}` with no name.\n 'parse.ref.empty': 'empty ${input:} reference',\n // resolveRef: an `${input:NAME}` no source answers.\n 'parse.ref.inputUnset':\n 'input \"{key}\" is not set (looked in plugin inputs, the project .env, the environment, and the credentials file)',\n // resolveRef: a `${NAME}` no source answers.\n 'parse.ref.varUnset':\n 'variable \"{name}\" is not set (looked in the project .env, the environment, and the credentials file)',\n // expandRecord: a reference failed inside an env/headers value; {name} is the inner message.\n 'parse.ref.failedInKey': '{key}: {name}',\n // mount(): a mount is registered. {sharing} is the two-level nesting of\n // mount.sharingShared / mount.sharingForwarded, substituted from sharingCode.\n 'mount.starting': 'mounting for session {sessionId} (trigger: {trigger}; {sharing})',\n // mount(): the session shares the project's instance directly (parent-linked).\n 'mount.sharingShared': 'one shared instance for every session of this project',\n // mount(): the session's key could not be linked, so the bridge forwards.\n 'mount.sharingForwarded':\n \"one shared instance for this project, forwarded into this session's own layer\",\n // recordMountFailure(): the activation or the registration threw.\n 'mount.failed': 'mount failed — {error}',\n // failureDetail(): one template, three lines — the name and the error, the\n // endpoint, the declaring document.\n 'mount.failedDetail': '{name}: mount failed — {error}\\nendpoint: {endpoint}\\ndeclared in: {source}',\n // refreshStatuses(): the mount's tools became visible to the session.\n 'mount.up': 'is up — tools visible to session {sessionId} after {elapsed}',\n // refreshStatuses(): the connect watchdog fired.\n 'mount.stalled': 'no tool appeared in {elapsed}',\n // stallDetail(): the same three facts as mount.failedDetail, for a stall.\n 'mount.stalledDetail': '{name}: no tool appeared in {elapsed}\\nendpoint: {endpoint}\\ndeclared in: {source}',\n // logUnmount(): a mount is going away. {reason} is the two-level nesting of\n // one of the unmount.reason.* codes, substituted from reasonCode.\n 'unmounting': 'unmounting — {reason} (it ran for {ran})',\n // retry(): the dropped error mount is being replaced by the operator pass.\n 'unmount.reason.operatorRetry': 'an operator retry replaces it',\n // disposeAll(): the whole runtime is going down.\n 'unmount.reason.unloading': 'the plugin is unloading',\n // agent scope event: the session's agent disappeared.\n 'unmount.reason.sessionGone': 'the session went away',\n // session sweep: the host registry dropped the session.\n 'unmount.reason.sessionUnlisted': 'the registry no longer lists the session',\n // syncAgent()/holdProject(): the session's cwd resolved to another root.\n 'unmount.reason.sessionMoved': 'the session moved to another project',\n // evictIdle(): the session was quiet past idleTimeoutMs.\n 'unmount.reason.sessionIdle': 'the session went idle',\n // release(): the operator asked for the release.\n 'unmount.reason.operatorReleased': 'an operator released it',\n // syncAgent(): a reserved name whose shadowing declaration disappeared.\n 'unmount.reason.profileShown': 'this project shows the profile-level copy instead',\n // syncAgent(): the documents stopped declaring the mounted name.\n 'unmount.reason.undeclared': 'the documents no longer declare it',\n // syncAgent(): the chosen local alias changed under a live mount.\n 'unmount.reason.nameChanged': 'its local name changed',\n // syncAgent(): the declaration's fingerprint changed under a live mount.\n 'unmount.reason.declarationChanged': 'its declaration changed',\n // syncAgent(): the declarations left mount nothing.\n 'unmount.reason.nothingMountable': 'nothing it declares is mountable any more',\n // syncAgent(): a declaration `lazy` has not mounted yet.\n 'idle.lazy': 'not mounted yet — this session has not started a turn (lazy mounting is on)',\n // syncAgent(): the entry declares `enabled: false`.\n 'idle.disabled': 'declared with enabled: false',\n // evictIdle() via releaseMounts(): the idle release's row detail.\n 'idle.releasedInactive':\n 'released after {seconds} without activity — {count} server(s) stopped; the next turn mounts them again',\n // release() via releaseMounts(): the requested release's row detail.\n 'idle.releasedRequest':\n 'released on request — {count} server(s) stopped; the next turn mounts them again',\n // conflictsFor(): a profile-level instance owns the name, and this project\n // has no local alias to offer.\n 'conflict.profile':\n '\"{name}\" is owned by a profile-level mcp-client instance, so the project entry does not mount under it; remove the profile entry to use the project one everywhere, or let this project\\'s copy take the name in this project\\'s sessions alone.',\n // conflictsFor(): the same, with the local alias the choice would mount under.\n 'conflict.profileAlias':\n '\"{name}\" is owned by a profile-level mcp-client instance; this project\\'s copy mounts as \"{alias}\" when chosen beside it, or under the contested name when chosen to shadow it in this project\\'s sessions, and does not mount at all while the profile\\'s copy is the one shown.',\n // conflictsFor(): one name declared by {count} documents; {winner} is the\n // document the merge kept.\n 'conflict.documents':\n '\"{name}\" is declared in {count} documents; {winner} wins and the other declaration is not mounted.',\n // conflictDetail(): the shadowed row's detail, no alias to offer.\n 'conflict.profileDetail':\n 'serverName \"{name}\" is already provided by a profile-level mcp-client instance — remove that entry from the profile to use the project one everywhere, or choose this project\\'s copy to let it take the name in this project\\'s sessions',\n // conflictDetail(): the shadowed row's detail, with the local alias.\n 'conflict.profileAliasDetail':\n 'serverName \"{name}\" is already provided by a profile-level mcp-client instance — choose this project\\'s copy to mount it as \"{alias}\", or under the contested name to shadow the profile instance here',\n // presentationOwner(): why this plugin and a second owner cannot shape one\n // request. No params — one fixed sentence.\n 'present.ownerNote':\n 'a second presentation owner rewrites assembly.tools after this plugin does, so the two never combine in one request: either this plugin shapes only its own mcp__* entries, or the other owner is unmounted.',\n // setPin/setPolicy/setConflictChoice: the host was built without a policy store.\n 'save.noPolicyStore': 'this host has no tool-policy store',\n // setPin/setPolicy/setConflictChoice: the named project has no live session here.\n 'save.noLiveSession': 'no live session in {projectRoot}',\n // setPolicy: a mode no assembly knows; {mode} is the JSON-stringified value.\n 'save.unknownMode': 'unknown tool mode {mode}',\n // setConflictChoice: an answer no build knows; {choice} is the JSON-stringified value.\n 'save.unknownChoice': 'unknown conflict choice {choice}',\n // saveEntry: no live row of this project carries the name.\n 'save.serverNotDeclared': 'server \"{server}\" is not declared for {projectRoot}',\n // saveEntry: the row names no declaring document to write to.\n 'save.noDeclaringDocument': 'server \"{server}\" has no declaring document to write',\n // saveEntry: the defensive readonly fallback — writeScopeFor's own reason\n // arrives coded (write.blocked.*) and is reused instead whenever it exists.\n 'save.notWritable': '{document} is not writable',\n // saveEntry: a global-tier write submitted without the explicit consent.\n 'save.needsConsent': 'writing {document} needs explicit consent',\n // saveEntry: a global-tier write with the deployment's allowGlobalWrite off.\n 'save.globalDisabled': 'writing the global tier is disabled by this deployment (allowGlobalWrite: false)',\n // saveEntry: the editor's document no longer declares the name.\n 'save.declaredElsewhere': 'server \"{server}\" is now declared by {document}',\n // saveEntry: the declaring document could not be read back at all.\n 'save.documentGone': 'the declaring document {document} is gone',\n // saveEntry: the document's revision moved past the one the editor read.\n 'save.documentChanged': '{document} changed since the entry was read; reload it and edit again',\n // saveEntry: the document read back is not JSON any more.\n 'save.invalidJson': 'the declaring document is not valid JSON: {error}',\n // saveEntry: the document holds no \"mcpServers\" object to rewrite.\n 'save.noMcpServers': '{document} does not use an \"mcpServers\" object, so this editor cannot rewrite it',\n // saveEntry: the document parses, but no key of it names the server.\n 'save.noLongerDeclared': 'server \"{server}\" is no longer declared in {document}',\n // saveEntry: the written-back entry failed the mount path's own parse. When\n // the parse named its failure, that failure's own code (parse.*) is reused\n // instead — this code names only the shapeless fallback.\n 'save.entryNotParsed': 'the edited entry \"{server}\" did not parse',\n // saveEntry: writeDocument threw (the backup, the temporary write or the rename).\n 'save.writeFailed': 'writing {document} failed: {error}',\n // applyEntry: the document text is not JSON at all.\n 'write.doc.invalidJson': 'the document is not valid JSON: {error}',\n // applyEntry: the document parses to something that is not an object.\n 'write.doc.notObject': 'the document is not a JSON object',\n // applyEntry: the document holds no \"mcpServers\" object.\n 'write.doc.noMcpServers': 'the document has no \"mcpServers\" object',\n}\n\n/** Chinese, complete across the namespace: the `Record<HostCode, string>` annotation proves it. */\nexport const zh: Record<HostCode, string> = {\n 'write.blocked.notConfigured': '{document} 不是此部署读取的文档,它也未配置任何可写入的文档',\n 'write.blocked.notWritable': '{document} 不是此部署的 MCP 文档之一;只能写入 {writable}',\n 'write.blocked.globalDisabled':\n '此部署已禁用全局级的写入(allowGlobalWrite: false);{document} 在此处保持只读',\n 'parse.json.invalid': '无效的 JSON:{error}',\n 'parse.doc.notObject': '预期是一个带有 \"mcpServers\" 对象的对象',\n 'parse.server.duplicateName': 'serverName \"{name}\" 在此文档中声明了两次',\n 'parse.server.badName': '\"{key}\" 无法转换为有效的 serverName({pattern})',\n 'parse.server.renamedName': 'serverName \"{key}\" 不是有效的 mcp-client 名称;改用 \"{slug}\"',\n 'parse.server.multiDocument': 'serverName \"{name}\" 在不止一份文档中声明;优先级最高的定义生效',\n 'parse.entry.notObject': '条目必须是对象',\n 'parse.entry.badType': '\"type\" 必须是字符串',\n 'parse.entry.typeUnknown': '\"type\" 必须是 \"stdio\"、\"http\"、\"streamable-http\" 或 \"sse\" 之一',\n 'parse.entry.noCommand': 'stdio 服务器需要 \"command\"',\n 'parse.entry.badArgs': '\"args\" 必须是字符串数组',\n 'parse.entry.badEnv': '\"env\" 必须是字符串组成的对象',\n 'parse.entry.badCwd': '\"cwd\" 必须是字符串',\n 'parse.entry.noUrl': 'http 服务器需要 \"url\"',\n 'parse.entry.badHeaders': '\"headers\" 必须是字符串组成的对象',\n 'parse.ref.empty': '空的 ${input:} 引用',\n 'parse.ref.inputUnset': '输入 \"{key}\" 未设置(已在插件 inputs、项目 .env、环境和凭据文件中查找)',\n 'parse.ref.varUnset': '变量 \"{name}\" 未设置(已在项目 .env、环境和凭据文件中查找)',\n 'parse.ref.failedInKey': '{key}:{name}',\n 'mount.starting': '正在为会话 {sessionId} 挂载(触发方式:{trigger};{sharing})',\n 'mount.sharingShared': '此项目的所有会话共享一个实例',\n 'mount.sharingForwarded': '此项目共享一个实例,已转发进此会话自己的层',\n 'mount.failed': '挂载失败 — {error}',\n 'mount.failedDetail': '{name}:挂载失败 — {error}\\n端点:{endpoint}\\n声明于:{source}',\n 'mount.up': '已就绪 — {elapsed} 后工具对会话 {sessionId} 可见',\n 'mount.stalled': '{elapsed} 内没有出现任何工具',\n 'mount.stalledDetail': '{name}:{elapsed} 内没有出现任何工具\\n端点:{endpoint}\\n声明于:{source}',\n 'unmounting': '正在卸载 — {reason}(已运行 {ran})',\n 'unmount.reason.operatorRetry': '操作员发起的重试将取代它',\n 'unmount.reason.unloading': '插件正在退出',\n 'unmount.reason.sessionGone': '会话已消失',\n 'unmount.reason.sessionUnlisted': '注册表不再列出该会话',\n 'unmount.reason.sessionMoved': '会话已移动到另一个项目',\n 'unmount.reason.sessionIdle': '会话已空闲',\n 'unmount.reason.operatorReleased': '操作员释放了它',\n 'unmount.reason.profileShown': '此项目改为显示配置文件级的副本',\n 'unmount.reason.undeclared': '文档不再声明它',\n 'unmount.reason.nameChanged': '它的本地名称已更改',\n 'unmount.reason.declarationChanged': '它的声明已更改',\n 'unmount.reason.nothingMountable': '它声明的内容不再有可挂载的',\n 'idle.lazy': '尚未挂载 — 此会话还没有开始任何一轮对话(惰性挂载已开启)',\n 'idle.disabled': '以 enabled: false 声明',\n 'idle.releasedInactive': '在 {seconds} 无活动后释放 — 已停止 {count} 个服务器;下一轮对话会重新挂载它们',\n 'idle.releasedRequest': '已按请求释放 — 已停止 {count} 个服务器;下一轮对话会重新挂载它们',\n 'conflict.profile':\n '\"{name}\" 已由配置文件级的 mcp-client 实例占用,因此项目条目不会以该名称挂载;请从配置文件中移除该条目以在各处使用项目副本,或让此项目的副本仅在此项目的会话中使用该名称。',\n 'conflict.profileAlias':\n '\"{name}\" 已由配置文件级的 mcp-client 实例占用;选择并存时此项目的副本以 \"{alias}\" 挂载,选择遮蔽时则在此项目的会话中使用被争用的名称,而在显示配置文件副本期间完全不挂载。',\n 'conflict.documents': '\"{name}\" 在 {count} 份文档中声明;{winner} 生效,另一份声明不会被挂载。',\n 'conflict.profileDetail':\n 'serverName \"{name}\" 已由配置文件级的 mcp-client 实例提供 — 从配置文件中移除该条目以在各处使用项目副本,或选择此项目的副本让它在此项目的会话中使用该名称',\n 'conflict.profileAliasDetail':\n 'serverName \"{name}\" 已由配置文件级的 mcp-client 实例提供 — 选择此项目的副本将其挂载为 \"{alias}\",或选择被争用的名称以在此处遮蔽配置文件实例',\n 'present.ownerNote':\n '第二个呈现所有者会在此插件之后重写 assembly.tools,因此两者永远不会在同一请求中合并:要么此插件只塑造自己的 mcp__* 条目,要么卸载另一个所有者。',\n 'save.noPolicyStore': '此宿主没有工具策略存储',\n 'save.noLiveSession': '{projectRoot} 中没有活跃会话',\n 'save.unknownMode': '未知的工具模式 {mode}',\n 'save.unknownChoice': '未知的冲突选择 {choice}',\n 'save.serverNotDeclared': '服务器 \"{server}\" 未在 {projectRoot} 中声明',\n 'save.noDeclaringDocument': '服务器 \"{server}\" 没有可写入的声明文档',\n 'save.notWritable': '{document} 不可写入',\n 'save.needsConsent': '写入 {document} 需要明确同意',\n 'save.globalDisabled': '此部署已禁用全局级的写入(allowGlobalWrite: false)',\n 'save.declaredElsewhere': '服务器 \"{server}\" 现在由 {document} 声明',\n 'save.documentGone': '声明文档 {document} 已不存在',\n 'save.documentChanged': '{document} 自读取条目后已更改;请重新加载后再编辑',\n 'save.invalidJson': '声明文档不是有效的 JSON:{error}',\n 'save.noMcpServers': '{document} 未使用 \"mcpServers\" 对象,因此此编辑器无法重写它',\n 'save.noLongerDeclared': '服务器 \"{server}\" 不再在 {document} 中声明',\n 'save.entryNotParsed': '编辑后的条目 \"{server}\" 无法解析',\n 'save.writeFailed': '写入 {document} 失败:{error}',\n 'write.doc.invalidJson': '文档不是有效的 JSON:{error}',\n 'write.doc.notObject': '文档不是 JSON 对象',\n 'write.doc.noMcpServers': '文档没有 \"mcpServers\" 对象',\n}\n\n/** Russian, complete across the namespace on the same annotation. */\nexport const ru: Record<HostCode, string> = {\n 'write.blocked.notConfigured':\n '{document} — не документ, который читает эта установка, и она не настраивает ни одного для записи',\n 'write.blocked.notWritable':\n '{document} не входит в MCP-документы этой установки; записать можно только {writable}',\n 'write.blocked.globalDisabled':\n 'запись в глобальный уровень отключена этой установкой (allowGlobalWrite: false); {document} остаётся здесь доступным только для чтения',\n 'parse.json.invalid': 'недопустимый JSON: {error}',\n 'parse.doc.notObject': 'ожидался объект с объектом \"mcpServers\"',\n 'parse.server.duplicateName': 'serverName \"{name}\" объявлен в этом документе дважды',\n 'parse.server.badName': '\"{key}\" невозможно преобразовать в допустимый serverName ({pattern})',\n 'parse.server.renamedName':\n 'serverName \"{key}\" не является допустимым именем mcp-client; используется \"{slug}\"',\n 'parse.server.multiDocument':\n 'serverName \"{name}\" объявлен более чем в одном документе; побеждает определение с наивысшим приоритетом',\n 'parse.entry.notObject': 'запись должна быть объектом',\n 'parse.entry.badType': '\"type\" должно быть строкой',\n 'parse.entry.typeUnknown': '\"type\" должно быть одним из \"stdio\", \"http\", \"streamable-http\" или \"sse\"',\n 'parse.entry.noCommand': 'stdio-серверы требуют \"command\"',\n 'parse.entry.badArgs': '\"args\" должно быть массивом строк',\n 'parse.entry.badEnv': '\"env\" должно быть объектом из строк',\n 'parse.entry.badCwd': '\"cwd\" должно быть строкой',\n 'parse.entry.noUrl': 'http-серверы требуют \"url\"',\n 'parse.entry.badHeaders': '\"headers\" должно быть объектом из строк',\n 'parse.ref.empty': 'пустая ссылка ${input:}',\n 'parse.ref.inputUnset':\n 'input \"{key}\" не задан (искали в inputs плагина, в .env проекта, в окружении и в файле учётных данных)',\n 'parse.ref.varUnset':\n 'переменная \"{name}\" не задана (искали в .env проекта, в окружении и в файле учётных данных)',\n 'parse.ref.failedInKey': '{key}: {name}',\n 'mount.starting': 'монтирование для сессии {sessionId} (триггер: {trigger}; {sharing})',\n 'mount.sharingShared': 'один общий экземпляр для каждой сессии этого проекта',\n 'mount.sharingForwarded':\n 'один общий экземпляр на этот проект, проброшенный в собственный слой этой сессии',\n 'mount.failed': 'монтирование не удалось — {error}',\n 'mount.failedDetail':\n '{name}: монтирование не удалось — {error}\\nэндпоинт: {endpoint}\\nобъявлено в: {source}',\n 'mount.up': 'поднят — инструменты видны сессии {sessionId} спустя {elapsed}',\n 'mount.stalled': 'за {elapsed} не появилось ни одного инструмента',\n 'mount.stalledDetail':\n '{name}: за {elapsed} не появилось ни одного инструмента\\nэндпоинт: {endpoint}\\nобъявлено в: {source}',\n 'unmounting': 'снятие — {reason} (проработал {ran})',\n 'unmount.reason.operatorRetry': 'его заменяет повторная попытка оператора',\n 'unmount.reason.unloading': 'плагин выгружается',\n 'unmount.reason.sessionGone': 'сессия исчезла',\n 'unmount.reason.sessionUnlisted': 'реестр больше не содержит эту сессию',\n 'unmount.reason.sessionMoved': 'сессия перешла в другой проект',\n 'unmount.reason.sessionIdle': 'сессия простаивает',\n 'unmount.reason.operatorReleased': 'оператор освободил его',\n 'unmount.reason.profileShown': 'этот проект вместо него показывает копию уровня профиля',\n 'unmount.reason.undeclared': 'документы больше не объявляют его',\n 'unmount.reason.nameChanged': 'его локальное имя изменилось',\n 'unmount.reason.declarationChanged': 'его объявление изменилось',\n 'unmount.reason.nothingMountable': 'ничего из объявленного им больше нельзя смонтировать',\n 'idle.lazy':\n 'ещё не смонтирован — эта сессия ещё не начала ни одного шага (ленивое монтирование включено)',\n 'idle.disabled': 'объявлен с enabled: false',\n 'idle.releasedInactive':\n 'освобождено после {seconds} без активности — остановлено серверов: {count}; следующий шаг смонтирует их снова',\n 'idle.releasedRequest':\n 'освобождено по запросу — остановлено серверов: {count}; следующий шаг смонтирует их снова',\n 'conflict.profile':\n '\"{name}\" принадлежит экземпляру mcp-client уровня профиля, поэтому запись проекта не монтируется под этим именем; удалите запись из профиля, чтобы использовать проектную везде, или позвольте копии этого проекта занять имя только в сессиях этого проекта.',\n 'conflict.profileAlias':\n '\"{name}\" принадлежит экземпляру mcp-client уровня профиля; копия этого проекта монтируется как \"{alias}\" при выборе рядом с ним или под спорным именем при выборе затенения в сессиях этого проекта и не монтируется вовсе, пока показана копия профиля.',\n 'conflict.documents':\n '\"{name}\" объявлен в документах: {count}; побеждает {winner}, а другое объявление не монтируется.',\n 'conflict.profileDetail':\n 'serverName \"{name}\" уже предоставлен экземпляром mcp-client уровня профиля — удалите эту запись из профиля, чтобы использовать проектную везде, или выберите копию этого проекта, чтобы она заняла имя в сессиях этого проекта',\n 'conflict.profileAliasDetail':\n 'serverName \"{name}\" уже предоставлен экземпляром mcp-client уровня профиля — выберите копию этого проекта, чтобы смонтировать её как \"{alias}\", или спорное имя, чтобы затенить экземпляр профиля здесь',\n 'present.ownerNote':\n 'второй владелец представления перезаписывает assembly.tools после этого плагина, поэтому оба никогда не объединяются в одном запросе: либо этот плагин формирует только свои записи mcp__*, либо другой владелец выгружается.',\n 'save.noPolicyStore': 'у этого хоста нет хранилища политики инструментов',\n 'save.noLiveSession': 'нет активной сессии в {projectRoot}',\n 'save.unknownMode': 'неизвестный режим инструментов {mode}',\n 'save.unknownChoice': 'неизвестный выбор конфликта {choice}',\n 'save.serverNotDeclared': 'сервер \"{server}\" не объявлен для {projectRoot}',\n 'save.noDeclaringDocument': 'у сервера \"{server}\" нет объявляющего документа для записи',\n 'save.notWritable': '{document} недоступен для записи',\n 'save.needsConsent': 'запись {document} требует явного согласия',\n 'save.globalDisabled': 'запись в глобальный уровень отключена этой установкой (allowGlobalWrite: false)',\n 'save.declaredElsewhere': 'сервер \"{server}\" теперь объявлен в {document}',\n 'save.documentGone': 'объявляющий документ {document} исчез',\n 'save.documentChanged': '{document} изменился с момента чтения записи; перезагрузите его и отредактируйте заново',\n 'save.invalidJson': 'объявляющий документ не является допустимым JSON: {error}',\n 'save.noMcpServers': '{document} не использует объект \"mcpServers\", поэтому этот редактор не может его переписать',\n 'save.noLongerDeclared': 'сервер \"{server}\" больше не объявлен в {document}',\n 'save.entryNotParsed': 'изменённая запись \"{server}\" не разобралась',\n 'save.writeFailed': 'запись {document} не удалась: {error}',\n 'write.doc.invalidJson': 'документ не является допустимым JSON: {error}',\n 'write.doc.notObject': 'документ не является JSON-объектом',\n 'write.doc.noMcpServers': 'в документе нет объекта \"mcpServers\"',\n}\n\n/**\n * The translator of last resort: every code echoes, so {@link resolveHost}\n * reads the harness's miss signal and falls back to the payload's `message`.\n */\nconst echo: Translate = (key) => key\n\n/**\n * A translator bound to the host namespace — and nothing more.\n *\n * This is deliberately not `uiTranslate`'s shape: the UI seat falls back to\n * the merged English table of its module, but this namespace has no merged\n * English table — the per-message fallback is the design, and it lives in\n * {@link resolveHost}, which detects the echo itself. Without a locale\n * service, or when the service refuses the namespace, the seat echoes, which\n * is exactly the miss signal the resolver reads.\n * @param locale - the shell's locale service, when there is one.\n * @returns a translate seat over `projectMcp.host`.\n */\nexport function hostTranslate(locale: TabLocale | undefined): Translate {\n if (locale === undefined) return echo\n try {\n return locale.bind(NS_HOST) as Translate\n } catch {\n // A service that refuses the namespace leaves the payload its own English.\n return echo\n }\n}\n\n/**\n * Resolve one host payload to the sentence the screen shows.\n *\n * The chain: the bound namespace answers first (the harness's own fallback —\n * active language, then this namespace's `en` table — rides inside it); a\n * miss, which the harness signals by echoing the code, falls back to the\n * payload's English `message`; a payload without a code renders its `message`\n * directly, so an old host's prose shows exactly as it did before codes\n * existed. The raw code survives only when the payload is malformed (no\n * `message` either) — the documented last resort.\n *\n * Params are flat, with one two-level convention: a param whose name ends in\n * `Code` is itself a wire code, resolved through `bound` first and substituted\n * under the plain name (`reasonCode` → `reason`). A nested lookup that misses —\n * the harness echoes the sub-code, which substituted would put a raw code on\n * screen inside an otherwise translated sentence — fails the whole lookup:\n * the payload's `message` answers instead.\n * @param bound - the host-namespace seat from {@link hostTranslate}.\n * @param code - the payload's wire code, when it carries one.\n * @param params - the payload's flat params, when it carries any.\n * @param message - the payload's English fallback text.\n * @returns the sentence to render.\n */\nexport function resolveHost(\n bound: Translate,\n code: string | undefined,\n params: Record<string, string> | undefined,\n message: string | undefined,\n): string {\n if (code === undefined) return message ?? ''\n const resolved = resolveParams(bound, params)\n if (resolved.missed) return message ?? code\n const text = bound(code, resolved.params)\n return text === code ? (message ?? code) : text\n}\n\n/**\n * The params a bound seat is called with: `*Code` values resolved two-level.\n * `missed` is the nested miss signal: a sub-code the namespace does not know\n * echoes, and an echo is never substituted into a sentence.\n */\nfunction resolveParams(\n bound: Translate,\n params: Record<string, string> | undefined,\n): { params: Record<string, string> | undefined; missed: boolean } {\n if (params === undefined) return { params: undefined, missed: false }\n const resolved: Record<string, string> = {}\n let missed = false\n for (const [name, value] of Object.entries(params)) {\n if (name.endsWith('Code') && name.length > 'Code'.length) {\n const nested = bound(value)\n if (nested === value) missed = true\n resolved[name.slice(0, -'Code'.length)] = nested\n } else {\n resolved[name] = value\n }\n }\n return { params: resolved, missed }\n}\n","/**\n * Shared row/snapshot vocabulary for `dsh-project-mcp`.\n *\n * The host half publishes a {@link ProjectSnapshot} through the `projectMcp`\n * service so a future Web UI (or a test) can read what is mounted without\n * importing the runtime.\n *\n * @module dsh-project-mcp/types\n */\n\n/**\n * Type-only, and imported for its effect on the ambient types rather than for\n * anything this module uses: `@deepseek-ai/dsh-tools` declares `Context.tools`\n * and the `tools/change` / `tools/result` events as module augmentation of\n * `@deepseek-ai/cordis`, and TypeScript applies an augmentation only when the\n * augmenting module is part of the compilation. Nothing of the package reaches\n * the runtime — the import is erased by the compiler, and the plugin still\n * takes the service off the context it is handed instead of importing the\n * module.\n */\nimport type {} from '@deepseek-ai/dsh-tools'\n\n/** Runtime state of one project-declared MCP server. */\nexport type ServerStatus =\n /** Mounted and its tools are visible in the owning scope. */\n | 'active'\n /** Mounted; activation or the initial connection has not settled yet. */\n | 'connecting'\n /**\n * Declared, parsed, and not mounted: either `lazy` has not seen this\n * session's first turn yet, or the session went idle and its mounts were\n * released (`idleTimeoutMs`). The next turn mounts it again.\n */\n | 'idle'\n /** Declared with `enabled: false` — never mounted. */\n | 'disabled'\n /** The same `serverName` is reserved by a live profile-level instance. */\n | 'conflict'\n /** The entry or its mount failed; `detail` carries the reason. */\n | 'error'\n\n/** One server row of a project snapshot. */\nexport interface ServerRow {\n /** `serverName` (the `mcpServers` key, sanitized). */\n name: string\n /** Current lifecycle state. */\n status: ServerStatus\n /** Project root the entry was read from. */\n projectRoot: string\n /** Absolute path of the declaring document. */\n source?: string\n /** `stdio` or `streamable-http`, when the entry parsed. */\n transport?: 'stdio' | 'streamable-http'\n /**\n * Failure, stall or conflict explanation. Redacted on purpose: it names the\n * command but never its arguments, and an HTTP endpoint keeps its path but\n * drops the query string, because both can carry credentials.\n */\n detail?: string\n /**\n * Stable wire code of `detail` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive, exactly like\n * {@link blockedCode}: the prose field keeps its byte-identical English and\n * stays the fallback, so a client and a host of different builds degrade\n * rather than break.\n */\n detailCode?: string\n /**\n * Flat params of {@link detailCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n detailParams?: Record<string, string>\n /**\n * Parsed body of the entry, for the editor. Absent when the entry did not\n * parse — there is nothing to edit then.\n */\n entry?: EntrySnapshot\n /** Where this row may be written back, when it may be written at all. */\n writeScope?: WriteScope\n /** One line saying why writing is unavailable; always set for `readonly`. */\n writeBlockedReason?: string\n /**\n * Stable wire code of `writeBlockedReason` (`projectMcp.host` namespace),\n * for client-side translation. Optional and additive: the prose field keeps\n * its byte-identical English and stays the fallback, so a client and a host\n * of different builds degrade rather than break.\n */\n blockedCode?: string\n /**\n * Flat params of {@link blockedCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n blockedParams?: Record<string, string>\n /**\n * Opaque content revision of the declaring document at snapshot time. A save\n * must carry the revision it was built from: a mismatch means the document\n * changed underneath the editor, and the write is refused rather than merged.\n */\n documentRevision?: string\n}\n\n/**\n * How one `env` or `headers` entry is known to the host.\n *\n * A value can come from the declaring document, be answered outside it (the\n * project's own `.env` or the credentials file), or be withheld because it is a\n * credential. {@link EntryField.masked} is the field\n * that changes how a write treats it: a masked key submitted without a `value` is\n * kept exactly as the document declares it, so an editor that cannot see a secret\n * can never erase or replace one.\n */\nexport interface EntryField {\n /** Key exactly as declared. */\n readonly key: string\n /** Literal value; absent when the host withholds it. */\n readonly value?: string\n /** `true` when `value` is absent because the value is a secret. */\n readonly masked?: true\n /**\n * `true` when the key is answered outside the document — by the project's\n * `.env` or by the credentials file. The name predates the project dotenv\n * sources; the meaning the write path reads is \"never write this value back\".\n */\n readonly fromCredentials?: true\n}\n\n/**\n * One server entry as the host parsed it, for an editor.\n *\n * Every field is what the declaring document holds — a resolved default is never\n * folded in, because a save replaces the declaration, not the runtime config.\n */\nexport interface EntrySnapshot {\n /** Transport the entry declares. */\n readonly transport: 'stdio' | 'streamable-http'\n /** `stdio`: the program to run. */\n readonly command?: string\n /** `stdio`: its arguments, verbatim. */\n readonly args?: readonly string[]\n /** `stdio`: working directory, when the entry declares one. */\n readonly cwd?: string\n /** `stdio`: declared environment, secrets masked. */\n readonly env?: readonly EntryField[]\n /** `streamable-http`: the endpoint, with a credential-bearing query dropped. */\n readonly url?: string\n /** `streamable-http`: declared headers, secrets masked. */\n readonly headers?: readonly EntryField[]\n /** `false` when the declaration disables the server; absent means enabled. */\n readonly enabled?: boolean\n /** Declared connect timeout in milliseconds, when the entry sets one. */\n readonly connectTimeoutMs?: number\n /**\n * Keys the editor does not present, kept in their declared order and written\n * back untouched. A save replaces the entry wholesale, so dropping them would\n * delete configuration the panel never showed.\n */\n readonly extra?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Whether one row's declaring document may be rewritten.\n *\n * - `project` — one of the deployment's project documents (`localFiles`,\n * `<project>/.dsh/mcp.json` out of the box);\n * - `global` — one of its global documents (`globalFiles`), written only with an\n * explicit per-write consent;\n * - `readonly` — the profile, `<DSH_HOME>` or a bundled document: never written.\n */\nexport type WriteScope = 'project' | 'global' | 'readonly'\n\n/**\n * One document a project is configured to read.\n *\n * The list a project publishes is exactly its read order — global documents\n * first, then the project's own — so the panel's priority number is an index\n * into it and never a table of hardcoded file names.\n */\nexport interface ConfiguredFile {\n /** Absolute path of the document. */\n readonly path: string\n /**\n * `global` — read for every project, before its own documents; `project` —\n * read from the project root.\n */\n readonly scope: 'global' | 'project'\n}\n\n/** Diagnostics surfaced alongside the rows. */\nexport interface SnapshotIssue {\n /** Absolute path of the declaring document. */\n source: string\n /** Server the diagnostic belongs to, when entry-scoped. */\n server?: string\n /** `error` or `warning`. */\n level: 'error' | 'warning'\n /** Human-readable text. */\n message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive: `message` keeps its\n * byte-identical English and stays the fallback. Behavioural matches key on\n * this field — never on the prose, which the client may have translated.\n */\n code?: string\n /**\n * Flat params of {@link SnapshotIssue.code}; a name ending in `Code` is\n * itself a wire code the client resolves two-level.\n */\n params?: Record<string, string>\n}\n\n/**\n * One session's own view of the project it works in.\n *\n * Sessions of one project are independent: each mounts its own servers, and one\n * may have them running while another has not started a turn yet. The panel\n * needs that split, because a project-level merge alone cannot say *which*\n * session holds a mount.\n */\nexport interface SessionSnapshot {\n /** Agent (session) id. */\n id: string\n /** Rows for this session alone, in document order. */\n rows: ServerRow[]\n /** Diagnostics this session surfaced. */\n issues: SnapshotIssue[]\n /** What this session offers the model, when the host has mounted for it. */\n tools?: SessionTools\n /**\n * How many events of the project's ring belong to this session. Absent for a\n * session that produced none, so the tab's log badge reads a real `0`.\n */\n logCount?: number\n /**\n * `serverName` conflicts this session last reconciled: a profile-level\n * instance that already owns a name, or one name two project documents\n * declare. Published even when empty, so a reader can tell \"this session\n * reported none\" from a host that does not report conflicts at all.\n */\n conflicts?: readonly ServerConflict[]\n}\n\n/** One tool a session offers the model, and what put it in the request. */\nexport interface OfferedTool {\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly name: string\n /**\n * The tier that offered it: `session` activated on demand through the search\n * tool, `context` ranked from the task text of the current conversation. The\n * counter-seeded baseline is not this shape — it is a plain name list in\n * {@link SessionTools.baseline}.\n */\n readonly via: 'session' | 'context'\n /**\n * Epoch milliseconds of the last offer or call. Absent for the context tier,\n * whose live state stamps an advance rather than a clock reading.\n */\n readonly at?: number\n /**\n * Number of the agent step (from `1`) the tool was offered at, or `undefined`\n * for a host that does not count steps. A panel that reads no number draws no\n * step tag at all rather than a made-up one.\n */\n readonly step?: number\n}\n\n/**\n * One accepted field of a tool's `parameters` schema, as the panel lists it.\n *\n * A field is listed from the definition the host already holds, so its type and\n * its `required` flag are the schema's own and neither is inferred from the\n * tool's name. Nesting stops at the top level: an object or array field is drawn\n * as its type, not expanded, because the panel lists what a call takes rather\n * than mirroring a schema. Schema `default` values are deliberately not part of\n * this shape — a default can carry a value the tool did not mean to publish.\n */\nexport interface ToolField {\n /** Property name, as the schema declares it. */\n readonly name: string\n /** JSON Schema `type` of the field, or `any` when the schema names none. */\n readonly type: string\n /** `true` when the schema's own `required` array names this property. */\n readonly required: boolean\n /** The property's own `description`, when the schema publishes one. */\n readonly description?: string\n}\n\n/**\n * Why one name is not in this session's request, in the host's own terms.\n *\n * The decision belongs to the host and the panel does not recompute it, so the\n * reason travels as data and its copy lives in the client's dictionaries. Every\n * figure here is a host measurement — the definition's own serialized size, the\n * session's budget, what the offered set already carries — so a reason line\n * invents no number. That is the same discipline as contract C2's step tag.\n */\nexport interface ToolReason {\n /**\n * Which decision left the name out. `budget` is the disclosure mode pushing it\n * past {@link ToolReason.budget}: the whole mounted surface is registered, and\n * this definition did not fit the request.\n */\n readonly kind: 'budget'\n /** Serialized size of this definition, in characters — the host's own figure. */\n readonly chars?: number\n /** The session's tool budget in characters, when the host budgeted one. */\n readonly budget?: number\n /** Characters the offered set already carries, when the host measured them. */\n readonly used?: number\n}\n\n/**\n * One tool's detail, answered on demand for a row the reader opened.\n *\n * The panel fetches this instead of carrying it in the snapshot: the snapshot\n * travels on every change frame and every poll, while a description and a schema\n * are read once per opened row. The text is model-facing and arrives as data —\n * it is never copied into a dictionary, is not translated, and is drawn as the\n * host published it.\n */\nexport interface ToolFacts {\n /** Public registry name this record answers about. */\n readonly name: string\n /** The definition's model-facing description, when the host holds one. */\n readonly description?: string\n /** Accepted fields, in schema order; empty when the tool declares none. */\n readonly fields: readonly ToolField[]\n /** Why the name is not offered, when it is not. Absent for an offered name. */\n readonly reason?: ToolReason\n}\n\n/**\n * Another loaded plugin that owns the assembled tool list.\n *\n * The plugin and such an owner cannot shape one request together: the outer\n * listener of whoever assembles last rewrites `assembly.tools`, so the plugin's\n * own deferral would be re-applied over an already-trimmed list. The host\n * reports the owner instead of silently composing with it, and a panel prints\n * the coexistence note only when this record is published.\n */\nexport interface PresentationOwner {\n /** Loader entry name, for example `dsh-progressive-tools`. */\n readonly name: string\n /** One line saying why coexisting in one request is impossible. */\n readonly note: string\n /**\n * The `projectMcp.host` code of {@link note} (F-48): the client translates\n * by it and falls back to `note`'s English, byte-identical, when the code is\n * absent or unknown. No params — the note is one fixed sentence.\n */\n readonly noteCode?: string\n}\n\n/**\n * One `serverName` two declarations fight over.\n *\n * `profile` is the profile-level `mcp-client` instance that already owns the\n * name: the project entry mounts only through the local alias the user chose,\n * and never under the contested name itself. `duplicate` is one name declared by\n * more than one project document: the highest-priority document wins and the\n * others are ignored.\n */\nexport interface ServerConflict {\n /** `serverName` the declarations share. */\n readonly server: string\n /** `profile` — a profile-level instance owns the name; `duplicate` — two documents. */\n readonly kind: 'profile' | 'duplicate'\n /** Declaring documents, the winner first. */\n readonly sources: readonly string[]\n /** One line: who wins, and why. */\n readonly message: string\n /**\n * The `projectMcp.host` code of {@link message} (F-48): the client translates\n * by it and falls back to `message`'s English, byte-identical, when the code\n * is absent (a host older than the field) or unknown to its dictionaries.\n */\n readonly code?: string\n /**\n * Flat params of {@link code}; numbers stringify at emission. A name ending\n * in `Code` is itself a wire code, resolved two-level through the same\n * namespace and substituted under the plain name.\n */\n readonly params?: Record<string, string>\n /**\n * The local name this project's entry mounts under when the user chose\n * `local`, as `mcp__<alias>__<tool>` in the model's own list. Published on a\n * `profile` conflict even while the choice is still the profile's, so the\n * panel can offer the alias it would use rather than inventing one.\n */\n readonly alias?: string\n /**\n * What the project's policy says about this name. Absent on a `duplicate`,\n * which no choice resolves, and on a host older than this field.\n */\n readonly choice?: ConflictChoice\n}\n\n/**\n * What one live session currently offers the model.\n *\n * Measured from the session's own state, not from the project: two sessions of\n * one project differ as soon as one of them has called a tool, and the panel's\n * promise is to show what *this* session's model sees.\n */\nexport interface SessionTools {\n /** Live agent (session) id this row describes. */\n readonly sessionId: string\n /**\n * Names offered because the durable counters proved them hot, plus the pins;\n * empty in `off`, which offers none of the project's tools.\n */\n readonly baseline: readonly string[]\n /** Names this session activated on demand, oldest first; empty in `off`. */\n readonly activated: readonly OfferedTool[]\n /** Names the task context offered, oldest first; empty in `off`. */\n readonly context: readonly OfferedTool[]\n /**\n * Names mounted for the project but not offered by this plugin, sorted. In\n * `disclosure` these are the names the budget pushed out of the request; in\n * `direct` the list is empty, because nothing is filtered; in `off` it is the\n * whole mounted surface, because a project that is switched off is offered not\n * at all. Its length is exactly the count a panel shows as hidden — and such a\n * panel has to read {@link ToolPolicy.mode} first, since tools another\n * presentation plugin leaves in the request are not this one's offers.\n */\n readonly deferred: readonly string[]\n /** Tools mounted for the project in total. */\n readonly mounted: number\n /** Serialized size of the mounted surface, in characters. */\n readonly surfaceChars: number\n /**\n * Serialized size of the offered set — {@link SessionTools.baseline} plus the\n * `activated` and `context` names — in characters. Absent from a host that\n * does not split the surface, and then a panel prints no request estimate\n * rather than inventing one.\n */\n readonly visibleChars?: number\n /**\n * Serialized size of {@link SessionTools.deferred}, in characters: exactly the\n * part of the mounted surface this plugin leaves out of the request. `0` when\n * nothing is deferred, so a panel that found this field may divide it by four\n * for a token estimate.\n */\n readonly deferredChars?: number\n /**\n * Configured deferral budget in characters. `0` means there is no threshold at\n * all: every surface counts as over budget, so tools are deferred however small\n * the project is. Read {@link SessionTools.deferring} rather than comparing this\n * with {@link SessionTools.surfaceChars} — the host owns the rule.\n */\n readonly budgetChars: number\n /**\n * `true` while the surface is over the budget, so tools really are deferred.\n * Only `disclosure` can defer: `direct` filters nothing and `off` offers\n * nothing, so both report `false` however large the mounted surface is.\n */\n readonly deferring: boolean\n}\n\n/** How one project's MCP tools are offered to the model. */\nexport type ToolMode =\n /** Offer the baseline and the on-demand tiers (the shipped behaviour). */\n | 'disclosure'\n /** Never defer: every mounted tool is listed in every request. */\n | 'direct'\n /** Do not offer this project's MCP tools at all. */\n | 'off'\n\n/**\n * How one `serverName` a project shares with a live profile instance is shown.\n *\n * The profile's instance owns the name in every scope, so the two declarations\n * cannot both mount under it. `profile` keeps the profile's tools exactly as\n * they are and leaves the project's entry unmounted; `local` mounts the\n * project's entry under a local namespace (see `src/naming.ts`) so both toolsets\n * reach the model — the only difference being the names they carry; `native`\n * mounts the project's entry under the name it declares, which is the nearer\n * declaration in this project's own sessions and so shadows the profile's tools\n * of that name there, while every other project keeps seeing the profile's.\n */\nexport type ConflictChoice =\n /** The profile instance keeps the name; the project entry does not mount. */\n | 'profile'\n /** The project entry mounts under its local alias, next to the profile's. */\n | 'local'\n /** The project entry mounts under the declared name, shadowing the profile's in this project. */\n | 'native'\n\n/**\n * One project's tool policy.\n *\n * The mode decides whether tools are deferred, the pins are the names the user\n * insists on — a pinned tool is offered from the first step of every request, is\n * never dropped by idle pruning or by a compaction, and is not counted against\n * the deferral budget's reading of what is hidden — and the aliases remember, per\n * conflicting `serverName`, which of the two declarations the user chose to see.\n */\nexport interface ToolPolicy {\n /** Mode in force. */\n readonly mode: ToolMode\n /**\n * Public registry names pinned for this project, in the order the user pinned\n * them. A name the project no longer mounts is kept: the declaration may come\n * back, and a pin that silently disappeared would be a surprise.\n */\n readonly pins: readonly string[]\n /**\n * Choice per contested `serverName`. Optional so every fixture, host and\n * stored document written before this field existed keeps meaning exactly\n * what it meant: a name that is absent is one the user never chose about,\n * and the shipped answer is the profile's instance. The store publishes an\n * empty map rather than dropping the field, so a reader may treat `undefined`\n * and `{}` alike.\n */\n readonly aliases?: Readonly<Record<string, ConflictChoice>>\n}\n\n/** The policy every project follows until one is configured. */\nexport const DEFAULT_TOOL_POLICY: ToolPolicy = { mode: 'disclosure', pins: [], aliases: {} }\n\n/**\n * How much one MCP server of one project has been used.\n *\n * Counted on the host from the tool registry's own events, so it is exact rather\n * than sampled, and keyed by project root: sessions come and go, the numbers\n * stay, which is what makes them usable for later decisions about a project.\n */\nexport interface ServerUsage {\n /** Calls dispatched through the registry, successful or not. */\n calls: number\n /** Calls whose result carried an error. */\n errors: number\n /** ISO timestamp of the most recent call. */\n lastUsedAt?: string\n /**\n * Per tool counts, keyed by the tool name as declared by the server, i.e.\n * without the `mcp__<serverName>__` prefix the registry publishes it under.\n */\n tools: Record<string, number>\n /**\n * The same readings split by session, keyed by the session (agent) id the\n * panel already uses everywhere else.\n *\n * Additive since F-34: a document written before this field existed is read as\n * it is — `USAGE_VERSION` does not move, because a reader that meets an unknown\n * version refuses the whole document and every counter would start from zero.\n * Absent means \"counted before the split\", never \"no calls\".\n */\n sessions?: Record<string, SessionUsage>\n}\n\n/**\n * One session's share of a server's counters.\n *\n * A server is mounted for a project and a project's sessions share it, so the\n * project total says what the project used while this says what *this* session\n * did; the two differ exactly when other sessions of the project called the\n * server, which is the case a panel scoped to one session could not show.\n */\nexport interface SessionUsage {\n /** Calls this session dispatched through the registry. */\n calls: number\n /** Of those, the ones whose result carried an error. */\n errors: number\n /** ISO timestamp of this session's most recent call. */\n lastUsedAt?: string\n /** This session's counts, keyed by the tool name as the server declares it. */\n tools: Record<string, number>\n}\n\n/**\n * How serious one plugin event is, as the Logs tab colours it.\n *\n * Four levels, mapped from the lifecycle line the host already writes: `info`\n * for a mount being registered, `up` for one whose tools became visible, `warn`\n * for a stall or a release, `error` for a failed mount and the unmount that\n * follows it. They are the labels the tab draws, not a host severity scale.\n */\nexport type LogLevel =\n /** The instance is being registered (`project-mcp: mounting …`). */\n | 'info'\n /** The instance's tools are visible (`… is up …`). */\n | 'up'\n /** A stall, a repeated pass, or a release the operator did not ask for. */\n | 'warn'\n /** The mount failed, or a failed mount is being torn down. */\n | 'error'\n\n/**\n * One lifecycle event, as the Logs tab lists it.\n *\n * The plugin's own events only — a mount, a start, a stop, a failure — mirroring\n * the lines the host writes to the DSH log, so the two readers see the same\n * facts. Events live in a per-project ring (`src/logs.ts`); the newest ones ride\n * in the snapshot, the rest are paged over the route.\n */\nexport interface LogEvent {\n /** When the event happened, epoch ms. */\n readonly at: number\n /** How serious it is, as the tab colours it. */\n readonly level: LogLevel\n /** Project root the event belongs to; the ring is keyed by it. */\n readonly projectRoot: string\n /**\n * Session the event is attributed to. Set exactly when the lifecycle line it\n * mirrors names one — `mounting`, `is up`, a stall — and absent on a\n * project-level event such as a shared instance's unmount.\n */\n readonly sessionId?: string\n /** `serverName` the event is about; absent for an event with no server. */\n readonly server?: string\n /** One line, without a newline: one event is one row of the tab. */\n readonly message: string\n /**\n * The three facts an error carries — the failure, the endpoint, the declaring\n * document — and no advice: the server row already offers the retry.\n */\n readonly detail?: string\n /**\n * Wire code of {@link LogEvent.message} (F-48), into the `projectMcp.host`\n * namespace. Optional: a host older than the field sends prose only, and the\n * client falls back to {@link LogEvent.message}.\n */\n readonly code?: string\n /** Flat params of {@link LogEvent.code}; numbers are stringified at emission. */\n readonly params?: Record<string, string>\n /** Wire code of {@link LogEvent.detail}, the same additive companion. */\n readonly detailCode?: string\n /** Flat params of {@link LogEvent.detailCode}. */\n readonly detailParams?: Record<string, string>\n}\n\n/** Everything one project contributes to the live runtime. */\nexport interface ProjectSnapshot {\n /** Project root the agents below resolved to. */\n projectRoot: string\n /**\n * Documents this project is configured to read, in priority order — global\n * ones first, then the project's own. Published even when empty, so a panel\n * can tell \"this deployment reads nothing\" from a host that does not report\n * its documents at all. Absent only from a snapshot a host older than this\n * field produced, and then a reader falls back to the shipped names rather\n * than inventing a priority.\n */\n files?: readonly ConfiguredFile[]\n /**\n * The tool policy in force for this project. Absent only from a snapshot a host\n * older than the policy store produced; a reader treats that as the shipped\n * default, {@link DEFAULT_TOOL_POLICY}.\n */\n policy?: ToolPolicy\n /** Live agent (session) ids currently bound to this project. */\n sessionIds: string[]\n /**\n * Merged rows for every declared server, in document order. When sessions\n * disagree about one server, the more actionable state wins, so a mounted or\n * broken server is never hidden behind a session that has not turned yet.\n */\n rows: ServerRow[]\n /** Parse and lifecycle diagnostics, deduplicated across the sessions. */\n issues: SnapshotIssue[]\n /** The same data split per session, in session-registration order. */\n sessions: SessionSnapshot[]\n /**\n * Usage counters keyed by `serverName`, remembered across sessions. Absent\n * while the host half has counted nothing for this project yet.\n */\n usage?: Record<string, ServerUsage>\n /**\n * Another loaded plugin that owns the assembled tool list, when the profile\n * has one. Absent means this plugin is the only owner — a panel that reads no\n * record draws no coexistence notice.\n */\n presentation?: PresentationOwner\n /**\n * Real `serverName` conflicts of this project: a profile-level instance that\n * already owns a name, or one name two project documents declare. The list is\n * always published — an empty one is the honest answer \"no conflicts\", which\n * is what lets a panel report that instead of offering a disabled button.\n */\n conflicts?: readonly ServerConflict[]\n /**\n * The newest events of this project's ring, oldest first, at most the page\n * size (50). Absent for a project that has recorded nothing, so a tab draws\n * its empty state rather than an empty list.\n */\n logs?: readonly LogEvent[]\n /**\n * How many events the project's ring holds right now, `0…200`. Absent exactly\n * when {@link ProjectSnapshot.logs} is: no events, nothing to count.\n */\n logCount?: number\n}\n\n/** Whole-plugin snapshot: one entry per project with live agents. */\nexport interface McpSnapshot {\n /** `true` while the agents service has been observed. */\n ready: boolean\n /** Projects with at least one live agent. */\n projects: ProjectSnapshot[]\n /**\n * Documents this deployment is configured to read, exactly as the config\n * spells them — `local` relative to a project root, `global` relative to\n * `$HOME` (or absolute). Published for the surfaces that must speak about the\n * deployment itself, with no project at hand: the empty state names what would\n * be read instead of a file name baked into the client. Absent from a snapshot\n * a host older than this field produced.\n */\n sources?: { readonly local: readonly string[]; readonly global: readonly string[] }\n /** Absolute paths currently watched for config edits. */\n watchedFiles: string[]\n}\n\n/**\n * One pushed picture: what the status channel sends.\n *\n * The snapshot travels whole rather than as a delta, so a frame that arrives\n * after a gap is still a complete answer — the panel can apply it without\n * asking for anything back. `revision` counts the changes the host has announced\n * and is what a late or repeated frame is judged by.\n */\nexport interface SnapshotChange {\n /** Monotonic change counter, starting at `0` for the picture a stream opens on. */\n revision: number\n /** The whole picture at that revision. */\n snapshot: McpSnapshot\n}\n","/**\n * The per-project tool policy, as the browser half reads and writes it.\n *\n * The host owns the policy: it stores it next to the usage counters, applies it\n * on every request assembly, and answers with the fresh snapshot. This module\n * only shapes what the panel asks for and turns what came back into the two\n * readings the surfaces print — the mode in force and the list the user pinned.\n * Keeping the shapes here (instead of in a component) is what lets a no-DOM test\n * assert the exact body a `Pin` click posts.\n *\n * Nothing here invents a value: a project the host has no policy for follows\n * {@link DEFAULT_TOOL_POLICY}, which is the frozen contract's own default.\n *\n * @module dsh-project-mcp/client/policy\n */\n\nimport { ROUTE_ACTIONS, ROUTE_PREFIX } from '../shared.ts'\nimport type { ConflictRequest, OperatorRequest, PinRequest, PolicyRequest } from '../shared.ts'\nimport { DEFAULT_TOOL_POLICY } from '../types.ts'\nimport type { ConflictChoice, ProjectSnapshot, ToolMode, ToolPolicy } from '../types.ts'\n\n/**\n * The project's effective policy.\n *\n * `policy` is absent only from a snapshot a host older than the policy store\n * produced; the contract makes that the shipped default, so the panel reads a\n * bare project correctly instead of guarding for the field everywhere.\n * @param project - one project of the host snapshot.\n * @returns the policy in force, never undefined.\n */\nexport function policyOf(project: Pick<ProjectSnapshot, 'policy'>): ToolPolicy {\n return project.policy ?? DEFAULT_TOOL_POLICY\n}\n\n/** The body the host expects for one pin or unpin, per `PinRequest`. */\nexport function pinBody(projectRoot: string, tool: string, pinned: boolean): PinRequest {\n return { projectRoot, tool, pinned }\n}\n\n/** The body the host expects for one mode change, per `PolicyRequest`. */\nexport function policyBody(projectRoot: string, mode: ToolMode): PolicyRequest {\n return { projectRoot, mode }\n}\n\n/**\n * The body the host expects for one conflict choice, per `ConflictRequest`.\n *\n * The name travels as the project declared it, never as the local alias: the\n * alias is the host's own computation from its config and the project folder,\n * and a panel that sent one back would disagree with the host the moment either\n * changed.\n * @param projectRoot - the project the contested name belongs to.\n * @param server - the contested `serverName`, as declared.\n * @param choice - the declaration to show.\n * @returns the request body.\n */\nexport function conflictBody(\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n): ConflictRequest {\n return { projectRoot, server, choice }\n}\n\n/**\n * The body of one operator request — `Sync`, `Retry`.\n *\n * A surface that shows a single project names it: the host then touches only\n * that project's servers and answers with that project's slice of the snapshot.\n * `full` keeps the answer whole for a surface that lists every project — the\n * settings page — while the action itself still stays inside `projectRoot`.\n * @param projectRoot - the project the action applies to, when the surface has one.\n * @param full - ask for the whole snapshot in the answer.\n * @returns the request body; `{}` when there is no project to name.\n */\nexport function operatorBody(projectRoot: string | undefined, full = false): OperatorRequest {\n if (projectRoot === undefined) return {}\n return full ? { projectRoot, full: true } : { projectRoot }\n}\n\n/**\n * Submit one pin or unpin and read the host's answer.\n *\n * The host answers with the fresh snapshot on success and with an explanation\n * otherwise (unknown project, unknown tool). Both are returned rather than\n * thrown, because a refusal is a state the panel shows, not a crash.\n * @param body - the `PinRequest` to post.\n * @returns the fresh snapshot, or the host's refusal.\n */\nexport async function postPin(body: PinRequest): Promise<PolicyAnswer> {\n return postPolicy(ROUTE_ACTIONS.pin, body)\n}\n\n/**\n * Submit one mode change and read the host's answer.\n * @param body - the `PolicyRequest` to post.\n * @returns the fresh snapshot, or the host's refusal.\n */\nexport async function postPolicyMode(body: PolicyRequest): Promise<PolicyAnswer> {\n return postPolicy(ROUTE_ACTIONS.policy, body)\n}\n\n/**\n * Submit one conflict choice and read the host's answer.\n * @param body - the `ConflictRequest` to post.\n * @returns the fresh snapshot, or the host's refusal.\n */\nexport async function postConflict(body: ConflictRequest): Promise<PolicyAnswer> {\n return postPolicy(ROUTE_ACTIONS.conflict, body)\n}\n\n/**\n * A refusal the host answered with: the English prose, plus the wire code and\n * its flat params when the host coded it (F-48). The companions are what the\n * render sites resolve through the host namespace; an old host's refusal\n * carries none and renders its `message` exactly as before.\n */\nexport interface PolicyRefusal {\n /** The host's own English sentence. */\n readonly message: string\n /** Wire code of {@link message} (`projectMcp.host` namespace), when coded. */\n readonly messageCode?: string | undefined\n /** Flat params of {@link messageCode}, when it has any. */\n readonly messageParams?: Record<string, string> | undefined\n}\n\n/** Either the snapshot the host re-read after a write, or the reason it refused. */\nexport type PolicyAnswer = { ok: true; snapshot: unknown } | ({ ok: false } & PolicyRefusal)\n\ninterface PolicyEnvelope {\n ok?: boolean\n value?: unknown\n error?: { code?: string; message?: string; messageCode?: string; messageParams?: Record<string, string> }\n}\n\n/**\n * `POST` one policy write and unwrap the host's envelope.\n *\n * Both call sites pass the frozen route constant rather than a literal, so a\n * rename cannot leave one of the two routes behind.\n * @param action - route action under `ROUTE_PREFIX`.\n * @param body - the pin or mode request.\n * @returns the fresh snapshot or the refusal message.\n */\nasync function postPolicy(\n action: typeof ROUTE_ACTIONS.pin | typeof ROUTE_ACTIONS.policy | typeof ROUTE_ACTIONS.conflict,\n body: PinRequest | PolicyRequest | ConflictRequest,\n): Promise<PolicyAnswer> {\n try {\n const response = await fetch(`${ROUTE_PREFIX}/${action}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n const payload = (await response.json()) as PolicyEnvelope\n if (payload.ok === true) return { ok: true, snapshot: payload.value }\n return {\n ok: false,\n message: payload.error?.message ?? `request failed (${response.status})`,\n // The coded companions are optional on the wire: an old host's refusal\n // has none, and the render sites fall back to the message.\n ...(typeof payload.error?.messageCode === 'string'\n ? { messageCode: payload.error.messageCode, messageParams: payload.error.messageParams }\n : {}),\n }\n } catch (error) {\n return { ok: false, message: error instanceof Error ? error.message : String(error) }\n }\n}\n\n/** Hooks a pin write reports through, so one row can disable and explain. */\nexport interface PinWriteHooks {\n /** Called before the request goes out, with the tool it is about. */\n onStart?: (tool: string) => void\n /** Called after it settles, successfully or not. */\n onSettled?: (tool: string) => void\n /**\n * Called only when the host refused, with its own words — and with the\n * refusal's wire code and flat params when the host coded them (F-48).\n */\n onRefused?: (message: string, messageCode?: string, messageParams?: Record<string, string>) => void\n}\n\n/**\n * Write one tool's pin and report what happened.\n *\n * The twin of {@link requestMode} for the other half of the policy: it `POST`s\n * through {@link postPin}, which answers rather than throws, and leaves the\n * pending set and the refusal line to the caller — so one row disables while its\n * own write is in flight and a refusal is shown instead of swallowed.\n * @param body - the project, the public tool name and the wanted pin state.\n * @param hooks - lifecycle callbacks; all optional.\n * @returns the host's answer, for a caller that wants to keep the snapshot.\n */\nexport async function requestPin(\n body: PinRequest,\n hooks: PinWriteHooks = {},\n): Promise<PolicyAnswer> {\n hooks.onStart?.(body.tool)\n const answer = await postPin(body)\n hooks.onSettled?.(body.tool)\n if (!answer.ok) hooks.onRefused?.(answer.message, answer.messageCode, answer.messageParams)\n return answer\n}\n\n/** Hooks a mode write reports through, so a surface can disable and explain. */\nexport interface ModeWriteHooks {\n /** Called before the request goes out. */\n onStart?: (projectRoot: string) => void\n /** Called after it settles, successfully or not. */\n onSettled?: (projectRoot: string) => void\n /**\n * Called only when the host refused, with its own words — and with the\n * refusal's wire code and flat params when the host coded them (F-48).\n */\n onRefused?: (message: string, messageCode?: string, messageParams?: Record<string, string>) => void\n}\n\n/**\n * Hooks a conflict choice reports through, so one card can disable its buttons.\n */\nexport interface ChoiceWriteHooks {\n /** Called before the request goes out, with the name it is about. */\n onStart?: (server: string) => void\n /** Called after it settles, successfully or not. */\n onSettled?: (server: string) => void\n /**\n * Called only when the host refused, with its own words — and with the\n * refusal's wire code and flat params when the host coded them (F-48).\n */\n onRefused?: (message: string, messageCode?: string, messageParams?: Record<string, string>) => void\n}\n\n/**\n * Write one conflict choice and report what happened.\n *\n * The twin of {@link requestPin} for the other durable decision a project\n * carries. A choice is what moves an entry between a conflict report and a\n * mounted server under its local name, so the host answers with the snapshot\n * that already reflects it and the caller can draw the new state at once.\n * @param body - the project, the contested name and the declaration to show.\n * @param hooks - lifecycle callbacks; all optional.\n * @returns the host's answer, for a caller that wants to keep the snapshot.\n */\nexport async function requestConflict(\n body: ConflictRequest,\n hooks: ChoiceWriteHooks = {},\n): Promise<PolicyAnswer> {\n hooks.onStart?.(body.server)\n const answer = await postConflict(body)\n hooks.onSettled?.(body.server)\n if (!answer.ok) hooks.onRefused?.(answer.message, answer.messageCode, answer.messageParams)\n return answer\n}\n\n/**\n * Write one project's mode and report what happened.\n *\n * `POST`s through {@link postPolicyMode}, which already answers rather than\n * throws, and is deliberately plain: the caller owns the pending set and the\n * error line, so the whole write is a pure function of the request and three\n * callbacks. That is what makes the disabled and refusal states of the switch\n * testable without a DOM.\n * @param body - the project and mode to store.\n * @param hooks - lifecycle callbacks; all optional.\n * @returns the host's answer, for a caller that wants to keep the snapshot.\n */\nexport async function requestMode(\n body: PolicyRequest,\n hooks: ModeWriteHooks = {},\n): Promise<PolicyAnswer> {\n hooks.onStart?.(body.projectRoot)\n const answer = await postPolicyMode(body)\n hooks.onSettled?.(body.projectRoot)\n if (!answer.ok) hooks.onRefused?.(answer.message, answer.messageCode, answer.messageParams)\n return answer\n}\n","/**\n * The host's own usage counters, read where a surface shows them.\n *\n * Nothing here is measured, sampled or invented: `ProjectSnapshot.usage`\n * (`src/types.ts:425`) is published by the host half from the tool registry's\n * own events, keyed by server name, and these two readings are the whole of it\n * — how often a tool was called, and how long a server has not been used. A\n * surface that has no record draws no text (the plugin's \"no data, no label\"\n * rule), which is why both functions answer `undefined` rather than `0` when\n * the host said nothing: an invented zero reads as a fact the host never\n * published.\n *\n * Pure and React-free, so the sidebar tab, the settings page and the pin picker\n * share one reading of the same numbers.\n *\n * @module dsh-project-mcp/client/usage-view\n */\n\nimport type { ServerUsage } from '../types.ts'\n\n/**\n * The prefix the registry publishes project MCP tools under.\n *\n * Five characters, underscores included: a name is `mcp__<server>__<tool>`, so\n * the server starts after the prefix, not after `mcp`. The vocabulary lives here\n * rather than in `view.ts` because this module reads the same names and must not\n * import the panel back — a cycle between the panel and its counter reader would\n * make the counter's own module graph depend on the surface that draws it.\n * `view.ts` re-exports both names, so every existing caller keeps its import.\n */\nexport const MCP_TOOL_PREFIX = 'mcp__'\n\n/** The `__` that closes the server segment of a registry name, and opens the tool's. */\nconst SEPARATOR = '__'\n\n/**\n * The server part of a registry tool name.\n * @param name - a public registry name, e.g. `mcp__tglider__workspace`.\n * @returns the server name, or undefined when the name is not an MCP one.\n */\nexport function serverOfToolName(name: string): string | undefined {\n if (!name.startsWith(MCP_TOOL_PREFIX)) return undefined\n const separator = name.indexOf(SEPARATOR, MCP_TOOL_PREFIX.length)\n return separator === -1 ? undefined : name.slice(MCP_TOOL_PREFIX.length, separator)\n}\n\n/** One project's counters, as the host published them; `undefined` — the host said nothing. */\nexport type ProjectUsage = Record<string, ServerUsage> | undefined\n\n/**\n * How often one tool was called, by its public registry name.\n *\n * The name is `mcp__<server>__<tool>` (see `serverOfToolName`), and the counter\n * is keyed by the tool name as the server declared it — everything after the\n * second separator, which is why the split is not `name.split('__')`.\n * @param name - a public registry name, e.g. `mcp__tglider__workspace`.\n * @param usage - the project's counters, when the host published any.\n * @returns the call count, or undefined when the host recorded nothing for it.\n */\nexport function callsOfToolName(name: string, usage: ProjectUsage): number | undefined {\n const split = splitToolName(name)\n if (split === undefined) return undefined\n return usage?.[split.server]?.tools[split.tool]\n}\n\n/**\n * Both readings one tool row may print: the project's counter and this session's.\n *\n * A server is mounted for a project and shared by its sessions, so the two\n * numbers answer different questions and differ exactly when another session of\n * the project called the tool (F-34). `recorded` is the host's mere existence of\n * a record for the name's server, which is what separates \"never called\" from\n * \"not counted at all\".\n */\nexport interface ToolCalls {\n /** `true` when the host published a record for this name's server. */\n recorded: boolean\n /**\n * `true` when the host published this session's own slice of that record.\n *\n * It is the difference between \"the host does not split by session yet\" and\n * \"this session is counted and has never called this tool\" — two states whose\n * `session` reading is both `undefined`, and which a row must not print the\n * same way.\n */\n split: boolean\n /** Calls the project counted for this tool, when it counted any. */\n project: number | undefined\n /** Calls this session counted for this tool, when it counted any. */\n session: number | undefined\n}\n\n/**\n * Read both counters of one tool, by its public registry name.\n * @param name - a public registry name, e.g. `mcp__tglider__workspace`.\n * @param usage - the project's counters, when the host published any.\n * @param sessionId - the session to read the split for; absent reads the project only.\n * @returns the two readings, and whether the host recorded the server at all.\n */\nexport function toolCalls(\n name: string,\n usage: ProjectUsage,\n sessionId: string | undefined,\n): ToolCalls {\n const split = splitToolName(name)\n const record = split === undefined ? undefined : usage?.[split.server]\n if (split === undefined || record === undefined) {\n return { recorded: false, split: false, project: undefined, session: undefined }\n }\n const own = sessionId === undefined ? undefined : record.sessions?.[sessionId]\n return {\n recorded: true,\n split: own !== undefined,\n project: record.tools[split.tool],\n session: own?.tools[split.tool],\n }\n}\n\n/** The server and the declared tool name inside one public registry name. */\nfunction splitToolName(name: string): { server: string; tool: string } | undefined {\n const server = serverOfToolName(name)\n if (server === undefined) return undefined\n // Past `mcp__<server>__`: the tool name as the server declared it, separator\n // included, because a declared name may hold one of its own.\n return { server, tool: name.slice(MCP_TOOL_PREFIX.length + server.length + SEPARATOR.length) }\n}\n\n/** How long a server has been unused, in the one unit its row prints. */\nexport interface IdleSpan {\n /** The largest whole unit the span holds. */\n unit: 'day' | 'hour' | 'minute'\n /** How many of that unit, floored. */\n count: number\n}\n\nconst MINUTE_MS = 60_000\nconst HOUR_MS = 60 * MINUTE_MS\nconst DAY_MS = 24 * HOUR_MS\n\n/**\n * The span since a server was last used, in its largest whole unit.\n *\n * `≥ 24 h → days`, `≥ 1 h → hours`, otherwise whole minutes (`0` is a real\n * answer: the call just landed). A date the parser does not accept, a missing\n * one, and one in the future are all \"nothing to print\" — the last one because\n * a host clock ahead of this viewer's is not a negative idle span.\n * @param lastUsedAt - ISO timestamp of the server's most recent call.\n * @param now - epoch milliseconds to measure against.\n * @returns the span, or undefined when there is no usable date.\n */\nexport function idleOf(lastUsedAt: string | undefined, now: number): IdleSpan | undefined {\n if (lastUsedAt === undefined) return undefined\n const at = Date.parse(lastUsedAt)\n if (!Number.isFinite(at)) return undefined\n const elapsed = now - at\n if (elapsed < 0) return undefined\n if (elapsed >= DAY_MS) return { unit: 'day', count: Math.floor(elapsed / DAY_MS) }\n if (elapsed >= HOUR_MS) return { unit: 'hour', count: Math.floor(elapsed / HOUR_MS) }\n return { unit: 'minute', count: Math.floor(elapsed / MINUTE_MS) }\n}\n\n/**\n * The order a list of tool names is drawn in: the most-called first.\n *\n * Sorting follows the figure the row leads with — this session's counter when\n * the host published the split, the project's otherwise — so the list is ordered\n * by the number a reader can see. That cuts both ways: a tool other sessions\n * called 290 times and this one never called leads with `never called`, so it\n * sinks below a tool this session really used, even though the project figure\n * printed beside it is larger. The host's counter is the only frequency there\n * is; a name with no reading of its own is \"not measured\", not \"zero\", and it\n * neither outranks a measured name nor loses the order it arrived in (the sort\n * is stable and this comparator returns `0` for a tie), so a list the host\n * already ordered is never reshuffled for no reason.\n * @param usage - the project's counters, as the host published them.\n * @param sessionId - the session whose split leads the ordering; absent reads the project.\n * @returns comparator for `Array.prototype.sort`.\n */\nexport function byCalls(\n usage: ProjectUsage,\n sessionId?: string,\n): (left: string, right: string) => number {\n const count = (name: string): number => {\n const calls = toolCalls(name, usage, sessionId)\n // The lead figure, and only it: a name the session is in the split without\n // is unmeasured, however loud the project total beside it is.\n return (calls.split ? calls.session : calls.project) ?? -1\n }\n return (left, right) => count(right) - count(left)\n}\n","/**\n * Browser half of the panel: the tab shows one surface for the project of the\n * session it is open in — the session's declared servers, the sessions that read\n * differently from the project, what the model sees, and the problems and the\n * event ring under their own disclosures — while the settings popup, opened from\n * the tab's actions menu, keeps the whole picture across every project with a\n * live session. The native Settings page (`settings.section`, see\n * `./settings.ts`) is the third surface and shares this module's fetch/poll path,\n * status colours and storage helpers.\n *\n * Data comes from the host over `/project-mcp/*` (see `src/ui.ts`): the browser\n * half has nothing to call in process. The host half's types are imported\n * type-only, which the bundler erases — the client bundle stays free of host\n * code.\n *\n * @module dsh-project-mcp/client/view\n */\n\nimport { createElement as h, useCallback, useEffect, useState } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { ROUTE_ACTIONS, ROUTE_PREFIX, TAB_ID } from '../shared.ts'\nimport type { LogEvent, McpSnapshot, ProjectSnapshot, ServerRow, ServerStatus, SessionTools, SnapshotChange, ToolFacts, ToolField, ToolMode, ToolPolicy, ToolReason } from '../types.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\nimport { operatorBody, pinBody, policyOf } from './policy.ts'\nimport { MCP_TOOL_PREFIX, idleOf, serverOfToolName, toolCalls } from './usage-view.ts'\nimport type { ProjectUsage, ToolCalls } from './usage-view.ts'\n\n// The registry-name vocabulary is defined in `./usage-view.ts` — the counter\n// reader, which must not import this module back — and re-exported here: the\n// panel and every caller outside it (`settings-tools.ts`, the tests) have always\n// read `MCP_TOOL_PREFIX` and `serverOfToolName` from this module.\nexport { MCP_TOOL_PREFIX, serverOfToolName, toolCalls }\nexport type { ToolCalls }\n\n/**\n * The panel's own English copy.\n *\n * The tab is created through the sidebar service rather than through a slot, so\n * it carries its English table here and reaches the render functions through\n * {@link Translate}; `./tab-locale.ts` binds that table to the shell's locale\n * service and repaints the tab when the language changes. The settings page\n * registers the same table with `ctx.locale.register` (see\n * `./settings.ts`), which is why both halves share one namespace: one plugin,\n * one dictionary.\n */\nexport const en = {\n // The tab itself: its label in the sidebar and the line under it.\n tab: 'Project MCP',\n tabDescription:\n 'MCP servers each project declares, and what is mounted for its sessions',\n sync: 'Sync',\n retryFailed: 'Retry failed',\n // Tool presentation: the tab's tools block and the settings page's Tools rows.\n toolsSeeModel: 'what the model sees',\n toolsPinned: 'pinned',\n toolsByCounters: 'by the counters',\n toolsDisclosed: 'disclosed',\n toolsHidden: 'hidden',\n toolsNotMounted: 'Nothing to hide yet',\n toolsNotMountedHint:\n 'lazy mounting: the project’s servers come up on the session’s first step, so the catalog is empty until then',\n toolsNotMountedCode: 'tools[] = built-ins only · mcp__* not registered yet',\n // The declared servers of this session, on the tools block: the reason an\n // apparently empty catalog is empty.\n toolsServers: 'Servers',\n toolsServersUp: '{up}/{total} up',\n toolsGroupPinned: 'pinned · always in the request',\n toolsGroupCounters: 'offered by the counters',\n toolsGroupDisclosed: 'disclosed by the model · until the session ends',\n toolsGroupHidden: 'hidden',\n toolsPin: 'Pin',\n toolsPinHint: 'Keep this tool in every request of this project',\n toolsUnpin: 'Unpin',\n toolsUnpinHint: 'Stop pinning this tool in every request of this project',\n toolsHide: 'Hide',\n toolsHideHint: 'Drop this disclosure and stop offering the tool',\n toolsHiddenVia: 'available to the model through mcp_search_tools only',\n // The tools block's own filter (F-43): the counter chips above the list stop\n // being a reading and become the tier switch, and a query narrows by name.\n toolsFilterPlaceholder: 'filter by name…',\n toolsFilterLabel: 'filter this session’s tools by registry name',\n toolsFilterTier: 'Show this tier alone; press again for every tier',\n toolsFilterClear: 'Clear',\n toolsFilterClearHint: 'Show every tier and drop the query',\n toolsFilterShown: 'showing {shown} of {total}',\n toolsFilterNone: 'No tool of this session matches the filter.',\n // The server-level pin (F-44): one press for a whole server's names, since a\n // server is how the hidden tier and the settings page both group them.\n toolsPinAll: 'Pin all',\n toolsPinAllHint: 'Pin every hidden tool of this server in every request',\n // The other direction of the same press, said by both surfaces when the set is\n // already wholly pinned. A tier's names are usually unpinned, but the snapshot\n // can hold a pin that is still listed as deferred — a pin written between two\n // assemblies, or one the host itself defers — and a button that read `Pin all`\n // while it released it would be a lie.\n toolsUnpinAll: 'Unpin all',\n toolsUnpinAllHint: 'Stop pinning every hidden tool of this server',\n // The same press on the pinned tier, where the names it releases are the ones\n // the user pinned rather than the ones the host hid.\n toolsUnpinServerHint: 'Stop pinning every tool of this server',\n toolsBudget: '{used} chars of {total} · ≈ {tokens} tokens',\n toolsBudgetExhausted: 'the budget is spent: further disclosures are rejected with a reason',\n toolsBudgetFree: 'free room in the budget or pin the tool in the project settings',\n toolsBudgetGateOff: 'the disclosure gate is off: every mounted tool goes into the request',\n toolsBudgetBreakdown: '{used} of {total} ({percent}%)',\n toolsModeOff: 'this project’s MCP tools are switched off',\n toolsModeOffCounters: '{mounted} mounted · none offered',\n toolsModeOffHint:\n 'Nothing from this project is offered to the model. Set the mode to “Disclosure” on the Tools page to offer them again.',\n toolsModeDirect: 'nothing is deferred: every mounted tool goes into the request',\n toolsPresentationOwner: 'Another plugin is shaping the request',\n toolsOtherOwner: 'Another presentation owner',\n toolsDemo: 'demo',\n toolsStep: 'step {step}',\n // The host's own usage counters (`ProjectSnapshot.usage`), read as two quiet\n // labels: how often one tool was called, and how long one server has gone\n // unused. Both are drawn only where the host published a record — no data, no\n // label — so `never called` means \"the server is in the counters and this tool\n // is not\", never \"the host said nothing\".\n callsOne: '1 call',\n callsMany: '{count} calls',\n callsNone: 'never called',\n callsProject: '{count} in the project',\n idleDay: 'idle {count}d',\n idleHour: 'idle {count}h',\n idleMinute: 'idle {count}m',\n // One tool row's detail block (F-56): the server the name was registered\n // under with the state it is in, the tier said as a sentence, the two counter\n // readings apart, and then what only the host can answer — the definition's\n // own description, its fields, and why a hidden name is not in the request.\n // The name, the clock and the step stay in the header, and the block prints\n // them again in its own fact line because the contract's own probe reads the\n // full `mcp__<server>__<tool>`, the step and the clock out of the open body\n // (`contracts/surfaces.md` §1.5) — see the `idea` row that parks that question\n // in `docs/features.md`. The host publishes no size for a single tool, so the\n // budget estimate stays in the group line above — the only figure the reason\n // line prints is a measurement the host sent it.\n toolServer: 'server {server}',\n toolServerState: '{server} · {state}',\n toolTierPinned: 'pinned — always in the request',\n toolTierSession: 'offered by this session',\n toolTierContext: 'offered by the context ranking',\n showTool: 'show this tool’s server, description, fields and how it was offered',\n hideTool: 'hide this tool’s detail',\n toolCallsSession: '{count} this session',\n toolLoading: 'reading this definition from the host…',\n toolFailed: 'the host did not answer for this definition',\n toolFieldsLabel: 'takes',\n toolFieldRequiredHint: 'required field',\n toolReasonBudget: 'not offered: {chars} chars over the {budget}-char budget',\n toolReasonChars: '{chars} chars',\n toolReasonBudgetOnly: '{budget}-char budget',\n toolReasonUsed: '{used} already offered',\n toolReason: 'not offered',\n // The errors and logs blocks, under their own disclosures: the event ring is\n // the plugin's own, one project at a time.\n errorsSection: 'Problems',\n showErrors: 'show the servers that need a look',\n hideErrors: 'hide the servers that need a look',\n logsSection: 'Logs',\n showLogs: 'show this project’s events',\n hideLogs: 'hide this project’s events',\n logsThisSession: 'this session',\n logsAllSessions: 'all sessions',\n logsAllLevels: 'all levels',\n logsErrorsOnly: 'errors',\n logsLevelInfo: 'info',\n logsLevelUp: 'up',\n logsLevelWarn: 'warn',\n logsLevelError: 'error',\n logsClear: 'Clear',\n logsClearHint: 'Hide every event recorded so far; new ones still appear',\n logsEmptyTitle: 'No events yet',\n logsEmptyHint:\n 'This project’s servers come up on the session’s first step or when you press Sync; mounting, start and stop will show up here.',\n logsNoErrorsTitle: 'No errors',\n logsNoErrorsHint:\n 'This project’s ring holds other events; switch the level filter to “all levels” to read them.',\n logsMore: 'Show older',\n logsMoreHint: 'Load the events older than the ones on screen',\n logsShown: 'showing {shown} of {total}',\n logsProjectCount: '{count} in this project',\n logsLoading: 'loading older events…',\n logsLoadFailed: 'older events could not be read',\n // The tab's own states, in the same table for the same reason.\n noSession: 'No session is attached to this tab.',\n noSessionHint: 'The panel reads the project of the session it is open in.',\n noProject: 'This session’s folder is not inside a project yet.',\n noProjectHint:\n 'The host walks up from the session cwd looking for .git · .dsh · .kimi-code · package.json · *.sln.',\n nothingNeedsAttention: 'Nothing needs attention.',\n noServersDeclared: 'This project declares no MCP servers.',\n noServersDeclaredHint: 'Add {documents}.',\n noServersDeclaredUnknown: 'Add an MCP document to the project.',\n noServersDeclaredNowhere:\n 'This deployment reads no project document, so there is nowhere to declare one — list one in the plugin config (`localFiles`).',\n // Surface A's own header and the vocabulary its rows are built from. The\n // segment bar is gone (F-26): the toolbar names the project and carries one\n // phrase on its right edge, and every count a mode segment used to badge lives\n // on the block it describes.\n thisSession: 'this session',\n noProjectLabel: 'no project',\n retry: 'Retry',\n retryHint: 'Retry this project’s failed mounts now',\n sessionsSection: 'sessions',\n // The `sessions` section is the project's *disagreement* view: its chip counts\n // the sessions whose own reading differs from the merged rows, not the\n // sessions that exist. The count of existing sessions lives on the toolbar's\n // right edge, which keeps `sessionsOne` / `sessionsMany` for itself.\n differsOne: '1 differs',\n differsMany: '{count} differ',\n sessionsOne: '1 session',\n sessionsMany: '{count} sessions',\n serversOne: '1 server',\n serversMany: '{count} servers',\n mergedAcrossSessions: 'merged across sessions',\n release: 'Release',\n nothingDeclared: 'nothing declared',\n showSessions: 'show the sessions of this project',\n hideSessions: 'hide the sessions of this project',\n showSession: 'show this session’s servers',\n hideSession: 'hide this session’s servers',\n mountedPerProject: 'Mounted per project',\n projectsCount: '{count} project(s)',\n nothingMounted: 'Nothing is mounted yet.',\n // The status vocabulary (F-47): the word a row wears and the one-line\n // explanation its tooltip carries. Both are read through `STATUS_KEYS` /\n // `STATUS_HINT` — `Record<ServerStatus, LocaleKey>` tables — so a new enum\n // member without a key is a compile error, never a raw token on screen.\n statusActive: 'active',\n statusConnecting: 'connecting',\n statusConflict: 'conflict',\n statusError: 'error',\n statusIdle: 'idle',\n statusDisabled: 'disabled',\n statusHintActive: 'mounted, its tools are visible in this session',\n statusHintConnecting: 'mounted, no tool published yet',\n statusHintIdle: 'declared but not mounted — mounts on the next turn',\n statusHintDisabled: 'declared with enabled: false',\n statusHintConflict: 'the same serverName is reserved by a profile-level instance',\n statusHintError: 'see the detail',\n // One project's or session's status line (`2 active, 1 idle`): one template\n // per status, so the count is a `{count}` placeholder in every language and\n // never a concatenation. `summarize` names no `disabled` count today; the\n // template is here so the day it does, the word is too.\n summaryActive: '{count} active',\n summaryConnecting: '{count} connecting',\n summaryIdle: '{count} idle',\n summaryDisabled: '{count} disabled',\n summaryError: '{count} error',\n summaryConflict: '{count} conflict',\n summaryNone: 'nothing declared',\n close: 'Close',\n // The frame-wide toasts (F-47): drafts carry these keys, and the stack\n // resolves them at render, so a language switch repaints the banners on\n // screen. The quieter line weaves the project around the fact behind the\n // moment — the host's own detail sentence, or a status hint.\n toastUp: '{server} is up',\n toastFailed: '{server} failed',\n toastReleased: '{server} released',\n toastDetail: '{project} · {detail}',\n // The poll interval's row in the settings panel, read live through the seat\n // on every render.\n refreshTitle: 'Refresh interval',\n refreshDesc: 'How often the panel re-reads the host snapshot',\n // The tab's actions menu (the chip's own menu): the row that opens the\n // settings popup, which used to be the sidebar's side card.\n settingsMenuItem: 'Panel settings…',\n // The design stand's own tab title and description (design.ts).\n designTitle: 'Project MCP · design ({variant})',\n designDesc: 'design mode: the {variant} fixture, no host behind it',\n}\n\n/** A dictionary key of this namespace. */\nexport type LocaleKey = keyof typeof en\n\n/** Translate one key, with optional `{name}` template params (the DSH seat). */\nexport type Translate = (key: string, params?: Record<string, unknown>) => string\n\n/**\n * Bind the translate seat a surface was given, falling back to this module's own\n * English dictionary when it renders outside a DSH shell (tests, or a browser\n * half newer than the host).\n * @param t - the injected `t` seat, when there is one.\n * @returns a translate function that always answers.\n */\nexport function translateOf(t?: Translate): Translate {\n return t ?? fallbackTranslate\n}\n\n/** The panel's own English copy, same shape as the settings page's fallback. */\nexport function fallbackTranslate(key: string, params?: Record<string, unknown>): string {\n const template = (en as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in params ? String(params[name]) : match,\n )\n}\n\n/** Name of the poll interval inside {@link REFRESH_STORAGE_KEY}. */\nexport const REFRESH_KEY = 'refreshMs'\n\n/**\n * `localStorage` key the poll interval is persisted under.\n *\n * The interval used to ride the side card's own settings blob\n * (`prefs.pluginSettings[TAB_ID]` of `dsh-better-sidebar`). That surface is gone\n * with the dependency, so the interval is a browser-local preference beside the\n * view, the log filters and the Clear mark — same lifetime, same hostile-storage\n * rule, one less service to read it from.\n */\nexport const REFRESH_STORAGE_KEY = `${TAB_ID}:${REFRESH_KEY}`\n\n/** Poll interval used until the setting is read. */\nexport const DEFAULT_REFRESH_MS = 5_000\n\n/**\n * Status colours, taken from the design system's alias layer\n * (`packages/client/ui-theme/src/styles/design-platform.css` in the DSH\n * checkout): `state-*` for the lifecycle, `label-tertiary` for the two quiet\n * states. The fallbacks only ever fire outside the DSH web client, where that\n * alias layer is not loaded.\n */\nexport const STATUS_COLOR: Record<ServerStatus, string> = {\n active: 'var(--dsw-alias-state-success-primary, #22c55e)',\n connecting: 'var(--dsw-alias-state-warn-primary, #f59e0b)',\n conflict: 'var(--dsw-alias-state-warn-primary, #f59e0b)',\n error: 'var(--dsw-alias-state-error-primary, #ec1313)',\n idle: 'var(--dsw-alias-label-tertiary, #81858c)',\n disabled: 'var(--dsw-alias-label-tertiary, #81858c)',\n}\n\n/**\n * The dictionary key of the word each status wears on its row, so the panel\n * never prints the enum token itself: a `ServerStatus` member without a key\n * here is a compile error, not a silent English leak in another language.\n */\nexport const STATUS_KEYS: Record<ServerStatus, LocaleKey> = {\n active: 'statusActive',\n connecting: 'statusConnecting',\n conflict: 'statusConflict',\n error: 'statusError',\n idle: 'statusIdle',\n disabled: 'statusDisabled',\n}\n\n/**\n * The dictionary key of each status's one-line explanation, so the panel needs\n * no legend. Readers translate through their own seat —\n * `t(STATUS_HINT[row.status])` — which keeps the sentence the tooltip or the\n * toast shows in the reader's language.\n */\nexport const STATUS_HINT: Record<ServerStatus, LocaleKey> = {\n active: 'statusHintActive',\n connecting: 'statusHintConnecting',\n idle: 'statusHintIdle',\n disabled: 'statusHintDisabled',\n conflict: 'statusHintConflict',\n error: 'statusHintError',\n}\n\nconst BORDER = '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))'\n\n/**\n * The alias layer's own tones, named once.\n *\n * The mockup's vocabulary has two levels of quiet text — `.muted` (secondary)\n * and `.dim` (tertiary) — and this surface used to paint both by dropping the\n * opacity of the primary colour, which is close to the token but not the same\n * value. Reading the token keeps the two tones distinguishable in both themes.\n */\nconst TONE = {\n /** `.muted`: the secondary label tone, for text the user reads next. */\n secondary: 'var(--dsw-alias-label-secondary, inherit)',\n /** `.dim`: the tertiary label tone, for captions and quiet states. */\n tertiary: 'var(--dsw-alias-label-tertiary, #81858c)',\n} as const\n\n/** The alias layer's layer-3 fill — the mockup's chip and the ring's filters. */\nconst LAYER_3 = 'var(--dsw-alias-bg-layer-3, rgba(127, 127, 127, 0.12))'\n\n/**\n * The counter chip's plate, named once because it has two readers now: the\n * reading chip of {@link STYLE.tag} and the pressable tier chip of the tools\n * block's filter (F-43). The two differ only in the three resets a `<button>`\n * needs and in the fill the pressed one takes, so the words and the count read\n * the same whether the tier is a label or a switch.\n */\nconst LAYER_3_CHIP = {\n background: LAYER_3,\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n fontSize: '0.85em',\n borderRadius: 4,\n padding: '0 5px',\n color: TONE.secondary,\n} satisfies CSSProperties\n\n/**\n * One step of the Servers surface's indentation ladder, in pixels.\n *\n * Surface A nests four levels and every one sits exactly one step right of the\n * one above it — `project 0 → sessions 12 → session 24 → that session's servers\n * 36`. The `sessions` rung is conditional: it exists only while at least one\n * session disagrees with the project's merged rows, so a project whose sessions\n * all agree stops at rung `0`. The scale lives here, once, and each level asks\n * for its rung through {@link STYLE.indent}; the hand-picked `paddingLeft`\n * values this replaced had drifted out of step with one another.\n */\nexport const INDENT = 12\n\n/**\n * The panel's own inline styles.\n *\n * Exported for the design-only render mode (`./design.ts`), which composes the\n * same `PanelHeader` / `tabBody` from a fixture and must therefore frame them\n * with the very same root and body — a second copy of these two objects is\n * exactly how a mockup drifts from the product.\n */\nexport const STYLE = {\n root: {\n display: 'flex',\n flexDirection: 'column',\n height: '100%',\n minHeight: 0,\n color: 'inherit',\n } satisfies CSSProperties,\n bar: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n // The mock's `.panel-bar` (`docs/design/mockups/harness.html`) — the panel's own inset, so the\n // chips and the project name start on the picture's margin.\n padding: '7px 9px',\n borderBottom: BORDER,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n body: {\n flex: 1,\n minHeight: 0,\n overflow: 'auto',\n // The one surface's blocks are direct children of this container (F-26), so\n // the inset the old per-mode wrapper used to supply is here now — the\n // mock's `.body { padding: 9px 10px }` (`docs/design/mockups/harness.html`).\n padding: '9px 10px',\n } satisfies CSSProperties,\n /** The rows' own inset: the mock's `.body` (`docs/design/mockups/harness.html`). */\n project: { padding: '9px 10px', borderBottom: BORDER } satisfies CSSProperties,\n projectHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n justifyContent: 'space-between',\n } satisfies CSSProperties,\n /**\n * `.muted`: the secondary tone, at the text's own size.\n *\n * The mock's `.muted` states a colour and nothing else (`docs/design/mockups/harness.html`),\n * and the dictionary's obligation is \"a muted colour, not a blindly reduced\n * size\" — so the tone is here and the size is the neighbouring text's.\n */\n muted: { color: TONE.secondary } satisfies CSSProperties,\n /** `.dim`: the tertiary tone, one step quieter than `.muted`. */\n dim: { color: TONE.tertiary, fontSize: '0.9em' } satisfies CSSProperties,\n row: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n padding: '2px 0',\n } satisfies CSSProperties,\n sessions: {\n marginTop: 4,\n paddingTop: 4,\n borderTop: BORDER,\n } satisfies CSSProperties,\n session: { padding: '2px 0' } satisfies CSSProperties,\n sessionHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n sessionToggle: {\n padding: 0,\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n textAlign: 'left',\n } satisfies CSSProperties,\n /**\n * `tag`: the mockup's chip is a short plate on a layer fill in mono type — not\n * a word in the row, and not a bordered box either (`docs/design/mockups/harness.html`,\n * dictionary line 13).\n */\n tag: { ...LAYER_3_CHIP } satisfies CSSProperties,\n /** The `idle` / `disabled` chip: the mockup's `.dim` tone, one step quieter. */\n tagQuiet: {\n color: TONE.tertiary,\n } satisfies CSSProperties,\n /** The `up/total` chip once a declared server is failing: red, not quiet. */\n tagWarn: {\n color: 'var(--dsw-alias-state-error-primary, #ec1313)',\n } satisfies CSSProperties,\n /**\n * One counter chip of the tools block, as the filter's tier switch (F-43).\n *\n * The same plate {@link STYLE.tag} draws — the words and the count do not\n * change with the tier — with the resets a `<button>` needs to sit in a row of\n * spans without becoming a form control the shell styles. The chip is a leaf\n * holding its text directly, which is also what lets the parity gate read\n * `{count} pinned` off it.\n *\n * `font: inherit` comes **before** the plate, and the order is the whole\n * point: `font` is a shorthand that resets `font-family` and `font-size` too,\n * and React writes the inline style in this object's own order — behind the\n * plate it silently turned the chips into the shell's sans face, which is the\n * one thing a chip of this vocabulary is not (see the neighbouring\n * `STYLE.logFilter`, where the shorthand is the last word on purpose because\n * that chip is the shell's own type).\n */\n filterChip: {\n font: 'inherit',\n cursor: 'pointer',\n border: 'none',\n ...LAYER_3_CHIP,\n } satisfies CSSProperties,\n /** The pressed tier chip: the applied filter is the one that reads as active. */\n filterChipOn: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n color: 'var(--dsw-alias-label-primary, inherit)',\n } satisfies CSSProperties,\n /**\n * The filter's query field: the shell's own input plate, one size down and\n * full width, so the field reads as the panel's own row rather than a form\n * control borrowed from the settings page.\n */\n filterInput: {\n flex: 1,\n minWidth: 0,\n border: BORDER,\n borderRadius: 4,\n padding: '2px 6px',\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.85em',\n } satisfies CSSProperties,\n /**\n * A group label that shares its line with a chip. {@link STYLE.group} owns a\n * whole line at the tertiary tone, which would bleach the chip with it.\n */\n groupInline: {\n color: TONE.tertiary,\n fontSize: '0.8em',\n letterSpacing: '0.08em',\n textTransform: 'uppercase',\n } satisfies CSSProperties,\n /** The session's declared-servers block, the single surface's first block. */\n serversBlock: {\n margin: '0 0 6px',\n paddingBottom: 4,\n borderBottom: BORDER,\n } satisfies CSSProperties,\n /**\n * One rung of the Servers surface's indentation ladder: `level` steps right of\n * the project's own rows, so `0` is the project, `1` the `sessions` section,\n * `2` one session of it, `3` that session's own servers. The only left padding\n * the surface has; nothing else may hand-pick one.\n */\n indent: (level: number): CSSProperties => ({ paddingLeft: level * INDENT }),\n // An identifier is one unbreakable token (`mcp__tglider__workspace`), and the\n // panel is 330px wide at its narrowest: without a break opportunity the name\n // overflows its own row button instead of wrapping inside it. `anywhere` rather\n // than `break-word` because only `anywhere` shrinks the item's own min-content\n // width, which is what the flex row measures.\n name: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n detail: { opacity: 0.7, overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' } satisfies CSSProperties,\n button: {\n padding: '2px 8px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n } satisfies CSSProperties,\n error: { padding: 8, color: STATUS_COLOR.error } satisfies CSSProperties,\n /**\n * The poll interval's row in the settings panel: a label that stacks the\n * toggle's own title and hint, the field it points at, and the unit beside it.\n * Laid out as one row so the panel reads like the side card the row came from.\n */\n settingRow: {\n display: 'flex',\n alignItems: 'center',\n gap: 8,\n padding: '8px 8px 0',\n } satisfies CSSProperties,\n settingLabel: { display: 'flex', flexDirection: 'column', gap: 2, flex: 1 } satisfies CSSProperties,\n settingTitle: { fontSize: 12 } satisfies CSSProperties,\n settingDesc: { fontSize: 11, color: TONE.tertiary } satisfies CSSProperties,\n settingInput: {\n width: 72,\n padding: '2px 6px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n } satisfies CSSProperties,\n settingUnit: { fontSize: 11, color: TONE.tertiary } satisfies CSSProperties,\n /**\n * One disclosure of the single surface (F-26): a block of the scrolling body\n * whose head is a button and whose body exists only while it is open. The\n * parity gate finds it as a `div` with a `button[aria-expanded]` child, so the\n * head is the block's first child and the body its second — the shape the\n * mockup's `.disclosure` declares.\n */\n disclosure: { marginTop: 5 } satisfies CSSProperties,\n disclosureHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n width: '100%',\n padding: '2px 0',\n border: 'none',\n background: 'transparent',\n font: 'inherit',\n textAlign: 'left',\n cursor: 'pointer',\n // `.disclosure-head`: the label is the control's word, read in the quiet\n // tone (`docs/design/mockups/harness.html`, F-26 block).\n color: TONE.tertiary,\n } satisfies CSSProperties,\n disclosureBody: { paddingLeft: 12 } satisfies CSSProperties,\n /**\n * One tool row: the line the user reads with its one action beside it, and the\n * detail block on its own line while it is open. The line is the disclosure's\n * `button[aria-expanded]` and a direct child of this wrapper, so a parity probe\n * that looks for `div > button[aria-expanded]` finds the row, and the action\n * stays a sibling — a button inside a button is not a thing HTML has.\n */\n tool: {\n display: 'flex',\n flexWrap: 'wrap',\n alignItems: 'baseline',\n gap: 6,\n } satisfies CSSProperties,\n /** The tool row's own line: the tier dot, the name, and the time and step. */\n toolLine: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n flex: 1,\n minWidth: 0,\n padding: '2px 0',\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n textAlign: 'left',\n } satisfies CSSProperties,\n /**\n * The open detail of one tool (F-56): the server it was registered under with\n * the state it is in, the tier as a sentence, the counter readings this row does\n * not show, and then the host's own on-demand answer about the definition — its\n * description, the fields it takes, and why a hidden name is not in the request.\n * One rung in from the row, like every other body of a disclosure.\n */\n toolDetail: {\n flexBasis: '100%',\n padding: '2px 0 4px 12px',\n } satisfies CSSProperties,\n /** One accepted field of a definition: its mono name, type, marker and description. */\n field: {\n display: 'flex',\n flexWrap: 'wrap',\n alignItems: 'baseline',\n gap: 5,\n padding: '1px 0',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldName: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldDesc: { color: TONE.secondary, opacity: 0.75 } satisfies CSSProperties,\n group: {\n opacity: 0.6,\n fontSize: '0.8em',\n letterSpacing: '0.08em',\n textTransform: 'uppercase',\n margin: '7px 0 1px',\n } satisfies CSSProperties,\n empty: {\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n gap: 6,\n padding: '14px 10px',\n textAlign: 'center',\n } satisfies CSSProperties,\n emptyTitle: { opacity: 0.9 } satisfies CSSProperties,\n hint: { opacity: 0.6, fontSize: '0.85em', overflowWrap: 'anywhere' } satisfies CSSProperties,\n dot: {\n width: 8,\n height: 8,\n borderRadius: '50%',\n display: 'inline-block',\n flex: 'none',\n alignSelf: 'center',\n } satisfies CSSProperties,\n codeLine: {\n margin: 8,\n padding: '5px 8px',\n border: BORDER,\n borderRadius: 5,\n background: 'var(--dsw-alias-markdown-code-block, transparent)',\n color: 'var(--dsw-alias-link, inherit)',\n fontSize: '0.8em',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n budget: {\n height: 4,\n margin: '4px 0 2px',\n borderRadius: 2,\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n overflow: 'hidden',\n } satisfies CSSProperties,\n budgetUsed: {\n display: 'block',\n height: '100%',\n background: 'var(--dsw-alias-state-business-primary, currentColor)',\n } satisfies CSSProperties,\n warnNote: {\n margin: '8px 0',\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-warn-primary, #f59e0b)',\n background: 'var(--dsw-alias-state-warn-tertiary, transparent)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n /** A quiet row — `idle` or `disabled` — reads at the same size, dimmed. */\n rowQuiet: { opacity: 0.6 } satisfies CSSProperties,\n /** A row of chips: the hidden-by-server tags the tools block draws. */\n chips: {\n display: 'inline-flex',\n alignItems: 'center',\n gap: 4,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n /** The header row of the collapsed sessions section. */\n sessionsHead: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n /** A failure banner: the coloured left rule carries the severity, not a word. */\n banner: {\n margin: '2px 0 4px',\n padding: '4px 7px',\n borderRadius: '0 5px 5px 0',\n borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',\n background: 'var(--dsw-alias-interactive-bg-hover-danger, transparent)',\n color: 'var(--dsw-alias-label-primary, inherit)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n // A mount detail is a multi-line diagnostic (error, endpoint, declaration,\n // next step); collapsing its line breaks is what made it unreadable.\n whiteSpace: 'pre-wrap',\n } satisfies CSSProperties,\n /** Laid over {@link STYLE.banner} for a restriction rather than a failure. */\n bannerWarn: {\n borderLeftColor: 'var(--dsw-alias-state-warn-primary, #f59e0b)',\n background: 'var(--dsw-alias-state-warn-tertiary, transparent)',\n } satisfies CSSProperties,\n /**\n * One log event's first line: time, level, server, message.\n *\n * `flexWrap` is the point of this row. A sidebar is narrow, and a message kept\n * in a trailing column turns into a staircase of two-word fragments; wrapping\n * the row lets the message take the rest of the line and the whole of the next\n * one, which is how the mockup reads.\n */\n logRow: {\n display: 'flex',\n alignItems: 'baseline',\n gap: 6,\n padding: '2px 0',\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n /** The event's clock: mono, tertiary, fixed width so the column aligns. */\n logTime: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n color: TONE.tertiary,\n fontSize: '0.85em',\n flex: 'none',\n } satisfies CSSProperties,\n /**\n * The level chip. It reuses {@link STYLE.tag}'s plate and is only coloured on\n * top of it, so `info` reads as the quiet chip it is and `error` as the alarm.\n */\n logLevel: { flex: 'none', textTransform: 'none', fontWeight: 500 } satisfies CSSProperties,\n /**\n * A filter chip of the Logs toolbar: a button that reads like {@link STYLE.tag}\n * but keeps the interface font, since it is a control rather than a value.\n */\n logFilter: {\n padding: '1px 6px',\n border: 'none',\n borderRadius: 4,\n background: LAYER_3,\n color: TONE.secondary,\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.85em',\n } satisfies CSSProperties,\n /** The filter currently applied: one pressed chip per pair. */\n logFilterOn: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n color: 'var(--dsw-alias-label-primary, inherit)',\n } satisfies CSSProperties,\n /** Server name of the event, in the same mono face as every other name. */\n logName: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n color: TONE.secondary,\n flex: 'none',\n } satisfies CSSProperties,\n /** The message: its own width, so it never becomes a two-word column. */\n logMessage: {\n flex: '1 1 100%',\n marginTop: 1,\n overflowWrap: 'anywhere',\n color: 'var(--dsw-alias-label-primary, inherit)',\n } satisfies CSSProperties,\n /** One fact line under a failing event; `marginLeft` sits it under the text. */\n logDetail: {\n margin: '0 0 3px',\n paddingLeft: 7,\n borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',\n color: 'var(--dsw-alias-label-primary, inherit)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n /** `error` chip: the alarm tone of {@link STATUS_COLOR}. */\n logError: { color: STATUS_COLOR.error } satisfies CSSProperties,\n /** `warn` chip: the same tone a stalled server row uses. */\n logWarn: { color: STATUS_COLOR.connecting } satisfies CSSProperties,\n /** `up` chip: a successful mount reads like an active server. */\n logUp: { color: STATUS_COLOR.active } satisfies CSSProperties,\n}\n\ninterface Envelope<T> {\n ok: boolean\n value?: T\n error?: { code?: string; message?: string }\n}\n\n/**\n * Call one host route, unwrapping the `{ ok, value }` envelope.\n *\n * Exported so a surface that needs the snapshot outside the tab's own polling\n * hook reads the same route the same way.\n * @param path - route action under `ROUTE_PREFIX`.\n * @param body - JSON body for a `POST` action; omitted for a `GET`.\n * @returns the unwrapped snapshot.\n */\nexport async function request(path: string, body?: unknown): Promise<McpSnapshot> {\n const response = await fetch(`${ROUTE_PREFIX}/${path}`, routeInit(path, body))\n const payload = (await response.json()) as Envelope<McpSnapshot>\n if (payload.ok !== true || payload.value === undefined) {\n throw new Error(payload.error?.message ?? `request failed (${response.status})`)\n }\n return payload.value\n}\n\n/**\n * The `fetch` init for one route call.\n *\n * The method follows the **action**, never whether a payload happened to be\n * passed: the reads — the snapshot, the status channel and a page of logs — are\n * `GET`, and every other action is a `POST` the host refuses for `GET`. Deciding\n * this from the body was a real defect — `Sync` and `Retry` pass no payload, so\n * they were sent as `GET` and answered `404` from both panels, while `Release`\n * (which sends a session id) worked.\n *\n * @param path - route action under `ROUTE_PREFIX`.\n * @param body - JSON body; an action without one sends `{}` rather than nothing.\n * @returns the init to hand to `fetch`.\n */\nexport function routeInit(path: string, body?: unknown): RequestInit {\n // `logs` is read out of the registry rather than repeated as a literal: the\n // contract gives the route one owner, and this stays correct once it lands.\n const logs = (ROUTE_ACTIONS as Record<string, string | undefined>).logs\n const reads = [ROUTE_ACTIONS.snapshot, ROUTE_ACTIONS.events, ...(logs === undefined ? [] : [logs])]\n if (reads.includes(path)) return {}\n return {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n }\n}\n\ninterface SnapshotState {\n snapshot: McpSnapshot | undefined\n error: string | undefined\n busy: boolean\n}\n\n/**\n * Poll the host snapshot while the panel is visible; the Settings page polls it\n * unconditionally. Exported so both surfaces share one fetch/unwrap/poll path.\n *\n * The poll is the **fallback**: the host pushes every change over the status\n * channel (`GET /project-mcp/events`, see `createEventStream` in `src/ui.ts`),\n * and a panel whose stream is open polls nothing. A host half older than the\n * route, a browser without `EventSource`, or a dropped connection all land in the\n * same place — the poll keeps the picture fresh, and `EventSource` reconnects on\n * its own until the stream is back.\n * @param visible - false suspends polling (the sidebar tab does this while hidden).\n * @param refreshMs - poll interval while the status channel is not connected.\n * @param path - route action to poll; the snapshot unless a surface asks for another.\n * @returns the latest snapshot, the last error, the in-flight flag and `run`.\n */\nexport function useSnapshot(visible: boolean, refreshMs: number, path: string = 'snapshot') {\n const [state, setState] = useState<SnapshotState>({ snapshot: undefined, error: undefined, busy: false })\n const [pushed, setPushed] = useState(false)\n const load = useCallback(async () => {\n try {\n const snapshot = await request(path)\n setState((previous) => ({ ...previous, snapshot, error: undefined }))\n } catch (error) {\n setState((previous) => ({ ...previous, error: messageOf(error) }))\n }\n }, [path])\n /**\n * Apply one pushed frame. Every frame carries the whole picture, so one that\n * arrived after a gap is still a complete answer — nothing to refetch.\n */\n const apply = useCallback((change: SnapshotChange) => {\n setState((previous) => ({ snapshot: change.snapshot, error: undefined, busy: previous.busy }))\n }, [])\n useEffect(() => {\n if (!visible || typeof EventSource === 'undefined') return\n const source = new EventSource(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.events}`)\n const onFrame = (event: Event): void => {\n try {\n apply(JSON.parse(String((event as MessageEvent).data)) as SnapshotChange)\n } catch {\n // A frame the panel cannot read is one poll away; the connection stays.\n }\n }\n source.addEventListener('hello', onFrame)\n source.addEventListener('change', onFrame)\n source.addEventListener('open', () => setPushed(true))\n source.addEventListener('error', () => setPushed(false))\n return () => {\n source.close()\n setPushed(false)\n }\n }, [visible, apply])\n useEffect(() => {\n if (!visible || pushed) return\n void load()\n const timer = setInterval(() => void load(), Math.max(1_000, refreshMs))\n return () => clearInterval(timer)\n }, [visible, pushed, refreshMs, load])\n /**\n * Run one action. The method comes from {@link routeInit}, so an action with\n * no payload is still a `POST`.\n * @param path - route action under `ROUTE_PREFIX`.\n * @param body - JSON body, when the action takes one.\n */\n const run = useCallback(async (path: string, body?: unknown) => {\n setState((previous) => ({ ...previous, busy: true }))\n try {\n setState({ snapshot: await request(path, body), error: undefined, busy: false })\n } catch (error) {\n setState((previous) => ({ ...previous, busy: false, error: messageOf(error) }))\n }\n }, [])\n /**\n * Run one action once per body, and set the picture once.\n *\n * The pin route writes exactly one name per call (`PinRequest`), so a server's\n * worth of names is a fan-out rather than one request — and a server-level\n * press is one intent, so it deserves one repaint: the requests go out\n * together and the last body's answer becomes the picture, instead of the\n * panel painting itself once per name and racing its own writes.\n *\n * That answer is the state *after* the last write of the batch, not\n * necessarily after the last one to settle: the host answers every call with\n * the whole picture, so a straggler's effect arrives with the next pushed\n * frame or poll, and the panel's own error line reports a refusal either way.\n * @param path - route action under `ROUTE_PREFIX`.\n * @param bodies - one body per write; nothing is sent for an empty batch.\n */\n const runAll = useCallback(async (path: string, bodies: readonly unknown[]) => {\n if (bodies.length === 0) return\n setState((previous) => ({ ...previous, busy: true }))\n try {\n const answers = await Promise.all(bodies.map((body) => request(path, body)))\n const fresh = answers[answers.length - 1]\n setState((previous) =>\n fresh === undefined\n ? { ...previous, busy: false }\n : { snapshot: fresh, error: undefined, busy: false },\n )\n } catch (error) {\n setState((previous) => ({ ...previous, busy: false, error: messageOf(error) }))\n }\n }, [])\n return { ...state, run, runAll, reload: load }\n}\n\n/**\n * Just enough of `Storage` for the log-filter and Clear-mark helpers, so tests\n * need no DOM. The tab has no mode to remember since F-26: one surface means one\n * screen, and browser-local storage only carries the ring's own filters.\n */\nexport interface PanelStorage {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n}\n\n/** The browser's storage, or undefined when this half runs without one. */\nexport function browserStorage(): PanelStorage | undefined {\n try {\n return (globalThis as { localStorage?: PanelStorage }).localStorage\n } catch {\n // Reading the property itself throws when a policy blocks storage.\n return undefined\n }\n}\n\n/**\n * Read one preference out of browser-local storage.\n *\n * Both the tab and the Settings page persist a single small choice; every\n * storage access is guarded, so a policy that blocks storage (or a browser\n * without one) only costs the choice at the next reload.\n * @param key - storage key.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored string, or undefined when absent or unavailable.\n */\nexport function storedString(\n key: string,\n storage: PanelStorage | undefined = browserStorage(),\n): string | undefined {\n try {\n return storage?.getItem(key) ?? undefined\n } catch {\n // Reading the property itself throws when a policy blocks storage.\n return undefined\n }\n}\n\n/**\n * Persist one preference; a storage that refuses the write only costs the\n * choice at the next reload.\n * @param key - storage key.\n * @param value - value to store.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function storeString(\n key: string,\n value: string,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n try {\n storage?.setItem(key, value)\n } catch {\n // Storage disabled: the value still applies until the page is reloaded.\n }\n}\n\n/**\n * Read the poll interval out of browser-local storage.\n *\n * A missing, unreadable or nonsensical value is not an error: the panel falls\n * back to {@link DEFAULT_REFRESH_MS}, exactly as it did when the value arrived\n * in an untyped plugin-settings blob.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored interval in milliseconds, or the default.\n */\nexport function storedRefreshMs(storage: PanelStorage | undefined = browserStorage()): number {\n const raw = storedString(REFRESH_STORAGE_KEY, storage)\n if (raw === undefined) return DEFAULT_REFRESH_MS\n const value = Number(raw)\n return Number.isFinite(value) && value > 0 ? value : DEFAULT_REFRESH_MS\n}\n\n/**\n * The poll interval as a live preference.\n *\n * Two surfaces read it — the panel it paces and the settings that change it —\n * and they are not in one tree (the settings live in the tab's actions menu), so\n * the value needs a seat both can subscribe to. The store is the same shape the\n * toast stack uses: a value, a setter, and listeners for whoever renders it.\n * Writes go to browser storage first, so a reload keeps the interval even when\n * no surface is left to re-render.\n */\nexport interface RefreshStore {\n /** The current interval in milliseconds. */\n get(): number\n /** Persist and publish a new interval; a value the surface cannot render is the caller's business. */\n set(value: number): void\n /** Subscribe to changes; the returned function unsubscribes. */\n subscribe(listener: () => void): () => void\n}\n\n/**\n * Build a {@link RefreshStore} on top of browser storage.\n * @param storage - storage to read and write; defaults to the browser's own.\n * @returns the store, seeded from what is already persisted.\n */\nexport function createRefreshStore(\n storage: PanelStorage | undefined = browserStorage(),\n): RefreshStore {\n let value = storedRefreshMs(storage)\n const listeners = new Set<() => void>()\n return {\n get: () => value,\n set: (next: number): void => {\n if (!Number.isFinite(next) || next <= 0 || next === value) return\n value = next\n storeString(REFRESH_STORAGE_KEY, String(next), storage)\n for (const listener of listeners) listener()\n },\n subscribe: (listener: () => void): (() => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\n/**\n * Read the store as a re-rendering hook.\n * @param store - the store to follow.\n * @returns the current interval, re-read after every change.\n */\nexport function useRefreshMs(store: RefreshStore): number {\n const [value, setValue] = useState(() => store.get())\n useEffect(() => store.subscribe(() => setValue(store.get())), [store])\n return value\n}\n\n/**\n * Which sessions the Logs tab reads: the tab's own session, or every session of\n * the project. The mockup offers exactly these two.\n */\nexport type LogScope = 'session' | 'all'\n\n/** Which levels the Logs tab reads: everything, or the failures only. */\nexport type LogLevelFilter = 'all' | 'error'\n\n/** `localStorage` key of the Logs tab's session-scope filter. */\nexport const LOG_SCOPE_KEY = `${TAB_ID}:logsScope`\n\n/** `localStorage` key of the Logs tab's level filter. */\nexport const LOG_LEVEL_KEY = `${TAB_ID}:logsLevel`\n\n/**\n * `localStorage` key of the Logs tab's **client-side** Clear mark.\n *\n * `Clear` has no route (see the frozen contract, C1): the tab remembers the\n * moment and stops drawing events at or before it. The host's ring is untouched,\n * so a later `Sync` still answers with the whole buffer.\n */\nexport const LOGS_CLEARED_KEY = `${TAB_ID}:logsClearedAt`\n\n/** Scope read when nothing valid is persisted: this tab's own session. */\nexport const DEFAULT_LOG_SCOPE: LogScope = 'session'\n\n/**\n * Level read when nothing valid is persisted: errors only.\n *\n * The ring records the whole lifecycle, and at a project's first step that is a\n * wall of `mounting`/`is up` lines; the owner asked for the tab to answer \"did\n * anything break\" before it answers anything else. Every level is one click\n * away, and a level the user chose is persisted and wins over this default.\n */\nexport const DEFAULT_LOG_LEVEL: LogLevelFilter = 'error'\n\n/**\n * Events one snapshot carries and one `GET logs` page answers with.\n *\n * A mirror of the host's `LOG_PAGE_SIZE` (`src/logs.ts`), not a second owner of\n * the rule: the client asks for a page and reads what it is handed.\n */\nexport const LOG_PAGE_SIZE = 50\n\n/**\n * Read the persisted session-scope filter.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored scope, or {@link DEFAULT_LOG_SCOPE}.\n */\nexport function logScopeOf(storage: PanelStorage | undefined = browserStorage()): LogScope {\n return storedString(LOG_SCOPE_KEY, storage) === 'all' ? 'all' : DEFAULT_LOG_SCOPE\n}\n\n/**\n * Read the persisted level filter.\n *\n * Both stored values are answered as themselves; only an unknown or absent\n * entry falls back to {@link DEFAULT_LOG_LEVEL}. Testing against the default\n * instead would silently swallow the other valid value whenever the default\n * changes — the filter has two states, so both are named here.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored filter, or {@link DEFAULT_LOG_LEVEL}.\n */\nexport function logLevelOf(storage: PanelStorage | undefined = browserStorage()): LogLevelFilter {\n const stored = storedString(LOG_LEVEL_KEY, storage)\n return stored === 'all' || stored === 'error' ? stored : DEFAULT_LOG_LEVEL\n}\n\n/**\n * Read the Clear mark.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the epoch ms of the last Clear, or undefined when none was pressed.\n */\nexport function logsClearedAt(storage: PanelStorage | undefined = browserStorage()): number | undefined {\n const stored = storedString(LOGS_CLEARED_KEY, storage)\n if (stored === undefined) return undefined\n const at = Number(stored)\n return Number.isFinite(at) ? at : undefined\n}\n\n/**\n * Persist one of the Logs tab's own choices.\n * @param key - {@link LOG_SCOPE_KEY} or {@link LOG_LEVEL_KEY}.\n * @param value - the choice to store.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function persistLogFilter(\n key: string,\n value: string,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n storeString(key, value, storage)\n}\n\n/**\n * Record a Clear: events at or before `at` stop being drawn from now on.\n * @param at - the moment Clear was pressed, in epoch ms.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function persistLogsClearedAt(\n at: number,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n storeString(LOGS_CLEARED_KEY, String(at), storage)\n}\n\n/** One page of events as `GET logs` answers it (contract C1). */\nexport interface LogPage {\n /** Events, oldest first. */\n readonly events: readonly LogEvent[]\n /** How many events the project's ring holds in total. */\n readonly total: number\n /** Whether the ring holds events older than the last one on this page. */\n readonly more: boolean\n}\n\n/** Build the `GET logs` query for one page request. */\nfunction logsQuery(projectRoot: string, before: number | undefined, limit: number): URLSearchParams {\n const query = new URLSearchParams({ projectRoot, limit: String(limit) })\n if (before !== undefined) query.set('before', String(before))\n return query\n}\n\n/**\n * Read one page of older events over the contract's `GET logs` route.\n *\n * The snapshot carries the newest {@link LOG_PAGE_SIZE} events; \"show older\"\n * asks the route for the page before the oldest one on screen. `before` is the\n * exclusive cursor the host pages on (`at < before`).\n * @param projectRoot - project the page belongs to.\n * @param before - epoch ms to page before; the snapshot page is requested without one.\n * @param limit - page size; {@link LOG_PAGE_SIZE} unless a test asks otherwise.\n * @param fetchImpl - `fetch` to use; defaults to the browser's.\n * @returns the page, or `undefined` when the host refused or the answer was unreadable.\n */\nexport async function fetchLogs(\n projectRoot: string,\n before?: number,\n limit: number = LOG_PAGE_SIZE,\n fetchImpl: typeof fetch | undefined = (globalThis as { fetch?: typeof fetch }).fetch,\n): Promise<LogPage | undefined> {\n if (fetchImpl === undefined) return undefined\n // The action is read out of the shared registry, so this route has one owner:\n // adding it there (contract C1) is what makes this line compile.\n const action = (ROUTE_ACTIONS as Record<string, string | undefined>).logs\n if (action === undefined) return undefined\n try {\n const query = logsQuery(projectRoot, before, limit)\n const response = await fetchImpl(`${ROUTE_PREFIX}/${action}?${query.toString()}`)\n const payload = (await response.json()) as Envelope<LogPage>\n if (payload.ok !== true || payload.value === undefined) return undefined\n return payload.value\n } catch {\n return undefined\n }\n}\n\n/**\n * What one opened row's definition costs to answer, and what is already known\n * about it: the one place a `GET tool` answer is held (F-56).\n *\n * One cache for the module, keyed by the route's own three parameters, rather\n * than one per mount. The answer is a fact about the name, not about a render —\n * folding a row and opening it again must not re-read the host, and the design\n * stand seeds this map directly instead of mounting a host to fake one. The key\n * carries the project and the session because the route takes them and two\n * surfaces of the panel may read different ones in one process.\n *\n * An entry is written **only** by answers that arrived: a fetch in flight is in\n * {@link toolFactsPending} and a failed one in {@link toolFactsFailed}, so a\n * mount that skipped the tool routes pulls in no fixture code and draws no\n * invented answer.\n */\ninterface ToolFactsEntry {\n readonly projectRoot: string\n readonly sessionId: string\n readonly name: string\n}\n\nconst TOOL_FACTS_SEPARATOR = '\\u0000'\nconst toolFacts = new Map<string, ToolFacts>()\nconst toolFactsPending = new Set<string>()\nconst toolFactsFailed = new Set<string>()\n\n/** The cache key of one `GET tool` answer. */\nfunction toolFactsKey(projectRoot: string, sessionId: string, name: string): string {\n return [projectRoot, sessionId, name].join(TOOL_FACTS_SEPARATOR)\n}\n\n/** Build the `GET tool` query for one opened row's definition. */\nfunction toolFactsQuery(projectRoot: string, sessionId: string, name: string): URLSearchParams {\n return new URLSearchParams({ projectRoot, sessionId, name })\n}\n\n/**\n * Read one tool's facts over the contract's `GET tool` route.\n *\n * The snapshot carries no definition, and cannot: a description and a schema are\n * the expensive part of a tool, while every change frame and every poll carries\n * the whole snapshot. This route is therefore read once per row the reader\n * opens, exactly as `GET logs` is read once per page — and it answers a\n * **deferred** name the same way as an offered one, because the definition is\n * read from the scope the bridge registered it in and not from the offer.\n * Unknown names answer `ok: false` and are indistinguishable here from a refusal,\n * which is the route's own decision: the panel draws its one failure line.\n * @param projectRoot - project the definition belongs to.\n * @param sessionId - session the row is open in; the host scopes the read to it.\n * @param name - public registry name, eg `mcp__tglider__workspace`.\n * @param fetchImpl - `fetch` to use; defaults to the browser's.\n * @returns the facts, or `undefined` when the host refused or the answer was unreadable.\n */\nexport async function fetchToolFacts(\n projectRoot: string,\n sessionId: string,\n name: string,\n fetchImpl: typeof fetch | undefined = (globalThis as { fetch?: typeof fetch }).fetch,\n): Promise<ToolFacts | undefined> {\n if (fetchImpl === undefined) return undefined\n // Read out of the shared registry like `logs`, so a build whose contract has\n // no `tool` action asks for nothing rather than for a route nobody serves.\n const action = (ROUTE_ACTIONS as Record<string, string | undefined>).tool\n if (action === undefined) return undefined\n try {\n const query = toolFactsQuery(projectRoot, sessionId, name)\n const response = await fetchImpl(`${ROUTE_PREFIX}/${action}?${query.toString()}`)\n const payload = (await response.json()) as Envelope<ToolFacts>\n if (payload.ok !== true || payload.value === undefined) return undefined\n // A host that answered the envelope with something that is not a record is\n // as unreadable as a refusal: caching it under the row's key would put a\n // shape the body cannot draw on screen, so the panel takes the failure line\n // instead of an invented definition.\n const value = payload.value as Partial<ToolFacts>\n if (typeof value.name !== 'string' || !Array.isArray(value.fields)) return undefined\n return payload.value\n } catch {\n return undefined\n }\n}\n\n/**\n * The facts known about one name, asked for at most once per route.\n *\n * Called from the render of a row that is open — the only moment the answer is\n * wanted — so a folded row costs nothing. A synchronous answer already in the\n * map is returned now; otherwise the read starts once and the caller draws\n * {@link toolFactsLoading}'s line until the promise settles and re-renders. The\n * name-only entry is read first because that is where a seeded stand writes, and\n * a definition is the same record whichever panel asked for it.\n * @param entry - the route's own parameters.\n * @returns the facts while they are held; `undefined` while the read is on its way.\n */\nfunction toolFactsOf(entry: ToolFactsEntry): ToolFacts | undefined {\n const seeded = toolFacts.get(entry.name)\n if (seeded !== undefined) return seeded\n const key = toolFactsKey(entry.projectRoot, entry.sessionId, entry.name)\n const held = toolFacts.get(key)\n if (held !== undefined || toolFactsPending.has(key) || toolFactsFailed.has(key)) return held\n toolFactsPending.add(key)\n void fetchToolFacts(entry.projectRoot, entry.sessionId, entry.name).then((facts) => {\n toolFactsPending.delete(key)\n if (facts === undefined) toolFactsFailed.add(key)\n else toolFacts.set(key, facts)\n })\n return undefined\n}\n\n/** `true` once the host refused to answer for this name. */\nfunction toolFactsUnreadable(entry: ToolFactsEntry): boolean {\n return toolFactsFailed.has(toolFactsKey(entry.projectRoot, entry.sessionId, entry.name))\n}\n\n/**\n * Publish one definition into the panel's cache, as the design mode's own host\n * would answer.\n *\n * The stand renders the same components with no host at all, so the body of an\n * opened row would sit on a read that never resolves. Seeding the very map the\n * product reads — rather than a second \"fixture mode\" branch inside the row —\n * is what keeps the product's drawing and the stand's one drawing: `view.ts`\n * has no code path that knows whether the answer came from a socket. The entry is\n * written under the name alone, which is the key a row with no route of its own\n * looks up; a panel that does hold one looks there first, for the same reason.\n * @param name - the public registry name the record answers about.\n * @param facts - the record the fixture host publishes for that name.\n */\nexport function seedToolFacts(name: string, facts: ToolFacts): void {\n toolFacts.set(name, facts)\n}\n\n/**\n * Forget every held definition.\n *\n * Exported for the specs: one process renders several panels for several\n * projects, and an answer held for one of them must not decide another's body.\n * The product never calls this — a definition does not change while a panel is\n * mounted.\n */\nexport function clearToolFacts(): void {\n toolFacts.clear()\n toolFactsPending.clear()\n toolFactsFailed.clear()\n}\n\n/**\n * The events one session's ring holds, as the logs disclosure's badge counts them.\n *\n * The snapshot field is the **session's** own count (contract C1) — not the\n * project's — so the badge answers \"how much happened here\" rather than \"how\n * busy is this folder\".\n * @param session - the session, or undefined when the tab has none.\n * @returns the session's event count, `0` when the field is absent.\n */\nexport function sessionLogCount(session: { readonly logCount?: number } | undefined): number {\n return session?.logCount ?? 0\n}\n\n/**\n * Keep the newest `at`-time first, and drop the duplicates a page overlap can\n * produce, so \"show older\" appends rather than repeats.\n * @param older - the page just read.\n * @param shown - what is already on screen.\n * @returns the merged list, newest first.\n */\nexport function mergeLogs(older: readonly LogEvent[], shown: readonly LogEvent[]): LogEvent[] {\n const seen = new Set(shown.map((event) => `${event.at}:${event.level}:${event.message}`))\n const fresh = older.filter((event) => !seen.has(`${event.at}:${event.level}:${event.message}`))\n return [...shown, ...fresh]\n}\n\n/**\n * Whether the ring holds events older than the ones on screen, and where the\n * next page starts.\n *\n * The exclusive cursor is the oldest event drawn, which is what the host pages\n * on. A cursor already asked for is spent: a page that added nothing the filters\n * let through must not ask for itself again, or a short session inside a busy\n * project would loop. Absent a project total the client trusts the snapshot's\n * own length, so a host half that predates `logCount` simply draws no button.\n * @param props - the visible events, the project's total, and the cursors already asked for.\n * @returns `more` and the `cursor` the next page starts at.\n */\nexport function logsPaging(props: {\n visible: readonly LogEvent[]\n total: number\n attempted: readonly number[]\n}): { more: boolean; cursor: number | undefined } {\n const cursor = props.visible.at(-1)?.at\n return {\n more: props.visible.length < props.total && cursor !== undefined && !props.attempted.includes(cursor),\n cursor,\n }\n}\n\n/**\n * The empty state of the Logs tab: nothing recorded yet, and where to look.\n * @param t - translate seat.\n * @returns the element, so the copy can be asserted without a DOM.\n */\nexport function logsEmptyState(t: Translate): ReactNode {\n return emptyState(t('logsEmptyTitle'), t('logsEmptyHint'), 'logs-empty')\n}\n\n/**\n * The empty state of the level filter, not of the ring.\n *\n * The tab opens on `errors`; a project whose ring holds only `mounting`/`is up`\n * lines would otherwise read \"no events yet\" while the counter beside the\n * disclosure's badge says it holds several. Saying so is the difference between a quiet\n * project and a hidden list.\n * @param t - translate seat.\n * @returns the element, keyed for the array {@link logList} returns.\n */\nexport function logsNoErrorsState(t: Translate): ReactNode {\n return emptyState(t('logsNoErrorsTitle'), t('logsNoErrorsHint'), 'logs-empty')\n}\n\n/**\n * The one project this tab belongs to: the project whose live sessions include\n * the tab's session. A tab never shows another project — the settings popup and\n * the native settings page are the surfaces with the whole picture.\n * @param snapshot - host snapshot, or undefined before the first poll lands.\n * @param sessionId - the session this tab is open in.\n * @returns the matching project, or undefined when there is none (yet).\n */\nexport function currentProject(\n snapshot: McpSnapshot | undefined,\n sessionId: string | undefined,\n): ProjectSnapshot | undefined {\n if (snapshot === undefined || sessionId === undefined) return undefined\n return snapshot.projects.find(\n (project) =>\n project.sessionIds.includes(sessionId) ||\n (project.sessions ?? []).some((session) => session.id === sessionId),\n )\n}\n\n/**\n * Statuses the \"Problems\" view lists, most actionable first. The quiet states —\n * `active`, `idle`, `disabled` — are answers, not problems.\n */\nexport const PROBLEM_STATUSES = ['error', 'conflict', 'connecting'] as const\n\n/** One status and the rows currently in it. */\nexport interface StatusGroup {\n status: ServerStatus\n rows: ServerRow[]\n}\n\n/**\n * Split merged rows into the groups the \"Problems\" view shows.\n * @param rows - merged project rows, in document order.\n * @returns one entry per non-empty group, in {@link PROBLEM_STATUSES} order.\n */\nexport function statusGroups(rows: readonly ServerRow[]): StatusGroup[] {\n const groups: StatusGroup[] = []\n for (const status of PROBLEM_STATUSES) {\n const matching = rows.filter((row) => row.status === status)\n if (matching.length > 0) groups.push({ status, rows: matching })\n }\n return groups\n}\n\n/**\n * Tab body: the project this session works in, and nothing else.\n *\n * The whole picture — every project with a live session — lives in the side card\n * settings popup, not in a tab that belongs to one conversation.\n */\nexport function ProjectMcpPanel(props: {\n visible: boolean\n sessionId: string | undefined\n refreshMs: number\n /**\n * The shell's translate seat for this namespace. Required on purpose: the\n * panel is one of the surfaces whose copy must follow the language\n * preference, so `./index.ts` composes it with the seat from `./tab-locale.ts`\n * rather than letting a missing prop silently fall back to English.\n */\n t: Translate\n /**\n * Host-namespace seat for the Logs tab's coded events (F-48); without one\n * the events render their payload's English, byte-identical to before codes.\n */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = props.t\n const { snapshot, error, busy, run, runAll } = useSnapshot(props.visible, props.refreshMs)\n const project = currentProject(snapshot, props.sessionId)\n const groups = project === undefined ? [] : statusGroups(project.rows)\n const policy = project === undefined ? undefined : policyOf(project)\n // The Logs disclosure counts this session's own events, not the project's: the\n // number the contract puts on `SessionSnapshot.logCount` (C1). A host half\n // without the field reports `0`, which the block prints as a real `0`.\n const session = (project?.sessions ?? []).find((entry) => entry.id === props.sessionId)\n const logsSession = sessionLogCount(session)\n // The pin keeps its own route and answers with the fresh snapshot, so the\n // panel's own `run` carries it: a refusal lands in the same line as every\n // other host refusal instead of being swallowed by a silent refresh.\n const onPin = useCallback(\n (tool: string, pinned: boolean): void => {\n if (project === undefined) return\n void run(ROUTE_ACTIONS.pin, pinBody(project.projectRoot, tool, pinned))\n },\n [project, run],\n )\n // A server's worth of names is one intent and one press (F-44): the names come\n // from the surface that showed them, the direction from what the project\n // already pins, and the writes go out as one batch.\n const onPinServer = useCallback(\n (server: string, names: readonly string[]): void => {\n if (project === undefined) return\n const press = serverPinPress(names, policy?.pins ?? [])\n void runAll(\n ROUTE_ACTIONS.pin,\n press.names.map((name) => pinBody(project.projectRoot, name, press.pinned)),\n )\n },\n [project, policy, runAll],\n )\n // Both operator actions are scoped to the project this tab shows: the panel\n // answers with that project's slice, and the host never starts a server for\n // another project because a row here was retried. Without a project there is\n // nothing to scope, so the request stays the global one it always was.\n const retry = useCallback(\n (): void => void run(ROUTE_ACTIONS.retry, operatorBody(project?.projectRoot)),\n [project, run],\n )\n const sync = useCallback(\n (): void => void run(ROUTE_ACTIONS.sync, operatorBody(project?.projectRoot)),\n [project, run],\n )\n const release = useCallback(\n (sessionId: string): void => void run(ROUTE_ACTIONS.release, { sessionId }),\n [run],\n )\n return h(\n 'div',\n { style: STYLE.root },\n h(PanelHeader, {\n project,\n sessions: project?.sessionIds.length ?? 0,\n busy,\n onSync: sync,\n t,\n }),\n h(\n 'div',\n { style: STYLE.body },\n // The host's refusal is the body's first line, so the toolbar is the\n // body's immediate sibling in the panel (the contract's own gate anchor)\n // whatever the read did.\n error === undefined ? null : h('div', { style: STYLE.error }, error),\n tabBody({\n project,\n sessionId: props.sessionId,\n groups,\n busy,\n policy,\n onPin,\n onPinServer,\n onRelease: release,\n onRetry: retry,\n sessionLogCount: logsSession,\n t,\n hostT: props.hostT,\n }),\n ),\n )\n}\n\n/**\n * The one-phrase reading of the toolbar's right edge.\n *\n * F-26 left the surface with one screen and no mode to branch on, so the phrase\n * answers the one question no block above it answers on its own: how many\n * sessions the project has. The problems block badges its own groups, the logs\n * block its own events, and the tools block its own counters, so nothing here\n * repeats them.\n * @param props - the project's session count.\n * @param t - translate seat.\n * @returns the phrase the toolbar's right edge prints.\n */\nexport function panelSummary(props: { sessions: number }, t: Translate): string {\n return sessionCount(props.sessions, t)\n}\n\n/** Everything the tab's toolbar reads. */\nexport interface PanelHeaderProps {\n /** The tab's own project, or undefined when its session has none. */\n project: ProjectSnapshot | undefined\n /** Sessions attached to the project; what the right edge counts. */\n sessions: number\n busy: boolean\n onSync: () => void\n t: Translate\n}\n\n/**\n * The tab's one toolbar row.\n *\n * The project's own header — the folder, the `this session` chip that says whose\n * tab this is, the summary phrase and the action at the right edge. The segment\n * bar that used to be the second row is gone (F-26): there is one screen, so\n * there is nothing to switch. Pure and exported: the panel around it owns the\n * poll and the state.\n * @param props - see {@link PanelHeaderProps}.\n * @returns the toolbar row.\n */\nexport function PanelHeader(props: PanelHeaderProps): ReactNode {\n const { t, project } = props\n return h(\n 'div',\n { style: STYLE.bar },\n project === undefined\n ? h('span', { style: STYLE.muted }, t('noProjectLabel'))\n : h(\n 'span',\n { style: STYLE.name, title: project.projectRoot },\n basename(project.projectRoot),\n ),\n project === undefined ? null : h('span', { style: STYLE.tag }, t('thisSession')),\n h('span', { style: { flex: 1 } }),\n h('button', { style: STYLE.button, disabled: props.busy, onClick: props.onSync }, t('sync')),\n // The toolbar's right edge is the mockup's `.dim`\n // (`docs/design/mockups/harness.html`, `.dim` — the tertiary tone):\n // one phrase, at the tertiary tone, and the only summary reading in the bar.\n h('span', { style: STYLE.dim }, panelSummary({ sessions: props.sessions }, t)),\n )\n}\n\n/** Everything the tab renders under its toolbar. */\nexport interface TabBodyProps {\n /** The tab's own project, or undefined when this session has none. */\n project: ProjectSnapshot | undefined\n /** Session this tab is open in. */\n sessionId: string | undefined\n /** Problem groups of {@link project}, precomputed by the panel. */\n groups: StatusGroup[]\n busy: boolean\n /** The project's policy, precomputed by the panel; read from the project when absent. */\n policy?: ToolPolicy | undefined\n /** Pin or unpin one tool of {@link project}; absent while nothing can be written. */\n onPin?: ((tool: string, pinned: boolean) => void) | undefined\n /**\n * Pin every name of one server in one press (F-44); absent while nothing can\n * be written. The names are the ones the surface that called it lists — the\n * hidden tier's own names — and the expansion into names is the whole\n * meaning: the host stores no server pin (`docs/design/contracts/policy.md`).\n */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n /**\n * Retry every failed mount of {@link project}; absent while nothing can be\n * written. The host route is project-scoped, so a row's own `Retry` sends the\n * request the errors block's button sends.\n */\n onRetry?: (() => void) | undefined\n onRelease: (sessionId: string) => void\n /** Events of this tab's own session, at the moment the snapshot was taken. */\n sessionLogCount?: number\n /** Storage the Logs block persists its filters and Clear mark in. */\n storage?: PanelStorage | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate\n /** Host-namespace seat for the Logs block's coded events (F-48). */\n hostT?: Translate | undefined\n}\n\n/**\n * What to add where, said from the host's own document list.\n *\n * The files a project is read from are a config fact — `ProjectSnapshot.files`,\n * published in read order — so the empty state names the project's own documents\n * instead of a path baked into this bundle, and says plainly when the deployment\n * reads none at all. A host older than the field reports nothing, and then no\n * file name is promised: the hint speaks about declaring one, not about a path\n * that host may never read.\n */\nfunction declaredHint(project: ProjectSnapshot, t: Translate): string {\n const files = project.files\n // No list at all is a host older than the field, and then no file name is\n // promised: the hint asks for a document without naming a path that host may\n // never read.\n if (files === undefined) return t('noServersDeclaredUnknown')\n const documents = files.filter((file) => file.scope === 'project').map((file) => file.path)\n if (documents.length === 0) return t('noServersDeclaredNowhere')\n return t('noServersDeclaredHint', { documents: documents.join(' · ') })\n}\n\n/**\n * The tab body: one screen, its blocks in the contract's order.\n *\n * F-26 folded the four modes into one surface, so the body is a list of blocks\n * rather than a branch: the session's declared servers, the sessions that\n * disagree with the project (F-24's section, still only while some do), the tool\n * offer, and the two disclosures — the problems, only while there are any, and\n * the event ring, always. Every situation where a surface has nothing to list\n * still answers for itself above the blocks.\n * @param props - see {@link TabBodyProps}.\n * @returns the blocks below the toolbar, in order.\n */\nexport function tabBody(props: TabBodyProps): ReactNode {\n const t = translateOf(props.t)\n if (props.sessionId === undefined) {\n return emptyState(t('noSession'), t('noSessionHint'))\n }\n const { project } = props\n if (project === undefined) {\n return emptyState(t('noProject'), t('noProjectHint'))\n }\n // This session's own rows, not the merged project view: what this conversation\n // resolves is the first thing the screen answers (`sessionRowsOf`).\n const rows = sessionRowsOf(project, props.sessionId)\n const sessions = sessionBreakdown(project, props.sessionId, t)\n const disagreeing = sessions.filter((session) => session.deviates)\n return [\n rows.length === 0\n ? emptyState(t('noServersDeclared'), declaredHint(project, t), 'servers')\n : h(ServersBlock, {\n key: 'servers',\n rows,\n usage: project.usage,\n t,\n hostT: props.hostT,\n onRetry: props.onRetry,\n busy: props.busy,\n }),\n // The F-24 disagreement view. The merged project rows are no longer drawn\n // here — the block above is this session's own reading — but `Release` for a\n // single session still lives only in this section.\n h(SessionList, {\n key: 'sessions',\n sessions: disagreeing,\n busy: props.busy,\n onRelease: props.onRelease,\n merged: sessions.length > 1,\n t: props.t,\n hostT: props.hostT,\n }),\n h(ToolsSection, {\n key: 'tools',\n project,\n sessionId: props.sessionId,\n policy: props.policy,\n onPin: props.onPin,\n onPinServer: props.onPinServer,\n pending: props.busy,\n t,\n hostT: props.hostT,\n }),\n // The errors disclosure exists only while there are problem groups; there is\n // no \"all quiet\" copy to draw, because an absent block is the quiet answer.\n props.groups.length === 0\n ? null\n : h(\n Disclosure,\n {\n key: 'errors',\n label: t('errorsSection'),\n count: props.groups.length,\n showHint: t('showErrors'),\n hideHint: t('hideErrors'),\n body: [\n h(IssueView, {\n key: 'issues',\n project,\n groups: props.groups,\n onRetry: props.onRetry,\n busy: props.busy,\n t,\n hostT: props.hostT,\n }),\n // `Retry failed` used to sit on the mode bar; the errors block is\n // where the action belongs now that the bar is gone.\n props.onRetry === undefined\n ? null\n : h(\n 'button',\n {\n key: 'retry',\n style: STYLE.button,\n title: t('retryHint'),\n disabled: props.busy,\n onClick: props.onRetry,\n },\n t('retryFailed'),\n ),\n ],\n t,\n },\n ),\n h(Disclosure, {\n key: 'logs',\n label: t('logsSection'),\n count: props.sessionLogCount ?? 0,\n showHint: t('showLogs'),\n hideHint: t('hideLogs'),\n body: h(LogsView, {\n project,\n sessionId: props.sessionId,\n t,\n hostT: props.hostT,\n storage: props.storage,\n }),\n t,\n }),\n ]\n}\n\n/**\n * The tools block of the one surface.\n *\n * {@link ToolsView} stays pure — the pure specs resolve it directly — so the\n * row whose detail block is open lives here, one state for the section, the way\n * {@link SessionList} keeps one session open at a time. Exported like the other\n * stateful block so {@link tabBody}'s block order can be asserted by type.\n *\n * The filter panel's query and pressed tiers (F-43) live here for the same\n * reason and outlive a snapshot\n * refresh: a poll repaints the block, and a filter that reset itself every five\n * seconds would be unusable.\n *\n * The filter is this component's own state and is not persisted anywhere: a\n * query is a reading aid for the minute, and the two filters the panel does\n * store — the log ring's — are stored because a page of that ring costs a\n * request. Nothing here does.\n * @param props - what {@link ToolsView} takes.\n * @returns the session's tool offer, with one row open at most.\n */\nexport function ToolsSection(props: {\n project: ProjectSnapshot\n sessionId: string\n policy?: ToolPolicy | undefined\n onPin?: ((tool: string, pinned: boolean) => void) | undefined\n /** Pin every hidden name of one server in one press (F-44). */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n pending?: boolean\n t: Translate\n /** Host-namespace seat for the presentation owner's coded note (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const [openTool, setOpenTool] = useState<string | undefined>(undefined)\n // Three states, not two: `undefined` is \"nobody has pressed the head\", and it\n // is what lets the filter open the hidden tier on its own without stealing the\n // press that follows (see {@link ToolsView}'s own `openHidden`).\n const [openHidden, setOpenHidden] = useState<boolean | undefined>(undefined)\n const [query, setQuery] = useState('')\n const [tiers, setTiers] = useState<readonly ToolTier[]>([])\n // The filter this section hands to the block, built once here because the\n // hidden head's own toggle has to know it: the press inverts the state the\n // user is *looking at*, and while a filter is live that state may be the one\n // the filter opened the tier in (`undefined`), not `false`.\n const filter: ToolFilter = { query, tiers }\n const filterActive = toolFilterActive(filter)\n const onToggleTool = useCallback((name: string): void => {\n setOpenTool((current) => (current === name ? undefined : name))\n }, [])\n const onToggleHidden = useCallback((): void => {\n setOpenHidden((value) => !(value ?? filterActive))\n }, [filterActive])\n const onQuery = useCallback((value: string): void => setQuery(value), [])\n const onTier = useCallback((tier: ToolTier): void => {\n setTiers((held) => toggledTier(held, tier))\n }, [])\n const onClearFilter = useCallback((): void => {\n setQuery('')\n setTiers([])\n }, [])\n return h(ToolsView, {\n ...props,\n openTool,\n onToggleTool,\n openHidden,\n onToggleHidden,\n filter,\n onQuery,\n onTier,\n onClearFilter,\n })\n}\n\n/**\n * One disclosure of the single surface: a head button and, while it is open, its\n * body.\n *\n * The `div`/`button[aria-expanded]` pair is the shape the parity gate reads a\n * disclosure by, which is why the head is a button of its own and the body is\n * the only thing that appears when it opens. The state is local on purpose: what\n * is folded away is this block's, not the panel's, so the panel keeps rendering\n * one pure tree per snapshot.\n */\n/**\n * The head one disclosure draws: toggled marker, label and the count badge.\n *\n * A pure function of its props on purpose. {@link Disclosure} is a component\n * with state, and the tools block is a pure tree of elements resolved by tests\n * without a React runtime — a stateful child in that tree would be invoked\n * outside a component and break the walk. The tiers that must be pure (the\n * hidden list) draw this head themselves and keep their open state one level up,\n * which is why the head exists apart from the wrapper that usually wears it.\n * @param props - label, count, open state and the head's tooltip.\n * @returns the `button[aria-expanded]` the parity gate reads a disclosure by.\n */\nexport function disclosureHead(props: {\n label: string\n count?: number | undefined\n open: boolean\n hint?: string | undefined\n onToggle: () => void\n}): ReactNode {\n return h(\n 'button',\n {\n style: STYLE.disclosureHead,\n 'aria-expanded': props.open,\n title: props.hint,\n onClick: props.onToggle,\n },\n `${props.open ? '▾' : '▸'} ${props.label}`,\n props.count === undefined ? null : h('span', { style: STYLE.tag }, String(props.count)),\n )\n}\n\nexport function Disclosure(props: {\n /** The head's word-label; the marker is drawn beside it, not stored. */\n label: string\n /** The number the head's badge prints, when it has one. */\n count?: number | undefined\n /** The head's tooltip while the block is open. */\n showHint?: string | undefined\n /** The head's tooltip while the block is closed. */\n hideHint?: string | undefined\n /** What the head reveals; rendered only while the disclosure is open. */\n body: ReactNode\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n}): ReactNode {\n const [open, setOpen] = useState(false)\n return h(\n 'div',\n { style: STYLE.disclosure },\n disclosureHead({\n label: props.label,\n count: props.count,\n open,\n hint: open ? props.hideHint : props.showHint,\n onToggle: (): void => setOpen((value) => !value),\n }),\n open ? h('div', { style: STYLE.disclosureBody }, props.body) : null,\n )\n}\n\n/**\n * The session's own tool offer, when the host half published one.\n * @param project - the project this tab belongs to.\n * @param sessionId - the tab's session.\n * @returns the per-session `tools`, or undefined when the host has none yet.\n */\nexport function sessionToolsOf(\n project: ProjectSnapshot,\n sessionId: string | undefined,\n): SessionTools | undefined {\n if (sessionId === undefined) return undefined\n const sessions = (project.sessions ?? []) as readonly { id: string; tools?: SessionTools }[]\n return sessions.find((session) => session.id === sessionId)?.tools\n}\n\n/**\n * The declared servers of the session this tab belongs to: the session's own\n * rows when the host published that session, the project's merged rows\n * otherwise.\n *\n * Per-session rows, not the merged project view: with the own-scope fallback a\n * session can run its own instance of a declaration, so its state — running,\n * stalled or released — is what this conversation actually has, and another\n * session of the same project may be in a different one.\n * @param project - the project snapshot the tab read.\n * @param sessionId - the conversation the tab is open in.\n * @returns the declared servers this session resolves.\n */\nexport function sessionRowsOf(\n project: ProjectSnapshot,\n sessionId: string | undefined,\n): readonly ServerRow[] {\n if (sessionId === undefined) return []\n const sessions = (project.sessions ?? []) as readonly { id: string; rows?: ServerRow[] }[]\n const session = sessions.find((entry) => entry.id === sessionId)\n return session === undefined ? project.rows : (session.rows ?? [])\n}\n\n/** The three counts the tools block answers for. */\nexport interface ToolCounts {\n /** Offered because the durable counters proved them hot. */\n pinned: number\n /** Offered because this session disclosed them, from either on-demand tier. */\n disclosed: number\n /** Mounted for the project but not offered in the request. */\n hidden: number\n /** Every tool the model would see: pins plus disclosures. */\n offering: number\n}\n\n/**\n * Count one session's offer into the three tiers the mockup names.\n *\n * Real data throughout — it reads only {@link SessionTools} — so every figure it\n * returns is a fact, not an invention.\n * @param tools - one session's tool offer.\n * @returns the pinned, disclosed and hidden counts.\n */\nexport function toolCounts(tools: SessionTools): ToolCounts {\n const pinned = tools.baseline.length\n const disclosed = tools.activated.length + tools.context.length\n return {\n pinned,\n disclosed,\n hidden: tools.deferred.length,\n offering: pinned + disclosed,\n }\n}\n\n/** One server's share of one list of registry names. */\nexport interface ServerNames {\n /** Registry names one list holds for this server, in that list's own order. */\n readonly names: readonly string[]\n /** Server the tools belong to, or `unknown` when the name is not prefixed. */\n server: string\n /** How many names of that list are this server's. */\n count: number\n}\n\n/**\n * The hidden tier's reading of {@link ServerNames}, under the name its callers\n * know it by: the grouping is the same one, only the list differs.\n */\nexport type HiddenServer = ServerNames\n\n/**\n * Split hidden tool names by the server they were mounted from.\n *\n * The registry's own naming is `mcp__<server>__<tool>` (a project-level prefix\n * is added by `mcp-client` only on a collision), so the server is the second\n * `__`-separated segment. A name that does not follow that shape is counted\n * under `unknown` rather than dropped: the hidden count must stay exact.\n * @param deferred - names the session mounted but did not offer.\n * @returns one entry per server, by descending count, then by name.\n */\nexport function hiddenByServer(deferred: readonly string[]): HiddenServer[] {\n return byServer(deferred)\n}\n\n/**\n * Split the pinned names by the server each one came from (F-44).\n *\n * The pinned tier reads its names per server for the same reason the hidden tier\n * does: a server is the unit a user thinks in when the list gets long, and it is\n * what the one press that releases a whole server acts on. The grouping is\n * {@link hiddenByServer}'s own, so the two tiers of one block order their groups\n * alike — biggest first, then by name — while each keeps its own list's order\n * inside a group.\n * @param pins - the project's pin list, as the host published it.\n * @returns one entry per server, each holding the names it contributed.\n */\nexport function pinnedByServer(pins: readonly string[]): ServerNames[] {\n return byServer(pins)\n}\n\n/**\n * One list of registry names, grouped by the server each name carries.\n *\n * A name without the registry's prefix belongs to no server and is filed under\n * `unknown` rather than dropped or attributed to a made-up one: the group is\n * real even when the name cannot be traced, and a row that vanished would hide a\n * pin the user wrote.\n * @param list - the names to group, in the order they are read in.\n * @returns one entry per server, biggest group first, then by server name.\n */\nfunction byServer(list: readonly string[]): ServerNames[] {\n const names = new Map<string, string[]>()\n for (const name of list) {\n const server = serverOfToolName(name) ?? 'unknown'\n const held = names.get(server)\n if (held === undefined) names.set(server, [name])\n else held.push(name)\n }\n return [...names.entries()]\n .map(([server, held]) => ({ server, count: held.length, names: held }))\n .sort((left, right) => right.count - left.count || left.server.localeCompare(right.server))\n}\n\n/**\n * The prefix the registry publishes project MCP tools under, and the server part\n * of one such name — defined in `./usage-view.ts` and re-exported at the top of\n * this module, where the panel's callers have always found them.\n */\n\n/** How much of the disclosure budget the session has spent. */\nexport interface BudgetSplit {\n /** Tools the model sees. */\n used: number\n /** Tools mounted for the project. */\n total: number\n /** `used / total` as a whole percentage, `0` when nothing is mounted. */\n percent: number\n /** `true` while the surface is over its configured budget. */\n exhausted: boolean\n}\n\n/**\n * Split the session's tool offer against the mounted surface: the bar and the\n * tooltip of the budget line. Both numbers are real counts the host published.\n * @param tools - one session's tool offer.\n * @returns the offering against the mounted total.\n */\nexport function budgetSplit(tools: SessionTools): BudgetSplit {\n const used = toolCounts(tools).offering\n const total = tools.mounted\n return {\n used,\n total,\n percent: total === 0 ? 0 : Math.min(100, Math.round((used / total) * 100)),\n exhausted: tools.deferring,\n }\n}\n\n/**\n * One tier of the tools block: the four parts its counter chips count, and the\n * four the filter panel switches between (F-43).\n */\nexport type ToolTier = 'pinned' | 'counters' | 'disclosed' | 'hidden'\n\n/**\n * The tools block's filter: one query over the registry names, and the tiers the\n * user narrowed the list to.\n *\n * The two halves answer different questions and are kept apart because of it: a\n * query asks \"where is this name\", a tier asks \"show me this rung alone\", and\n * the block draws the names that pass both. The filter is the tools block's own\n * state rather than a persisted one — unlike the log ring's filters, which are\n * stored because a page of the ring costs a request — because a query is a\n * reading aid for the minute, and a panel that reopened onto a stale one would\n * read as an empty catalogue.\n */\nexport interface ToolFilter {\n /** Free text, matched against the registry name; empty passes every name. */\n query: string\n /** Tiers to draw; empty — every tier — is the state the block opens in. */\n tiers: readonly ToolTier[]\n}\n\n/** The filter of a block nobody has narrowed, where everything passes. */\nexport const NO_TOOL_FILTER: ToolFilter = { query: '', tiers: [] }\n\n/**\n * `true` when `name` passes the query.\n *\n * A case-insensitive substring, so `grafana` finds `mcp__grafana-local__query`:\n * the registry name carries its server as its own prefix, and one field answers\n * both readings. The query is trimmed first, because a search field with a\n * trailing space would otherwise match nothing and look broken.\n * @param name - the registry name of the row.\n * @param query - what the user typed.\n * @returns whether the name passes.\n */\nexport function matchesToolQuery(name: string, query: string): boolean {\n const needle = query.trim().toLowerCase()\n return needle === '' || name.toLowerCase().includes(needle)\n}\n\n/**\n * `true` while the filter narrows anything at all — a query, a tier, or both.\n *\n * The block asks this to decide whether it is showing a filtered list: the\n * counts line, the empty state and the hidden tier's own opening all turn on it.\n * @param filter - the block's filter.\n * @returns whether the filter is doing something.\n */\nexport function toolFilterActive(filter: ToolFilter): boolean {\n return filter.query.trim() !== '' || filter.tiers.length > 0\n}\n\n/**\n * `true` when the filter lets this tier through: no tier pressed means every\n * tier, which is the reading the block opens in.\n * @param filter - the block's filter.\n * @param tier - the tier being drawn.\n * @returns whether the tier is drawn.\n */\nexport function tierVisible(filter: ToolFilter, tier: ToolTier): boolean {\n return filter.tiers.length === 0 || filter.tiers.includes(tier)\n}\n\n/**\n * The rows of one tier that pass the query, in the order they were given.\n * @param rows - the tier's rows, already in the block's own order.\n * @param query - what the user typed.\n * @returns the rows to draw.\n */\nexport function filterToolRows<T extends { name: string }>(rows: readonly T[], query: string): T[] {\n return rows.filter((row) => matchesToolQuery(row.name, query))\n}\n\n/**\n * The hidden names that pass the query, grouped by server as they were.\n *\n * A server whose every hidden name is filtered out goes with its count: the\n * group head prints `{server} · {count}` of what is drawn under it, and a head\n * over an empty list would be a number the user cannot spend.\n * @param servers - the hidden names, grouped by server ({@link hiddenByServer}).\n * @param query - what the user typed.\n * @returns the groups that kept at least one name, their counts renumbered.\n */\nexport function filterHiddenServers(\n servers: readonly HiddenServer[],\n query: string,\n): HiddenServer[] {\n const kept: HiddenServer[] = []\n for (const entry of servers) {\n const names = entry.names.filter((name) => matchesToolQuery(name, query))\n if (names.length > 0) kept.push({ server: entry.server, names, count: names.length })\n }\n return kept\n}\n\n/**\n * The tier list with one tier toggled: a press adds it, a second press releases\n * it. An empty list means every tier, so releasing the last one hands the block\n * its full list back.\n * @param tiers - the tiers currently pressed.\n * @param tier - the tier the user pressed.\n * @returns the new tier list, in the order the presses happened.\n */\nexport function toggledTier(tiers: readonly ToolTier[], tier: ToolTier): ToolTier[] {\n return tiers.includes(tier) ? tiers.filter((held) => held !== tier) : [...tiers, tier]\n}\n\n/** How much of one server's tool set a project already pins. */\nexport type ServerPinState = 'all' | 'some' | 'none'\n\n/**\n * How much of one server's names the project already pins (F-44).\n *\n * The question a server-level control answers is about a *set* of names — the\n * ones its own surface lists — so the reading is a proportion and not a flag:\n * `all`, a part, or none. Both surfaces ask it before they draw their switch and\n * again before they write.\n * @param names - the names this control speaks for, as its surface lists them.\n * @param pins - the project's own pin list.\n * @returns the proportion of `names` the pin list holds.\n */\nexport function serverPinState(\n names: readonly string[],\n pins: readonly string[],\n): ServerPinState {\n const held = new Set(pins)\n const pinned = names.filter((name) => held.has(name)).length\n if (pinned === 0) return 'none'\n return pinned === names.length ? 'all' : 'some'\n}\n\n/**\n * What one press of a server-level control writes (F-44).\n *\n * A server pin is the names themselves — the same list, the same route — and not\n * a rule of its own: this unit expands a server into its names, so a tool the\n * server mounts later is covered by no earlier press (the limits are in\n * `docs/design/contracts/policy.md`).\n *\n * The direction is the reading's own: a set that is wholly pinned is released,\n * and any other set is completed. A half-pinned server therefore *adds* the\n * names it is missing rather than throwing the pinned ones away, so one press\n * ever moves the set towards a state the user asked for and never loses a pin\n * nobody touched.\n * @param names - the names this control speaks for.\n * @param pins - the project's own pin list.\n * @returns the names to write and the state to write them in. The names are\n * empty only when the set is empty: a set that is wholly pinned is released\n * whole, and any other set has at least one name missing.\n */\nexport function serverPinPress(\n names: readonly string[],\n pins: readonly string[],\n): { pinned: boolean; names: string[] } {\n const held = new Set(pins)\n if (serverPinState(names, pins) === 'all') {\n return { pinned: false, names: names.filter((name) => held.has(name)) }\n }\n return { pinned: true, names: names.filter((name) => !held.has(name)) }\n}\n\n/** One counter of the tools vocabulary: which tier, its label, and the count. */\nexport interface CounterPart {\n /** Tier the counter answers for. */\n key: ToolTier\n /** Locale label of the tier, already translated. */\n label: string\n count: number\n}\n\n/**\n * The four counters, one part each.\n *\n * Two of them are tiers of one list and have to be told apart: `pinned` is the\n * user's own pin list, `counters` is the rest of the baseline — the names the\n * durable usage counters proved hot. As one number they could say \"2 pinned\"\n * over a pin list of one, which is exactly what the block drew before: the\n * sentence promised an action on rows that carried none. The budget still counts\n * both, because both are offered in every request ({@link toolCounts}).\n *\n * One source for every reading of these numbers: the tools block draws one chip\n * per part, and the settings page's Tools rows read the same parts, so the two\n * surfaces can never disagree. A part whose count is zero is not a chip — the\n * block prints numbers, not the absence of them.\n * @param tools - one session's tool offer.\n * @param policy - the project's tool policy, which owns the pin list.\n * @param t - translate seat.\n * @returns pinned, counters, disclosed and hidden, in that order.\n */\nexport function counterParts(\n tools: SessionTools,\n policy: ToolPolicy,\n t: Translate,\n): CounterPart[] {\n const counts = toolCounts(tools)\n const byCounters = tools.baseline.filter((name) => !policy.pins.includes(name)).length\n return [\n { key: 'pinned', label: t('toolsPinned'), count: policy.pins.length },\n { key: 'counters', label: t('toolsByCounters'), count: byCounters },\n { key: 'disclosed', label: t('toolsDisclosed'), count: counts.disclosed },\n { key: 'hidden', label: t('toolsHidden'), count: counts.hidden },\n ]\n}\n\n/** A tool row the tools block draws, with the action it offers. */\nexport interface ToolRow {\n /** Registry name. */\n name: string\n /** `true` when the project's own pin list holds this name, not the counters. */\n pinned?: boolean\n /** Clock time of the last offer or call, as `HH:MM`, when the host published one. */\n time?: string | undefined\n /** Short label shown on the row, when there is one. */\n note?: string | undefined\n /**\n * Both of the host's readings for this row: the project's counter and this\n * session's, and whether the host recorded the row's server at all.\n *\n * The property is absent where the host published nothing for the project,\n * which is what keeps a row the counters never saw from reading as a row of\n * zeroes.\n */\n calls?: ToolCalls | undefined\n}\n\n/**\n * The pinned rows to draw: the user's own pin list, then the counter-seeded\n * remainder of the baseline tier.\n *\n * The pin list is the only durable user choice here, so it comes first and is\n * the only part with an `Unpin` action. The rest of `baseline` is offered for\n * the same reason the counters say \"pinned\": the durable usage counters proved\n * those names hot, and a name that disappeared from the list would make the\n * toolbar's own badge disagree with what is under it. Those rows carry no\n * action — unpinning a name the user never pinned is not a thing this panel\n * offers — and get {@link ToolRow.pinned} `false`.\n * @param tools - one session's tool offer.\n * @param policy - the project's policy, whose `pins` are the user's own list.\n * @returns one row per offered name, user-pinned first, in list order.\n */\nexport function pinnedRows(tools: SessionTools, policy: ToolPolicy): ToolRow[] {\n const pinned = policy.pins.map((name) => ({ name, pinned: true }))\n const pinnedNames = new Set(policy.pins)\n const counted = tools.baseline\n .filter((name) => !pinnedNames.has(name))\n .map((name) => ({ name, pinned: false }))\n return [...pinned, ...counted]\n}\n\n/**\n * The clock time of one offer, as a disclosed row shows it.\n *\n * Only the `session` tier carries `at`; the `context` tier records a step, not a\n * time, so a row without one renders no clock at all.\n * @param at - epoch milliseconds of the last offer or call.\n * @returns `HH:MM` in the viewer's own zone.\n */\nexport function toolTime(at: number): string {\n const date = new Date(at)\n const pad = (value: number): string => String(value).padStart(2, '0')\n return `${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\n/**\n * Surface A's budget line, one branch per state the host can publish.\n *\n * `deferring` decides first, because it is the same flag that fills `deferred`:\n * a line that claimed the gate was off while the list below it showed hidden\n * tools would contradict itself. With nothing deferred, `budgetChars: 0` means\n * the gate is switched off in this deployment — the contract's own reading of a\n * zero budget — and any other budget means the surface simply fits, which is\n * not a state: a fitting surface gets no line at all, because the chips above\n * already carry `0 hidden` and a sentence repeating that is the empty row the\n * block stopped drawing.\n *\n * The figure is the host's own measurement in **characters** (`surfaceChars` /\n * `budgetChars`, contract C7), with the token count derived from it at the\n * contract's own rate of four characters per token. There are no slots here:\n * the host has never modelled them, so the line no longer invents them.\n * @param tools - one session's tool offer.\n * @param t - translate seat.\n * @returns the budget row, `null` when there is nothing to say, without the\n * exhausted note above it.\n */\nexport function budgetLine(tools: SessionTools, t: Translate): ReactNode {\n if (tools.deferring) {\n const split = budgetSplit(tools)\n const tokens = Math.round(tools.surfaceChars / 4)\n return h(\n 'div',\n null,\n h(\n 'div',\n {\n style: STYLE.budget,\n title: t('toolsBudgetBreakdown', {\n used: split.used,\n total: split.total,\n percent: split.percent,\n }),\n },\n h('span', { style: { ...STYLE.budgetUsed, width: `${split.percent}%` } }),\n ),\n h(\n 'div',\n { style: STYLE.muted },\n t('toolsBudget', {\n used: tools.surfaceChars,\n total: tools.budgetChars,\n tokens,\n }),\n ),\n )\n }\n if (tools.budgetChars === 0) return h('div', { style: STYLE.muted }, t('toolsBudgetGateOff'))\n return null\n}\n\n/**\n * What one tool row's detail block is opened with (F-26, F-56).\n *\n * The block prints only what the host published about this one name. `SessionTools`\n * measures the whole set (`surfaceChars` / `visibleChars` / `deferredChars`), not\n * a single tool, so there is no per-tool size here to print and none is derived:\n * the group's own budget line is where an estimate is real.\n *\n * What F-56 removed from the block is what the header already carries: the\n * registry name, the clock and the step. The tier stays here, but as the one\n * thing the header's dot cannot say while nobody hovers — and it reads as a\n * sentence rather than as the wire word.\n */\nexport interface ToolDetail {\n /** Tier that offered the name: the pin list, this session, or context ranking. */\n via: 'pin' | 'session' | 'context'\n /** The host's own step counter, when it published one (contract C2). */\n step?: number | undefined\n /** Epoch milliseconds of the last offer or call, when the host published one. */\n at?: number | undefined\n /** `true` while this row's detail block is open. */\n open: boolean\n /** Toggle this row's detail block. */\n onToggle: () => void\n /**\n * The session's own declared rows, read for the serving server's state — the\n * same {@link ServerRow} the block above draws. Absent on a surface that has no\n * servers to hand down (a unit test of the row, the design stand's own rows),\n * and then the state is simply not printed: the panel never guesses a status.\n */\n rows?: readonly ServerRow[] | undefined\n /**\n * Both counter readings the row's header was seeded with, so the block can\n * print the two of them apart: the header keeps the lead figure\n * ({@link callsLabel}'s choice) and the body adds the reading the header had no\n * room for. Absent where the host published no record for the row's server.\n */\n calls?: ToolCalls | undefined\n /**\n * Project the definition belongs to — the route's own first parameter.\n *\n * Absent together with {@link ToolDetail.sessionId} on a surface that is not\n * reading a host at all (the design stand's fixtures are seeded straight into\n * the cache, and a unit test of the row composes it without a route): the body\n * then draws no line rather than asking an address it was never given.\n */\n projectRoot?: string | undefined\n /** Session the row is open in — the route's own second parameter. */\n sessionId?: string | undefined\n}\n\n/**\n * The state of the server one registry name was registered under, as the row's\n * own block prints it.\n *\n * The rows handed down are the session's declared ones — `sessionRowsOf`'s list\n * — so a name whose server the host never declared gets no status, and neither\n * does a name without the `mcp__` prefix. \"The server is not in the list\" and\n * \"the server is idle\" are different facts, and only the second is printable.\n * @param name - the registry name on the row.\n * @param rows - the session's declared rows; absent draws no state at all.\n * @param t - translate seat.\n * @returns the sentence, or `undefined` when there is no server row to read.\n */\nexport function toolServerState(\n name: string,\n rows: readonly ServerRow[] | undefined,\n t: Translate,\n): string | undefined {\n const server = serverOfToolName(name)\n if (server === undefined) return undefined\n const row = (rows ?? []).find((entry) => entry.name === server)\n if (row === undefined) return undefined\n return t('toolServerState', { server, state: t(STATUS_KEYS[row.status]) })\n}\n\n/** The tier one row was offered by, said as a sentence (F-56). */\nexport function toolTierSentence(via: ToolDetail['via'], t: Translate): string {\n return via === 'pin'\n ? t('toolTierPinned')\n : via === 'session'\n ? t('toolTierSession')\n : t('toolTierContext')\n}\n\n/**\n * The two counter readings of one row's block (F-56), one line, each figure\n * labelled by what it counts.\n *\n * The block no longer repeats what the header shows — the header keeps the lead\n * figure, `callsLabel`'s own choice — so the project's total comes back only when\n * the host published it, and the session's own only when the session's slice\n * exists. A server the host never recorded draws nothing at all: this is the same\n * \"no data, no label\" rule the row obeys, one level down.\n * @param calls - the two readings, absent when the host published no record.\n * @param t - translate seat.\n * @returns the line, or `undefined` when there is no figure to print.\n */\nexport function toolCallsLine(calls: ToolCalls | undefined, t: Translate): string | undefined {\n if (calls === undefined || !calls.recorded) return undefined\n const project = calls.project\n const session = calls.session\n const parts = [\n project === undefined ? undefined : t('callsProject', { count: project }),\n session === undefined ? undefined : t('toolCallsSession', { count: session }),\n ].filter((part): part is string => part !== undefined)\n return parts.length === 0 ? undefined : parts.join(' · ')\n}\n\n/**\n * Why one name is not in this session's request, in the host's own figures\n * (F-56).\n *\n * Every number here arrived in `ToolFacts.reason`; a figure the host did not\n * measure leaves its phrase out rather than printing a zero, which is the same\n * discipline as contract C2's step tag. The whole sentence uses the complete\n * template while all three figures are there, so a reader of any language gets\n * its own grammar; a shorter answer falls back to the phrases that did arrive.\n * @param reason - the host's reason, or `undefined` for an offered name.\n * @param t - translate seat.\n * @returns the sentence, or `undefined` when there is nothing to print.\n */\nexport function toolReasonLine(reason: ToolReason | undefined, t: Translate): string | undefined {\n if (reason === undefined) return undefined\n const { chars, budget, used } = reason\n if (chars !== undefined && budget !== undefined && used !== undefined) {\n return t('toolReasonBudget', { chars, budget, used })\n }\n return [\n chars === undefined ? undefined : t('toolReasonChars', { chars }),\n budget === undefined ? undefined : t('toolReasonBudgetOnly', { budget }),\n used === undefined ? undefined : t('toolReasonUsed', { used }),\n ].filter((part): part is string => part !== undefined)\n .join(', ') || t('toolReason')\n}\n\n/**\n * The view model one opened row's body is drawn from.\n *\n * `loading` is the state of a read that has started and not landed, and it is\n * drawn as its own muted line rather than as an empty body: the answer is on its\n * way, and a block that drew nothing would read as \"there is nothing to say\".\n * `failure` is the host's refusal — an unknown name, or an older host without the\n * route — and it is drawn as a muted line too. Neither state invents a fact.\n */\nexport interface ToolFactsView {\n readonly state: 'loading' | 'failure' | 'facts'\n readonly facts?: ToolFacts | undefined\n}\n\n/**\n * What one opened row currently knows, read from the module's own cache.\n *\n * This is the **only** place the row's body asks for the definition: one call per\n * open row, from the row's own render, so a folded row costs nothing and a\n * refolded one is answered from {@link toolFacts}. A row with no route to ask —\n * the stand's seeded rows carry one, a unit test's may not — still reads the\n * cache, so a seeded answer is answered synchronously and an unseeded one draws\n * the loading line instead of contacting an address nobody gave.\n * @param name - the registry name on the row.\n * @param detail - the row's disclosure state and the session's own rows.\n * @returns the view model for the body; `loading` while the read is in flight.\n */\nexport function toolFactsView(name: string, detail: ToolDetail): ToolFactsView {\n const { projectRoot, sessionId } = detail\n // No route to ask: read what the cache already holds and start nothing. This\n // is the design stand's and a unit test's own path — a seeded answer is drawn,\n // an unseeded one waits, and neither opens a connection nobody asked for.\n if (projectRoot === undefined || sessionId === undefined) {\n // With no route in hand the panel reads the cache the way the seeded stand\n // does: a name is looked up as itself, so \"no route\" costs a definition\n // nothing rather than hiding it behind parameters nobody has.\n const failed = toolFactsFailed.has(name)\n const held = failed ? undefined : toolFacts.get(name)\n if (held !== undefined) return { state: 'facts', facts: held }\n return failed ? { state: 'failure' } : { state: 'loading' }\n }\n const entry: ToolFactsEntry = { projectRoot, sessionId, name }\n const held = toolFactsOf(entry)\n if (held !== undefined) return { state: 'facts', facts: held }\n return toolFactsUnreadable(entry) ? { state: 'failure' } : { state: 'loading' }\n}\n\n/** One accepted field, as the block lists it: mono name, type, marker, description. */\nfunction fieldLine(field: ToolField, index: number, t: Translate): ReactNode {\n return h(\n 'div',\n { key: `${field.name}-${String(index)}`, style: STYLE.field },\n // The marker rides with the type rather than with the name: `name*` reads as\n // part of the identifier, and a `*` the schema did not mean would be a\n // requirement the tool never declared.\n h('span', { style: STYLE.fieldName }, field.name),\n h('span', { style: STYLE.muted }, field.type),\n field.required ? h('span', { title: t('toolFieldRequiredHint') }, '*') : null,\n field.description === undefined\n ? null\n : h('span', { style: STYLE.fieldDesc }, `— ${field.description}`),\n )\n}\n\n/**\n * The one line that says where the definition is coming from: the read on its\n * way, or the host's own refusal. Nothing at all once the record is in hand —\n * the record draws itself.\n * @param view - what the cache holds for this name right now.\n * @param t - translate seat.\n * @returns the read's own line, or `null` while there is nothing to say.\n */\nfunction toolFactsReadLine(view: ToolFactsView, t: Translate): ReactNode {\n if (view.state === 'facts') return null\n const copy = view.state === 'failure' ? t('toolFailed') : t('toolLoading')\n return h('div', { key: 'read', style: STYLE.dim }, copy)\n}\n\n/**\n * The row's own fact line: the server the name was registered under — carrying\n * the state the session's declared rows give that server, when they name it —\n * the tier as a sentence, and the step and the clock only while the host\n * published them. A name without the `mcp__` prefix names no server and gets no\n * server phrase rather than an invented one.\n * @param name - the registry name on the row.\n * @param detail - the tier, the step, the clock and the session's own rows.\n * @param t - translate seat.\n * @returns the facts joined as one line, in the contract's order.\n */\nfunction toolFactsLine(name: string, detail: ToolDetail, t: Translate): string {\n const server = serverOfToolName(name)\n const state = toolServerState(name, detail.rows, t)\n return [\n server === undefined ? undefined : t('toolServer', { server: state ?? server }),\n toolTierSentence(detail.via, t),\n detail.step === undefined ? undefined : t('toolsStep', { step: detail.step }),\n detail.at === undefined ? undefined : toolTime(detail.at),\n ]\n .filter((part): part is string => part !== undefined)\n .join(' · ')\n}\n\n/**\n * The body of one opened tool row: the facts the header does not hold.\n *\n * A row that reads a host shows the full registry name, then one fact line —\n * the serving server with its state, the tier as a sentence, the step and the\n * clock, each only while the host published it — then the two counter readings,\n * and then the host's own answer about the definition: its model-facing\n * description verbatim, the fields it accepts, and the reason a hidden name is\n * not in the request. Empty groups are not printed, which is this file's rule\n * everywhere: no fields, no field list.\n *\n * A row composed without a route (a unit test's own row, a surface that never\n * read a host) has no address to ask and no declared rows to name: its body is\n * the read's own line alone, never a name and a fact line the block would then\n * have to invent.\n *\n * The reason leads the definition for a **hidden** row: there, it is the answer\n * to the question the reader opened the row with, while for an offered name the\n * same block is a definition rather than an apology.\n * @param name - the registry name on the row.\n * @param detail - the tier, the disclosure state and the session's own rows.\n * @param view - what the cache holds for this name right now.\n * @param t - translate seat.\n * @returns the body's lines, in order.\n */\nexport function toolFactsBody(\n name: string,\n detail: ToolDetail,\n view: ToolFactsView,\n t: Translate,\n): ReactNode {\n const read = toolFactsReadLine(view, t)\n if (detail.projectRoot === undefined || detail.sessionId === undefined) return read\n const facts = view.state === 'facts' ? view.facts : undefined\n const calls = toolCallsLine(detail.calls, t)\n const reason = facts === undefined ? undefined : toolReasonLine(toolReasonOf(name, facts), t)\n const fieldsLabel = t('toolFieldsLabel')\n return [\n h('div', { key: 'name', style: STYLE.name }, name),\n h('div', { key: 'facts', style: STYLE.detail }, toolFactsLine(name, detail, t)),\n ...(calls === undefined ? [] : [h('div', { key: 'calls', style: STYLE.muted }, calls)]),\n // The reason leads a hidden row's body: there it is the answer to the\n // question the reader opened the row with, while for an offered name the same\n // block is a definition rather than an apology.\n ...(reason === undefined ? [] : [h('div', { key: 'reason', style: STYLE.muted }, reason)]),\n read,\n ...(facts?.description === undefined\n ? []\n : [\n // The host's own model-facing text, exactly as it arrived: not\n // translated, not shortened, and not passed through a dictionary.\n h('div', { key: 'description', style: STYLE.detail }, facts.description),\n ]),\n ...(facts === undefined || facts.fields.length === 0\n ? []\n : [\n h('div', { key: 'fields', style: STYLE.group }, fieldsLabel),\n ...facts.fields.map((field, index) => fieldLine(field, index, t)),\n ]),\n ]\n}\n\n/**\n * The host's reason for one name, read from the record the row is holding.\n *\n * A record whose `name` is not the row's own is a host bug, and the panel draws\n * no reason rather than another tool's: the fact belongs to the definition the\n * body was asked about.\n * @param name - the registry name on the row.\n * @param facts - the record the cache holds.\n * @returns the reason, or `undefined` for an offered name.\n */\nfunction toolReasonOf(name: string, facts: ToolFacts): ToolReason | undefined {\n return facts.name === name ? facts.reason : undefined\n}\n\n/**\n * One row of the one surface's tools block: a header button that opens the\n * registry name and how the tool was offered, and the row's one action beside it.\n *\n * F-26 turned the row into a disclosure. The header keeps what it always showed\n * — the tier dot, the name, the time and the step the host gave, and the pin\n * action — and lives in a `button[aria-expanded]` so the row itself is the parity\n * gate's tool line. The action stays a sibling: a button inside a button is not a\n * thing HTML has.\n * @param row - the name, its time and its note.\n * @param action - the row's one action, when it has one.\n * @param tier - which tier offered the row; `pinned` when not given.\n * @param detail - the disclosure state and the facts it opens.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the row element.\n */\nexport function toolRow(\n row: ToolRow,\n action: { label: string; hint: string; onClick: () => void; disabled?: boolean } | undefined,\n tier: 'pinned' | 'disclosed' | 'hidden',\n detail: ToolDetail,\n t: Translate = translateOf(),\n): ReactNode {\n const open = detail.open\n const calls = callsLabel(row.calls, t)\n // Read once, and only while this row is the open one (F-56): the host route\n // answers one definition at a time, and a folded row asks for nothing.\n const facts = open\n ? toolFactsBody(row.name, { ...detail, calls: row.calls }, toolFactsView(row.name, detail), t)\n : null\n return h(\n 'div',\n { key: row.name, style: STYLE.tool },\n h(\n 'button',\n {\n style: STYLE.toolLine,\n 'aria-expanded': open,\n title: open ? t('hideTool') : t('showTool'),\n onClick: detail.onToggle,\n },\n h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[tier === 'pinned' ? 'active' : 'idle'] },\n }),\n h('span', { style: STYLE.name }, row.name),\n // The host's own counter, immediately after the name it counts: the one\n // reading on the row that is about how the tool has been used rather than\n // about what it is.\n calls === undefined ? null : h('span', { style: STYLE.dim }, calls),\n row.time === undefined ? null : h('span', { style: STYLE.muted }, row.time),\n row.note === undefined ? null : h('span', { style: STYLE.muted }, row.note),\n ),\n action === undefined\n ? null\n : h(\n 'button',\n { style: STYLE.button, title: action.hint, disabled: action.disabled === true, onClick: action.onClick },\n action.label,\n ),\n open\n ? h(\n 'div',\n { style: STYLE.toolDetail },\n // What the header cannot hold (F-56): the full registry name, the fact\n // line — the server with its state, the tier as a sentence, the step and\n // the clock only while the host published them — the counter readings\n // apart, and then the host's own answer about the definition, read once,\n // on demand, while this row is the one that is open.\n facts,\n )\n : null,\n )\n}\n\n/**\n * The declared servers of this session, in document order, with the state each\n * one is in.\n *\n * The first block of the one surface answers \"what is declared, and what is it\n * doing right now\", and a server that is declared but not serving is exactly why\n * an apparently empty catalog is empty: without this list `Nothing to hide yet`\n * reads as \"nothing is wrong\" while a stalled process quietly withholds all of\n * its tools.\n *\n * The row is the status and nothing else — the dot, the name, the status word\n * and the transport chip. Its `title` still carries the host's own multi-line\n * diagnostic, so hovering answers \"why\" without a click, but the diagnostic is\n * not drawn under the rows: F-26 hid it behind the errors disclosure, which\n * prints the same host text through {@link IssueView}'s rows. Drawing it in both\n * places put an amber wall between the model's tools and the reader.\n * @param props - the rows to list and the translate seat.\n * @returns the section, or `null` when the session declares nothing.\n */\nexport function ServersBlock(props: {\n rows: readonly ServerRow[]\n /** The project's usage counters, when the host published any (`idle {n}d`). */\n usage?: ProjectUsage\n t: Translate\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n /**\n * The project's retry, handed down to the failing rows so a broken server can\n * be pressed where it shows instead of behind the errors disclosure (F-55).\n */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight; the row button goes still with it. */\n busy?: boolean | undefined\n}): ReactNode {\n const { rows, t } = props\n if (rows.length === 0) return null\n const up = rows.filter((row) => row.status === 'active').length\n const failed = rows.filter((row) => row.status === 'error').length\n return h(\n 'div',\n { style: STYLE.serversBlock },\n h(\n 'div',\n { style: STYLE.row },\n h('span', { style: STYLE.groupInline }, t('toolsServers')),\n h('span', { style: { flex: 1 } }),\n h(\n 'span',\n {\n style: failed === 0 ? STYLE.tag : { ...STYLE.tag, ...STYLE.tagWarn },\n title: rows.map((row) => `${row.name}: ${t(STATUS_KEYS[row.status])}`).join('\\n'),\n },\n t('toolsServersUp', { up, total: rows.length }),\n ),\n ),\n ...rows.map((row) => {\n // The host's own record of this server; a row the counters never saw has\n // no `lastUsedAt` to read and the quiet word is simply not drawn.\n const idle = idleNote(row.status, props.usage?.[row.name]?.lastUsedAt, t)\n // The one job a row here can carry: a failing server gets the project's\n // retry, at the row's right edge, and nothing else does.\n const retry = row.status === 'error' ? props.onRetry : undefined\n return h(\n 'div',\n {\n style: STYLE.row,\n key: `tools#server#${row.name}`,\n title: rowDetail(row, props.hostT) ?? t(STATUS_HINT[row.status]),\n },\n h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[row.status] },\n 'aria-hidden': true,\n }),\n h('span', { style: STYLE.name }, row.name),\n // The status as a word, not only as the dot's colour: the question this\n // block answers is asked by someone who may not know the palette.\n h('span', { style: { ...STYLE.muted, color: STATUS_COLOR[row.status] } }, t(STATUS_KEYS[row.status])),\n idle === undefined ? null : h('span', { style: STYLE.dim }, idle),\n row.transport === undefined\n ? null\n : h('span', { style: STYLE.tag }, shortTransport(row.transport)),\n retry === undefined ? null : h('span', { style: { flex: 1 } }),\n retryButton(t, retry, props.busy),\n )\n }),\n )\n}\n\n/**\n * The hidden tier of the tools block: the names the model does not see, in a\n * list the user can open and act on.\n *\n * Hidden is the one tier whose contents are a list rather than a reading. The\n * counters already say how many names are left out, so this block adds the two\n * things they cannot: the names themselves, grouped by the server they were\n * mounted from, and the `Pin` that pulls one back into every request. The open\n * state arrives from the parent, so the tier is a pure function of its props —\n * the same reason the head is drawn by {@link disclosureHead} rather than by\n * {@link Disclosure}.\n * @param props - the hidden names, the requested `Pin` write and the open state.\n * @returns the head and, while open, one row per server and name.\n */\nexport function HiddenTier(props: {\n /** How many names the head's badge prints, the counters' own hidden figure. */\n count: number\n /** The hidden names, grouped by server, in the host's order. */\n servers: readonly HiddenServer[]\n /** `true` while the list is open. */\n open: boolean\n /** Toggle the list. */\n onToggle: () => void\n /** Pin one name, or absent while there is nothing to write to. */\n onChange?: ((tool: string, pinned: boolean) => void) | undefined\n /**\n * Pin every name of one server in one press (F-44), or absent while there is\n * nothing to write to. The names are this group's own: the list is what the\n * user is reading, and a server action that wrote names the tier does not show\n * would be a press with a hidden meaning.\n */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n /**\n * The project's own pin list, read for one thing only: whether a server's group\n * is already wholly pinned, which decides whether the line says `Pin all` or\n * `Unpin all`. A tier's names are usually unpinned, but nothing in the snapshot\n * forbids a pinned name to sit in `deferred` — a pin written between two\n * assemblies, or one the host itself still defers — and the label may not\n * promise the opposite of what the press does.\n */\n pins?: readonly string[] | undefined\n /** `true` while a pin write is in flight, so the buttons stay still. */\n pending: boolean\n /**\n * The one name of this tier whose body is open (F-56), as {@link ToolsView}\n * holds it, plus the writer that toggles it.\n *\n * Until F-56 every row here was handed `onToggle: () => undefined`: the tier\n * drew a disclosure that had nothing to disclose. The very reason a name is\n * hidden is what its body now prints, so the press that opens it is real.\n */\n openTool?: string | undefined\n /** Toggle one row's body. */\n onToggleTool?: ((name: string) => void) | undefined\n /**\n * The project the definitions belong to and the session the tier is read in —\n * the `GET tool` route's own two parameters, handed down by {@link ToolsView}.\n */\n projectRoot?: string | undefined\n sessionId?: string | undefined\n /** The session's own declared rows, for each open body's server state. */\n rows?: readonly ServerRow[] | undefined\n t: Translate\n}): ReactNode {\n const { t } = props\n /**\n * One server line's own press.\n *\n * The words follow the reading both surfaces share ({@link serverPinState}): a\n * group that is wholly pinned says `Unpin all`, anything else says `Pin all` —\n * and the direction the parent writes is {@link serverPinPress}'s, which is the\n * same rule. In the ordinary case a group's names are unpinned and the second\n * word never appears: it exists for the snapshot where a name is pinned and\n * still deferred — a pin written between two assemblies, or a hidden name the\n * user pinned from this very list — because there the first word would be the\n * opposite of what the press does.\n * @param entry - one server's hidden names.\n * @returns the press of that line.\n */\n const serverPress = (entry: HiddenServer): ReactNode => {\n const all = serverPinState(entry.names, props.pins ?? []) === 'all'\n return h(\n 'button',\n {\n type: 'button',\n style: STYLE.button,\n title: all ? t('toolsUnpinAllHint') : t('toolsPinAllHint'),\n disabled: props.pending,\n onClick: () => props.onPinServer?.(entry.server, entry.names),\n },\n all ? t('toolsUnpinAll') : t('toolsPinAll'),\n )\n }\n return h(\n 'div',\n { style: STYLE.disclosure },\n disclosureHead({\n label: t('toolsGroupHidden'),\n count: props.count,\n open: props.open,\n hint: t('toolsHiddenVia'),\n onToggle: props.onToggle,\n }),\n props.open\n ? h(\n 'div',\n { style: STYLE.disclosureBody },\n ...props.servers.flatMap((entry) => [\n // The server's own line, with the one press that takes all of it\n // (F-44): the label stays the reading it was, and the action sits at\n // the right edge the way every other action in the block does.\n h(\n 'div',\n { key: `${entry.server}-group`, style: STYLE.row },\n h('span', { style: STYLE.group }, `${entry.server} · ${entry.count}`),\n h('span', { style: { flex: 1 } }),\n props.onPinServer === undefined ? null : serverPress(entry),\n ),\n // One row per name, the full `mcp__<server>__<tool>` the registry\n // carries, with the pin that moves it into the always-offered list.\n // Since F-56 the row is a real disclosure: its body carries the\n // reason the name is not in the request, which is the question this\n // list is open to answer.\n ...entry.names.map((name) =>\n toolRow(\n { name },\n {\n label: t('toolsPin'),\n hint: t('toolsPinHint'),\n onClick: () => props.onChange?.(name, true),\n disabled: props.pending,\n },\n 'hidden',\n {\n via: 'pin',\n open: props.openTool === name,\n onToggle: () => props.onToggleTool?.(name),\n rows: props.rows,\n projectRoot: props.projectRoot,\n sessionId: props.sessionId,\n },\n t,\n ),\n ),\n ]),\n )\n : null,\n )\n}\n\n/**\n * The tools block's filter row (F-43): one query over the registry names, the\n * count of what is left on screen, and the `Clear` that hands the whole list\n * back.\n *\n * The tier half of the filter is not here but in the counter chips of the row\n * above, which stop being a reading and become the switch. The block prints one\n * number per tier (F-28) and says it once (F-37), so a second row of the same\n * four words without their counts would be a copy of a figure the chips already\n * carry.\n *\n * Nothing is drawn while the caller hands in no writer: a pure tree composed by\n * a spec keeps the block it had — an input whose value could never change is the\n * worse half of a control. The design-only render mode is not that caller: it\n * composes {@link tabBody}, so its panel is the product's own. The caption is\n * the exception: a filter the block was handed still hides rows, and hiding them\n * without saying so is the one thing the row exists to prevent.\n * @param props - the filter, what it kept, and the writers behind it.\n * @returns the panel's row with its own caption; the caption alone without a\n * writer, and `null` when a filter nobody applied has no writer either.\n */\nexport function ToolsFilter(props: {\n filter: ToolFilter\n /** Names passing the filter, and every name the block holds before it. */\n shown: number\n total: number\n /** Replace the query; absent leaves the field out of the tree. */\n onQuery?: ((query: string) => void) | undefined\n /** Drop the query and every pressed tier. */\n onClear?: (() => void) | undefined\n t: Translate\n}): ReactNode {\n const { t } = props\n const active = toolFilterActive(props.filter)\n // The caption is the only place the filter's own effect is readable: the chips\n // above it count the tiers, not what the query left of them.\n const caption = active\n ? h(\n 'div',\n { style: STYLE.dim },\n props.shown === 0\n ? t('toolsFilterNone')\n : t('toolsFilterShown', { shown: props.shown, total: props.total }),\n )\n : null\n if (props.onQuery === undefined) return caption\n return h(\n 'div',\n null,\n h(\n 'div',\n { style: STYLE.row },\n h('input', {\n type: 'search',\n style: STYLE.filterInput,\n value: props.filter.query,\n placeholder: t('toolsFilterPlaceholder'),\n 'aria-label': t('toolsFilterLabel'),\n onChange: (event: { target: { value: string } }) => props.onQuery?.(event.target.value),\n }),\n active && props.onClear !== undefined\n ? h(\n 'button',\n {\n type: 'button',\n style: STYLE.button,\n title: t('toolsFilterClearHint'),\n onClick: () => props.onClear?.(),\n },\n t('toolsFilterClear'),\n )\n : null,\n ),\n caption,\n )\n}\n\n/**\n * The tools block of the single surface: what this session's model sees now.\n *\n * Answers with the three counters, the pinned list, the tools the session\n * disclosed, and the hidden remainder grouped by the server it was mounted from.\n * Every reading is the host's own: `policy.pins` for the list a user wrote by\n * hand, `SessionTools` for the offer counters, `OfferedTool.step` for the\n * disclosure step (contract C2), and `ProjectSnapshot.presentation` for a second\n * owner of the request (contract C3). Pure and without state: the row whose\n * detail block is open is handed in by {@link ToolsSection}, which keeps one\n * open at a time.\n *\n * The filter (F-43) arrives the same way, from {@link ToolsSection}: the query,\n * the pressed tiers and the three writers. Without them the block draws every\n * tier and every name, exactly as it did before the panel existed.\n */\nexport function ToolsView(props: {\n project: ProjectSnapshot\n sessionId: string\n /** Policy to read the pin list from; the project's own when omitted. */\n policy?: ToolPolicy | undefined\n /** Pin or unpin one name; absent while there is nothing to write to. */\n onPin?: ((tool: string, pinned: boolean) => void) | undefined\n /**\n * Pin every hidden name of one server in one press (F-44). The names travel\n * with the call because this block is what grouped them; the writer above\n * expands them into the pin list the host stores.\n */\n onPinServer?: ((server: string, names: readonly string[]) => void) | undefined\n /** `true` while a pin request is in flight, so the buttons stay still. */\n pending?: boolean\n /** The one row whose detail block is open, when a row is open. */\n openTool?: string | undefined\n /** Toggle one row's detail block. */\n onToggleTool?: ((name: string) => void) | undefined\n /**\n * The hidden list's own state: `true` / `false` once the user has pressed its\n * head, `undefined` while nobody has — which is the state the filter is\n * allowed to open the tier in. Held by {@link ToolsSection} and not by the\n * tier itself, so this block stays a pure tree of elements: its tests resolve\n * it without a React runtime.\n */\n openHidden?: boolean | undefined\n /** Toggle the hidden list. */\n onToggleHidden?: (() => void) | undefined\n /** The filter the panel shows; absent means every tier, every name. */\n filter?: ToolFilter | undefined\n /** Replace the query. */\n onQuery?: ((query: string) => void) | undefined\n /** Fold one tier in or out of the filter. */\n onTier?: ((tier: ToolTier) => void) | undefined\n /** Drop the query and every pressed tier. */\n onClearFilter?: (() => void) | undefined\n t: Translate\n /** Host-namespace seat for the presentation owner's coded note (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t } = props\n const tools = sessionToolsOf(props.project, props.sessionId)\n /**\n * One row's disclosure state: the tier, the host's own step and time, this\n * session's declared rows (so the open body can name the serving server's\n * state) and the route the body's definition is read from (F-56).\n */\n const detailOf = (\n name: string,\n via: ToolDetail['via'],\n step?: number | undefined,\n at?: number | undefined,\n ): ToolDetail => ({\n via,\n step,\n at,\n open: props.openTool === name,\n onToggle: () => props.onToggleTool?.(name),\n rows: serverRows,\n projectRoot: props.project.projectRoot,\n sessionId: props.sessionId,\n })\n // This session's own declared rows, read once for the open body's server state\n // — the same list `tabBody` draws above this block (`sessionRowsOf`).\n const serverRows = sessionRowsOf(props.project, props.sessionId)\n // `tools` absent is the host's only \"not mounted yet\" signal: a session with a\n // published offer that happens to be empty has real zeroes to print, and the\n // two states must not be conflated. The declared servers of the session are not\n // part of this block any more — the one surface draws them above it (F-26).\n if (tools === undefined) {\n return h(\n 'div',\n { style: STYLE.project },\n emptyState(t('toolsNotMounted'), t('toolsNotMountedHint')),\n h('div', { style: STYLE.codeLine }, t('toolsNotMountedCode')),\n )\n }\n const counts = toolCounts(tools)\n const split = budgetSplit(tools)\n const policy = props.policy ?? policyOf(props.project)\n // A mode the owner chose is not this plugin hiding tools, and the counters\n // cannot say which it is: `deferred` is the whole surface under `off` and empty\n // under `direct`, so printing them raw would report a switched-off project as\n // `0 pinned` and `N hidden` — the plugin taking credit for a decision it did not\n // make, and inviting the user to free slots that would change nothing.\n if (policy.mode === 'off') {\n return h(\n 'div',\n { style: STYLE.project },\n h(\n 'div',\n { style: STYLE.row },\n h('span', { style: STYLE.muted }, t('toolsSeeModel')),\n h('span', { style: { flex: 1 } }),\n h('span', null, t('toolsModeOffCounters', { mounted: tools.mounted })),\n ),\n h('div', { style: STYLE.warnNote }, t('toolsModeOff')),\n h('div', { style: STYLE.muted }, t('toolsModeOffHint')),\n )\n }\n // The host's own counters for this project and for the session the block is\n // open in: one row reads its server's record by registry name, and a row whose\n // server the host never recorded carries a value that draws nothing (no data,\n // no label) rather than a zero.\n const usage = props.project.usage\n const withCalls = (row: ToolRow): ToolRow => ({\n ...row,\n calls: toolCalls(row.name, usage, props.sessionId),\n })\n const rows = pinnedRows(tools, policy).map(withCalls)\n // The filter arrives from {@link ToolsSection}; a block nobody can write a\n // filter to draws the unfiltered tree it always did.\n const filter = props.filter ?? NO_TOOL_FILTER\n const active = toolFilterActive(filter)\n const everyPinned = rows.filter((row) => row.pinned)\n const everyCounted = rows.filter((row) => !row.pinned)\n const everyHidden = hiddenByServer(tools.deferred)\n // Only the `session` tier carries `at`; the `context` tier has no timestamp to\n // render, and the step tag both tiers show comes from the host's counter\n // (contract C2). The detail block prints the step and the time only while the\n // host published them, so each raw value is kept beside the row it belongs to;\n // the header keeps the note and the clock it always had.\n const everyDisclosed: { row: ToolRow; detail: ToolDetail }[] = [\n ...tools.activated.map((tool) => ({\n row: withCalls({\n name: tool.name,\n time: tool.at === undefined ? undefined : toolTime(tool.at),\n // The step is real once the host stamps it (contract C2). Absent, the row\n // shows no tag at all — no invented `step 4`.\n note: tool.step === undefined ? undefined : t('toolsStep', { step: tool.step }),\n }),\n detail: detailOf(tool.name, 'session', tool.step, tool.at),\n })),\n ...tools.context.map((tool) => ({\n row: withCalls({\n name: tool.name,\n note: tool.step === undefined ? undefined : t('toolsStep', { step: tool.step }),\n }),\n detail: detailOf(tool.name, 'context', tool.step),\n })),\n ]\n // What each tier draws once the filter has had its say: a tier the filter left\n // out draws nothing at all, a tier it kept draws the rows the query kept, and\n // the two figures below answer for exactly those rows. `total` is every row the\n // block holds before the filter — the denominator counts rows, not distinct\n // names, because rows are what the block draws: a name the session both pinned\n // and disclosed is two lines, and the caption answers for the lines.\n const pinned = tierVisible(filter, 'pinned') ? filterToolRows(everyPinned, filter.query) : []\n const counted = tierVisible(filter, 'counters') ? filterToolRows(everyCounted, filter.query) : []\n const disclosed = tierVisible(filter, 'disclosed')\n ? everyDisclosed.filter(({ row }) => matchesToolQuery(row.name, filter.query))\n : []\n const hidden = tierVisible(filter, 'hidden') ? filterHiddenServers(everyHidden, filter.query) : []\n const hiddenShown = hidden.reduce((sum, entry) => sum + entry.count, 0)\n const shown = pinned.length + counted.length + disclosed.length + hiddenShown\n const total =\n everyPinned.length +\n everyCounted.length +\n everyDisclosed.length +\n everyHidden.reduce((sum, entry) => sum + entry.names.length, 0)\n const onChange = props.onPin\n // The counters as chips, and only the ones that carry a number: `0 pinned` is\n // the empty row this block no longer draws, one chip at a time. With all four\n // at zero the row keeps its label and stops there, rather than printing four\n // zeroes at a panel that has nothing to count.\n //\n // One exception, and it is the price of the chip having become a control: a\n // tier the user pressed keeps its chip even after a host refresh drove its\n // count to zero, because a filter whose switch vanished would leave an empty\n // list nobody can explain — `Clear` is reachable, the chip that caused it is\n // not. It prints `0 {label}` while it is pressed, and the moment it is\n // released the zero is not drawn again.\n const chips = counterParts(tools, policy, t).filter(\n (part) => part.count > 0 || filter.tiers.includes(part.key),\n )\n // One pinned row per name, so a server's group can draw the row it stands for\n // without searching the list again.\n const pinnedByName = new Map(pinned.map((row) => [row.name, row]))\n // The chips are the filter's tier half (F-43): the same plate, the same\n // `{count} {label}` words, a button instead of a span while the block can write\n // the filter to something. A pressed chip means \"this tier alone\", and pressing\n // it again hands every tier back — an empty tier list is what \"every tier\"\n // means, so there is no fifth `all` chip to press and no state where none of\n // the four reads as applied.\n const tierChip = (part: CounterPart): ReactNode => {\n const on = filter.tiers.includes(part.key)\n const label = `${part.count} ${part.label}`\n if (props.onTier === undefined) return h('span', { key: part.key, style: STYLE.tag }, label)\n return h(\n 'button',\n {\n key: part.key,\n type: 'button',\n style: on ? { ...STYLE.filterChip, ...STYLE.filterChipOn } : STYLE.filterChip,\n 'aria-pressed': on,\n title: t('toolsFilterTier'),\n onClick: () => props.onTier?.(part.key),\n },\n label,\n )\n }\n return h(\n 'div',\n { style: STYLE.project },\n h(\n 'div',\n { style: STYLE.row },\n h('span', { style: STYLE.muted }, t('toolsSeeModel')),\n h('span', { style: { flex: 1 } }),\n chips.length === 0 ? null : h('span', { style: STYLE.chips }, chips.map(tierChip)),\n ),\n policy.mode === 'direct'\n ? h('div', { style: STYLE.muted }, t('toolsModeDirect'))\n : budgetLine(tools, t),\n split.exhausted\n ? h('div', { style: STYLE.warnNote }, `${t('toolsBudgetExhausted')} — ${t('toolsBudgetFree')}`)\n : null,\n // The filter sits between the head's readings and the list it narrows: the\n // counters above it say what the session offers, this row says what is left\n // of it on screen. Without a writer it draws nothing at all.\n h(ToolsFilter, {\n key: 'filter',\n filter,\n shown,\n total,\n onQuery: props.onQuery,\n onClear: props.onClearFilter,\n t,\n }),\n // A tier with nothing in it is not a heading over an apology, it is nothing:\n // each group below is drawn only while it has rows, and the zero it would\n // have printed lives in the chips above. One number per block (F-28), said\n // once (F-37). A tier the filter left out is nothing too — the chip that\n // pressed it is what says so.\n pinned.length === 0\n ? null\n : [\n h('div', { key: 'pinned', style: STYLE.group }, t('toolsGroupPinned')),\n // Since F-44 the pinned list is grouped by the server each name came\n // from, and each group carries the press that releases that whole\n // server — the counterpart of pinning one from the hidden tier or from\n // the settings page. The rows keep their own order inside a group: the\n // order the user pinned them in.\n ...pinnedByServer(pinned.map((row) => row.name)).flatMap((group) => [\n h(\n 'div',\n { key: `${group.server}-pinned`, style: STYLE.row },\n h('span', { style: STYLE.group }, `${group.server} · ${group.count}`),\n h('span', { style: { flex: 1 } }),\n props.onPinServer === undefined\n ? null\n : h(\n 'button',\n {\n type: 'button',\n style: STYLE.button,\n title: t('toolsUnpinServerHint'),\n disabled: props.pending === true,\n onClick: () => props.onPinServer?.(group.server, group.names),\n },\n t('toolsUnpinAll'),\n ),\n ),\n // The only real user choice on this surface: it is the host's pin list\n // that decides the row, so the action writes it back.\n ...group.names.map((name) => {\n const row = pinnedByName.get(name)\n return row === undefined\n ? null\n : toolRow(\n row,\n {\n label: t('toolsUnpin'),\n hint: t('toolsUnpinHint'),\n onClick: () => onChange?.(row.name, false),\n disabled: props.pending === true,\n },\n 'pinned',\n detailOf(row.name, 'pin'),\n t,\n )\n }),\n ]),\n ],\n counted.length === 0\n ? null\n : [\n h('div', { key: 'counters', style: STYLE.group }, t('toolsGroupCounters')),\n // Offered by the counters rather than chosen by the user, which is why\n // the action here is the pin that turns one into a user pin: the host's\n // own `POST pin` writes the very list the pinned group above reads.\n ...counted.map((row) =>\n toolRow(\n row,\n {\n label: t('toolsPin'),\n hint: t('toolsPinHint'),\n onClick: () => onChange?.(row.name, true),\n disabled: props.pending === true,\n },\n 'pinned',\n detailOf(row.name, 'pin'),\n t,\n ),\n ),\n ],\n disclosed.length === 0\n ? null\n : [\n h('div', { key: 'disclosed', style: STYLE.group }, t('toolsGroupDisclosed')),\n ...disclosed.map(({ row, detail }) =>\n toolRow(\n row,\n { label: t('toolsHide'), hint: t('toolsHideHint'), onClick: () => undefined },\n 'disclosed',\n detail,\n t,\n ),\n ),\n ],\n hidden.length === 0\n ? null\n : [\n // The one tier whose contents are a list rather than a reading: the\n // counters can say how many names are hidden, but only the names\n // themselves let a user pull one back. So the head opens, and the\n // sentence that used to sit under it as a caption became the head's own\n // tooltip — nothing hidden draws no head at all.\n h(HiddenTier, {\n key: 'hidden',\n // While the filter is on, the head counts what is under it, so the\n // number and the list agree: the chip above keeps the tier's own\n // total, which is why the two read differently and neither lies.\n count: active ? hiddenShown : counts.hidden,\n servers: hidden,\n // A query that found hidden names is a question about them: the tier\n // opens itself rather than leaving the matches behind a fold the user\n // has to guess at. The user's own press outranks that, which is why\n // `openHidden` has three states and not two: `undefined` — nobody has\n // pressed the head — is where the filter may open the tier, and the\n // first press replaces it with a choice that stands, filter or not.\n open: props.openHidden ?? active,\n onToggle: () => props.onToggleHidden?.(),\n onChange,\n onPinServer: props.onPinServer,\n pins: policy.pins,\n pending: props.pending === true,\n // One open body at a time across the whole block (F-56), and the\n // route its definition is read from: the hidden list's own rows are\n // rows of this same surface, so they open on the same writer.\n openTool: props.openTool,\n onToggleTool: props.onToggleTool,\n projectRoot: props.project.projectRoot,\n sessionId: props.sessionId,\n rows: serverRows,\n t,\n }),\n ],\n // Another plugin owning `assembly.tools` is the host's finding, not the\n // mockup's (contract C3). No field, no banner; the banner is a fact the host\n // reported.\n props.project.presentation === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.warnNote },\n `${t('toolsPresentationOwner')}: ${props.project.presentation.name}. ${resolveHost(props.hostT ?? hostTranslate(undefined), props.project.presentation.noteCode, undefined, props.project.presentation.note)}`,\n ),\n )\n}\n\n/**\n * \"Problems\" body: the rows that need a look, grouped by status.\n *\n * This is the body of the errors disclosure (F-26), so nothing above it repeats\n * the groups: the block starts at the first group — `error`, then `conflict`,\n * then `connecting`, in the order {@link statusGroups} triage puts them in —\n * and the disclosure's own badge is what says how many groups there are.\n * @param props - the project, its problem groups and the row action.\n * @returns the grouped rows.\n */\nexport function IssueView(props: {\n project: ProjectSnapshot\n groups: StatusGroup[]\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight, so the row buttons stay still. */\n busy?: boolean | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n return h(\n 'div',\n { style: STYLE.project },\n props.groups.map((group) =>\n h(\n 'div',\n { key: group.status },\n h('div', { style: STYLE.group }, `${t(STATUS_KEYS[group.status])} · ${group.rows.length}`),\n group.rows.flatMap((row) =>\n serverRow(row, `problem-${group.status}`, {\n onRetry: props.onRetry,\n busy: props.busy,\n t: props.t,\n hostT: props.hostT,\n }),\n ),\n ),\n ),\n )\n}\n\n/**\n * Centred message for a state that has nothing to list.\n * @param title - the headline.\n * @param hint - the line under it.\n * @param key - React key, for the callers that place the result inside an array\n * (React requires one there); variadic callers leave it out.\n */\nexport function emptyState(title: string, hint: string, key?: string): ReactNode {\n return h(\n 'div',\n key === undefined ? { style: STYLE.empty } : { key, style: STYLE.empty },\n h('div', { style: STYLE.emptyTitle }, title),\n h('div', { style: STYLE.hint }, hint),\n )\n}\n\n/** `info` and `up` are the quiet half of the level vocabulary. */\nconst LOG_CHIP: Record<LogEvent['level'], CSSProperties> = {\n info: {},\n up: { color: STATUS_COLOR.active },\n warn: { color: STATUS_COLOR.connecting },\n error: { color: STATUS_COLOR.error },\n}\n\n/** `12:41:31` — the clock the mockup's log rows carry, seconds included. */\nfunction logTime(at: number): string {\n const date = new Date(at)\n const pad = (value: number): string => String(value).padStart(2, '0')\n return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n}\n\n/**\n * The three facts of a failure, one per line.\n *\n * The host hands the facts over as separate lines — the endpoint, the document\n * that declared the server, and what did not appear — so they are relayed as\n * they are: split, trimmed, and with anything labelled as advice dropped. The\n * hint and the reminder about `Retry` are not facts, and `Retry` is already a\n * button on the server's own row.\n * @param detail - the event's `detail`, when it has one.\n * @returns the lines to draw under the event, empty when there is nothing to say.\n */\nexport function logFacts(detail: string | undefined): string[] {\n if (detail === undefined) return []\n return detail\n .split('\\n')\n .map((line) => line.trim())\n // The host's own advice is not a fact: the row above already carries the\n // reason, and `Retry` is a button on the server's row, not a sentence here.\n .filter((line) => !/^(hint|note|next step)\\s*:/i.test(line))\n .filter((line) => line.length > 0)\n}\n\n/**\n * One line of the event list.\n *\n * The message takes its own width (see {@link STYLE.logRow}) rather than a right\n * column, which is what keeps the row readable in a sidebar. A coded event is\n * resolved through the host seat (F-48): the translated template wins, and a\n * code the namespace does not know — or an event that carries none — renders\n * the payload's English exactly as before.\n * @param event - the event to draw.\n * @param key - React key for the row.\n * @param t - translate seat.\n * @param hostT - host-namespace seat; without one the payload's English shows.\n * @returns the row, plus the failure's fact lines under it.\n */\nexport function logRow(event: LogEvent, key: string, t: Translate, hostT?: Translate | undefined): ReactNode {\n const host = hostT ?? hostTranslate(undefined)\n const detail = resolveHost(host, event.detailCode, event.detailParams, event.detail)\n const facts = logFacts(detail === '' ? undefined : detail)\n return h(\n 'div',\n { key },\n h(\n 'div',\n { style: STYLE.logRow },\n h('span', { style: STYLE.logTime }, logTime(event.at)),\n h(\n 'span',\n { style: { ...STYLE.tag, ...STYLE.logLevel, ...LOG_CHIP[event.level] ?? {} } },\n t(`logsLevel${event.level.charAt(0).toUpperCase()}${event.level.slice(1)}`),\n ),\n event.server === undefined ? null : h('span', { style: STYLE.logName }, event.server),\n h('span', { style: STYLE.logMessage }, resolveHost(host, event.code, event.params, event.message)),\n ),\n facts.map((fact, index) => h('div', { key: `${key}#fact${index}`, style: STYLE.logDetail }, fact)),\n )\n}\n\n/**\n * The events the toolbar's two filters let through, newest first.\n *\n * Scope and level first, then the Clear mark: a cleared event is one the user\n * has said they are done with, whatever the filters say. The ring holds oldest\n * first, so the result is reversed to read newest first, like every log view.\n * @param props - the events and the three filters.\n * @returns the visible events, newest first.\n */\nexport function logVisible(props: {\n logs: readonly LogEvent[]\n scope: LogScope\n level: LogLevelFilter\n sessionId: string | undefined\n clearedAt: number | undefined\n}): LogEvent[] {\n return props.logs\n .filter(\n (event) =>\n (props.level === 'all' || event.level === 'error') &&\n (props.scope === 'all' || event.sessionId === props.sessionId) &&\n (props.clearedAt === undefined || event.at > props.clearedAt),\n )\n .sort((left, right) => right.at - left.at)\n}\n\n/**\n * The event ring, as the logs block reads it.\n *\n * The snapshot carries the newest page (contract C1); everything older is one\n * route call behind \"Show older\". The two filters and the Clear mark are the\n * tab's own, stored locally — Clear has no route, by contract, so it only\n * remembers a moment and stops drawing events at or before it.\n * Exported and pure (no hooks) so a test can drive the toolbar and the list\n * directly; {@link LogsView} is the stateful wrapper around it.\n * @param project - the project whose ring is shown.\n * @param logs - events to draw, newest first.\n * @param props - the filters, the paging state and the callbacks behind them.\n * @returns the toolbar and the list.\n */\nexport function logList(\n project: ProjectSnapshot,\n logs: readonly LogEvent[],\n props: {\n scope: LogScope\n level: LogLevelFilter\n total: number\n loading: boolean\n failed: boolean\n t: Translate\n /** Host-namespace seat for the coded events (F-48); the payload's English shows without one. */\n hostT?: Translate | undefined\n onScope: (scope: LogScope) => void\n onLevel: (level: LogLevelFilter) => void\n onClear: () => void\n onOlder: () => void\n more: boolean\n },\n): ReactNode {\n const { t } = props\n const chip = (\n filter: { label: string; on: boolean; onClick: () => void },\n ): ReactNode =>\n h(\n 'button',\n {\n key: filter.label,\n style: filter.on ? { ...STYLE.logFilter, ...STYLE.logFilterOn } : STYLE.logFilter,\n // The applied chip of each pair is the pressed one. The mode switch is\n // what F-26 took away, and with it every `[aria-pressed]` outside a\n // disclosure; these two pairs live inside the logs body, where the gate\n // reads them as such.\n 'aria-pressed': filter.on,\n onClick: filter.on ? undefined : filter.onClick,\n },\n filter.label,\n )\n return [\n h(\n 'div',\n { style: STYLE.bar, key: 'logs-toolbar' },\n chip({\n label: t('logsThisSession'),\n on: props.scope === 'session',\n onClick: () => props.onScope('session'),\n }),\n chip({\n label: t('logsAllSessions'),\n on: props.scope === 'all',\n onClick: () => props.onScope('all'),\n }),\n h('span', { style: { flex: 1 } }),\n chip({\n label: t('logsAllLevels'),\n on: props.level === 'all',\n onClick: () => props.onLevel('all'),\n }),\n chip({\n label: t('logsErrorsOnly'),\n on: props.level === 'error',\n onClick: () => props.onLevel('error'),\n }),\n h(\n 'button',\n { style: STYLE.button, title: t('logsClearHint'), onClick: props.onClear },\n t('logsClear'),\n ),\n ),\n logs.length === 0\n ? props.level === 'error' && props.total > 0\n ? logsNoErrorsState(t)\n : logsEmptyState(t)\n : h(\n 'div',\n { key: 'logs-events' },\n h('div', { style: STYLE.group }, t('logsProjectCount', { count: props.total })),\n logs.map((event, index) => logRow(event, `${event.at}-${index}`, t, props.hostT)),\n ),\n props.failed ? h('div', { style: STYLE.muted, key: 'logs-failed' }, t('logsLoadFailed')) : null,\n props.loading\n ? h('div', { style: STYLE.muted, key: 'logs-loading' }, t('logsLoading'))\n : props.more\n ? h(\n 'div',\n { key: 'logs-more' },\n h(\n 'button',\n { style: STYLE.button, title: t('logsMoreHint'), onClick: props.onOlder },\n t('logsMore'),\n ),\n h(\n 'span',\n { style: STYLE.muted },\n t('logsShown', { shown: logs.length, total: props.total }),\n ),\n )\n : null,\n ]\n}\n\n/**\n * The logs block of the tab: this plugin's own event ring, one project's\n * worth of it, with the two filters the mockup shows.\n * @param props - the project, the tab's session, that session's event count and\n * the storage the filters live in.\n * @returns the toolbar plus the newest events.\n */\nexport function LogsView(props: {\n project: ProjectSnapshot\n sessionId: string | undefined\n /** Storage seam for tests; defaults to the browser's own. */\n storage?: PanelStorage | undefined\n t: Translate\n /** Host-namespace seat for the coded events (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t, project } = props\n const [scope, setScope] = useState<LogScope>(() => logScopeOf(props.storage))\n const [level, setLevel] = useState<LogLevelFilter>(() => logLevelOf(props.storage))\n const [clearedAt, setClearedAt] = useState<number | undefined>(() => logsClearedAt(props.storage))\n const [older, setOlder] = useState<readonly LogEvent[]>([])\n const [request, setRequest] = useState<number | undefined>(undefined)\n const [failed, setFailed] = useState(false)\n // Cursors already paged for. A page whose events the filters hide still\n // advances the buffer, so this only ever stops a genuinely spent cursor.\n const [attempted, setAttempted] = useState<readonly number[]>([])\n const projectRoot = project.projectRoot\n const snapshot = project.logs ?? []\n // The page buffer is unfiltered on purpose: the filters decide what is drawn,\n // not what is buffered, so a page whose events the filters hide still moves\n // the cursor past itself instead of being asked for again.\n const buffered = [...older, ...snapshot]\n const visible = logVisible({ logs: buffered, scope, level, sessionId: props.sessionId, clearedAt })\n const total = project.logCount ?? snapshot.length\n const { more, cursor } = logsPaging({ visible, total, attempted })\n useEffect(() => {\n if (request === undefined) return\n let live = true\n setAttempted((seen) => (seen.includes(request) ? seen : [...seen, request]))\n setFailed(false)\n void fetchLogs(projectRoot, request).then((page) => {\n if (!live) return\n if (page === undefined) setFailed(true)\n else setOlder((shown) => mergeLogs(page.events, shown))\n setRequest(undefined)\n })\n return () => {\n live = false\n }\n }, [request, projectRoot])\n const changeScope = (next: LogScope): void => {\n setScope(next)\n persistLogFilter(LOG_SCOPE_KEY, next, props.storage)\n }\n const changeLevel = (next: LogLevelFilter): void => {\n setLevel(next)\n persistLogFilter(LOG_LEVEL_KEY, next, props.storage)\n }\n const clear = (): void => {\n // One millisecond back, so the next event landing in the same millisecond as\n // the click is not swallowed with the ones the user cleared.\n const at = Date.now() - 1\n setClearedAt(at)\n persistLogsClearedAt(at, props.storage)\n }\n return h(\n 'div',\n { style: STYLE.project },\n logList(project, visible, {\n scope,\n level,\n total,\n loading: request !== undefined,\n failed,\n t,\n hostT: props.hostT,\n onScope: changeScope,\n onLevel: changeLevel,\n onClear: clear,\n onOlder: () => setRequest(cursor),\n more,\n }),\n )\n}\n\n/**\n * Side card settings panel: the poll interval, the declaration detail and\n * per-project release.\n *\n * The interval row used to be drawn by the sidebar itself, out of the tab\n * descriptor's `pluginToggles`; the surface that drew it went with\n * `dsh-better-sidebar`, so the row is part of this panel now, next to the state\n * it paces. Everywhere else the panel is read-only.\n */\nexport function ProjectMcpSettings(props: {\n refreshMs: number\n /** Write a new interval; absent makes the row read-only (the design stand). */\n onRefreshMs?: ((value: number) => void) | undefined\n onClose?: (() => void) | undefined\n /** Translate seat; the popup follows the shell's language when it is given one. */\n t?: Translate | undefined\n /** Host-namespace seat for the wire-coded payload fields (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const { snapshot, error, busy, run } = useSnapshot(true, props.refreshMs)\n const projects = snapshot?.projects ?? []\n return h(\n 'div',\n { style: STYLE.root },\n h(\n 'div',\n { style: STYLE.bar },\n h('span', { style: STYLE.name }, t('mountedPerProject')),\n h('span', { style: STYLE.muted }, t('projectsCount', { count: projects.length })),\n h('span', { style: { flex: 1 } }),\n h(\n 'button',\n { style: STYLE.button, disabled: busy, onClick: () => void run(ROUTE_ACTIONS.sync) },\n t('sync'),\n ),\n props.onClose === undefined\n ? null\n : h('button', { style: STYLE.button, onClick: () => props.onClose?.() }, t('close')),\n ),\n h(RefreshRow, { refreshMs: props.refreshMs, onRefreshMs: props.onRefreshMs, t }),\n error === undefined ? null : h('div', { style: STYLE.error }, error),\n h(\n 'div',\n { style: STYLE.body },\n projects.length === 0\n ? h('div', { style: { ...STYLE.muted, padding: 8 } }, t('nothingMounted'))\n : projects.map((project) =>\n h(ProjectBlock, {\n key: project.projectRoot,\n project,\n busy,\n onRelease: (sessionId) => void run('release', { sessionId }),\n hostT: props.hostT,\n }),\n ),\n ),\n )\n}\n\n/** Bounds the row offers, the steps a press moves it by, and the unit it prints. */\nexport const REFRESH_MIN_MS = 1_000\nexport const REFRESH_MAX_MS = 60_000\nexport const REFRESH_STEP_MS = 500\n/** The unit symbol beside the field; a symbol, not copy, so it is not translated. */\nexport const REFRESH_UNIT = 'ms'\n/** The field's id, so the row's label can point at it. */\nexport const REFRESH_INPUT_ID = 'dsh-project-mcp-refresh-ms'\n\n/**\n * The poll interval as one labelled row: the copy the sidebar's toggle used,\n * the number field that replaces it, and the unit beside it.\n *\n * One implementation for both renderers — the product's settings panel and the\n * design stand's popup draw this same row — so the two cannot drift. Without a\n * writer the field is `readOnly` rather than absent: the stand shows the control\n * the product shows, it just does not pretend a press changed anything.\n */\nexport function RefreshRow(props: {\n refreshMs: number\n onRefreshMs?: ((value: number) => void) | undefined\n t?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n return h(\n 'div',\n { style: STYLE.settingRow },\n h(\n 'label',\n { style: STYLE.settingLabel, htmlFor: REFRESH_INPUT_ID },\n h('span', { style: STYLE.settingTitle }, t('refreshTitle')),\n h('span', { style: STYLE.settingDesc }, t('refreshDesc')),\n ),\n h('input', {\n id: REFRESH_INPUT_ID,\n style: STYLE.settingInput,\n type: 'number',\n min: REFRESH_MIN_MS,\n max: REFRESH_MAX_MS,\n step: REFRESH_STEP_MS,\n value: props.refreshMs,\n readOnly: props.onRefreshMs === undefined,\n 'aria-label': t('refreshTitle'),\n onChange: (event: { target: { value: string } }) => {\n const next = Number(event.target.value)\n if (Number.isFinite(next)) props.onRefreshMs?.(next)\n },\n }),\n h('span', { style: STYLE.settingUnit }, REFRESH_UNIT),\n )\n}\n\n/**\n * One project block: the merged rows (what the project as a whole reports) plus\n * the per-session breakdown underneath — but only for the sessions whose own\n * reading differs from the merge.\n *\n * The project is the subject now that one project-level mount serves every\n * session: a session that reads exactly like the merged rows adds no answer, so\n * the section is left out entirely and the block is just the project. A session\n * that mounts something else, or has not turned yet, is the only reason to show\n * the breakdown under it.\n */\nexport function ProjectBlock(props: {\n project: ProjectSnapshot\n /** Session this tab belongs to; missing in the settings popup. */\n currentSessionId?: string | undefined\n /** True while a host action is in flight. */\n busy: boolean\n /** Called with the id of the session whose servers should be released. */\n onRelease: (sessionId: string) => void\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /**\n * `false` when the surface above already names the project and carries its\n * `this session` chip — the sidebar tab's own header does. Defaults to `true`.\n */\n showName?: boolean | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /**\n * Host-namespace seat for the wire-coded payload fields (F-48); without one\n * the echo seat applies and every coded field shows its payload's English.\n */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const hostT = props.hostT ?? hostTranslate(undefined)\n const { project } = props\n const totals = countStatuses(project.rows)\n const sessions = sessionBreakdown(project, props.currentSessionId, t)\n const current = sessions.some((session) => session.current)\n // Project-first: the section is the disagreement view, so it is handed only\n // the sessions that read differently. An empty list makes it render nothing at\n // all — the header included — which is the quiet case this exists for.\n const deviating = sessions.filter((session) => session.deviates)\n return h(\n 'div',\n { style: STYLE.project, key: project.projectRoot },\n props.showName === false\n ? null\n : h(\n 'div',\n { style: STYLE.projectHead },\n h(\n 'span',\n { style: STYLE.name, title: project.projectRoot },\n basename(project.projectRoot),\n ),\n current ? h('span', { style: STYLE.tag }, t('thisSession')) : null,\n h('span', { style: { flex: 1 } }),\n h('span', { style: STYLE.muted }, summarize(totals, t)),\n ),\n h(\n 'div',\n // Rung 0: the project's merged rows are the ladder's baseline.\n { style: STYLE.indent(0) },\n project.rows.flatMap((row) =>\n serverRow(row, 'merged', { onRetry: props.onRetry, busy: props.busy, t: props.t, hostT: props.hostT }),\n ),\n ),\n projectIssueLines(project).map((issue, index) =>\n h(\n 'div',\n { style: STYLE.detail, key: `${issue.source}#${index}` },\n `${issue.level}: ${resolveHost(hostT, issue.code, issue.params, issue.message)}`,\n ),\n ),\n h(SessionList, {\n key: `${project.projectRoot}#sessions`,\n sessions: deviating,\n busy: props.busy,\n onRelease: props.onRelease,\n // The note is about the rows above, which stay the merge of *all* the\n // project's sessions even when only one of them is out of step.\n merged: sessions.length > 1,\n t: props.t,\n hostT: props.hostT,\n }),\n )\n}\n\n/**\n * The issues the rows below do not already carry.\n *\n * A failing mount is reported twice by the host: once as the row's own `detail`,\n * which the row renders in its banner, and once as a snapshot issue naming the\n * same server. Only the issues that no banner repeats belong under the rows —\n * the document-level ones.\n * @param project - one project from the host snapshot.\n * @returns the issues left to print, in host order.\n */\nexport function projectIssueLines(project: ProjectSnapshot): ProjectSnapshot['issues'] {\n return project.issues.filter(\n (issue) =>\n issue.server === undefined ||\n !project.rows.some((row) => row.name === issue.server && row.detail !== undefined),\n )\n}\n\n/** Per-session view model the panel renders under one project. */\nexport interface SessionBreakdown {\n /** Agent (session) id; shown truncated, in full in the tooltip. */\n id: string\n /** True when this is the session the tab is open in. */\n current: boolean\n /** This session's own rows, in document order. */\n rows: ServerRow[]\n /** One-line status summary. */\n summary: string\n /**\n * True when this session's own reading disagrees with the project's merged\n * rows. The `sessions` section exists only for these sessions: the project's\n * rows come first, and a session that reads exactly like them says nothing.\n */\n deviates: boolean\n}\n\n/**\n * Whether one session's own rows disagree with the project's merged rows.\n *\n * The project's `rows` are the merge of every session, so one that mounts a\n * different set, or that has not turned yet, reads differently from them. The\n * comparison is per server and order-insensitive: each side is read as a\n * `name → set of statuses` map, so the same rows in another order are not a\n * disagreement. A name declared twice counts only for what it says — the same\n * status twice collapses into one, while two different statuses are a\n * disagreement whichever order the two sides list them in. A session whose own\n * `rows` are empty claims nothing and therefore never disagrees — a host half\n * older than the per-session field must not make the section appear.\n * @param merged - the project's merged rows.\n * @param own - one session's own rows.\n * @returns `true` when the two readings differ.\n */\nexport function sessionDeviates(merged: readonly ServerRow[], own: readonly ServerRow[]): boolean {\n if (own.length === 0) return false\n const projectStatus = statusesByName(merged)\n const sessionStatus = statusesByName(own)\n if (projectStatus.size !== sessionStatus.size) return true\n for (const [name, statuses] of projectStatus) {\n const ownStatuses = sessionStatus.get(name)\n if (ownStatuses === undefined || ownStatuses.size !== statuses.size) return true\n for (const status of statuses) {\n if (!ownStatuses.has(status)) return true\n }\n }\n return false\n}\n\n/** One side's rows as `name → the statuses that name was declared with`. */\nfunction statusesByName(rows: readonly ServerRow[]): Map<string, Set<ServerRow['status']>> {\n const byName = new Map<string, Set<ServerRow['status']>>()\n for (const row of rows) {\n const statuses = byName.get(row.name)\n if (statuses === undefined) byName.set(row.name, new Set([row.status]))\n else statuses.add(row.status)\n }\n return byName\n}\n\n/**\n * Split a project's snapshot into its per-session view.\n *\n * Sessions of one project mount independently, so the merged `rows` cannot say\n * which session holds a server. Each entry also carries whether that session's\n * own reading {@link sessionDeviates} from the merge: the panel prints the\n * project's rows first and the section only for the sessions that differ, so the\n * answer to \"is anything not as the project says\" is computed once, here.\n * `sessions`, and each entry's `rows` with it, are read defensively: the browser\n * half hot-reloads while the host half only picks up a new build at restart, so\n * a newer panel can meet a host that predates either field.\n * @param project - one project from the host snapshot.\n * @param currentSessionId - the session this tab belongs to, if known.\n * @param t - translate seat for the summary line; English without one.\n * @returns one entry per session, in host order.\n */\nexport function sessionBreakdown(\n project: ProjectSnapshot,\n currentSessionId: string | undefined,\n t?: Translate,\n): SessionBreakdown[] {\n return (project.sessions ?? []).map((session) => {\n const rows = session.rows ?? []\n return {\n id: session.id,\n current: currentSessionId !== undefined && session.id === currentSessionId,\n rows,\n summary: summarize(countStatuses(rows), translateOf(t)),\n deviates: sessionDeviates(project.rows, rows),\n }\n })\n}\n\n/**\n * The deviating sessions' own rows, read as one summary line.\n *\n * The collapsed `sessions` section answers \"who is not holding this project the\n * way the rows above say\", so its header counts the statuses across the sessions\n * it lists — the deviating ones — not across the whole project.\n * @param sessions - the deviating part of the project's per-session breakdown.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the merged status summary, e.g. `2 active, 1 idle`.\n */\nexport function sessionsSummary(sessions: readonly SessionBreakdown[], t?: Translate): string {\n return summarize(countStatuses(sessions.flatMap((session) => session.rows)), translateOf(t))\n}\n\n/**\n * The header row of the collapsed sessions section.\n *\n * Collapsed is the default: the section is a disclosure, so the header has to\n * carry the whole answer on its own — the label, how many sessions are out of\n * step, and their merged status. The list handed to it is already the deviating\n * one, so the count chip counts those, never how many sessions the project has\n * (the toolbar's right edge is where that count lives). Exported and pure so\n * the shape is asserted without a renderer; {@link SessionList} owns the open\n * state and the rows below it.\n * @param props - the deviating sessions, the open flag and the toggle.\n * @returns the header row.\n */\nexport function sessionsHeader(props: {\n sessions: readonly SessionBreakdown[]\n open: boolean\n onToggle: () => void\n /** `true` when the rows above are a merge of these sessions, not one session's own. */\n merged?: boolean | undefined\n t?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n return h(\n 'div',\n // Rung 1: the `sessions` section sits one step right of the project rows.\n { style: { ...STYLE.sessionHead, ...STYLE.indent(1) } },\n h(\n 'button',\n {\n // The mockup draws the section label in the tertiary tone\n // (`docs/design/mockups/harness.html`) — it names the seam, it is not the content.\n style: { ...STYLE.sessionToggle, ...STYLE.dim },\n 'aria-expanded': props.open,\n title: props.open ? t('hideSessions') : t('showSessions'),\n onClick: props.onToggle,\n },\n `${props.open ? '▾' : '▸'} ${t('sessionsSection')}`,\n ),\n h('span', { style: STYLE.tag }, deviationCount(props.sessions.length, t)),\n h('span', { style: STYLE.muted }, sessionsSummary(props.sessions, t)),\n h('span', { style: { flex: 1 } }),\n props.merged === true ? h('span', { style: STYLE.muted }, t('mergedAcrossSessions')) : null,\n )\n}\n\n/**\n * The list of the sessions that read differently from the project.\n *\n * Project-first: the rows above are the project's own reading, and a session\n * that reads exactly like them adds nothing, so the panel hands this component\n * only the sessions whose own rows disagree. An empty list therefore means the\n * whole project agrees with itself — the quiet case — and the section renders\n * nothing at all: no header, no rows. When there is something to explain, the\n * section still starts collapsed so a single out-of-step session does not push\n * the project's rows out of the way; opening it lists one row per deviating\n * session, and each of those opens its own rows.\n */\nexport function SessionList(props: {\n sessions: SessionBreakdown[]\n busy: boolean\n onRelease: (sessionId: string) => void\n /** `true` when the rows above are a merge of the project's sessions, not one session's own. */\n merged?: boolean | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const [section, setSection] = useState(false)\n const [open, setOpen] = useState<string | undefined>(undefined)\n // Nothing to explain: the section is the whole disagreement view, header\n // included, and a project that reads like every one of its sessions gets none.\n if (props.sessions.length === 0) return null\n return h(\n 'div',\n { style: STYLE.sessions },\n sessionsHeader({\n sessions: props.sessions,\n open: section,\n merged: props.merged,\n onToggle: () => setSection((value) => !value),\n t: props.t,\n }),\n section\n ? props.sessions.map((session) =>\n h(sessionEntry, {\n key: session.id,\n session,\n expanded: open === session.id,\n onToggle: () => setOpen((value) => (value === session.id ? undefined : session.id)),\n busy: props.busy,\n onRelease: props.onRelease,\n t: props.t,\n hostT: props.hostT,\n }),\n )\n : null,\n )\n}\n\n/**\n * One session's block inside the expanded `sessions` section: its own header row\n * (the short id, `this session` when it is, the summary, `Release`) and, when it\n * is open, the servers that session holds.\n *\n * Pure, with the disclosure state given to it rather than owned, so the ladder it\n * draws — rung `2` for the header, rung `3` for the rows under it — is asserted\n * without rendering {@link SessionList}.\n * @param props - the session, its open state and the row action.\n * @returns the session's block.\n */\nexport function sessionEntry(props: {\n session: SessionBreakdown\n expanded: boolean\n onToggle: () => void\n busy: boolean\n onRelease: (sessionId: string) => void\n t?: Translate | undefined\n /** Host-namespace seat for the rows' coded details (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const { session } = props\n return h(\n 'div',\n // Rung 2: one session of the section, one step right of its header.\n { style: { ...STYLE.session, ...STYLE.indent(2) } },\n h(\n 'div',\n { style: STYLE.sessionHead },\n h(\n // The marker belongs to a **collapsed** row only (mockup `:323`): an\n // expanded session already shows its servers, so a turned-down triangle\n // beside them would be a second, redundant marker. The button stays\n // either way, so the row is still the control that folds it back up.\n 'button',\n {\n // A collapsed session's id is the mock's `.dim` (`docs/design/mockups/harness.html`):\n // once open, the id is content and reads in the primary tone.\n style: props.expanded ? STYLE.sessionToggle : { ...STYLE.sessionToggle, ...STYLE.dim },\n title: props.expanded ? t('hideSession') : t('showSession'),\n 'aria-expanded': props.expanded,\n onClick: props.onToggle,\n },\n props.expanded ? shortSessionId(session.id) : `▸ ${shortSessionId(session.id)}`,\n ),\n session.current ? h('span', { style: STYLE.tag }, t('thisSession')) : null,\n h('span', { style: STYLE.muted }, session.summary),\n h('span', { style: { flex: 1 } }),\n h(\n 'button',\n {\n style: STYLE.button,\n disabled: props.busy,\n title: session.id,\n onClick: () => props.onRelease(session.id),\n },\n t('release'),\n ),\n ),\n props.expanded ? sessionRows(session, props.t, props.hostT) : null,\n )\n}\n\n/**\n * One session's own server rows, or the placeholder when that session declared\n * nothing, at rung `3` — the deepest level of the surface's indentation ladder.\n * Exported so the panel tests can assert what a session block shows without a\n * DOM.\n * @param session - one entry of {@link sessionBreakdown}.\n * @param t - translate seat; falls back to this module's English copy.\n * @param hostT - host-namespace seat for the rows' coded details (F-48).\n * @returns the rows element tree for that session.\n */\nexport function sessionRows(session: SessionBreakdown, t?: Translate, hostT?: Translate): ReactNode {\n return h(\n 'div',\n // Rung 3: the servers a session holds, one step right of the session row.\n { style: STYLE.indent(3) },\n session.rows.length === 0\n ? h('div', { style: STYLE.muted }, translateOf(t)('nothingDeclared'))\n : session.rows.map((row) => serverRow(row, session.id, { t, hostT })),\n )\n}\n\n/** `session-8fce1c` reads better as `8fce1c` in a narrow sidebar. */\nfunction shortSessionId(id: string): string {\n const trimmed = id.replace(/^session-/, '')\n return trimmed.length > 8 ? `${trimmed.slice(0, 8)}…` : trimmed\n}\n\n/**\n * `1 session` / `3 sessions`, through the locale table.\n *\n * The toolbar's right edge answers how many sessions the project has; the\n * `sessions` section counts something else and uses\n * {@link deviationCount} instead.\n */\nexport function sessionCount(count: number, t: Translate): string {\n return count === 1 ? t('sessionsOne') : t('sessionsMany', { count })\n}\n\n/**\n * `1 differs` / `3 differ` — how many sessions are out of step with the project.\n *\n * A chip of its own phrase rather than `{count} sessions`: the section lists the\n * deviating sessions only, and \"1 session\" beside one row would read as the\n * project having a single session, which the toolbar already says.\n */\nexport function deviationCount(count: number, t: Translate): string {\n return count === 1 ? t('differsOne') : t('differsMany', { count })\n}\n\n/** `1 server` / `3 servers`, through the locale table. */\nexport function serverCount(count: number, t: Translate): string {\n return count === 1 ? t('serversOne') : t('serversMany', { count })\n}\n\n/**\n * The short form of a transport: the mockup's rows carry `http` / `stdio`.\n * @param transport - the transport the host reported.\n * @returns the chip's label.\n */\nexport function shortTransport(transport: string): string {\n return transport === 'streamable-http' ? 'http' : transport\n}\n\n/** Everything one server row needs beyond the row itself. */\nexport interface ServerRowOptions {\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight, so the row's button stays still. */\n busy?: boolean | undefined\n /**\n * The host's own `lastUsedAt` for this server, when it published a record for\n * it: the quiet row then reads `idle 3d` beside its status word\n * ({@link idleNote}).\n */\n lastUsedAt?: string | undefined\n /** Translate seat; falls back to this module's English copy without one. */\n t?: Translate | undefined\n /**\n * Host-namespace seat for the row's coded detail (F-48); without one the\n * payload's English shows, byte-identical to before codes existed.\n */\n hostT?: Translate | undefined\n}\n\n/**\n * A row's detail line as the screen shows it (F-48): the coded companions\n * resolved through the host seat, and the payload's English prose when they\n * are absent (an old host) or the seat does not know the code (a client older\n * than the host). `undefined` stays `undefined`, so a detail-less row keeps\n * its status hint as the tooltip.\n * @param row - the server row.\n * @param hostT - the host-namespace seat, when the surface has one.\n * @returns the sentence to render, or `undefined` for a row with no detail.\n */\nexport function rowDetail(row: ServerRow, hostT?: Translate | undefined): string | undefined {\n if (row.detail === undefined) return undefined\n return resolveHost(hostT ?? hostTranslate(undefined), row.detailCode, row.detailParams, row.detail)\n}\n\n/**\n * The quiet `idle {n}d` word a server row shows beside its status word.\n *\n * Only the two quiet statuses get one: `active`, `connecting`, `error` and\n * `conflict` already say what the server is doing, and a figure of inactivity\n * beside them would be a second answer to a question nobody asked. The word is\n * the span since the host's own `lastUsedAt` (`ProjectSnapshot.usage`), and it\n * is drawn only while that record exists and parses: no data, no word — never a\n * `0`.\n * @param status - the row's status.\n * @param lastUsedAt - ISO timestamp of the server's most recent call.\n * @param t - translate seat; falls back to this module's English copy.\n * @param now - epoch milliseconds to measure against; `Date.now()` by default.\n * @returns the label, or undefined when this row shows none.\n */\nexport function idleNote(\n status: ServerStatus,\n lastUsedAt: string | undefined,\n t: Translate = translateOf(),\n now: number = Date.now(),\n): string | undefined {\n if (status !== 'idle' && status !== 'disabled') return undefined\n const span = idleOf(lastUsedAt, now)\n if (span === undefined) return undefined\n const key = span.unit === 'day' ? 'idleDay' : span.unit === 'hour' ? 'idleHour' : 'idleMinute'\n return t(key, { count: span.count })\n}\n\n/**\n * How often one tool was called, as its row writes it.\n *\n * The counters belong to the host's record of the tool's server, and there are\n * two of them: the project's, which is what proved the tool hot, and the reading\n * session's own share of it (F-34). The row leads with the session's figure —\n * the question a reader at one session asks — and names the project's when the\n * two disagree, because that disagreement is the whole point: tools are mounted\n * for the project and used inside a session. Three states are told apart: a\n * figure to print, a server the host recorded whose counter for this tool is\n * absent (`never called`), and no record at all, which draws nothing.\n * @param calls - the two readings, absent when the host published no record.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the label, or undefined when the row shows none.\n */\nexport function callsLabel(calls: ToolCalls | undefined, t: Translate = translateOf()): string | undefined {\n if (calls === undefined || !calls.recorded) return undefined\n // The session's own reading leads whenever the host splits its counters by\n // session; without a split the project total is the only figure there is.\n const lead = calls.split ? calls.session : calls.project\n const figure =\n lead === undefined ? t('callsNone') : lead === 1 ? t('callsOne') : t('callsMany', { count: lead })\n const project = calls.project\n // The project's figure rides along exactly while it adds something: it is\n // published, and the session's own reading does not already say it. Two numbers\n // that agree are one number, and `never called · 182 in the project` says what\n // \"never called\" alone would leave unsaid.\n const adds = project !== undefined && project !== lead\n return adds ? `${figure} · ${t('callsProject', { count: project })}` : figure\n}\n\n/**\n * The one `Retry` a failing server row carries.\n *\n * Two surfaces draw a server row — the errors disclosure's {@link serverRow} and\n * the tab's own {@link ServersBlock} — and both offer the same action: the host\n * route drops this project's failed mounts and re-mounts them. The button is\n * built here once, so its label, its hint and the `disabled` flag that keeps\n * every press still while one host action is in flight cannot drift apart\n * between them. A surface that hands no action down gets no button at all,\n * which is what makes a read-only panel read-only instead of drawing a dead\n * press.\n * @param t - translate seat.\n * @param onRetry - the project's retry, or undefined where nothing can be written.\n * @param busy - `true` while a host action is in flight.\n * @returns the button, or `null` where there is no action to press.\n */\nfunction retryButton(\n t: Translate,\n onRetry: (() => void) | undefined,\n busy: boolean | undefined,\n): ReactNode {\n return onRetry === undefined\n ? null\n : h(\n 'button',\n {\n style: STYLE.button,\n title: t('retryHint'),\n disabled: busy === true,\n onClick: onRetry,\n },\n t('retry'),\n )\n}\n\n/**\n * One server, as the tab draws it.\n *\n * The status is the dot, not a word: its colour comes from the shared\n * {@link STATUS_COLOR} table and its tooltip through {@link STATUS_HINT}, so the\n * row reads at a glance and still explains itself on hover. The transport and\n * the quiet states (`idle`, `disabled`) are chips, and the quiet rows are dimmed\n * rather than recoloured. A row the host reported a failure for carries its own\n * `Retry` — the host route is project-scoped, so it sends exactly the request\n * the toolbar's button sends — and its detail in a banner underneath, with the\n * coloured left rule the mockup uses for a failure.\n * @param row - the server row.\n * @param keyPrefix - prefix for the two element keys of this row.\n * @param options - the row action and the translate seat.\n * @returns the row and, when it has one, its detail banner.\n */\nexport function serverRow(\n row: ServerRow,\n keyPrefix: string,\n options: ServerRowOptions = {},\n): ReactNode[] {\n const t = translateOf(options.t)\n const quiet = row.status === 'idle' || row.status === 'disabled'\n // The host's detail line, translated when the row carries its wire code.\n const detail = rowDetail(row, options.hostT)\n // The span since the host's own `lastUsedAt`, drawn beside the quiet status\n // word and only there: `idle 3d` says how long a quiet server has been quiet,\n // which is a fact the status word alone cannot carry.\n const idle = idleNote(row.status, options.lastUsedAt, t)\n return [\n h(\n 'div',\n {\n style: quiet ? { ...STYLE.row, ...STYLE.rowQuiet } : STYLE.row,\n key: `${keyPrefix}#${row.name}`,\n title: detail ?? t(STATUS_HINT[row.status]),\n },\n h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[row.status] },\n 'aria-hidden': true,\n }),\n h('span', { style: STYLE.name }, row.name),\n row.transport === undefined\n ? null\n : h('span', { style: STYLE.tag }, shortTransport(row.transport)),\n // The quiet chip takes the mock's `.dim` tone (`docs/design/mockups/harness.html`),\n // one step below the transport chip beside it.\n quiet ? h('span', { style: { ...STYLE.tag, ...STYLE.tagQuiet } }, t(STATUS_KEYS[row.status])) : null,\n idle === undefined ? null : h('span', { style: STYLE.dim }, idle),\n h('span', { style: { flex: 1 } }),\n retryButton(t, row.status === 'error' ? options.onRetry : undefined, options.busy),\n ),\n // A quiet row's detail (\"not mounted yet — this session has not started a\n // turn\") is a fact about a *normal* state, and the mockup draws `idle` as a\n // chip with no note under it (`docs/design/mockups/harness.html`): a warning banner per\n // idle server turns a calm list into a wall of amber. The reason stays on\n // the row's own `title`, and the errors disclosure (error / conflict /\n // connecting only) is where the host's text is read out in full.\n row.detail === undefined || quiet\n ? null\n : h(\n 'div',\n {\n style:\n row.status === 'error'\n ? STYLE.banner\n : { ...STYLE.banner, ...STYLE.bannerWarn },\n key: `${keyPrefix}#${row.name}#detail`,\n },\n detail,\n ),\n ]\n}\n\nfunction countStatuses(rows: readonly ServerRow[]): Partial<Record<ServerStatus, number>> {\n const totals: Partial<Record<ServerStatus, number>> = {}\n for (const row of rows) totals[row.status] = (totals[row.status] ?? 0) + 1\n return totals\n}\n\n/** The statuses a summary line names, in the order it names them. */\nconst SUMMARY_ORDER = ['active', 'connecting', 'idle', 'error', 'conflict'] as const\n\n/**\n * The `{count}` template key of every status — a full `ServerStatus` record,\n * so a status the order above ever names without a template is a compile\n * error, not a raw token in the summary line.\n */\nconst SUMMARY_KEYS: Record<ServerStatus, LocaleKey> = {\n active: 'summaryActive',\n connecting: 'summaryConnecting',\n idle: 'summaryIdle',\n disabled: 'summaryDisabled',\n error: 'summaryError',\n conflict: 'summaryConflict',\n}\n\n/**\n * One line of status counts (`2 active, 1 idle`), every count a `{count}`\n * placeholder of its status's template so no language reads a concatenation.\n * @param totals - the counted rows.\n * @param t - translate seat; falls back to this module's English copy.\n * @returns the summary, or the `summaryNone` answer when nothing was counted.\n */\nfunction summarize(\n totals: Partial<Record<ServerStatus, number>>,\n t: Translate = fallbackTranslate,\n): string {\n const parts: string[] = []\n for (const status of SUMMARY_ORDER) {\n const count = totals[status]\n if (count !== undefined && count > 0) parts.push(t(SUMMARY_KEYS[status], { count }))\n }\n return parts.length === 0 ? t('summaryNone') : parts.join(', ')\n}\n\n/** Last path segment; used for every project and document label. */\nexport function basename(path: string): string {\n const parts = path.split('/').filter((part) => part !== '')\n return parts[parts.length - 1] ?? path\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * The tools side of the plugin's page in DSH's native Settings.\n *\n * The page has two pages of its own, because one plugin is one row of the\n * settings navigation: `Servers` is the declaration view this module never\n * touches, and `Tools` is the per-project policy the disclosure half of the\n * mockup lays out. Both live in the same `settings.section` registration — this\n * module adds the tab, it does not register a second navigation item.\n *\n * Tools answers a different question than the live surfaces: not \"what does the\n * model see right now\", but \"what will this project offer, and what is pinned\".\n * Everything on it is measured rather than invented: the server and tool counts\n * come from the host snapshot's rows and each session's `tools`, the pinned list\n * and the mode are the project's own `policy`, the per-server counters are\n * counted from the session's own offer by the registry's `mcp__<server>__`\n * prefix, the conflicts are the host's report, and the request preview lists the\n * names the session really offers with the token estimate the contract derives\n * from the serialized sizes. Nothing here reads `./demo.ts`, and no row invents\n * a value the host does not publish.\n *\n * @module dsh-project-mcp/client/settings-tools\n */\n\nimport { createElement as h } from 'react'\nimport type { ReactNode } from 'react'\nimport type {\n ConflictChoice,\n ProjectSnapshot,\n ServerConflict,\n SessionTools,\n ToolMode,\n ToolPolicy,\n} from '../types.ts'\nimport { policyOf } from './policy.ts'\nimport { STYLE } from './settings.ts'\nimport type { LocaleKey, Translate } from './settings.ts'\nimport {\n basename,\n callsLabel,\n serverOfToolName,\n serverPinPress,\n serverPinState,\n toolCounts,\n toolCalls,\n} from './view.ts'\nimport type { ToolCalls } from './view.ts'\nimport { byCalls } from './usage-view.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\n\n/**\n * A serialized size in tokens, by the contract's own reading: `chars / 4`.\n *\n * The estimate is printed only where a size is known: a session the host\n * published without `deferredChars` gets the hidden count and no estimate,\n * rather than an invented one.\n * @param chars - serialized size in characters.\n * @returns the estimate, rounded to a whole token.\n */\nexport function tokenEstimate(chars: number): number {\n return Math.round(chars / 4)\n}\n\n/**\n * The three values the mode switch offers, in the order the contract lists them.\n *\n * Straight from the frozen `ToolMode`, so the form cannot drift into the\n * mockup's `all-direct` spelling of the same state.\n */\nexport const TOOL_MODES: readonly ToolMode[] = ['disclosure', 'direct', 'off']\n\n/** Which of the plugin page's own pages is open. */\nexport type SettingsPageKey = 'servers' | 'tools'\n\n/** Page shown when nothing else was chosen, so the page never opens blank. */\nexport const DEFAULT_SETTINGS_PAGE: SettingsPageKey = 'servers'\n\n/** One page of the plugin's own settings page, in the switch's order. */\nexport interface SettingsPageTab {\n key: SettingsPageKey\n /** Dictionary key of the label; the switch resolves it through `t`. */\n labelKey: LocaleKey\n}\n\n/**\n * The two pages of our own settings page.\n *\n * `Servers` is what the plugin has shipped since the write path landed; `Tools`\n * is the disclosure policy, added next to it rather than as a second row of the\n * settings navigation.\n */\nexport const SETTINGS_PAGES: readonly SettingsPageTab[] = [\n { key: 'servers', labelKey: 'tabServers' },\n { key: 'tools', labelKey: 'tabTools' },\n]\n\n/** The `Servers` / `Tools` switch inside our own settings page. */\nexport function SettingsPageSwitch(props: {\n page: SettingsPageKey\n onChange: (page: SettingsPageKey) => void\n t: Translate\n}): ReactNode {\n const item = (tab: SettingsPageTab): ReactNode =>\n h(\n 'button',\n {\n key: tab.key,\n style:\n tab.key === props.page\n ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }\n : STYLE.segmentItem,\n 'aria-pressed': tab.key === props.page,\n onClick: () => props.onChange(tab.key),\n },\n props.t(tab.labelKey),\n )\n return h('div', { style: STYLE.segment }, SETTINGS_PAGES.map(item))\n}\n\n// ── the project table ─────────────────────────────────────────────────────────\n\n/** How many live sessions one project has; the table's \"seen\" column. */\nexport function liveSessions(project: ProjectSnapshot): number {\n return project.sessionIds.length\n}\n\n/**\n * The live snapshot of one project's first session, when the host published one.\n * @param project - project row of the settings page.\n * @returns that session's snapshot, or undefined when nothing is live.\n */\nexport function firstSession(project: ProjectSnapshot): ProjectSnapshot['sessions'][number] | undefined {\n return (project.sessions ?? [])[0]\n}\n\n/** The tools one project shows in the table, with their provenance. */\nexport interface ProjectToolCounts {\n /** Servers the project declares. */\n servers: number\n /** Tools mounted for the project, when the session published them. */\n tools: number | undefined\n /** Tools the session activated on demand. */\n disclosed: number\n}\n\n/**\n * Count one project's servers and tools.\n *\n * Both numbers are real: servers are `project.rows`, tools are the mounted total\n * of the first live session's `SessionTools`. A project whose sessions published\n * no offer has no tool count at all — the row shows a dash — because the count of\n * its *servers* is not the count of its tools.\n * @param project - project row of the settings page.\n * @returns the counts; `tools` is undefined when no session published an offer.\n */\nexport function projectToolCounts(project: ProjectSnapshot): ProjectToolCounts {\n const live = firstSession(project)?.tools\n return {\n servers: project.rows.length,\n tools: live?.mounted,\n disclosed: live === undefined ? 0 : toolCounts(live).disclosed,\n }\n}\n\n/** The policy row of one project: the host's own counts and the policy in force. */\nexport interface ProjectPolicyRow {\n /** Project root. */\n projectRoot: string\n /** Short label the table shows. */\n label: string\n /** Declared servers and mounted tools. */\n counts: ProjectToolCounts\n /** The policy in force, as the host published it. */\n policy: ToolPolicy\n}\n\n/**\n * One table row per project with a live session, in snapshot order.\n * @param projects - projects the host snapshot carries.\n * @returns the rows the table renders.\n */\nexport function projectPolicyRows(projects: readonly ProjectSnapshot[]): ProjectPolicyRow[] {\n return projects.map((project) => ({\n projectRoot: project.projectRoot,\n label: basename(project.projectRoot),\n counts: projectToolCounts(project),\n policy: policyOf(project),\n }))\n}\n\n/** What one mode value is called in the UI. */\nconst MODE_KEYS: Record<ToolMode, LocaleKey> = {\n disclosure: 'modeDisclosure',\n direct: 'modeDirect',\n off: 'modeOff',\n}\n\n/** The label of one mode value. */\nexport function modeLabel(mode: ToolMode, t: Translate): string {\n return t(MODE_KEYS[mode])\n}\n\n/**\n * The dense per-project overview: one row per project with a live session.\n *\n * The mode cell is the one interactive column: a mode is a value the host\n * stores, so it is written as soon as it is clicked (the page says so under the\n * form) and the button goes quiet while the answer is in flight.\n *\n * Seven columns did not fit the settings panel's content column on every window;\n * the five the host answers for do, and the table is still a scroll region\n * rather than a block that runs under the panel edge. Its headers stay on one\n * line, and the project name — the only free-form text in it — wraps inside its\n * cell instead of widening the table.\n */\nexport function ToolsProjectTable(props: {\n rows: readonly ProjectPolicyRow[]\n /** Roots the host is currently writing a mode or a pin for. */\n pending: ReadonlySet<string>\n onMode: (projectRoot: string, mode: ToolMode) => void\n t: Translate\n}): ReactNode {\n const { t } = props\n const th = { ...STYLE.th, whiteSpace: 'nowrap' as const }\n return h(\n 'div',\n { style: STYLE.tableScroll },\n h(\n 'table',\n { style: STYLE.table },\n h(\n 'thead',\n null,\n h(\n 'tr',\n null,\n h('th', { style: th }, t('project')),\n h('th', { style: th }, t('servers')),\n h('th', { style: th }, t('toolsCount')),\n h('th', { style: th }, t('pinned')),\n h('th', { style: th }, t('mode')),\n ),\n ),\n h(\n 'tbody',\n null,\n props.rows.map((row) =>\n h(\n 'tr',\n { key: row.projectRoot },\n h('td', { style: { ...STYLE.td, overflowWrap: 'anywhere' as const } }, row.label),\n h('td', { style: STYLE.td }, String(row.counts.servers)),\n h(\n 'td',\n { style: STYLE.td },\n row.counts.tools === undefined ? '—' : String(row.counts.tools),\n ),\n h('td', { style: STYLE.td }, String(row.policy.pins.length)),\n h(\n 'td',\n { style: STYLE.td },\n ModeSwitchRow({\n mode: row.policy.mode,\n busy: props.pending.has(row.projectRoot),\n onMode: (mode) => props.onMode(row.projectRoot, mode),\n t,\n }),\n ),\n ),\n ),\n ),\n ),\n )\n}\n\n// ── the tools tab ─────────────────────────────────────────────────────────────\n\n/** Props of the `Tools` page: the selected project and its host policy. */\nexport interface ToolsPageProps {\n /** The project the page shows; selected by the shared project picker. */\n project: ProjectSnapshot\n /** Every project with a live session, for the overview table above the form. */\n rows: readonly ProjectPolicyRow[]\n /** Switch one project's mode; the host stores it, so it is written at once. */\n onMode: (projectRoot: string, mode: ToolMode) => void\n /** Roots with a policy write in flight. */\n pending: ReadonlySet<string>\n /** Last refusal from a policy write, when the host did not take it. */\n modeError: string | undefined\n /** Wire companions of `modeError`, when the host coded the refusal (F-48). */\n modeErrorCode?: string | undefined\n /** Flat params of `modeErrorCode`. */\n modeErrorParams?: Record<string, string> | undefined\n /** Re-read the host snapshot now; the conflict report's own action. */\n onSync: () => void\n /** Pin or unpin one tool of one project; the host stores it at once. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight, per `projectRoot` + `tool`. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal from a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n /**\n * Choose which declaration of one contested name the project shows. The host\n * stores the answer and answers with the snapshot that already reflects it,\n * so this page draws the new state instead of guessing it.\n */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a choice write in flight, per `projectRoot` + name. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal from a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n t: Translate\n /** Host-namespace seat for the conflicts' coded messages (F-48). */\n hostT?: Translate | undefined\n}\n\n/**\n * The `Tools` page: the project table, then the form of the selected project.\n *\n * The page is a vertical list of setting rows rather than the mockup's split:\n * a policy form is a list of settings, which is what DSH's own settings pages\n * are, and the split's panes are too narrow for the sentences they had to hold.\n */\nexport function ToolsPage(props: ToolsPageProps): ReactNode {\n const { t } = props\n const policy = policyOf(props.project)\n return h(\n 'div',\n null,\n h(ToolsProjectTable, {\n rows: props.rows,\n pending: props.pending,\n onMode: props.onMode,\n t,\n }),\n props.modeError === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.noteError },\n // A coded refusal translates through the host seat; prose alone\n // renders exactly as it did before codes existed.\n `${t('modeRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.modeErrorCode, props.modeErrorParams, props.modeError)}`,\n ),\n h(ProjectForm, {\n project: props.project,\n policy,\n onMode: props.onMode,\n pending: props.pending.has(props.project.projectRoot),\n onSync: props.onSync,\n onPin: props.onPin,\n pinPending: props.pinPending,\n pinError: props.pinError,\n pinErrorCode: props.pinErrorCode,\n pinErrorParams: props.pinErrorParams,\n onChoice: props.onChoice,\n choicePending: props.choicePending,\n choiceError: props.choiceError,\n choiceErrorCode: props.choiceErrorCode,\n choiceErrorParams: props.choiceErrorParams,\n t,\n hostT: props.hostT,\n }),\n )\n}\n\n/**\n * The switch that stands for a whole server (F-44).\n *\n * It wears the control every per-name row below wears, and its reading is\n * {@link serverPinState}'s proportion: on while the project pins **every** name\n * this page lists for that server, off otherwise. A half-pinned server\n * therefore reads off, and that is the honest reading of the only store there\n * is — the pin list holds names, no rule about servers, and this page has no\n * third visual for \"some\". What the press does is said by the tooltip and is\n * never a loss: the set is completed when it is not complete and released only\n * when it is ({@link serverPinPress}).\n *\n * The names are **every** name the host published for that server: the offered\n * ones this page lists below, and the ones it kept hidden. A pin is what pulls a\n * hidden name into the request (that is what the tab's hidden tier does with its\n * own `Pin`), so a switch that stood for the server while skipping them would\n * leave the server half-pinned — and the row's own description already counts\n * them (`1 of 3 tools offered directly`).\n * @param props - the project, the server, the names that stand for it and the writer.\n * @returns the switch, inert while there is nothing to write to.\n */\nfunction serverPinSwitch(props: {\n projectRoot: string\n server: string\n /** Every name the host published for this server, hidden ones included. */\n names: readonly string[]\n /** The project's own pin list. */\n pins: readonly string[]\n /** `true` while a pin write of this server is in flight. */\n pending: boolean\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n t: Translate\n}): ReactNode {\n const { t } = props\n const all = serverPinState(props.names, props.pins) === 'all'\n const press = serverPinPress(props.names, props.pins)\n // `names` is never empty for a row that is drawn: the rows come from\n // `serverToolCounts`, and a server is in that list because it contributed at\n // least one name. A switch over nothing would not exist to be disabled.\n const disabled = props.onPin === undefined || props.pending\n return h(\n 'button',\n {\n type: 'button',\n style: all ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n 'aria-checked': all,\n 'aria-label': `${props.server} — ${all ? t('serverUnpin') : t('serverPin')}`,\n title: all ? t('serverUnpinHint') : t('serverPinHint'),\n disabled,\n onClick: () => {\n for (const name of press.names) props.onPin?.(props.projectRoot, name, press.pinned)\n },\n },\n h('span', { style: all ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob }),\n )\n}\n\n/**\n * The form of one project's policy: the setting rows — the mode, then one row\n * per server of the session — under the page's own note, then the pinned group\n * with the conflict report, the mounted tool list and the request preview as\n * full-width blocks.\n *\n * The server rows are the mockup's \"not to be touched\" field, made real: each\n * one names a server this session mounts and says, from the session's own offer,\n * how many of its tools the model is offered directly. A row that used to\n * promise a locked example service now counts the project's own servers.\n */\nexport function ProjectForm(props: {\n project: ProjectSnapshot\n /** The host's policy for that project: the mode and the pin list. */\n policy: ToolPolicy\n onMode: (projectRoot: string, mode: ToolMode) => void\n /** `true` while this project's mode is being written. */\n pending: boolean\n /** Re-read the host snapshot now; the conflict report's own action. */\n onSync: () => void\n /** Pin or unpin one tool of this project; the host stores it at once. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal from a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n /** Choose which declaration of one contested name this project shows. */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a choice write in flight. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal from a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n t: Translate\n /** Host-namespace seat for the conflicts' coded messages (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t, policy } = props\n const tools = firstSession(props.project)?.tools\n const servers = tools === undefined ? [] : serverToolCounts(tools)\n // The names this page lists, read once: the per-name list below works from\n // this set.\n const offered = offeredNames(tools)\n /**\n * Every name the host published for one server, offered and hidden alike.\n *\n * The per-name list below shows the offered half only, but a server's switch\n * speaks for the server: the hidden names are exactly the ones a pin pulls\n * into the request, and the row's own description counts them, so leaving them\n * out would make the switch quieter than the sentence beside it.\n * @param server - the `serverName` as the registry spells it in the prefix.\n * @returns the names, offered first, each once.\n */\n const mountedOf = (server: string): string[] => [\n ...new Set([\n ...offered.filter((name) => serverOfToolName(name) === server),\n ...(tools?.deferred ?? []).filter((name) => serverOfToolName(name) === server),\n ]),\n ]\n return h(\n 'div',\n null,\n // The mode is the host's own value: the write goes out on the click, so\n // the row carries the hint about that instead of a Save of its own. The\n // longer explanation rides the row's tooltip rather than a paragraph above\n // it — the mockup spends its lines on controls, not on prose.\n SettingRow({\n label: t('mode'),\n description: t('modeHint'),\n title: t('policyNote'),\n control: ModeSwitchRow({\n mode: policy.mode,\n busy: props.pending,\n onMode: (mode) => props.onMode(props.project.projectRoot, mode),\n t,\n }),\n last: servers.length === 0,\n }),\n // One row per server, and since F-44 the row is also where a whole server\n // gets pinned: the name keeps its place at the right edge and the switch\n // stands beside it, so the reading and the action share one line.\n ...servers.map((count, index) => {\n const names = mountedOf(count.server)\n return SettingRow({\n label: t('server'),\n description: serverOfferLabel(count, t),\n control: h(\n 'span',\n { style: STYLE.settingRowControl },\n h('span', { style: STYLE.muted }, count.server),\n serverPinSwitch({\n projectRoot: props.project.projectRoot,\n server: count.server,\n names,\n pins: policy.pins,\n pending: names.some((name) => props.pinPending?.has(name) === true),\n onPin: props.onPin,\n t,\n }),\n ),\n last: index === servers.length - 1,\n })\n }),\n h(\n 'div',\n { style: STYLE.settingGroup },\n h('div', { style: STYLE.settingGroupHead }, t('pinned')),\n // The pin list is the host's: names the user pinned by hand, in the order\n // they pinned them. No badge, because nothing here is invented — and the\n // list gets the whole width, so a long name cannot be clipped.\n h(\n 'div',\n { style: STYLE.tagList },\n policy.pins.length === 0\n ? h('span', { style: STYLE.hint }, t('pinListEmpty'))\n : policy.pins.map((name) => h('span', { key: name, style: STYLE.tag }, name)),\n ),\n // The conflict check is real: the report is the host's own\n // `ProjectSnapshot.conflicts`, drawn under the row, and the button asks\n // the host for a fresh snapshot rather than standing in for one. Both the\n // hint and the button carry the label \"Check conflicts\": the head is the\n // block's own title, and the button repeats it as the action.\n SettingRow({\n label: t('checkConflicts'),\n description: t('pinList'),\n title: t('checkConflictsHint'),\n control: h(\n 'button',\n { style: STYLE.button, title: t('checkConflictsHint'), onClick: props.onSync },\n t('checkConflicts'),\n ),\n last: true,\n }),\n ConflictReport({\n projectRoot: props.project.projectRoot,\n conflicts: props.project.conflicts ?? [],\n onChoice: props.onChoice,\n choicePending: props.choicePending,\n choiceError: props.choiceError,\n choiceErrorCode: props.choiceErrorCode,\n choiceErrorParams: props.choiceErrorParams,\n t,\n hostT: props.hostT,\n }),\n ),\n h(ToolList, {\n project: props.project,\n policy,\n onPin: props.onPin,\n pinPending: props.pinPending,\n pinError: props.pinError,\n pinErrorCode: props.pinErrorCode,\n pinErrorParams: props.pinErrorParams,\n t,\n hostT: props.hostT,\n }),\n h(RequestPreview, { project: props.project, policy, t }),\n )\n}\n\n/**\n * The host's conflict report for one project, always drawn.\n *\n * The report needs no click to appear: the host counts the conflicts when it\n * builds the snapshot, so hiding them behind a button would hide an answer the\n * page already holds. The empty state is a real answer too — \"no conflicts\" is\n * the good case, and the row above it says so instead of showing nothing.\n * @param props - the conflicts, in the host's order.\n * @returns one row per conflict, or the empty state.\n */\nexport function ConflictReport(props: {\n /** Project the names belong to; the choice is stored per project. */\n projectRoot: string\n conflicts: readonly ServerConflict[]\n /** Choose a declaration; absent leaves the cards read-only. */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a write in flight. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal from a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n t: Translate\n /**\n * Host-namespace seat for the conflicts' coded messages (F-48); without one\n * each card renders its payload's English, byte-identical to before codes.\n */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t } = props\n if (props.conflicts.length === 0) {\n return h('div', { style: { ...STYLE.hint, padding: '8px 0' } }, t('conflictsNone'))\n }\n return h(\n 'div',\n null,\n props.conflicts.map((conflict) =>\n // One conflict is one card, in the alarm tone: the mockups draw a conflict\n // as a note that reads as a warning, not as another table row.\n h(\n 'div',\n { key: conflict.server, style: STYLE.noteError },\n h('strong', null, conflict.server),\n ' ',\n h('span', { style: conflictTone(conflict.kind) }, conflictKindLabel(conflict.kind, t)),\n h(\n 'div',\n { style: STYLE.muted },\n resolveHost(props.hostT ?? hostTranslate(undefined), conflict.code, conflict.params, conflict.message),\n ),\n conflict.sources.length === 0\n ? null\n : h(\n 'div',\n { style: STYLE.hint },\n t('conflictSources', { sources: conflict.sources.join(' · ') }),\n ),\n ConflictChoiceRow({\n projectRoot: props.projectRoot,\n conflict,\n onChoice: props.onChoice,\n pending: props.choicePending?.has(choiceKey(props.projectRoot, conflict.server)) ?? false,\n t,\n }),\n ),\n ),\n props.choiceError === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.noteError },\n `${t('choiceRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.choiceErrorCode, props.choiceErrorParams, props.choiceError)}`,\n ),\n )\n}\n\n/**\n * The choice control of one conflict card: which of the declarations this\n * project shows.\n *\n * Drawn wherever a profile-level reservation meets a surface that can write the\n * answer. A duplicate declaration has no toggle on purpose: both copies live in\n * this project's own documents, and no rename of the winner brings the loser\n * back.\n *\n * The three answers are the host's own `ConflictChoice`, in its order. `profile`\n * and `native` need nothing but the name the conflict already carries; `local`\n * is the one that cannot be drawn without a worked-out alias, so a host that\n * published none loses that button alone — an alias-less project can still keep\n * the profile instance or mount its own declaration under the declared name.\n * @param props - the conflict, its project and the write surface.\n * @returns the row, or `null` when the conflict carries no choice.\n */\nfunction ConflictChoiceRow(props: {\n projectRoot: string\n conflict: ServerConflict\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n pending: boolean\n t: Translate\n}): ReactNode {\n const { conflict, t } = props\n const write = props.onChoice\n if (conflict.kind !== 'profile' || write === undefined) return null\n const choice = conflict.choice ?? 'profile'\n const button = (next: ConflictChoice, title: string, label: string): ReactNode =>\n h(\n 'button',\n {\n type: 'button',\n style: choice === next ? STYLE.choiceOn : STYLE.choiceOff,\n disabled: props.pending,\n 'aria-pressed': choice === next,\n title,\n onClick: () => write(props.projectRoot, conflict.server, next),\n },\n label,\n )\n const alias = conflict.alias\n return h(\n 'div',\n { style: STYLE.choiceRow },\n h('span', { style: STYLE.hint }, t('choiceLabel')),\n button('profile', t('choiceProfileHint'), t('conflictProfile')),\n // Only a `local` answer names the alias it would mount under, so the button\n // exists exactly where the host published one.\n alias === undefined\n ? null\n : button('local', t('choiceLocalHint', { alias }), t('choiceLocal', { alias })),\n button('native', t('choiceNativeHint'), t('choiceNative')),\n )\n}\n\n/** The key one contested name's write is tracked under: project + name. */\nexport function choiceKey(projectRoot: string, server: string): string {\n return `${projectRoot}\\u0000${server}`\n}\n\n/**\n * The chip rule an alarm about this kind of conflict wears.\n *\n * A profile-level reservation is the warning tone — the name is taken, nothing\n * is broken. A duplicate declaration inside one project is the error tone: only\n * one of the two can win, so a declaration the file states is being dropped.\n * @param kind - the host's own conflict kind.\n * @returns the chip style for that kind.\n */\nfunction conflictTone(kind: ServerConflict['kind']): Record<string, unknown> {\n return kind === 'profile' ? STYLE.tagWarn : STYLE.tagError\n}\n\n/** What one conflict kind is called in the UI. */\nconst CONFLICT_KEYS: Record<ServerConflict['kind'], LocaleKey> = {\n profile: 'conflictProfile',\n duplicate: 'conflictDuplicate',\n}\n\n/** The label of one conflict kind. */\nexport function conflictKindLabel(kind: ServerConflict['kind'], t: Translate): string {\n return t(CONFLICT_KEYS[kind])\n}\n\n/**\n * One setting row of the `Tools` page: the label and its description in the\n * text column, the control in the column on the right.\n *\n * The text column is the wide one and the one that wraps — `flex: 1` takes the\n * leftover width and `minWidth: 0` lets it shrink below its content instead of\n * pushing the control out of the panel. The control column is `flex: none`, so\n * it measures to its own content and never wraps. That is exactly the shape the\n * old three-pane grid got wrong: it put sentences in panes narrower than one of\n * their words, so they rendered as one-word-wide slivers.\n * @param props - label, optional description and the row's own control.\n * @returns the row element.\n */\nexport function SettingRow(props: {\n /** Bold text of the text column. */\n label: string\n /** Muted one-line description under the label, when the row has one. */\n description?: string\n /**\n * The longer explanation of the row, as a tooltip rather than a paragraph.\n *\n * The mockups keep a settings line to a label and a control; anything that\n * needs a sentence hangs it off the label it explains.\n */\n title?: string\n /** The control, sized to its content in the column on the right. */\n control: ReactNode\n /** `true` on the last row of a group, whose trailing separator is dropped. */\n last?: boolean\n}): ReactNode {\n return h(\n 'div',\n { style: props.last === true ? { ...STYLE.settingRow, ...STYLE.lastRow } : STYLE.settingRow },\n h(\n 'div',\n {\n style: STYLE.settingRowText,\n ...(props.title === undefined ? null : { title: props.title }),\n },\n h('div', { style: STYLE.settingRowLabel }, props.label),\n props.description === undefined\n ? null\n : h('div', { style: STYLE.settingRowDesc }, props.description),\n ),\n h('div', { style: STYLE.settingRowControl }, props.control),\n )\n}\n\n/**\n * The mode switch: `disclosure / direct / off`, the host's own three values.\n *\n * Unlike the mockup's segmented controls below it, this one writes through to\n * the host the moment it is clicked (the caller owns the request), so each\n * button stays disabled until the answer lands and the row re-reads the mode the\n * host actually stored.\n */\nexport function ModeSwitchRow(props: {\n mode: ToolMode\n busy: boolean\n onMode: (mode: ToolMode) => void\n t: Translate\n}): ReactNode {\n return h(\n 'span',\n { style: STYLE.segment },\n TOOL_MODES.map((mode) =>\n h(\n 'button',\n {\n key: mode,\n style:\n mode === props.mode\n ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }\n : STYLE.segmentItem,\n 'aria-pressed': mode === props.mode,\n disabled: props.busy,\n onClick: () => props.onMode(mode),\n },\n modeLabel(mode, props.t),\n ),\n ),\n )\n}\n\n// ── the session's own offer, counted per server ───────────────────────────────\n\n/** One server's share of a session's offer. */\nexport interface ServerToolCount {\n /** Server name, without the registry's `mcp__` prefix. */\n server: string\n /** Its tools the session offers the model right now. */\n offered: number\n /** Its tools mounted for the project but held back from this offer. */\n hidden: number\n /** `offered + hidden`. */\n total: number\n}\n\n/**\n * The names one session offers, in offer order: the durable baseline, then the\n * two on-demand tiers.\n *\n * Each name once: the tiers are not disjoint — a pinned or hot name can be\n * activated too — and both readers of this list count, so a repeat would be\n * counted twice (the per-server rows) or printed twice (the picker below).\n * @param tools - one session's offer, when the host published one.\n * @returns the public names, each once; empty without an offer.\n */\nexport function offeredNames(tools: SessionTools | undefined): string[] {\n if (tools === undefined) return []\n return [\n ...new Set([\n ...tools.baseline,\n ...tools.activated.map((tool) => tool.name),\n ...tools.context.map((tool) => tool.name),\n ]),\n ]\n}\n\n/**\n * The names this project's request would carry, in offer order: the host's pin\n * list first, then the session's own offer, each name once.\n *\n * Pins lead because that is where the request builder starts: a pinned name is\n * offered from the first step whatever the counters say. A pin the project no\n * longer mounts is kept — the declaration may come back — which is why the list\n * follows `policy.pins` rather than filtering it first.\n * @param tools - one session's tool offer.\n * @param policy - the project's policy, whose `pins` lead the list.\n * @returns the visible names, in request order.\n */\nexport function visibleToolNames(tools: SessionTools, policy: ToolPolicy): string[] {\n const seen = new Set<string>()\n const names: string[] = []\n for (const name of [...policy.pins, ...offeredNames(tools)]) {\n if (seen.has(name)) continue\n seen.add(name)\n names.push(name)\n }\n return names\n}\n\n/**\n * Count the session's offer per server, by the registry's `mcp__<server>__`\n * prefix (contract C6).\n *\n * `offered` and `hidden` are the session's own lists, so a name without the\n * prefix — a built-in, or one another owner contributes — belongs to no server\n * and is left out rather than filed under a made-up one. The sum of `total` is\n * therefore a lower bound on `SessionTools.mounted`, which stays the control.\n * @param tools - one session's tool offer.\n * @returns one entry per server, ordered by name.\n */\nexport function serverToolCounts(tools: SessionTools): ServerToolCount[] {\n const counts = new Map<string, ServerToolCount>()\n const bump = (name: string, tier: 'offered' | 'hidden'): void => {\n const server = serverOfToolName(name)\n if (server === undefined) return\n const entry = counts.get(server) ?? { server, offered: 0, hidden: 0, total: 0 }\n if (tier === 'offered') entry.offered += 1\n else entry.hidden += 1\n entry.total = entry.offered + entry.hidden\n counts.set(server, entry)\n }\n for (const name of offeredNames(tools)) bump(name, 'offered')\n for (const name of tools.deferred) bump(name, 'hidden')\n return [...counts.values()].sort((left, right) => left.server.localeCompare(right.server))\n}\n\n/**\n * What one server's counters mean in words: everything it mounts is offered\n * directly, or only part of it is.\n * @param count - one server's counters.\n * @param t - translate seat.\n * @returns the sentence the filter row carries.\n */\nexport function serverOfferLabel(count: ServerToolCount, t: Translate): string {\n return count.hidden === 0\n ? t('serverAllOffered', { count: count.offered })\n : t('serverPartlyOffered', { offered: count.offered, total: count.total })\n}\n\n/** One name and its switch: the picker's row. */\nfunction pinRow(\n name: string,\n pinned: boolean,\n pending: boolean,\n calls: ToolCalls | undefined,\n props: {\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n project: ProjectSnapshot\n t: Translate\n },\n): ReactNode {\n const { t } = props\n const disabled = props.onPin === undefined || pending\n const figure = callsLabel(calls, t)\n return h(\n 'div',\n { key: name, style: STYLE.listItem },\n h('span', { style: STYLE.muted }, name),\n figure === undefined ? null : h('span', { style: STYLE.hint }, figure),\n h('span', { style: { flex: 1 } }),\n h(\n 'button',\n {\n type: 'button',\n style: pinned ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n 'aria-checked': pinned,\n 'aria-label': name,\n title: pinned ? t('toolsUnpinHint') : t('toolsPinHint'),\n disabled,\n onClick: () => props.onPin?.(props.project.projectRoot, name, !pinned),\n },\n h('span', { style: pinned ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob }),\n ),\n )\n}\n\n/**\n * The project's mounted tools as a full-width block, with the pinned ones\n * marked.\n *\n * It lists the names the host actually offers — the pinned list first, then\n * whatever this session's own `tools` published — so a name on screen is a name\n * the project really mounts. The total in the head is the host's count of\n * mounted tools; a project whose session has published no offer yet shows a\n * dash and no rows rather than a number nobody measured.\n *\n * The block used to be the split's left pane, which is why it carried a\n * fixed-width rail and a right border; it is a card between two other blocks\n * now, so its rows are separated by the card's own rules instead.\n *\n * Since F-32 the rows are ordered by the host's own call counters and carry\n * that count, so the name worth pinning is the name at the top rather than the\n * one the session happened to list first.\n */\nexport function ToolList(props: {\n project: ProjectSnapshot\n policy: ToolPolicy\n /** Pin or unpin one tool of this project; absent leaves the switches inert. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal from a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n t: Translate\n /** Host-namespace seat for the refusal's coded message (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const { t } = props\n const counts = projectToolCounts(props.project)\n const live = firstSession(props.project)\n const tools = live?.tools\n const offered = offeredNames(tools)\n const pinnedNames = new Set(props.policy.pins)\n const pending = props.pinPending ?? new Set<string>()\n const rest = counts.tools === undefined ? 0 : Math.max(0, counts.tools - offered.length)\n return h(\n 'div',\n { style: STYLE.card },\n h('div', { style: STYLE.cardHead }, `${t('tabTools')} · ${counts.tools ?? '—'}`),\n offered.length === 0\n ? h(\n 'div',\n { style: STYLE.listItem },\n h('span', { style: STYLE.hint }, t('requestPreviewNoOffer')),\n )\n : [...offered]\n .sort(byCalls(props.project.usage, live?.id))\n .map((name) =>\n pinRow(\n name,\n pinnedNames.has(name),\n pending.has(name),\n toolCalls(name, props.project.usage, live?.id),\n props,\n ),\n ),\n rest > 0\n ? h(\n 'div',\n { style: { ...STYLE.listItem, ...STYLE.muted } },\n h('span', { style: STYLE.hint }, t('moreTools', { count: rest })),\n )\n : null,\n // The prefix is a fact of the registry, not a setting of this page: it is\n // stated once, under the names it explains, and is not a control.\n h(\n 'div',\n { style: { ...STYLE.listItem, ...STYLE.lastRow } },\n h('span', { style: STYLE.hint }, t('prefixFact')),\n ),\n props.pinError === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.noteError },\n `${t('pinRefused')} ${resolveHost(props.hostT ?? hostTranslate(undefined), props.pinErrorCode, props.pinErrorParams, props.pinError)}`,\n ),\n )\n}\n\n/**\n * The request the policy would build, as far as the host publishes it: the names\n * this session offers, in request order, with the pinned ones marked.\n *\n * The names are real — the session's own `tools` plus the policy's pin list —\n * and the sizes are the contract's own (`visibleChars` / `deferredChars`), so\n * the token estimate is `Math.round(chars / 4)` and is printed only where a size\n * is known: a snapshot without `deferredChars` shows the hidden count and no\n * estimate at all, rather than an invented one. The mockup's `tools[] = 6` with\n * its five made-up lines and its invented savings went with the other\n * placeholders.\n *\n * It used to be the split's third column, where the widest line of the preview\n * was wider than the pane and collided with the form beside it.\n */\nexport function RequestPreview(props: {\n project: ProjectSnapshot\n policy: ToolPolicy\n t: Translate\n}): ReactNode {\n const { t } = props\n const tools = firstSession(props.project)?.tools\n if (tools === undefined) {\n return h(\n 'div',\n { style: STYLE.card },\n h('div', { style: STYLE.cardHead }, t('requestPreview')),\n h(\n 'div',\n { style: { ...STYLE.listItem, ...STYLE.lastRow } },\n h('span', { style: STYLE.hint }, t('requestPreviewNoOffer')),\n ),\n )\n }\n const names = visibleToolNames(tools, props.policy)\n const pinned = new Set(props.policy.pins)\n const footer =\n tools.deferredChars === undefined\n ? t('requestPreviewHidden', { count: tools.deferred.length })\n : t('requestPreviewSaved', {\n count: tools.deferred.length,\n tokens: tokenEstimate(tools.deferredChars),\n })\n return h(\n 'div',\n { style: STYLE.card },\n h(\n 'div',\n { style: STYLE.cardHead },\n t('requestPreview'),\n h('span', { style: STYLE.tag }, t('requestPreviewTools', { count: names.length })),\n tools.visibleChars === undefined\n ? null\n : h(\n 'span',\n { style: STYLE.tag },\n t('requestPreviewTokens', { tokens: tokenEstimate(tools.visibleChars) }),\n ),\n ),\n h(\n 'pre',\n { style: STYLE.json },\n names.map((name) =>\n h('div', { key: name }, pinned.has(name) ? `${name} ${t('pinTag')}` : name),\n ),\n h('div', { style: STYLE.muted }, footer),\n ),\n )\n}\n","/**\n * The plugin's page inside DSH's native Settings.\n *\n * A sidebar tab belongs to one conversation, so it deliberately shows **only**\n * that session's project. This page is the other half of the picture: every\n * project with a live session, one selected at a time, with two remembered\n * views — `Table` (a dense overview) and `By files` (the plugin's own model:\n * documents read in priority order, a later document overriding an earlier\n * entry) — plus the split editor.\n *\n * The editor writes, and only within the frozen contract of\n * `docs/design/contracts/write-path.md`: the form edits the parsed {@link EntrySnapshot}\n * the row carries, the JSON pane shows that entry against the snapshot as a\n * line diff, and a save goes through a confirmation that names the document,\n * the `.bak` copy and the format normalization. A row whose\n * {@link ServerRow.writeScope} is `readonly` keeps the old blocked rendering,\n * with `writeBlockedReason` on every control. Secrets stay out of the editor's\n * reach: a masked `env`/`headers` key submitted untouched carries `masked: true`\n * and no value, so the document keeps the secret the form never saw.\n *\n * Registration contract (DSH `settings.section`, kind `list`, scope\n * `root`, owner copy intentionally empty):\n *\n * ```ts\n * ctx.slots.inject('settings.section', () => ctx.slots.register({\n * name: 'settings.section', id, order, label: () => t('tab'), locale: NS,\n * inject: () => ({}),\n * }, SettingsTab))\n * ```\n *\n * `slots.inject` is not decoration: the slot is declared by the Plugins\n * settings section at runtime, and `slots.register` **throws** on an undeclared\n * slot. Data comes from the host over `/project-mcp/snapshot` (see\n * `src/ui.ts`), through the same poll path the sidebar tab uses.\n *\n * The DSH client packages (`@deepseek-ai/dsh-client-ui-slots`, `-locale`,\n * `-ui-settings`) are provided by the web shell and are not dependencies of\n * this package, so the contract is mirrored structurally here: the composed\n * props type is `PropsRuntime<'settings.section'> & PropsLocale<NS> &\n * InjectFace<SettingsTabInjected>`, which for this slot means \"no owner props,\n * the namespace-bound `t` seat, and the inject factory's members\".\n *\n * @module dsh-project-mcp/client/settings\n */\n\nimport { createElement as h, useCallback, useEffect, useRef, useState } from 'react'\nimport type { CSSProperties, ReactHTML, ReactNode } from 'react'\nimport { PACKAGE_NAME, ROUTE_ACTIONS, ROUTE_PREFIX } from '../shared.ts'\nimport type { SaveErrorCode, SaveRequest } from '../shared.ts'\nimport type {\n ConflictChoice,\n EntryField,\n EntrySnapshot,\n McpSnapshot,\n ProjectSnapshot,\n ServerRow,\n ServerStatus,\n ToolMode,\n} from '../types.ts'\nimport {\n DEFAULT_REFRESH_MS,\n STATUS_COLOR,\n STATUS_HINT,\n STATUS_KEYS,\n basename,\n browserStorage,\n emptyState,\n idleNote,\n rowDetail,\n serverCount,\n storeString,\n storedString,\n useSnapshot,\n} from './view.ts'\nimport type { PanelStorage } from './view.ts'\nimport { DEFAULT_SETTINGS_PAGE, SettingsPageSwitch, ToolsPage, choiceKey } from './settings-tools.ts'\nimport type { SettingsPageKey } from './settings-tools.ts'\nimport {\n conflictBody,\n operatorBody,\n pinBody,\n policyBody,\n postConflict,\n requestMode,\n requestPin,\n} from './policy.ts'\nimport type { PolicyRefusal } from './policy.ts'\nimport { projectPolicyRows } from './settings-tools.ts'\nimport { uiTranslate } from './locales/ui.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\n\n/** Locale namespace the page's copy is registered under. */\nexport const NS = 'settings.projectMcp'\n\n/**\n * The settings page's own English copy, half of the namespace's dictionary.\n *\n * Keys only; the language switch stays with the shell, which re-registers\n * nothing here — a second language is one more dictionary, not a code change.\n * `./locales/ui.ts` adds the panel's half for the one\n * `ctx.locale.register(NS, { zh, en, ru })` call the plugin makes.\n */\nexport const EN = {\n project: 'Project',\n projectsOne: '1 project with a live session',\n projectsMany: '{count} projects with live sessions',\n viewTable: 'Table',\n viewFiles: 'By files',\n sync: 'Sync',\n syncHint: 'Re-read the host snapshot now',\n server: 'Server',\n transport: 'Transport',\n status: 'Status',\n source: 'Source',\n on: 'On',\n servers: 'Servers',\n paneEntry: 'Entry',\n name: 'Name',\n detail: 'Detail',\n loading: 'Reading the host snapshot…',\n loadingHint: 'The page polls /project-mcp/snapshot as soon as it opens.',\n hostUnavailable: 'The page did not get an answer from the plugin host.',\n hostUnavailableHint:\n 'The host half serves {route}; it picks up changes only after a dsh web restart — check the log.',\n noSessions: 'No session is attached to a project yet.',\n noSessionsHint:\n 'Servers come up when a session starts working inside a project folder — nothing is mounted for a project without one.',\n noSessionsPaths: 'read: {paths}',\n noSessionsNoPaths:\n 'this deployment reads no MCP document — list the documents to read in the plugin config (`localFiles`, `globalFiles`)',\n noServers: 'This project declares no MCP servers.',\n noServersHint: 'Nothing is declared, so nothing is mounted for its sessions.',\n noServersNoPath: 'This deployment reads no project document, so there is nowhere to declare one.',\n documentUnknown: 'declaration document unknown',\n global: 'global',\n priority: 'priority {tier}/{total}',\n overrideFrom: '↳ overrides {name} from {from}',\n overrideUnpinned: '↳ overrides {name} declared in a lower-priority document',\n nameReason: 'Read-only: the server name is the declaration key the host reports.',\n statusReason: 'Read-only: the status comes from the running host, not from a document.',\n sourceReason: 'Read-only: the declaring document path comes from the host.',\n detailReason: 'Read-only: the host redacts this text and never includes arguments.',\n openToEdit: 'Read-only here: open the server to edit its entry.',\n rowActionsMore: '…',\n rowActionsHint: 'Open this entry in the editor',\n retry: 'Retry',\n retryHint: 'Retry this project’s failed mounts now',\n showJson: 'Show JSON',\n hideJson: 'Hide JSON',\n jsonPreview: 'snapshot JSON',\n jsonPreviewHint: 'Read from the host snapshot; the document on disk is not touched.',\n back: 'Back to the list',\n backHint: 'Return to the overview without changing anything',\n // Editor: the fields of the parsed entry.\n entryUnavailable: 'The host did not parse this entry, so there is nothing to edit.',\n commandField: 'Command',\n argsField: 'Args',\n cwdField: 'CWD',\n urlField: 'URL',\n envField: 'Env',\n headersField: 'Headers',\n enabledField: 'Enabled',\n timeoutField: 'Timeout',\n keyField: 'Key',\n valueField: 'Value',\n argsHint: 'One argument per line; every line is written verbatim.',\n envHint: 'One value per key; a key the form drops is removed from the entry.',\n headersHint: 'One value per header; a key the form drops is removed from the entry.',\n timeoutHint: 'Milliseconds; empty means the declaration sets no timeout.',\n enabledValue: 'enabled: {value}',\n absent: 'absent',\n maskedValue: '•••• unchanged — type to replace',\n valuePlaceholder: 'value',\n keyPlaceholder: 'KEY',\n credentialsNote:\n 'Comes from an external source — the project .env or the credentials file — not from this document: it is shown and written back untouched.',\n credentialValue: 'from the project .env or the credentials file',\n addKey: 'Add key',\n addKeyHint: 'Append an empty key; an unnamed key is not written.',\n removeKey: '✕',\n removeKeyHint: 'Drop this key; a dropped key is removed from the entry.',\n // Writing.\n editableNote:\n 'Editing {document}: Save asks for confirmation, keeps {backup} and rewrites the entry wholesale.',\n writeBlocked: 'Read-only: {reason}',\n writeBlockedUnknown: 'the host did not report why this document may not be written.',\n save: 'Save…',\n saveHint: 'Open the confirmation for this write',\n saveNoChange: 'No change to save yet.',\n saveUnavailable: 'The snapshot carries no declaring document or revision to write back to.',\n saveTimeoutInvalid: 'The timeout is not a whole number of milliseconds.',\n saving: 'Writing…',\n discard: 'Discard',\n discardHint: 'Restore every field from the snapshot and write nothing',\n discardReason: 'No change to restore yet.',\n unsaved: 'unsaved',\n jsonDiff: 'diff',\n jsonClean: 'no change',\n jsonUnavailable: 'no parsed entry',\n jsonInvalid: 'The JSON does not parse into an entry: {reason}',\n jsonEditHint: 'Edit the entry as the document declares it',\n saveJsonInvalid: 'Fix the JSON pane first: it does not parse into an entry.',\n footerWrite: '→ {document} · .bak copy · confirmation',\n footerReadonly: '→ {document} · read-only',\n confirmTitle: 'Write {document}?',\n confirmBackup: 'The current document is copied to {backup} first.',\n confirmFormat:\n 'The entry replaces mcpServers[{server}] wholesale. The document is re-serialized with two-space indentation and a trailing newline, so the indentation and the key order of the rest of the document are normalized.',\n confirmConsent:\n 'This is a global document: every project reads it, so the write needs explicit consent.',\n consentLabel: 'I understand this rewrites a global document shared by every project.',\n confirmWrite: 'Write the document',\n confirmWriteHint: 'Write the document after the checks above',\n confirmBlocked: 'Tick the consent box first: a global write without it is refused.',\n cancel: 'Cancel',\n saveOk: 'Saved: the document was written and re-read.',\n saveErrorInvalid:\n 'The host refused the entry: it is not one this plugin would mount. Nothing was written.',\n saveErrorBlocked:\n 'The document may not be written on this tier, or the consent is missing. Nothing was written.',\n saveErrorConflict: 'The document changed since this snapshot was taken. Nothing was written.',\n saveErrorNotFound: 'The document or the server is no longer there. Nothing was written.',\n saveErrorFailed: 'The write itself failed; the document is left as it was. Nothing was written.',\n hostMessage: 'The host said: {message}',\n reRead: 'Re-read',\n reReadHint: 'Refetch the host snapshot and rebuild the form from it',\n // Our own two pages, and the disclosure policy page next to `Servers`.\n tabServers: 'Servers',\n tabTools: 'Tools',\n policyNote: 'the mode this project follows, and the tools pinned for it',\n checkConflicts: 'Check conflicts',\n checkConflictsHint:\n 'the conflicting server names the host reports for this project, read from its snapshot; the button re-reads it now',\n conflictsNone: 'no conflicting server name in this project',\n conflictProfile: 'profile name',\n conflictDuplicate: 'duplicate declaration',\n conflictSources: 'declared in {sources}',\n choiceLabel: 'show',\n choiceLocal: 'this project\\u2019s copy as {alias}',\n choiceProfileHint: 'keep the profile instance\\u2019s tools exactly as they are',\n choiceLocalHint:\n 'mount this project\\u2019s own declaration beside the profile one, under the local name {alias}',\n choiceNative: 'this project\\u2019s declaration under its own name',\n choiceNativeHint:\n 'mount this project\\u2019s own declaration under the name it declares: it is the nearer one in this project, so it shadows the profile instance\\u2019s tools here while every other project keeps seeing them',\n choiceRefused: 'The host refused the choice:',\n toolsCount: 'tools',\n pinned: 'Pinned',\n mode: 'Mode',\n modeDisclosure: 'disclosure',\n modeDirect: 'all direct',\n modeOff: 'off',\n modeHint: 'written straight away, on the request the host assembles next',\n modeRefused: 'The host refused the mode:',\n pinRefused: 'The host refused the pin:',\n pinList: 'pinned · written by hand, offered in every request',\n pinListEmpty: 'no pins yet — switch one on in the tool list below',\n serverAllOffered: 'all {count} of its tools are offered directly',\n serverPartlyOffered: '{offered} of {total} tools offered directly',\n // The server-level pin (F-44): one switch for the whole server row, above the\n // per-name rows it stands for.\n serverPin: 'pin this server’s tools',\n serverPinHint: 'Pin every tool this server mounts — the hidden ones too — so every request carries them',\n serverUnpin: 'unpin this server’s tools',\n serverUnpinHint: 'Stop pinning the tools of this server',\n prefixFact: 'mcp__<server>__<tool>; the registry applies the prefix, not this page',\n pinTag: 'pin',\n moreTools: '… {count} more',\n requestPreview: 'request preview',\n requestPreviewTools: 'tools[] = {count}',\n requestPreviewTokens: '≈ {tokens} tokens',\n requestPreviewHidden: 'hidden {count}',\n requestPreviewSaved: 'hidden {count} · ≈ {tokens} tokens saved',\n requestPreviewNoOffer: 'no offer published by this session yet',\n // The host's own usage counters, the same six keys and the same words the\n // panel's table holds: the settings page draws its server rows and its pin\n // picker itself, and one namespace means one spelling of `never called`\n // (merged with the panel's half in `./locales/ui.ts`, panel last).\n callsOne: '1 call',\n callsMany: '{count} calls',\n callsNone: 'never called',\n idleDay: 'idle {count}d',\n idleHour: 'idle {count}h',\n idleMinute: 'idle {count}m',\n} satisfies Record<string, string>\n\n/** A dictionary key of this namespace. */\nexport type LocaleKey = keyof typeof EN\n\n/** Translate one key, with optional `{name}` template params (the DSH seat). */\nexport type Translate = (key: string, params?: Record<string, unknown>) => string\n\n/**\n * Bind the translate seat the framework injects, falling back to this module's\n * own English dictionary when the page renders outside a DSH shell (tests, or a\n * browser half newer than the host).\n * @param t - the `t` seat of the composed props, when the framework passes one.\n * @returns a translate function that always answers.\n */\nexport function translateOf(t?: Translate): Translate {\n return t ?? fallbackTranslate\n}\n\nfunction fallbackTranslate(key: string, params?: Record<string, unknown>): string {\n const template = (EN as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in params ? String(params[name]) : match,\n )\n}\n\n/**\n * Slot key the page contributes to.\n *\n * `settings.section` is the settings navigation itself: one entry per settings\n * page, rendered as the content column when it is selected. The plugin's page is\n * a page in its own right — it has a project selector, its own view switch and a\n * write path — not a detail tab of the plugin inventory, so it belongs here\n * rather than inside the Plugins section.\n */\nexport const SETTINGS_SLOT = 'settings.section'\n\n/** Section id inside the navigation: the package name, so the row reads like the plugin. */\nexport const SETTINGS_TAB_ID = PACKAGE_NAME\n\n/**\n * Navigation position. The in-box sections run from `0` (General) to `25`\n * (Archived sessions), and installed plugins fill the rows after them; a page\n * about this plugin's own project data belongs at the end of that list.\n */\nexport const SETTINGS_TAB_ORDER = 900\n\n/** Options a `list` slot accepts for one registration. */\nexport interface SlotRegistration<Slot extends string = string> {\n name: Slot\n id: string\n order: number\n /** The shell re-reads this per render, so a language switch needs no re-register. */\n label?: () => string\n locale: string\n /** The registrant's business face; empty while the page reads the host over HTTP. */\n inject?: () => Record<string, never>\n}\n\n/** Options the settings page registers with; the slot it may claim is fixed. */\nexport type SettingsTabRegistration = SlotRegistration<typeof SETTINGS_SLOT>\n\n/** Injected business face of the settings tab. Nothing yet: the page fetches. */\nexport type SettingsTabInjected = Record<never, never>\n\n/**\n * Composed component props, mirroring\n * `PropsRuntime<'settings.section'> & PropsLocale<NS> & InjectFace<SettingsTabInjected>`:\n * the slot's owner passes no props, the framework contributes the\n * namespace-bound `t` seat, and the inject face's members arrive flattened.\n *\n * `t` is optional so the page still renders its own English copy outside a DSH\n * shell, which is also what the no-DOM view tests rely on.\n */\nexport interface SettingsTabProps {\n t?: Translate\n /**\n * The `projectMcp.host` seat, injected by {@link registerSettingsTab} from\n * the locale service the framework's own `t` cannot reach: `t` is bound to\n * the UI namespace, while host messages resolve through their own. Absent in\n * tests and outside a shell — the resolver then falls back to the payload's\n * English message.\n */\n hostT?: Translate | undefined\n}\n\n/**\n * The two client services the settings contribution needs. Both are optional in\n * a composition, which is exactly why registration goes through `ctx.inject`\n * rather than a module-level `inject` list: dropping either one must not take\n * the sidebar tab down with it.\n */\nexport interface SlotLocale {\n register(namespace: string, dictionaries: Record<string, Record<string, string>>): () => void\n bind(namespace: string): Translate\n /**\n * Add a language the shell does not ship, so dictionaries registered under\n * its id resolve. Optional: a shell whose locale service predates the method\n * must not break this plugin's boot — its keys then fall back to English.\n */\n addLanguage?(input: { id: string; label: string; fallback: string }): () => void\n}\n\n/**\n * The slot service, as a registrant uses it.\n *\n * `register`'s component seat is the slots package's own generic (a component of\n * the slot's composed props), which this package mirrors structurally: each\n * registrant supplies the props type it reads, so the settings page keeps its\n * `SettingsTabProps` and nothing else has to share it.\n */\nexport interface SlotSlots<Slot extends string = string> {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(\n options: SlotRegistration<Slot>,\n component: (props: Props) => ReactNode,\n ): unknown\n}\n\n/**\n * The two client services a contribution needs. Both are optional in a\n * composition, which is exactly why registration goes through `ctx.inject`\n * rather than a module-level `inject` list: dropping either one must not take\n * the sidebar tab down with it.\n */\nexport interface SettingsSlotServices {\n effect(execute: () => unknown, label?: string): unknown\n locale: SlotLocale\n slots: SlotSlots<typeof SETTINGS_SLOT>\n}\n\n/**\n * Contribute the page to the Plugins settings section.\n *\n * Two steps, because the slot is declared by the section at runtime:\n * `slots.inject` waits for the declaration (and re-registers after a collapse,\n * so a settings-section reload does not leave the tab missing), and the callback\n * calls `slots.register`, which would throw if the slot were not declared yet.\n * @param services - the injected `slots` and `locale` services.\n * @param component - the page to register; the real one by default. The\n * design-only render mode passes its fixture-fed page (`./design.ts`) so the\n * slot, the id and the order stay a single implementation.\n */\nexport function registerSettingsTab(\n services: SettingsSlotServices,\n component: (props: SettingsTabProps) => ReactNode = SettingsTab,\n): void {\n // The one translator both seats share: the bound namespace answers first,\n // the merged English table answers a key the active language lacks, and the\n // raw key shows only when even English has nothing for it. The slot keeps\n // `locale: NS` so the framework's own seat stays consistent.\n const t = uiTranslate(services.locale)\n // The second namespace's seat: the framework binds `t` to `NS` only, so the\n // host messages' translator is bound here and handed to the page as a prop.\n const hostT = hostTranslate(services.locale)\n services.slots.inject(SETTINGS_SLOT, () =>\n services.slots.register(\n {\n name: SETTINGS_SLOT,\n id: SETTINGS_TAB_ID,\n order: SETTINGS_TAB_ORDER,\n label: () => t('tab'),\n locale: NS,\n inject: () => ({}),\n },\n (props: SettingsTabProps) => component({ ...props, hostT }),\n ),\n )\n}\n\n/** Which overview the page shows; the choice is remembered. */\nexport type SettingsView = 'table' | 'files'\n\n/** View shown when nothing valid is persisted. */\nexport const DEFAULT_SETTINGS_VIEW: SettingsView = 'table'\n\n/**\n * `localStorage` key the page persists its view under.\n *\n * The settings page has no `pluginSettings` blob of its own — that helper\n * belongs to a sidebar tab descriptor — so the view is a browser-local\n * preference rather than a synced one.\n */\nexport const SETTINGS_VIEW_STORAGE_KEY = `${PACKAGE_NAME}:settings-view`\n\n/**\n * Read the persisted view.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the stored view, or {@link DEFAULT_SETTINGS_VIEW}.\n */\nexport function settingsViewOf(storage: PanelStorage | undefined = browserStorage()): SettingsView {\n return storedString(SETTINGS_VIEW_STORAGE_KEY, storage) === 'files'\n ? 'files'\n : DEFAULT_SETTINGS_VIEW\n}\n\n/**\n * Persist the view; hostile storage only costs the choice at the next reload.\n * @param view - view to store.\n * @param storage - storage to write; defaults to the browser's own.\n */\nexport function persistSettingsView(\n view: SettingsView,\n storage: PanelStorage | undefined = browserStorage(),\n): void {\n storeString(SETTINGS_VIEW_STORAGE_KEY, view, storage)\n}\n\n/**\n * The project the page shows.\n *\n * The page is the one surface that lists every project with a live session, but\n * it renders exactly one project's rows at a time: an unknown or stale\n * selection falls back to the first project, never to a mix.\n * @param snapshot - host snapshot, or undefined before the first poll lands.\n * @param projectRoot - the selected project root, when known.\n * @returns the selected project, or undefined while there is none.\n */\nexport function selectedProject(\n snapshot: McpSnapshot | undefined,\n projectRoot: string | undefined,\n): ProjectSnapshot | undefined {\n if (snapshot === undefined || snapshot.projects.length === 0) return undefined\n if (projectRoot !== undefined) {\n const match = snapshot.projects.find((project) => project.projectRoot === projectRoot)\n if (match !== undefined) return match\n }\n return snapshot.projects[0]\n}\n\n/**\n * Display label of a declaring document: relative to the project root, or\n * home-shortened when it is a global document.\n * @param source - absolute document path.\n * @param projectRoot - the project the document belongs to.\n * @returns the label shown on a card or in the Source column.\n */\nexport function documentLabel(source: string, projectRoot: string): string {\n if (source.startsWith(`${projectRoot}/`)) return source.slice(projectRoot.length + 1)\n return source.replace(/^(\\/Users\\/[^/]+|\\/home\\/[^/]+)/, '~')\n}\n\n/**\n * Where one declaring document sits in the read order of its project.\n *\n * The order is the host's to publish (`ProjectSnapshot.files`): global documents\n * first, then the project's own, so a tier is the 1-based place in that list and\n * `total` is how many it holds — a deployment that reads one document prints\n * `priority 1/1` instead of a `3` it cannot have. A host older than the field\n * reports nothing, and then the shipped names answer: the global documents, then\n * `<project>/.kimi-code/mcp.json`, then `<project>/.dsh/mcp.json`. A document\n * outside either table has no priority, and the panel says nothing rather than\n * inventing one.\n */\nexport interface DocumentPriority {\n /** 1-based place in the read order of this project. */\n readonly tier: number\n /** How many documents that read order holds. */\n readonly total: number\n /** True for a global document, read before the project's own. */\n readonly global: boolean\n}\n\n/** Documents this version reads when the host reports none — the shipped names. */\nconst SHIPPED_LOCAL_FILES = ['.kimi-code/mcp.json', '.dsh/mcp.json'] as const\n\n/** The one project document this version ships with, for a host that says none. */\nconst DEFAULT_LOCAL_SPECS = ['.dsh/mcp.json'] as const\n\n/**\n * Priority of a declaring document, per {@link DocumentPriority}.\n * @param source - absolute document path, or `''` when the host reported none.\n * @param project - the project the document belongs to.\n * @returns the tier, or `undefined` when the document is not one this project reads.\n */\nexport function documentPriority(source: string, project: ProjectSnapshot): DocumentPriority | undefined {\n if (source === '') return undefined\n const files = project.files\n if (files !== undefined) {\n const index = files.findIndex((file) => file.path === source)\n const file = files[index]\n if (file === undefined) return undefined\n return { tier: index + 1, total: files.length, global: file.scope === 'global' }\n }\n const projectRoot = project.projectRoot\n if (!source.startsWith(`${projectRoot}/`)) {\n return /(\\.dsh|\\.kimi-code)\\/mcp\\.json$/.test(source)\n ? { tier: 1, total: SHIPPED_LOCAL_FILES.length + 1, global: true }\n : undefined\n }\n const index = SHIPPED_LOCAL_FILES.findIndex((relative) => source === `${projectRoot}/${relative}`)\n return index < 0 ? undefined : { tier: index + 2, total: SHIPPED_LOCAL_FILES.length + 1, global: false }\n}\n\n/** A spec that already names where it lives, so the panel prints it as written. */\nfunction isRootedSpec(spec: string): boolean {\n return spec.startsWith('/') || spec.startsWith('~') || spec.startsWith('$') || /^[A-Za-z]:[\\\\/]/.test(spec)\n}\n\n/**\n * Documents of the deployment itself, written the way a person would write them\n * in the config: `<project>/…` for a local spec, `~/…` for a relative global one.\n * A host older than `sources` reported nothing, and then this version's shipped\n * names answer — the same ones its own default reads.\n */\nfunction deploymentDocuments(snapshot: McpSnapshot): string[] {\n const sources = snapshot.sources\n if (sources === undefined) return DEFAULT_LOCAL_SPECS.map((relative) => `<project>/${relative}`)\n return [\n ...sources.global.map((spec) => (isRootedSpec(spec) ? spec : `~/${spec}`)),\n ...sources.local.map((spec) => (isRootedSpec(spec) ? spec : `<project>/${spec}`)),\n ]\n}\n\n/**\n * The `read: …` code line under an empty state, said from the config rather than\n * from a file name baked into this bundle.\n */\nfunction readPaths(snapshot: McpSnapshot, t: Translate): string {\n const documents = deploymentDocuments(snapshot)\n return documents.length === 0 ? t('noSessionsNoPaths') : t('noSessionsPaths', { paths: documents.join(' · ') })\n}\n\n/** One overridden declaration, as the host's merge warning reports it. */\nexport interface OverrideNote {\n /** `serverName` that was declared in more than one document. */\n name: string\n /**\n * The overridden document, when the snapshot pins it; `undefined` when more\n * than one lower-priority document could have carried the losing entry.\n */\n from: string | undefined\n}\n\n/** One card of the \"By files\" view: a document and the servers it declares. */\nexport interface DocumentGroup {\n /** Absolute document path, or `''` when the host reported no source. */\n source: string\n /** Path relative to the project (or `~`-shortened); `''` when source is `''`. */\n label: string\n /** Where the document sits in the read order, per {@link documentPriority}. */\n priority: DocumentPriority | undefined\n /** The surviving rows that this document declares. */\n rows: ServerRow[]\n /** Declarations of this document's servers that a later document replaced. */\n overrides: OverrideNote[]\n}\n\n/**\n * Group a project's rows per declaring document, in priority order.\n *\n * The plugin's native model is the document, not the server: a document read\n * later overrides an earlier entry with the same `serverName`, so the earlier\n * declaration is a property of the file that won. The host reports the\n * overridden *name* in a merge warning (`project.issues`) and the winner's\n * document in the row's `source`; this function pairs the two. Which earlier\n * document carried the losing entry is only knowable when a single\n * lower-priority document is in the picture, so {@link OverrideNote.from} stays\n * `undefined` otherwise and the view says so instead of guessing.\n * @param project - one project from the host snapshot.\n * @returns one group per declaring document, lowest priority first.\n */\nexport function fileGroups(project: ProjectSnapshot): DocumentGroup[] {\n const groups: DocumentGroup[] = []\n for (const row of project.rows) {\n const source = row.source ?? ''\n let group = groups.find((candidate) => candidate.source === source)\n if (group === undefined) {\n group = {\n source,\n label: source === '' ? '' : documentLabel(source, project.projectRoot),\n priority: source === '' ? undefined : documentPriority(source, project),\n rows: [],\n overrides: [],\n }\n groups.push(group)\n }\n group.rows.push(row)\n }\n // Stable in modern engines: documents keep their first-appearance order inside\n // one tier, and documents the read order does not know come last.\n groups.sort((left, right) => (left.priority?.tier ?? Number.MAX_SAFE_INTEGER) - (right.priority?.tier ?? Number.MAX_SAFE_INTEGER))\n for (const issue of project.issues) {\n // The merge warning is recognised by its wire code, never by its prose:\n // the client translates the payload, so an English string-match would both\n // miss under another language and misread a translated message.\n if (issue.server === undefined || issue.code !== 'parse.server.multiDocument') continue\n const winnerIndex = groups.findIndex((group) =>\n group.rows.some((row) => row.name === issue.server),\n )\n if (winnerIndex < 0) continue\n const winner = groups[winnerIndex]\n if (winner === undefined) continue\n const earlier = groups\n .slice(0, winnerIndex)\n .filter(\n (group) =>\n group.priority === undefined ||\n winner.priority === undefined ||\n group.priority.tier < winner.priority.tier,\n )\n winner.overrides.push({\n name: issue.server,\n from: earlier.length === 1 ? earlier[0]?.label : undefined,\n })\n }\n return groups\n}\n\n/** The `1 project …` / `3 projects …` toolbar summary. */\nfunction liveProjectCount(count: number, t: Translate): string {\n return count === 1 ? t('projectsOne') : t('projectsMany', { count })\n}\n\n// ── styles ────────────────────────────────────────────────────────────────────\n// Same vocabulary as `view.ts`: only the DSH alias layer's own custom\n// properties, each with the fallback a non-DSH page needs.\n\nconst BORDER = '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))'\nconst BORDER_L2 = '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.4))'\n\n/**\n * The longest a line of copy is allowed to run before it wraps.\n *\n * The settings panel is a modal `min(800px, 100vw - 48px)` wide, so a hint laid\n * out at full width runs to ~110 characters and the eye loses the line. The\n * mockups cap their prose at 74–84ch for the same reason; this is the cap the\n * page's own copy uses.\n */\nconst COPY_COLUMN = '72ch'\n\nexport const STYLE = {\n root: {\n display: 'flex',\n flexDirection: 'column',\n height: '100%',\n minHeight: 0,\n color: 'inherit',\n } satisfies CSSProperties,\n bar: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n padding: '6px 8px',\n borderBottom: BORDER,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n muted: { opacity: 0.9, fontSize: '0.9em' } satisfies CSSProperties,\n title: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n marginRight: 4,\n } satisfies CSSProperties,\n body: { flex: 1, minHeight: 0, overflow: 'auto', padding: '2px 2px 18px' } satisfies CSSProperties,\n segment: {\n display: 'flex',\n gap: 2,\n border: BORDER,\n borderRadius: 6,\n padding: 1,\n } satisfies CSSProperties,\n segmentItem: {\n padding: '1px 8px',\n border: 'none',\n borderRadius: 4,\n background: 'transparent',\n color: 'inherit',\n opacity: 0.65,\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.9em',\n } satisfies CSSProperties,\n segmentItemActive: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n opacity: 1,\n } satisfies CSSProperties,\n button: {\n padding: '2px 8px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n buttonPrimary: {\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid transparent',\n background: 'var(--dsw-alias-button-primary-fill, currentColor)',\n color: 'var(--dsw-alias-label-primary-foreground, inherit)',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n select: {\n border: BORDER,\n borderRadius: 4,\n padding: '2px 4px',\n background: 'var(--dsw-alias-bg-layer-2, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.9em',\n } satisfies CSSProperties,\n card: {\n border: BORDER,\n borderRadius: 7,\n marginBottom: 7,\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n overflow: 'hidden',\n } satisfies CSSProperties,\n cardHead: {\n display: 'flex',\n alignItems: 'center',\n gap: 7,\n padding: '6px 9px',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n background: 'var(--dsw-alias-bg-layer-2, transparent)',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n cardPath: {\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n fontSize: '0.9em',\n } satisfies CSSProperties,\n tag: {\n opacity: 0.75,\n fontSize: '0.8em',\n border: BORDER,\n borderRadius: 4,\n padding: '0 5px',\n color: 'var(--dsw-alias-label-secondary, inherit)',\n whiteSpace: 'nowrap',\n } satisfies CSSProperties,\n /** The `warn` chip of the mockups: the same rule, in the warning tone. */\n tagWarn: {\n opacity: 1,\n borderColor: 'var(--dsw-alias-state-warn-label, #b45309)',\n color: 'var(--dsw-alias-state-warn-label, #b45309)',\n } satisfies CSSProperties,\n /**\n * The choice control of a conflict card: the label, then the two answers side\n * by side. Four pixels apart like the mockups' own switch, and one row that\n * wraps rather than a column, because a long local name widens its button.\n */\n choiceRow: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n flexWrap: 'wrap',\n marginTop: 6,\n } satisfies CSSProperties,\n /** One answer of that control, while it is the one in force. */\n choiceOn: {\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid var(--dsw-alias-state-warn-label, #b45309)',\n background: 'var(--dsw-alias-bg-layer-2, rgba(127, 127, 127, 0.08))',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n /** One answer of that control, while the other one is in force. */\n choiceOff: {\n padding: '2px 8px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'var(--dsw-alias-label-secondary, inherit)',\n cursor: 'pointer',\n font: 'inherit',\n } satisfies CSSProperties,\n /** The `error` chip of the mockups, for the conflicts the host reports. */\n tagError: {\n opacity: 1,\n borderColor: 'var(--dsw-alias-state-error-primary, #ec1313)',\n color: 'var(--dsw-alias-state-error-primary, #ec1313)',\n } satisfies CSSProperties,\n row: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n padding: '5px 9px',\n borderTop: BORDER,\n } satisfies CSSProperties,\n dot: {\n width: 8,\n height: 8,\n borderRadius: '50%',\n display: 'inline-block',\n flex: 'none',\n alignSelf: 'center',\n } satisfies CSSProperties,\n serverButton: {\n padding: 0,\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n textAlign: 'left',\n } satisfies CSSProperties,\n serverButtonActive: {\n color: 'var(--dsw-alias-state-business-primary, inherit)',\n } satisfies CSSProperties,\n overrideNote: {\n padding: '3px 8px 3px 22px',\n borderTop: BORDER,\n opacity: 0.75,\n fontSize: '0.85em',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n } satisfies CSSProperties,\n note: {\n marginTop: 8,\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-warn-primary, #f59e0b)',\n background: 'var(--dsw-alias-state-warn-tertiary, transparent)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n maxWidth: COPY_COLUMN,\n // The failing-mount notes reuse this style and carry a multi-line detail.\n whiteSpace: 'pre-wrap',\n } satisfies CSSProperties,\n table: { width: '100%', borderCollapse: 'collapse' } satisfies CSSProperties,\n th: {\n textAlign: 'left',\n fontWeight: 500,\n fontSize: '0.75em',\n letterSpacing: '0.06em',\n textTransform: 'uppercase',\n // A header cell is a label, not prose: letting it wrap turns a column into a\n // one-word sliver at the panel's width.\n whiteSpace: 'nowrap',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n padding: '0 8px 5px 0',\n } satisfies CSSProperties,\n td: {\n padding: '6px 8px 6px 0',\n borderTop: BORDER,\n verticalAlign: 'baseline',\n // A cell is a value, not a heading: without this the browser's own `th`/`td`\n // default would render every name in the table bolder than the mockups do.\n fontWeight: 400,\n } satisfies CSSProperties,\n /** The editor's own checkboxes: a real input, so it only needs the reset. */\n switch: { margin: 0 } satisfies CSSProperties,\n /** The On column: the mockups' switch, drawn from the tokens they name. */\n switchOn: {\n display: 'inline-flex',\n alignItems: 'center',\n width: 26,\n height: 15,\n borderRadius: 8,\n padding: 0,\n border: 'none',\n background: 'var(--dsw-alias-state-business-primary, var(--dsw-alias-state-success-primary, #22c55e))',\n cursor: 'pointer',\n verticalAlign: '-2px',\n } satisfies CSSProperties,\n switchOff: { background: 'var(--dsw-alias-border-l3, #d0d3d8)' } satisfies CSSProperties,\n /** The knob inside {@link STYLE.switchOn}, pushed right when the row is on. */\n switchKnob: {\n width: 11,\n height: 11,\n borderRadius: '50%',\n background: 'var(--dsw-alias-label-primary-foreground, #ffffff)',\n marginLeft: 2,\n pointerEvents: 'none',\n } satisfies CSSProperties,\n switchKnobOn: { marginLeft: 13 } satisfies CSSProperties,\n // The vertical setting rows the `Tools` page is built from — the shape DSH's\n // own settings pages use (one row per setting: text column left, control\n // right, rule under). The `split` / `pane*` styles below belong to the entry\n // editor, whose three panes are deliberately not reused by a policy form:\n // its panes are far too narrow for a sentence, so the copy has nowhere to go\n // but a one-word-wide sliver.\n /** One setting row: label and description left, control right, rule under. */\n settingRow: {\n display: 'flex',\n alignItems: 'center',\n gap: 16,\n padding: '16px 0',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n /** The last row of a group or a block, which carries no trailing rule. */\n lastRow: { borderBottom: 'none' } satisfies CSSProperties,\n /** The row's text column: the wide one, and the one copy wraps in. */\n settingRowText: {\n flex: 1,\n minWidth: 0,\n display: 'flex',\n flexDirection: 'column',\n gap: 3,\n } satisfies CSSProperties,\n settingRowLabel: { fontWeight: 600 } satisfies CSSProperties,\n settingRowDesc: {\n fontSize: '0.85em',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n /** The control column: sized to its content, never the column that wraps. */\n settingRowControl: {\n flex: 'none',\n display: 'inline-flex',\n alignItems: 'center',\n gap: 6,\n } satisfies CSSProperties,\n /** A titled group of rows below the first one. */\n settingGroup: { marginTop: 16 } satisfies CSSProperties,\n settingGroupHead: {\n fontSize: '0.75em',\n letterSpacing: '0.06em',\n textTransform: 'uppercase',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n marginBottom: 6,\n } satisfies CSSProperties,\n /** The pinned names: chips that wrap across the row, not a column of their own. */\n tagList: {\n display: 'flex',\n flexWrap: 'wrap',\n alignItems: 'center',\n gap: 4,\n } satisfies CSSProperties,\n /** A table too wide for the panel scrolls instead of colliding with it. */\n tableScroll: { maxWidth: '100%', overflowX: 'auto' } satisfies CSSProperties,\n split: {\n display: 'flex',\n alignItems: 'stretch',\n minHeight: 260,\n border: BORDER,\n borderRadius: 7,\n overflow: 'hidden',\n } satisfies CSSProperties,\n /** Laid on top of {@link STYLE.split} while the panes stack. */\n splitNarrow: { flexDirection: 'column' } satisfies CSSProperties,\n splitBar: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n marginBottom: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n splitFooter: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n marginTop: 6,\n flexWrap: 'wrap',\n } satisfies CSSProperties,\n paneList: {\n flex: '1 1 168px',\n minWidth: 0,\n borderRight: BORDER,\n overflow: 'auto',\n } satisfies CSSProperties,\n /** The server list stacked: full width, its rule on the bottom edge. */\n paneListNarrow: {\n flex: 'none',\n width: '100%',\n maxHeight: 180,\n borderRight: 'none',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n paneHead: {\n padding: '5px 8px',\n fontSize: '0.75em',\n letterSpacing: '0.06em',\n textTransform: 'uppercase',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n listItem: {\n display: 'flex',\n alignItems: 'center',\n gap: 6,\n padding: '4px 8px',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n listItemActive: {\n background: 'var(--dsw-alias-interactive-bg-active, rgba(127, 127, 127, 0.18))',\n } satisfies CSSProperties,\n /**\n * The right column: the entry's form, and the JSON body under it.\n *\n * The JSON used to be a third column beside the form, which made both narrow\n * and put the entry in two places at once. Under the form it is the same entry\n * — the form's fields on top, the document body below — and the list keeps the\n * only fixed width.\n */\n paneColumn: {\n flex: '1 1 240px',\n minWidth: 0,\n display: 'flex',\n flexDirection: 'column',\n } satisfies CSSProperties,\n /** The form on top of the column: its own height, its rule on the bottom edge. */\n paneForm: {\n flex: 'none',\n minWidth: 0,\n padding: '8px 10px',\n borderBottom: BORDER,\n } satisfies CSSProperties,\n /** The column stacked: full width, no rules left over from the row. */\n paneColumnNarrow: {\n flex: 'none',\n width: '100%',\n } satisfies CSSProperties,\n paneFormNarrow: {\n width: '100%',\n } satisfies CSSProperties,\n paneJson: {\n flex: '1 1 auto',\n minWidth: 0,\n display: 'flex',\n flexDirection: 'column',\n background: 'var(--dsw-alias-markdown-code-block, transparent)',\n } satisfies CSSProperties,\n /** The JSON pane stacked: full width, its own height under the form. */\n paneJsonNarrow: {\n flex: 'none',\n width: '100%',\n minHeight: 200,\n } satisfies CSSProperties,\n json: {\n margin: 0,\n padding: '8px 10px',\n fontSize: '0.8em',\n whiteSpace: 'pre',\n overflowX: 'auto',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n } satisfies CSSProperties,\n /**\n * The editable body: the pane's own `pre`, as a control.\n *\n * `pre-wrap` rather than `pre`: the pane is a column of the settings panel and\n * a long `args` line would otherwise scroll sideways inside it. `resize` is on\n * because the entry is read as a whole and a wrapped line is not always the\n * shape someone wants.\n */\n jsonArea: {\n flex: '1 1 auto',\n minHeight: 160,\n margin: 0,\n padding: '8px 10px',\n border: 'none',\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.8em',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n lineHeight: '1.5',\n whiteSpace: 'pre-wrap',\n overflowWrap: 'anywhere',\n overflowY: 'auto',\n resize: 'vertical',\n boxSizing: 'border-box',\n width: '100%',\n } satisfies CSSProperties,\n field: {\n display: 'grid',\n gridTemplateColumns: '90px 1fr',\n gap: '5px 9px',\n alignItems: 'center',\n marginBottom: 4,\n } satisfies CSSProperties,\n fieldLabel: {\n fontSize: '0.75em',\n letterSpacing: '0.05em',\n textTransform: 'uppercase',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n } satisfies CSSProperties,\n input: {\n border: BORDER,\n borderRadius: 4,\n padding: '2px 6px',\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.85em',\n minWidth: 0,\n } satisfies CSSProperties,\n /**\n * The read-only Detail row. A mount detail is a multi-line diagnostic, and an\n * `<input>` collapses its line breaks — the operator would lose exactly the\n * structure that makes the message readable.\n */\n fieldText: {\n border: BORDER,\n borderRadius: 4,\n padding: '2px 6px',\n background: 'var(--dsw-alias-bg-layer-1, transparent)',\n color: 'inherit',\n font: 'inherit',\n fontSize: '0.85em',\n minWidth: 0,\n whiteSpace: 'pre-wrap',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldHint: {\n margin: '-2px 0 6px 99px',\n fontSize: '0.8em',\n opacity: 0.6,\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n fieldGroup: {\n display: 'grid',\n gridTemplateColumns: '90px 1fr',\n gap: '4px 9px',\n alignItems: 'start',\n marginBottom: 5,\n } satisfies CSSProperties,\n fieldRow: { display: 'flex', gap: 4, alignItems: 'center', marginBottom: 3 } satisfies CSSProperties,\n fieldKey: {\n flex: 'none',\n minWidth: 90,\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n fontSize: '0.8em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n iconButton: {\n flex: 'none',\n padding: '1px 5px',\n borderRadius: 4,\n border: BORDER,\n background: 'transparent',\n color: 'inherit',\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.8em',\n } satisfies CSSProperties,\n confirm: {\n marginTop: 6,\n padding: '7px 9px',\n border: BORDER,\n borderRadius: 6,\n background: 'var(--dsw-alias-bg-layer-2, transparent)',\n display: 'flex',\n flexDirection: 'column',\n gap: 4,\n } satisfies CSSProperties,\n noteOk: {\n marginTop: 8,\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-success-primary, #22c55e)',\n background: 'var(--dsw-alias-state-success-tertiary, transparent)',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n } satisfies CSSProperties,\n noteError: {\n marginTop: 8,\n padding: '5px 7px',\n borderLeft: '2px solid var(--dsw-alias-state-error-primary, #ec1313)',\n background: 'var(--dsw-alias-interactive-bg-hover-danger, var(--dsw-alias-state-error-tertiary, transparent))',\n borderRadius: '0 5px 5px 0',\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n maxWidth: COPY_COLUMN,\n } satisfies CSSProperties,\n errorState: { padding: '10px 12px' } satisfies CSSProperties,\n stateTitle: { opacity: 0.9, marginBottom: 4 } satisfies CSSProperties,\n /** Muted one-liner under a row or a card: a short label, never a paragraph. */\n hint: {\n opacity: 0.6,\n fontSize: '0.85em',\n overflowWrap: 'anywhere',\n maxWidth: COPY_COLUMN,\n } satisfies CSSProperties,\n codeLine: {\n margin: '6px auto 0',\n maxWidth: 560,\n padding: '5px 8px',\n border: BORDER,\n borderRadius: 5,\n background: 'var(--dsw-alias-markdown-code-block, transparent)',\n color: 'var(--dsw-alias-link, inherit)',\n fontSize: '0.8em',\n fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)',\n textAlign: 'left',\n } satisfies CSSProperties,\n} as const\n\n// ── layout adaptivity ─────────────────────────────────────────────────────────\n\n/**\n * The query the page stacks its split editor's panes on.\n *\n * The editor lives inside DSH's settings panel, not in the viewport: the panel\n * is `min(800px, 100vw - 48px)` wide, its navigation rail is 188px and its\n * options column pads 24px per side, so the page is given `min(564px, 100vw -\n * 284px)`. Three panes need all 564px of that, which is why they are flexible;\n * a viewport below 848px starts shrinking the panel itself, and three panes\n * there are slivers. The query sits at that break, so the panes stack whenever\n * the settings panel is not at its full 800px width.\n */\nexport const NARROW_SETTINGS_QUERY = '(max-width: 850px)'\n\n/** Just enough of `MediaQueryList` for the detector, so tests need no DOM. */\nexport interface MediaQueryLike {\n /** `true` while the query matches the current viewport. */\n matches: boolean\n /** Optional, so a test double can drive the flag by hand. */\n addEventListener?(type: 'change', listener: () => void): void\n /** Optional, for the same reason. */\n removeEventListener?(type: 'change', listener: () => void): void\n}\n\n/** One `matchMedia` query, as the detector asks for it. */\nexport type MediaQueryMatcher = (query: string) => MediaQueryLike\n\n/**\n * The browser's media-query matcher, or undefined when this half runs without\n * one — a non-browser host, or a policy that blocks the property.\n * @returns a matcher bound to the host, or undefined.\n */\nexport function browserMatchMedia(): MediaQueryMatcher | undefined {\n try {\n const host = globalThis as { matchMedia?: MediaQueryMatcher }\n if (typeof host.matchMedia !== 'function') return undefined\n const match = host.matchMedia\n return (query) => match.call(host, query)\n } catch {\n // Reading the property itself throws when a policy blocks it.\n return undefined\n }\n}\n\n/**\n * Resolve the narrow layout against a media-query matcher.\n * @param match - the browser's matcher, or undefined outside a browser.\n * @returns `true` when the panes must stack; `false` without a matcher.\n */\nexport function narrowSettingsLayout(match: MediaQueryMatcher | undefined): boolean {\n return match?.(NARROW_SETTINGS_QUERY).matches === true\n}\n\n/**\n * The narrow flag the page renders with, tracked across viewport resizes.\n *\n * Only the shell reads the media query: everything below it takes the flag as a\n * prop, which is what lets the no-DOM tests render both layouts.\n * @returns `true` while the viewport is at or below {@link NARROW_SETTINGS_QUERY}.\n */\nexport function useNarrowSettings(): boolean {\n const [narrow, setNarrow] = useState(() => narrowSettingsLayout(browserMatchMedia()))\n useEffect(() => {\n const match = browserMatchMedia()\n if (match === undefined) return undefined\n const list = match(NARROW_SETTINGS_QUERY)\n const sync = (): void => setNarrow(list.matches === true)\n sync()\n list.addEventListener?.('change', sync)\n return () => list.removeEventListener?.('change', sync)\n }, [])\n return narrow\n}\n\n// ── entry draft ───────────────────────────────────────────────────────────────\n\n/**\n * One `env`/`headers` row as the editor holds it.\n *\n * The row is the key plus what the input shows, never a copy of the declared\n * value: a masked key the user did not touch carries no value at all, which is\n * exactly what {@link draftEntry} has to submit for it.\n */\nexport interface FieldDraft {\n /** Key exactly as the document declares it, or the key being typed. */\n key: string\n /** What the value input shows; empty for a masked key until it is replaced. */\n text: string\n /** `true` when the host withheld the declared value as a secret. */\n masked: boolean\n /** `true` when the key resolves through the credentials file, not the document. */\n fromCredentials: boolean\n /** `true` once the user typed into a masked input, even back to empty. */\n replaced: boolean\n /** `true` for a row the user added; only its key is still editable. */\n added: boolean\n}\n\n/**\n * The form state of one open row.\n *\n * Optional entry fields hold exactly what the snapshot reported — `undefined`\n * means the document declares nothing — so an untouched draft rebuilds the\n * declared entry field for field and the editor opens clean instead of\n * announcing a change the user never made.\n */\nexport interface EntryDraft {\n /** Server the draft belongs to; a draft built for another row is ignored. */\n server: string\n /** `documentRevision` the draft was built from. */\n revision: string | undefined\n transport: 'stdio' | 'streamable-http'\n command: string | undefined\n args: readonly string[] | undefined\n cwd: string | undefined\n url: string | undefined\n /** `stdio`: declared environment, with the masked keys among them. */\n env: FieldDraft[]\n /** `true` when the declaration carried an `env`, so an emptied list still writes one. */\n envDeclared: boolean\n /** `streamable-http`: declared headers, with the masked keys among them. */\n headers: FieldDraft[]\n /** `true` when the declaration carried `headers`. */\n headersDeclared: boolean\n /** `enabled` exactly as declared: `undefined` means the document sets nothing. */\n enabled: boolean | undefined\n /** Milliseconds as typed; `''` means the declaration sets no timeout. */\n connectTimeoutMs: string\n /** Declared keys the editor never presents, written back untouched. */\n extra: Readonly<Record<string, unknown>>\n}\n\n/** Build the editable rows of one `env`/`headers` list. */\nexport function fieldDrafts(fields: readonly EntryField[] | undefined): FieldDraft[] {\n return (fields ?? []).map((field) => ({\n key: field.key,\n text: field.value ?? '',\n masked: field.masked === true,\n fromCredentials: field.fromCredentials === true,\n replaced: false,\n added: false,\n }))\n}\n\n/**\n * The draft the editor opens on: the snapshot's own entry, field for field.\n * @param row - the row being edited.\n * @returns the draft, or undefined when the host did not parse the entry.\n */\nexport function draftOf(row: ServerRow): EntryDraft | undefined {\n const entry = row.entry\n if (entry === undefined) return undefined\n return {\n server: row.name,\n revision: row.documentRevision,\n transport: entry.transport,\n command: entry.command,\n args: entry.args,\n cwd: entry.cwd,\n url: entry.url,\n env: fieldDrafts(entry.env),\n envDeclared: entry.env !== undefined,\n headers: fieldDrafts(entry.headers),\n headersDeclared: entry.headers !== undefined,\n enabled: entry.enabled,\n connectTimeoutMs: entry.connectTimeoutMs === undefined ? '' : String(entry.connectTimeoutMs),\n extra: entry.extra ?? {},\n }\n}\n\n/**\n * The draft actually shown: the stored one while it still belongs to this row\n * and this document revision, otherwise a fresh one.\n *\n * A background poll that re-reads a changed document therefore drops a stale\n * edit instead of writing it back on the snapshot's revision: the save would be\n * refused as `conflict` anyway.\n * @param row - the row being edited.\n * @param stored - the draft the shell still holds, if any.\n * @returns the draft to render, or undefined when there is nothing to edit.\n */\nexport function activeDraft(row: ServerRow, stored: EntryDraft | undefined): EntryDraft | undefined {\n const fresh = draftOf(row)\n if (fresh === undefined) return undefined\n if (stored === undefined || stored.server !== row.name || stored.revision !== row.documentRevision) {\n return fresh\n }\n return stored\n}\n\n/** One declared key as the save request carries it; undefined when it is not ours to write. */\nfunction fieldOf(row: FieldDraft): EntryField | undefined {\n if (row.key === '') return undefined\n // A key the credentials file answers is not editable, but it must still be\n // submitted: the host replaces the whole `env`/`headers` object with what this\n // request carries, so a dropped key is a key deleted from the document — the\n // reference to the credential would vanish on any unrelated edit. The host\n // writes the declared text back for a `fromCredentials` field and never a value\n // from here.\n if (row.fromCredentials) return { key: row.key, masked: true, fromCredentials: true }\n // Untouched and masked: no value at all, so the document keeps its secret.\n if (row.masked && !row.replaced) return { key: row.key, masked: true }\n return { key: row.key, value: row.text }\n}\n\nfunction fieldsOf(rows: readonly FieldDraft[]): EntryField[] {\n const fields: EntryField[] = []\n for (const row of rows) {\n const field = fieldOf(row)\n if (field !== undefined) fields.push(field)\n }\n return fields\n}\n\n/** The timeout as typed, or undefined when the field is empty or not a duration. */\nexport function timeoutOf(text: string): number | undefined {\n if (text.trim() === '') return undefined\n const value = Number(text)\n return Number.isInteger(value) && value >= 0 ? value : undefined\n}\n\n/** `true` when the timeout field holds something that is not a duration. */\nexport function timeoutInvalid(text: string): boolean {\n return text.trim() !== '' && timeoutOf(text) === undefined\n}\n\n/**\n * The entry a save writes: the whole declaration, rebuilt from the draft.\n *\n * Everything the editor presents is taken from the draft; `extra` rides along\n * untouched, because a save replaces `mcpServers[server]` wholesale and dropping\n * the keys the form never showed would delete configuration.\n * @param draft - the open row's form state.\n * @returns the entry body of a {@link SaveRequest}.\n */\nexport function draftEntry(draft: EntryDraft): EntrySnapshot {\n const env = fieldsOf(draft.env)\n const headers = fieldsOf(draft.headers)\n const timeout = timeoutOf(draft.connectTimeoutMs)\n const body: EntrySnapshot =\n draft.transport === 'stdio'\n ? {\n transport: 'stdio',\n ...(draft.command === undefined ? {} : { command: draft.command }),\n ...(draft.args === undefined ? {} : { args: draft.args }),\n ...(draft.cwd === undefined ? {} : { cwd: draft.cwd }),\n ...(env.length === 0 && !draft.envDeclared ? {} : { env }),\n }\n : {\n transport: 'streamable-http',\n ...(draft.url === undefined ? {} : { url: draft.url }),\n ...(headers.length === 0 && !draft.headersDeclared ? {} : { headers }),\n }\n return {\n ...body,\n ...(draft.enabled === undefined ? {} : { enabled: draft.enabled }),\n ...(timeout === undefined ? {} : { connectTimeoutMs: timeout }),\n ...(Object.keys(draft.extra).length === 0 ? {} : { extra: draft.extra }),\n }\n}\n\n/**\n * The save request for one row, or undefined when the snapshot does not carry\n * what a write needs (the row has no declaring document or no revision).\n */\nexport function saveRequestOf(\n project: ProjectSnapshot,\n row: ServerRow,\n entry: EntrySnapshot,\n consent: boolean,\n): SaveRequest | undefined {\n if (row.source === undefined || row.documentRevision === undefined) return undefined\n return {\n projectRoot: project.projectRoot,\n server: row.name,\n document: row.source,\n revision: row.documentRevision,\n ...(row.writeScope === 'global' ? { consent } : {}),\n entry,\n }\n}\n\n// ── the JSON pane's diff ──────────────────────────────────────────────────────\n\n/** One line of the JSON pane: shared context, or one side of a change. */\nexport interface DiffLine {\n kind: 'context' | 'removed' | 'added'\n text: string\n}\n\n/**\n * Line diff between two pretty-printed entries.\n *\n * A plain longest-common-subsequence walk: entries are small, and a faithful\n * diff is what makes the pane show the edit instead of a copy of the snapshot.\n * @param before - the declared entry, line by line.\n * @param after - the entry the draft would write.\n * @returns every line of both sides, in reading order.\n */\nexport function diffLines(before: readonly string[], after: readonly string[]): DiffLine[] {\n const table: number[][] = Array.from({ length: before.length + 1 }, () =>\n new Array<number>(after.length + 1).fill(0),\n )\n for (let i = before.length - 1; i >= 0; i -= 1) {\n for (let j = after.length - 1; j >= 0; j -= 1) {\n const row = table[i]\n const next = table[i + 1]\n if (row === undefined || next === undefined) continue\n row[j] =\n before[i] === after[j]\n ? (next[j + 1] ?? 0) + 1\n : Math.max(next[j] ?? 0, row[j + 1] ?? 0)\n }\n }\n const lines: DiffLine[] = []\n let i = 0\n let j = 0\n while (i < before.length && j < after.length) {\n const left = before[i] ?? ''\n const right = after[j] ?? ''\n if (left === right) {\n lines.push({ kind: 'context', text: left })\n i += 1\n j += 1\n } else if ((table[i + 1]?.[j] ?? 0) >= (table[i]?.[j + 1] ?? 0)) {\n lines.push({ kind: 'removed', text: left })\n i += 1\n } else {\n lines.push({ kind: 'added', text: right })\n j += 1\n }\n }\n for (; i < before.length; i += 1) lines.push({ kind: 'removed', text: before[i] ?? '' })\n for (; j < after.length; j += 1) lines.push({ kind: 'added', text: after[j] ?? '' })\n return lines\n}\n\n/**\n * The entry in the shape the document holds it: the keys the form never showed\n * sit beside the parsed ones instead of under `extra`, and the keys that resolve\n * through the credentials file are gone, because the document does not declare\n * them at all.\n *\n * Both sides of the diff go through this, so an untouched draft compares equal\n * to the snapshot however the host bucketed the unparsed and credential keys.\n */\nexport function entryBody(entry: EntrySnapshot): Record<string, unknown> {\n const body: Record<string, unknown> = { transport: entry.transport }\n if (entry.command !== undefined) body.command = entry.command\n if (entry.args !== undefined) body.args = entry.args\n if (entry.cwd !== undefined) body.cwd = entry.cwd\n const env = documentFields(entry.env)\n if (env !== undefined) body.env = env\n if (entry.url !== undefined) body.url = entry.url\n const headers = documentFields(entry.headers)\n if (headers !== undefined) body.headers = headers\n if (entry.enabled !== undefined) body.enabled = entry.enabled\n if (entry.connectTimeoutMs !== undefined) body.connectTimeoutMs = entry.connectTimeoutMs\n for (const [key, value] of Object.entries(entry.extra ?? {})) body[key] = value\n return body\n}\n\n/** A declared list without the keys that only exist in the credentials file. */\nfunction documentFields(fields: readonly EntryField[] | undefined): EntryField[] | undefined {\n return fields?.filter((field) => field.fromCredentials !== true)\n}\n\n/** The declared entry against the entry the draft would write, line by line. */\nexport function entryDiff(declared: EntrySnapshot | undefined, edited: EntrySnapshot): DiffLine[] {\n const before = declared === undefined ? [] : JSON.stringify(entryBody(declared), null, 2).split('\\n')\n return diffLines(before, JSON.stringify(entryBody(edited), null, 2).split('\\n'))\n}\n\n/** `true` when the draft would write something other than the declared entry. */\nexport function entryDirty(declared: EntrySnapshot | undefined, edited: EntrySnapshot): boolean {\n return entryDiff(declared, edited).some((line) => line.kind !== 'context')\n}\n\n/**\n * One `env`/`headers` list as the document holds it: a flat object of strings.\n *\n * The snapshot's own shape is a list of `{ key, value }` — that is what a diff\n * compares and what the JSON preview prints — while a document declares an\n * object. The pane edits the document, so this is the shape it shows.\n * @param fields - the draft's rows.\n * @returns the object; a key with no value (a secret the panel is not shown) and\n * a key answered outside the document are both left out, because neither has a\n * value the pane could print.\n */\nfunction recordFields(fields: readonly FieldDraft[]): Record<string, string> {\n const record: Record<string, string> = {}\n for (const field of fields) {\n if (field.key === '' || field.text === '' || field.fromCredentials === true) continue\n record[field.key] = field.text\n }\n return record\n}\n\n/**\n * One draft as its document declares it: the shape a person writes in `mcp.json`.\n *\n * The keys a document cannot carry are the same ones {@link entryBody} drops: a\n * secret the panel is not shown has no value to print, and a key answered by the\n * project's `.env` or the credentials file is not in the document at all. Both\n * are kept by {@link draftFromJson} when the pane's text omits them, so editing\n * the body never erases one by accident.\n * @param draft - the entry the form and the pane edit.\n * @returns the declaration object the host would write.\n */\nexport function documentBody(draft: EntryDraft): Record<string, unknown> {\n const body: Record<string, unknown> = { transport: draft.transport }\n if (draft.command !== undefined) body.command = draft.command\n if (draft.args !== undefined) body.args = draft.args\n if (draft.cwd !== undefined) body.cwd = draft.cwd\n if (draft.envDeclared) body.env = recordFields(draft.env)\n if (draft.url !== undefined) body.url = draft.url\n if (draft.headersDeclared) body.headers = recordFields(draft.headers)\n if (draft.enabled !== undefined) body.enabled = draft.enabled\n if (draft.connectTimeoutMs !== '') body.connectTimeoutMs = Number(draft.connectTimeoutMs)\n for (const [key, value] of Object.entries(draft.extra)) body[key] = value\n return body\n}\n\n/** The entry as the JSON pane shows and writes it: the document's own body. */\nexport function jsonBodyOf(draft: EntryDraft): string {\n return `${JSON.stringify(documentBody(draft), null, 2)}\\n`\n}\n\n/** One edit of the JSON pane: the draft it parses into, or why it does not. */\nexport type JsonDraftAnswer = { draft: EntryDraft } | { error: string }\n\n/** A string field, or `undefined` when the document sets nothing. */\nfunction jsonString(body: Record<string, unknown>, key: string): string | undefined | false {\n const value = body[key]\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : false\n}\n\n/** One `env`/`headers` pair of the parsed body, or `false` for a value that is not text. */\nfunction jsonFields(value: unknown, path: string): EntryField[] | undefined | false {\n if (value === undefined) return undefined\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const fields: EntryField[] = []\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (typeof entry !== 'string') return false\n void path\n fields.push({ key, value: entry })\n }\n return fields\n}\n\n/**\n * Read one JSON edit back into a draft.\n *\n * This is the inverse of {@link entryBody}, and it is deliberately the same\n * shape the form edits: whatever the pane parses becomes the draft the form\n * renders and the confirmation compares, so both entries edit one value.\n *\n * Two things the document cannot express are preserved rather than dropped:\n * keys answered outside it (the project's `.env` or the credentials file) are\n * not part of the body the pane shows, so a hand edit that omits them keeps the\n * ones the draft already had. Unknown keys travel in `extra` exactly as written,\n * because a save replaces the entry wholesale.\n * @param text - the pane's text.\n * @param base - the draft the pane opened on: its server, revision and the keys\n * the document does not carry.\n * @returns the parsed draft, or the first field that does not parse.\n */\nexport function draftFromJson(text: string, base: EntryDraft): JsonDraftAnswer {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch (error) {\n return { error: error instanceof Error ? error.message : String(error) }\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return { error: 'not an object' }\n }\n const body = value as Record<string, unknown>\n const transport = body.transport\n if (transport !== 'stdio' && transport !== 'streamable-http') return { error: 'transport' }\n\n const command = jsonString(body, 'command')\n if (command === false) return { error: 'command' }\n const cwd = jsonString(body, 'cwd')\n if (cwd === false) return { error: 'cwd' }\n const url = jsonString(body, 'url')\n if (url === false) return { error: 'url' }\n\n let args: readonly string[] | undefined\n if (body.args !== undefined) {\n if (!Array.isArray(body.args)) return { error: 'args' }\n const lines: string[] = []\n for (const [index, entry] of body.args.entries()) {\n if (typeof entry !== 'string') return { error: `args[${index}]` }\n lines.push(entry)\n }\n args = lines\n }\n\n const env = jsonFields(body.env, 'env')\n if (env === false) return { error: 'env' }\n const headers = jsonFields(body.headers, 'headers')\n if (headers === false) return { error: 'headers' }\n\n const enabled = body.enabled\n if (enabled !== undefined && typeof enabled !== 'boolean') return { error: 'enabled' }\n const timeout = body.connectTimeoutMs\n if (timeout !== undefined && (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout < 0)) {\n return { error: 'connectTimeoutMs' }\n }\n\n const known = new Set([\n 'transport',\n 'command',\n 'args',\n 'cwd',\n 'env',\n 'headers',\n 'url',\n 'enabled',\n 'connectTimeoutMs',\n ])\n const extra: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(body)) {\n if (!known.has(key)) extra[key] = entry\n }\n\n /**\n * The parsed list, plus the keys the pane cannot show a value for.\n *\n * Both are keys the document holds and the pane's body does not print: a key\n * answered outside the document, and a secret whose value the host withholds.\n * The pane's text omitting them is \"unchanged\", not \"deleted\" — a save removes\n * a key when the draft drops it, and only the form's own row can do that.\n */\n const carryUnshown = (\n parsed: EntryField[] | undefined,\n was: readonly FieldDraft[],\n ): FieldDraft[] => {\n const text1 = (parsed ?? []).map((field) => ({\n key: field.key,\n text: field.value ?? '',\n masked: false,\n fromCredentials: false,\n replaced: false,\n added: false,\n }))\n const carried = new Set(text1.map((field) => field.key))\n for (const field of was) {\n const unshown = field.fromCredentials === true || (field.masked === true && field.text === '')\n if (unshown && !carried.has(field.key)) text1.push(field)\n }\n return text1\n }\n\n return {\n draft: {\n server: base.server,\n revision: base.revision,\n // Every field above is narrowed to its real type by its own `false` check.\n transport,\n command,\n args,\n cwd,\n url,\n env: carryUnshown(env, base.env),\n envDeclared: env !== undefined,\n headers: carryUnshown(headers, base.headers),\n headersDeclared: headers !== undefined,\n enabled: enabled as boolean | undefined,\n connectTimeoutMs: timeout === undefined ? '' : String(timeout),\n extra,\n },\n }\n}\n\n// ── saving ────────────────────────────────────────────────────────────────────\n\n/** What the host answered to a save: written, or one of the frozen error codes. */\nexport type SaveAnswer =\n | { readonly ok: true }\n | {\n readonly ok: false\n readonly code: SaveErrorCode\n readonly message: string\n /**\n * Wire code of `message` (`projectMcp.host` namespace), when the host\n * coded the refusal (F-48); `saveNotice` resolves it through the host\n * seat and an answer without it keeps the `hostMessage` wrapper.\n */\n readonly messageCode?: string | undefined\n /** Flat params of {@link SaveAnswer}'s messageCode, when it has any. */\n readonly messageParams?: Record<string, string> | undefined\n }\n\n/** The sentence each frozen {@link SaveErrorCode} gets; the keys live in {@link EN}. */\nconst SAVE_ERROR_KEYS: Record<SaveErrorCode, LocaleKey> = {\n invalid: 'saveErrorInvalid',\n blocked: 'saveErrorBlocked',\n conflict: 'saveErrorConflict',\n 'not-found': 'saveErrorNotFound',\n failed: 'saveErrorFailed',\n}\n\nconst SAVE_ERROR_CODES = Object.keys(SAVE_ERROR_KEYS) as SaveErrorCode[]\n\nfunction codeOf(code: string | undefined): SaveErrorCode {\n return SAVE_ERROR_CODES.find((known) => known === code) ?? 'failed'\n}\n\n/** The shape of the `{ ok, value | error }` envelope every host route answers with. */\ninterface SaveEnvelope {\n ok?: boolean\n error?: { code?: string; message?: string; messageCode?: string; messageParams?: Record<string, string> }\n}\n\n/**\n * `POST` one save and unwrap the envelope.\n *\n * Unlike the snapshot poll this never throws: every failure is one of the five\n * frozen codes, and `invalid` keeps the host's own text — the only place the\n * parser's reason reaches the user.\n * @param request - the entry, the document and the revision it was built from.\n * @returns the host's answer, normalized to {@link SaveAnswer}.\n */\nexport async function postSave(request: SaveRequest): Promise<SaveAnswer> {\n try {\n const response = await fetch(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.save}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(request),\n })\n const payload = (await response.json()) as SaveEnvelope\n if (payload.ok === true) return { ok: true }\n return {\n ok: false,\n code: codeOf(payload.error?.code),\n message: payload.error?.message ?? `request failed (${response.status})`,\n // The coded companions are optional on the wire: an old host's refusal\n // has none, and the notice falls back to the message.\n ...(typeof payload.error?.messageCode === 'string'\n ? { messageCode: payload.error.messageCode, messageParams: payload.error.messageParams }\n : {}),\n }\n } catch (error) {\n return { ok: false, code: 'failed', message: error instanceof Error ? error.message : String(error) }\n }\n}\n\n/** One save answer, as a sentence, plus what the notice has to offer. */\nexport interface SaveNotice {\n /** The sentence to show, one locale key per code. */\n text: string\n /** `true` when the document was written. */\n written: boolean\n /**\n * The host's own sentence, ready to render; only `invalid` shows it. A\n * coded refusal is resolved through the host seat and stands alone (F-48);\n * an uncoded one keeps the `hostMessage` wrapper it always had.\n */\n detail: string | undefined\n /** `true` when the page offers the re-read action that `conflict` asks for. */\n reRead: boolean\n}\n\n/**\n * Turn a save answer into the sentence the page shows.\n * @param answer - the host's answer, normalized by {@link postSave}.\n * @param t - the UI-namespace seat.\n * @param hostT - the `projectMcp.host` seat for a coded refusal's message;\n * absent — or a seat that does not know the code — the payload's English\n * message answers, never the raw code.\n */\nexport function saveNotice(answer: SaveAnswer, t: Translate, hostT?: Translate | undefined): SaveNotice {\n if (answer.ok) return { text: t('saveOk'), written: true, detail: undefined, reRead: false }\n return {\n text: t(SAVE_ERROR_KEYS[answer.code]),\n written: false,\n detail:\n answer.code !== 'invalid'\n ? undefined\n : answer.messageCode === undefined\n ? t('hostMessage', { message: answer.message })\n : resolveHost(hostT ?? hostTranslate(undefined), answer.messageCode, answer.messageParams, answer.message),\n reRead: answer.code === 'conflict',\n }\n}\n\n// ── form controls ─────────────────────────────────────────────────────────────\n\n/**\n * One control that feeds the save request.\n *\n * Enabled while the row may be written; when the tier is `readonly` it renders\n * disabled with the row's own `writeBlockedReason`. The internal `data-write`\n * marker lets the no-DOM tests find every such control without a rendered\n * document.\n */\nfunction formControl<T extends keyof ReactHTML>(\n kind: T,\n props: Record<string, unknown>,\n editable: boolean,\n reason: string,\n children?: ReactNode,\n): ReactNode {\n const marked: Record<string, unknown> = {\n ...props,\n title: reason,\n 'data-write': true,\n ...(editable ? {} : { disabled: true }),\n }\n return h(kind, marked as never, children)\n}\n\n/** A field the host owns: shown, never editable, with the reason why. */\nfunction hostField(label: string, value: string, reason: string): ReactNode {\n return h(\n 'div',\n { style: STYLE.field, key: label },\n h('span', { style: STYLE.fieldLabel }, label),\n h('input', {\n style: STYLE.input,\n value,\n readOnly: true,\n disabled: true,\n title: reason,\n 'aria-label': label,\n 'data-read': true,\n }),\n )\n}\n\n/**\n * The same host-owned row for a value that carries line breaks — the mount\n * detail. It keeps the label, the read-only marker and the reason tooltip, but\n * renders pre-wrapped text so the diagnostic's structure survives.\n */\nfunction hostDetailField(label: string, value: string, reason: string): ReactNode {\n return h(\n 'div',\n { style: STYLE.field, key: label },\n h('span', { style: STYLE.fieldLabel }, label),\n h(\n 'div',\n {\n style: STYLE.fieldText,\n title: reason,\n 'aria-label': label,\n 'data-read': true,\n },\n value,\n ),\n )\n}\n\n/** One editable text field of the parsed entry. */\nfunction textField(\n label: string,\n value: string,\n editable: boolean,\n reason: string,\n onChange: (value: string) => void,\n hint?: string,\n): ReactNode {\n return h(\n 'div',\n { key: label },\n h(\n 'div',\n { style: STYLE.field },\n h('span', { style: STYLE.fieldLabel }, label),\n formControl(\n 'input',\n {\n style: STYLE.input,\n value,\n readOnly: !editable,\n 'aria-label': label,\n ...(editable\n ? { onChange: (event: { target: { value: string } }) => onChange(event.target.value) }\n : {}),\n },\n editable,\n reason,\n ),\n ),\n hint === undefined ? null : h('div', { style: STYLE.fieldHint }, hint),\n )\n}\n\n/** Reproduce one `env`/`headers` list as key/value rows plus an add button. */\nfunction fieldList(\n label: string,\n rows: readonly FieldDraft[],\n editable: boolean,\n reason: string,\n t: Translate,\n hint: string,\n onChange: (rows: FieldDraft[]) => void,\n): ReactNode {\n return h(\n 'div',\n { style: STYLE.fieldGroup, key: label },\n h('span', { style: STYLE.fieldLabel }, label),\n h(\n 'div',\n null,\n rows.length === 0 ? h('div', { style: STYLE.hint }, hint) : null,\n rows.map((row, index) =>\n h(\n 'div',\n { key: `${row.key}#${index}` },\n h(\n 'div',\n { style: STYLE.fieldRow },\n row.added\n ? formControl(\n 'input',\n {\n style: STYLE.input,\n value: row.key,\n placeholder: t('keyPlaceholder'),\n 'aria-label': t('keyField'),\n ...(editable\n ? {\n onChange: (event: { target: { value: string } }) =>\n onChange(replaceRow(rows, index, { key: event.target.value })),\n }\n : {}),\n },\n editable,\n reason,\n )\n : h('span', { style: STYLE.fieldKey, title: row.key }, row.key),\n row.fromCredentials\n ? h('input', {\n style: STYLE.input,\n value: row.text,\n readOnly: true,\n disabled: true,\n title: t('credentialsNote'),\n placeholder: t('credentialValue'),\n 'aria-label': `${row.key} — ${t('credentialsNote')}`,\n 'data-read': true,\n })\n : formControl(\n 'input',\n {\n style: STYLE.input,\n value: row.text,\n placeholder:\n row.masked && !row.replaced ? t('maskedValue') : t('valuePlaceholder'),\n 'aria-label': `${row.key} ${t('valueField')}`,\n ...(editable\n ? {\n onChange: (event: { target: { value: string } }) =>\n onChange(\n replaceRow(rows, index, {\n // A masked input becomes a replacement on the first\n // keystroke, even when the user clears it back to empty.\n text: event.target.value,\n replaced: row.masked ? true : row.replaced,\n }),\n ),\n }\n : {}),\n },\n editable,\n reason,\n ),\n row.fromCredentials || !editable\n ? null\n : h(\n 'button',\n {\n style: STYLE.iconButton,\n title: t('removeKeyHint'),\n 'aria-label': `${t('removeKey')} ${row.key}`,\n onClick: () => onChange(rows.filter((_entry, at) => at !== index)),\n },\n t('removeKey'),\n ),\n ),\n row.fromCredentials ? h('div', { style: STYLE.fieldHint }, t('credentialsNote')) : null,\n ),\n ),\n h(\n 'button',\n {\n style: { ...STYLE.button, fontSize: '0.8em' },\n disabled: !editable,\n title: editable ? t('addKeyHint') : reason,\n onClick: () =>\n onChange([\n ...rows,\n {\n key: '',\n text: '',\n masked: false,\n fromCredentials: false,\n replaced: false,\n added: true,\n },\n ]),\n },\n t('addKey'),\n ),\n ),\n )\n}\n\n/** One row of a key/value list, replaced by key change or a typed value. */\nfunction replaceRow(\n rows: readonly FieldDraft[],\n index: number,\n patch: Partial<FieldDraft>,\n): FieldDraft[] {\n return rows.map((row, at) => (at === index ? { ...row, ...patch } : row))\n}\n\n/** The JSON pane's lines, coloured by side of the change. */\n/**\n * The reason a disabled control carries: the host's payload resolved through\n * the host namespace (a known code translates; an unknown one falls back to\n * the payload's own English, never the raw code), or the page's fallback when\n * the host reported no reason at all.\n */\nfunction blockedReason(row: ServerRow, t: Translate, hostT?: Translate | undefined): string {\n if (row.writeBlockedReason === undefined) return t('writeBlockedUnknown')\n return resolveHost(hostT ?? hostTranslate(undefined), row.blockedCode, row.blockedParams, row.writeBlockedReason)\n}\n\n/** `true` when the row's declaring document may be rewritten at all. */\nfunction writable(row: ServerRow): boolean {\n return row.writeScope !== undefined && row.writeScope !== 'readonly'\n}\n\n// ── the page ──────────────────────────────────────────────────────────────────\n\n/**\n * Everything the page renders, as plain props — the tests drive this directly.\n *\n * The editor props ride along from {@link EditorProps}: the shell owns the draft\n * and the confirmation state, the page is a function of them.\n */\nexport interface SettingsPageProps extends Omit<EditorProps, 'project' | 'row'> {\n /** Host snapshot, or undefined before the first poll lands. */\n snapshot: McpSnapshot | undefined\n /** Last fetch failure, when the host did not answer. */\n error: string | undefined\n /** True while a host action is in flight. */\n busy: boolean\n view: SettingsView\n onView: (view: SettingsView) => void\n /** Which page of this plugin's own settings page is open. */\n page: SettingsPageKey\n onPage: (page: SettingsPageKey) => void\n /** Selected project root; a stale value falls back to the first project. */\n selectedRoot: string | undefined\n onSelectProject: (projectRoot: string) => void\n /** Selected server name; opens the split editor. */\n selectedServer: string | undefined\n onSync: () => void\n /** Retry every failed mount of the selected project. */\n onRetry: () => void\n /** `true` while the table view also shows the snapshot's own JSON. */\n json: boolean\n onJson: (next: boolean) => void\n /** Switch one project's mode; written straight through to the host. */\n onMode: (projectRoot: string, mode: ToolMode) => void\n /** Roots with a mode write in flight. */\n modePending: ReadonlySet<string>\n /** Last refusal of a mode write, when the host did not take it. */\n modeError: string | undefined\n /** Wire companions of `modeError`, when the host coded the refusal (F-48). */\n modeErrorCode?: string | undefined\n /** Flat params of `modeErrorCode`. */\n modeErrorParams?: Record<string, string> | undefined\n /** Pin or unpin one tool of one project; the host stores it at once. */\n onPin?: ((projectRoot: string, tool: string, pinned: boolean) => void) | undefined\n /** Tool names with a pin write in flight. */\n pinPending?: ReadonlySet<string> | undefined\n /** Last refusal of a pin write, when the host did not take it. */\n pinError?: string | undefined\n /** Wire companions of `pinError`, when the host coded the refusal (F-48). */\n pinErrorCode?: string | undefined\n /** Flat params of `pinErrorCode`. */\n pinErrorParams?: Record<string, string> | undefined\n /** Choose which declaration of one contested name the project shows. */\n onChoice?: ((projectRoot: string, server: string, choice: ConflictChoice) => void) | undefined\n /** Contested names with a choice write in flight, per `projectRoot` + name. */\n choicePending?: ReadonlySet<string> | undefined\n /** Last refusal of a choice write, when the host did not take it. */\n choiceError?: string | undefined\n /** Wire companions of `choiceError`, when the host coded the refusal (F-48). */\n choiceErrorCode?: string | undefined\n /** Flat params of `choiceErrorCode`. */\n choiceErrorParams?: Record<string, string> | undefined\n}\n\n/**\n * The registered component: wire the host poll, the remembered view and the\n * editor's own state into the pure page. Kept thin on purpose — everything below\n * this line is a plain function of its props, which is what the no-DOM tests\n * exercise.\n */\nexport function SettingsTab(props: SettingsTabProps): ReactNode {\n const t = translateOf(props.t)\n const { snapshot, error, busy, run, reload } = useSnapshot(true, DEFAULT_REFRESH_MS)\n const [view, setView] = useState<SettingsView>(() => settingsViewOf())\n const [page, setPage] = useState<SettingsPageKey>(DEFAULT_SETTINGS_PAGE)\n const [selectedRoot, setSelectedRoot] = useState<string | undefined>(undefined)\n const [selectedServer, setSelectedServer] = useState<string | undefined>(undefined)\n const [modePending, setModePending] = useState<ReadonlySet<string>>(() => new Set())\n // Each refusal is the host's whole answer — prose plus the F-48 wire code\n // and its params — so the render site resolves the coded message through\n // the host seat and an old host's prose renders exactly as before.\n const [modeRefusal, setModeRefusal] = useState<PolicyRefusal | undefined>(undefined)\n // The other half of the policy: one row of the tool list disables while its own\n // pin is in flight, and the host's refusal is shown rather than reverted.\n const [pinPending, setPinPending] = useState<ReadonlySet<string>>(() => new Set())\n const [pinRefusal, setPinRefusal] = useState<PolicyRefusal | undefined>(undefined)\n // The durable answer to a name two declarations fight over: which of them the\n // project shows. One card disables while its own write is in flight.\n const [choicePending, setChoicePending] = useState<ReadonlySet<string>>(() => new Set())\n const [choiceRefusal, setChoiceRefusal] = useState<PolicyRefusal | undefined>(undefined)\n // The editor's own state: the draft the user is building, the confirmation\n // step, the consent a global write needs, and the last answer from the host.\n const [stored, setStored] = useState<EntryDraft | undefined>(undefined)\n /**\n * The JSON pane's parse error, held here rather than in the pane.\n *\n * The pane owns the text, but Save is decided here: a document must never be\n * written from text the pane could not read, so a failed parse blocks the\n * confirmation until the text parses again.\n */\n const [jsonError, setJsonError] = useState<string | undefined>(undefined)\n const [confirming, setConfirming] = useState(false)\n const [consent, setConsent] = useState(false)\n const [saveState, setSaveState] = useState<SaveAnswer | undefined>(undefined)\n const [saving, setSaving] = useState(false)\n // The one place the media query is read; the page below takes the flag as a prop.\n const narrow = useNarrowSettings()\n const resetEditor = useCallback((): void => {\n setStored(undefined)\n setConfirming(false)\n setConsent(false)\n setSaveState(undefined)\n setSaving(false)\n setJsonError(undefined)\n }, [])\n const chooseView = useCallback((next: SettingsView): void => {\n setView(next)\n persistSettingsView(next)\n }, [])\n const chooseProject = useCallback(\n (projectRoot: string): void => {\n setSelectedRoot(projectRoot)\n setSelectedServer(undefined)\n resetEditor()\n },\n [resetEditor],\n )\n const chooseServer = useCallback(\n (name: string | undefined): void => {\n setSelectedServer(name)\n resetEditor()\n },\n [resetEditor],\n )\n // Both operator actions act on the selected project and ask for the whole\n // snapshot back: this page lists every project, so a narrowed answer would\n // empty it, while the action itself must not start a server for a project the\n // user is not looking at. The toolbar's button and every broken row's own\n // `Retry` send exactly the same request.\n const sync = useCallback((): void => {\n void run(\n ROUTE_ACTIONS.sync,\n operatorBody(selectedProject(snapshot, selectedRoot)?.projectRoot, true),\n )\n }, [snapshot, selectedRoot, run])\n const retry = useCallback((): void => {\n void run(\n ROUTE_ACTIONS.retry,\n operatorBody(selectedProject(snapshot, selectedRoot)?.projectRoot, true),\n )\n }, [snapshot, selectedRoot, run])\n const [json, setJson] = useState(false)\n const chooseJson = useCallback((next: boolean): void => setJson(next), [])\n /**\n * Write one project's mode. The switch is not a draft: the host reads the mode\n * on each request assembly, so the answer of this call is the only source of\n * truth and a refusal is shown rather than silently reverted.\n */\n const onMode = useCallback(\n (projectRoot: string, mode: ToolMode): void => {\n setModeRefusal(undefined)\n void requestMode(policyBody(projectRoot, mode), {\n onStart: (root) => setModePending((previous) => new Set(previous).add(root)),\n onSettled: (root) =>\n setModePending((previous) => {\n const next = new Set(previous)\n next.delete(root)\n return next\n }),\n onRefused: (message, messageCode, messageParams) => setModeRefusal({ message, messageCode, messageParams }),\n })\n },\n [],\n )\n const onPin = useCallback((projectRoot: string, tool: string, pinned: boolean): void => {\n setPinRefusal(undefined)\n void requestPin(pinBody(projectRoot, tool, pinned), {\n onStart: (name) => setPinPending((previous) => new Set(previous).add(name)),\n onSettled: (name) =>\n setPinPending((previous) => {\n const next = new Set(previous)\n next.delete(name)\n return next\n }),\n onRefused: (message, messageCode, messageParams) => setPinRefusal({ message, messageCode, messageParams }),\n })\n }, [])\n const onChoice = useCallback(\n (projectRoot: string, server: string, choice: ConflictChoice): void => {\n setChoiceRefusal(undefined)\n const key = choiceKey(projectRoot, server)\n const settle = (): void =>\n setChoicePending((previous) => {\n const next = new Set(previous)\n next.delete(key)\n return next\n })\n setChoicePending((previous) => new Set(previous).add(key))\n void postConflict(conflictBody(projectRoot, server, choice))\n .then((answer) => {\n if (!answer.ok) {\n setChoiceRefusal({\n message: answer.message,\n messageCode: answer.messageCode,\n messageParams: answer.messageParams,\n })\n }\n })\n .finally(settle)\n },\n [],\n )\n const project = selectedProject(snapshot, selectedRoot)\n const row = project?.rows.find((entry) => entry.name === selectedServer)\n const draft = row === undefined ? undefined : activeDraft(row, stored)\n const onDraft = useCallback((next: EntryDraft): void => {\n setStored(next)\n // The form re-derives the pane's text from this draft, so whatever the pane\n // failed to parse is no longer what is on screen.\n setJsonError(undefined)\n }, [])\n const onJsonEdit = useCallback(\n (next: EntryDraft | undefined, error: string | undefined): void => {\n setJsonError(error)\n if (next !== undefined) setStored(next)\n },\n [],\n )\n const onDiscard = useCallback((): void => {\n setStored(undefined)\n setConfirming(false)\n setSaveState(undefined)\n }, [])\n const onAskSave = useCallback((): void => {\n setSaveState(undefined)\n setConfirming(true)\n }, [])\n const onCancelSave = useCallback((): void => setConfirming(false), [])\n const onConsent = useCallback((next: boolean): void => setConsent(next), [])\n const onReRead = useCallback((): void => {\n setStored(undefined)\n setConfirming(false)\n setSaveState(undefined)\n void reload()\n }, [reload])\n const onConfirmSave = useCallback((): void => {\n if (project === undefined || row === undefined || draft === undefined) return\n // Belt and braces with the disabled confirm button: a global write without\n // the explicit consent is never sent.\n if (row.writeScope === 'global' && !consent) return\n const request = saveRequestOf(project, row, draftEntry(draft), consent)\n if (request === undefined) return\n setSaving(true)\n void postSave(request).then((answer) => {\n setSaving(false)\n setConfirming(false)\n setSaveState(answer)\n if (!answer.ok) return\n // The write landed: drop the draft and pull the fresh snapshot the host\n // re-read after the save.\n setStored(undefined)\n setConsent(false)\n void reload()\n })\n }, [project, row, draft, consent, run, reload])\n return h(SettingsPage, {\n snapshot,\n error,\n busy,\n view,\n onView: chooseView,\n page,\n onPage: setPage,\n onMode,\n modePending,\n modeError: modeRefusal?.message,\n modeErrorCode: modeRefusal?.messageCode,\n modeErrorParams: modeRefusal?.messageParams,\n onPin,\n pinPending,\n pinError: pinRefusal?.message,\n pinErrorCode: pinRefusal?.messageCode,\n pinErrorParams: pinRefusal?.messageParams,\n onChoice,\n choicePending,\n choiceError: choiceRefusal?.message,\n choiceErrorCode: choiceRefusal?.messageCode,\n choiceErrorParams: choiceRefusal?.messageParams,\n selectedRoot,\n onSelectProject: chooseProject,\n selectedServer,\n onSelectServer: chooseServer,\n onSync: sync,\n onRetry: retry,\n json,\n onJson: chooseJson,\n draft,\n confirming,\n consent,\n saveState,\n saving,\n onDraft,\n onJsonEdit,\n jsonError,\n onDiscard,\n onAskSave,\n onCancelSave,\n onConsent,\n onConfirmSave,\n onReRead,\n narrow,\n t,\n hostT: props.hostT,\n })\n}\n\n/**\n * The page: toolbar, then one state body. Exported so every state — before the\n * first poll, no live project, no declared server, a failed fetch — is asserted\n * without a DOM.\n * @param props - see {@link SettingsPageProps}.\n * @returns the page element tree.\n */\nexport function SettingsPage(props: SettingsPageProps): ReactNode {\n const t = props.t\n const projects = props.snapshot?.projects ?? []\n return h(\n 'div',\n { style: STYLE.root },\n h(\n 'div',\n { style: STYLE.bar },\n projects.length === 0\n ? null\n : h(ProjectSelector, {\n projects,\n selected: props.selectedRoot,\n onSelect: props.onSelectProject,\n t,\n }),\n projects.length === 0\n ? null\n : h('span', { style: STYLE.muted }, liveProjectCount(projects.length, t)),\n h('span', { style: { flex: 1 } }),\n h(SettingsPageSwitch, { page: props.page, onChange: props.onPage, t }),\n // The view switch, the JSON reading and the way out of it belong to the\n // server page: `Tools` is one policy form, not a second way to read the\n // same documents, so it keeps the toolbar it shares and drops the rest.\n props.page === 'tools' ? null : h(ViewSwitch, { view: props.view, onChange: props.onView, t }),\n props.page === 'tools' || props.view !== 'table'\n ? null\n : h(\n 'button',\n {\n style: STYLE.button,\n 'aria-pressed': props.json,\n title: props.json ? t('hideJson') : t('showJson'),\n onClick: () => props.onJson(!props.json),\n },\n props.json ? t('hideJson') : t('showJson'),\n ),\n h(\n 'button',\n {\n style: STYLE.button,\n disabled: props.busy,\n title: t('syncHint'),\n onClick: props.onSync,\n },\n t('sync'),\n ),\n ),\n // A poll that fails after data has landed keeps the page: the rows stay, and\n // the failure is reported above them instead of replacing them.\n props.error === undefined || props.snapshot === undefined\n ? null\n : h(\n 'div',\n { style: STYLE.note },\n `${t('hostUnavailable')} `,\n h('span', { style: STYLE.hint }, props.error),\n ),\n h('div', { style: STYLE.body }, settingsBody(props)),\n )\n}\n\n/**\n * The body below the toolbar: exactly one branch per situation, and every empty\n * branch names what is missing instead of showing an empty box.\n * @param props - see {@link SettingsPageProps}.\n * @returns the element tree below the toolbar.\n */\nexport function settingsBody(props: SettingsPageProps): ReactNode {\n const t = props.t\n // The error state only when there is nothing to show; a later failure is\n // reported by the page above the rows it kept.\n if (props.error !== undefined && props.snapshot === undefined) {\n return h(\n 'div',\n { style: STYLE.errorState },\n h('div', { style: STYLE.stateTitle }, t('hostUnavailable')),\n h('div', { style: STYLE.hint }, t('hostUnavailableHint', { route: `${ROUTE_PREFIX}/snapshot` })),\n h('div', { style: STYLE.hint }, props.error),\n )\n }\n if (props.snapshot === undefined) {\n return h(\n 'div',\n { style: STYLE.errorState },\n emptyState(t('loading'), t('loadingHint')),\n )\n }\n const projects = props.snapshot.projects\n if (projects.length === 0) {\n return withCodeLine(t('noSessions'), t('noSessionsHint'), readPaths(props.snapshot, t))\n }\n const project = selectedProject(props.snapshot, props.selectedRoot)\n if (project === undefined) return null\n if (props.page === 'tools') {\n return h(ToolsPage, {\n project,\n rows: projectPolicyRows(projects),\n onMode: props.onMode,\n pending: props.modePending,\n modeError: props.modeError,\n modeErrorCode: props.modeErrorCode,\n modeErrorParams: props.modeErrorParams,\n onSync: props.onSync,\n onPin: props.onPin,\n pinPending: props.pinPending,\n pinError: props.pinError,\n pinErrorCode: props.pinErrorCode,\n pinErrorParams: props.pinErrorParams,\n onChoice: props.onChoice,\n choicePending: props.choicePending,\n choiceError: props.choiceError,\n choiceErrorCode: props.choiceErrorCode,\n choiceErrorParams: props.choiceErrorParams,\n t,\n hostT: props.hostT,\n })\n }\n const row = project.rows.find((entry) => entry.name === props.selectedServer)\n if (row !== undefined) {\n return h(EditorSplit, {\n project,\n row,\n onSelectServer: props.onSelectServer,\n draft: props.draft,\n confirming: props.confirming,\n consent: props.consent,\n saveState: props.saveState,\n saving: props.saving,\n onDraft: props.onDraft,\n onJsonEdit: props.onJsonEdit,\n jsonError: props.jsonError,\n onDiscard: props.onDiscard,\n onAskSave: props.onAskSave,\n onCancelSave: props.onCancelSave,\n onConsent: props.onConsent,\n onConfirmSave: props.onConfirmSave,\n onReRead: props.onReRead,\n narrow: props.narrow,\n t,\n hostT: props.hostT,\n })\n }\n if (project.rows.length === 0) {\n // Where to declare one: this project's own documents, as configured. An\n // empty list is the honest answer \"nowhere\", not a file name this bundle\n // would otherwise invent.\n const documents = (project.files ?? [])\n .filter((file) => file.scope === 'project')\n .map((file) => file.path)\n return documents.length === 0\n ? emptyState(t('noServers'), t('noServersNoPath'))\n : withCodeLine(t('noServers'), t('noServersHint'), documents.join(' · '))\n }\n return props.view === 'files'\n ? h(FileCards, {\n project,\n selectedServer: props.selectedServer,\n onSelectServer: props.onSelectServer,\n t,\n hostT: props.hostT,\n })\n : h(\n 'div',\n null,\n h(ServerTable, {\n project,\n selectedServer: props.selectedServer,\n onSelectServer: props.onSelectServer,\n onRetry: props.onRetry,\n busy: props.busy,\n t,\n hostT: props.hostT,\n }),\n // The table keeps the failure banners it renders; the JSON reading is an\n // extra, below them, and only while the toolbar's toggle is on.\n props.json ? h(JsonPreview, { project, t }) : null,\n )\n}\n\n/** A centred empty state followed by the path or command that fixes it. */\nfunction withCodeLine(title: string, hint: string, code: string): ReactNode {\n return h('div', null, emptyState(title, hint), h('div', { style: STYLE.codeLine }, code))\n}\n\n/** The `Table` / `By files` switch. Not a write: it only changes this page. */\nexport function ViewSwitch(props: {\n view: SettingsView\n onChange: (view: SettingsView) => void\n t: Translate\n}): ReactNode {\n const item = (value: SettingsView, label: string): ReactNode =>\n h(\n 'button',\n {\n key: value,\n style:\n value === props.view\n ? { ...STYLE.segmentItem, ...STYLE.segmentItemActive }\n : STYLE.segmentItem,\n 'aria-pressed': value === props.view,\n onClick: () => props.onChange(value),\n },\n label,\n )\n return h(\n 'div',\n { style: STYLE.segment },\n item('table', props.t('viewTable')),\n item('files', props.t('viewFiles')),\n )\n}\n\n/**\n * Project picker. The only seat on this page where another project is visible,\n * and it only ever selects which single project's rows the body renders.\n */\nexport function ProjectSelector(props: {\n projects: readonly ProjectSnapshot[]\n selected: string | undefined\n onSelect: (projectRoot: string) => void\n t: Translate\n}): ReactNode {\n const value =\n props.selected !== undefined &&\n props.projects.some((project) => project.projectRoot === props.selected)\n ? props.selected\n : (props.projects[0]?.projectRoot ?? '')\n return h(\n 'label',\n { style: STYLE.muted },\n `${props.t('project')}: `,\n h(\n 'select',\n {\n style: STYLE.select,\n value,\n title: value,\n onChange: (event: { target: { value: string } }) => props.onSelect(event.target.value),\n },\n props.projects.map((project) =>\n h(\n 'option',\n { key: project.projectRoot, value: project.projectRoot },\n basename(project.projectRoot),\n ),\n ),\n ),\n )\n}\n\n/** The dense overview: one row per declared server of the selected project. */\n/**\n * The table's status cell: the host's word for the row, in the colour of that\n * status, and — for a quiet row the host counted — how long it has been unused.\n *\n * The figure comes from the host's own `usage[server].lastUsedAt`; a row the\n * counters never recorded has nothing to print, and the cell stays the word it\n * has always been rather than saying `idle 0m`.\n */\nfunction statusCell(row: ServerRow, project: ProjectSnapshot, t: Translate): ReactNode {\n const idle = idleNote(row.status, project.usage?.[row.name]?.lastUsedAt, t)\n return h(\n 'td',\n { style: { ...STYLE.td, color: STATUS_COLOR[row.status] } },\n t(STATUS_KEYS[row.status]),\n idle === undefined ? null : h('span', { style: STYLE.hint }, ` ${idle}`),\n )\n}\n\nexport function ServerTable(props: {\n project: ProjectSnapshot\n selectedServer?: string | undefined\n onSelectServer: (name: string | undefined) => void\n /** Retry the project's failed mounts; absent while nothing can be written. */\n onRetry?: (() => void) | undefined\n /** `true` while a host action is in flight, so the row buttons stay still. */\n busy?: boolean | undefined\n t: Translate\n /** The host namespace's seat, for the rows' coded blocked reasons. */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = props.t\n return h(\n 'div',\n { style: STYLE.tableScroll },\n h(\n 'table',\n { style: STYLE.table },\n h(\n 'thead',\n null,\n h(\n 'tr',\n null,\n h('th', { style: STYLE.th }, t('server')),\n h('th', { style: STYLE.th }, t('transport')),\n h('th', { style: STYLE.th }, t('status')),\n h('th', { style: STYLE.th }, t('source')),\n h('th', { style: STYLE.th }, t('on')),\n h('th', { style: STYLE.th }, ''),\n ),\n ),\n h(\n 'tbody',\n null,\n props.project.rows.map((row) =>\n h(\n 'tr',\n { key: row.name },\n h(\n 'td',\n { style: STYLE.td },\n statusDot(row.status, t),\n ' ',\n serverButton(row, row.name === props.selectedServer, props.onSelectServer, t, props.hostT),\n ),\n h('td', { style: STYLE.td }, h('span', { style: STYLE.muted }, row.transport ?? '—')),\n statusCell(row, props.project, t),\n h('td', { style: STYLE.td }, sourceLabel(row, props.project, t)),\n h('td', { style: STYLE.td }, enabledSwitch(row, t, props.hostT)),\n h('td', { style: STYLE.td }, rowAction(row, props, t)),\n ),\n ),\n ),\n ),\n ...props.project.rows\n .filter((row) => row.status === 'error' && row.detail !== undefined)\n .map((row) =>\n h(\n 'div',\n { style: STYLE.note, key: `detail-${row.name}` },\n h('strong', null, row.name),\n // The row passed the filter, so its detail is present; the seat\n // translates it when the host sent the wire code (F-48).\n ` — ${rowDetail(row, props.hostT) ?? ''}`,\n ),\n ),\n )\n}\n\n/**\n * The table's last cell: the one action the row has.\n *\n * A broken row offers a real `Retry` — the host route is project-scoped, so it\n * sends the request the toolbar's own button sends. Every other row offers `…`,\n * which opens the entry in the split editor: on this surface a row is read-only,\n * so the only thing left to do with it is go and edit it. Both labels are keys;\n * neither control writes anything itself.\n * @param row - the server row.\n * @param props - the table's own props, for the action and the busy flag.\n * @param t - translate seat.\n * @returns the cell's content.\n */\nfunction rowAction(\n row: ServerRow,\n props: {\n onSelectServer: (name: string | undefined) => void\n onRetry?: (() => void) | undefined\n busy?: boolean | undefined\n },\n t: Translate,\n): ReactNode {\n if (row.status === 'error' && props.onRetry !== undefined) {\n return h(\n 'button',\n {\n style: STYLE.button,\n title: t('retryHint'),\n disabled: props.busy === true,\n onClick: props.onRetry,\n },\n t('retry'),\n )\n }\n return h(\n 'button',\n {\n style: STYLE.button,\n title: t('rowActionsHint'),\n onClick: () => props.onSelectServer(row.name),\n },\n t('rowActionsMore'),\n )\n}\n\n/**\n * The snapshot's own reading of a project's entries, as JSON.\n *\n * Built from the parsed entries the host published, not from the document on\n * disk: the page never reads a file, and this preview must not imply it does. A\n * row the host did not parse has no entry and is left out rather than invented.\n * @param project - the selected project.\n * @returns the two-space JSON body the preview prints.\n */\nexport function projectJson(project: ProjectSnapshot): string {\n const servers: Record<string, unknown> = {}\n for (const row of project.rows) {\n if (row.entry === undefined) continue\n servers[row.name] = entryBody(row.entry)\n }\n return JSON.stringify({ mcpServers: servers }, null, 2)\n}\n\n/**\n * The table view's optional JSON pane: the snapshot's entries, read-only.\n *\n * @param props - the project and the translate seat.\n * @returns the titled code block.\n */\nexport function JsonPreview(props: { project: ProjectSnapshot; t: Translate }): ReactNode {\n return h(\n 'div',\n null,\n h('div', { style: STYLE.paneHead }, props.t('jsonPreview')),\n h('div', { style: STYLE.hint }, props.t('jsonPreviewHint')),\n h('pre', { style: STYLE.json }, projectJson(props.project)),\n )\n}\n\n/** The \"By files\" overview: one card per declaring document, in priority order. */\nexport function FileCards(props: {\n project: ProjectSnapshot\n selectedServer?: string | undefined\n onSelectServer: (name: string | undefined) => void\n t: Translate\n /** The host namespace's seat, for the rows' coded blocked reasons. */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = props.t\n return h(\n 'div',\n null,\n fileGroups(props.project).map((group) =>\n h(\n 'div',\n { key: group.source, style: STYLE.card },\n h(\n 'div',\n { style: STYLE.cardHead },\n h(\n 'span',\n { style: STYLE.cardPath },\n group.source === '' ? t('documentUnknown') : group.label,\n ),\n group.priority?.global === true ? h('span', { style: STYLE.tag }, t('global')) : null,\n group.priority === undefined\n ? null\n : h('span', { style: STYLE.tag }, t('priority', { tier: group.priority.tier, total: group.priority.total })),\n h('span', { style: { flex: 1 } }),\n h('span', { style: STYLE.muted }, serverCount(group.rows.length, t)),\n ),\n group.rows.map((row) =>\n h(\n 'div',\n { key: row.name, style: STYLE.row },\n statusDot(row.status, t),\n serverButton(row, row.name === props.selectedServer, props.onSelectServer, t, props.hostT),\n row.transport === undefined\n ? null\n : h('span', { style: STYLE.tag }, row.transport),\n // The status carries the row's tone here too: the document view is\n // the same rows as the table, read by document instead of by column.\n h('span', { style: { ...STYLE.muted, color: STATUS_COLOR[row.status] } }, t(STATUS_KEYS[row.status])),\n h('span', { style: { flex: 1 } }),\n enabledSwitch(row, t, props.hostT),\n ),\n ),\n group.overrides.map((note, index) =>\n h(\n 'div',\n { key: `${note.name}#${index}`, style: STYLE.overrideNote },\n note.from === undefined\n ? t('overrideUnpinned', { name: note.name })\n : t('overrideFrom', { name: note.name, from: note.from }),\n ),\n ),\n ),\n ),\n )\n}\n\n/** Everything the split editor renders, as plain props. */\nexport interface EditorProps {\n /** Project the row belongs to; its root rides in the save request. */\n project: ProjectSnapshot\n /** The row being edited. */\n row: ServerRow\n /** Called with the server to open, or undefined to go back to the overview. */\n onSelectServer: (name: string | undefined) => void\n /**\n * The open row's form state, already resolved through {@link activeDraft} by\n * the shell: the stored draft while it still matches the row's revision, a\n * fresh one otherwise. Undefined when the host did not parse the entry.\n */\n draft: EntryDraft | undefined\n /** True while the confirmation step is open. */\n confirming: boolean\n /** Consent checkbox state; only `global` rows read it. */\n consent: boolean\n /** Last save answer, when one has landed. */\n saveState: SaveAnswer | undefined\n /** True while the save request is in flight. */\n saving: boolean\n /** The JSON pane's parse error, when the last edit did not parse. */\n jsonError?: string | undefined\n /** Report one JSON edit: a parsed draft, or the reason it did not parse. */\n onJsonEdit?: ((draft: EntryDraft | undefined, error: string | undefined) => void) | undefined\n onDraft: (draft: EntryDraft) => void\n onDiscard: () => void\n /** Open the confirmation step; writes nothing on its own. */\n onAskSave: () => void\n onCancelSave: () => void\n onConsent: (consent: boolean) => void\n /** Write the document: the only control that reaches the host. */\n onConfirmSave: () => void\n /** Refetch the snapshot after a `conflict`. */\n onReRead: () => void\n /**\n * Stack the three panes instead of laying them in a row. The shell passes\n * {@link useNarrowSettings}'s flag; the tests pass it by hand, which is why\n * the editor itself never reads the media query. Defaults to `false`.\n */\n narrow?: boolean | undefined\n t: Translate\n /**\n * The `projectMcp.host` seat for the host's coded messages (the blocked\n * reason is the first channel). Optional: absent outside a shell and in\n * tests, where the payload's English message renders exactly as before.\n */\n hostT?: Translate | undefined\n}\n\n/**\n * One pane's rule for the current layout.\n * @param base - the pane's side-by-side rule.\n * @param stacked - the overrides for the stacked layout.\n * @param narrow - `true` while the panes render stacked.\n * @returns the style object the pane renders with.\n */\nfunction paneStyle(\n base: CSSProperties,\n stacked: CSSProperties,\n narrow: boolean,\n): CSSProperties {\n return narrow ? { ...base, ...stacked } : base\n}\n\n/**\n * The entry as JSON, editable: the pane under the form.\n *\n * One value, two views: the text is what the pane last showed or the user typed,\n * and every keystroke is parsed back into the shell's draft through\n * {@link draftFromJson}. A parse that fails leaves the draft alone and reports\n * the reason upward — the shell blocks Save on it, so a document can never be\n * written from text the pane could not read. The text re-syncs only when the\n * draft changes from somewhere else (the form above, another server): the draft\n * the pane itself produced is the one it already shows.\n * @param props - the draft, the write scope, the pane's own label and the\n * shell's error line.\n * @returns the editable body; its head belongs to the editor, which reads\n * whether the body differs from the snapshot.\n */\nexport function JsonPane(props: {\n /** The draft the form and the pane both edit. */\n draft: EntryDraft\n /** `true` while the declaring document may be written. */\n editable: boolean\n /** Why it may not be written, when it may not. */\n reason: string\n /** The pane head's label: the document, and whether it differs from the snapshot. */\n label: string\n /** The parse error the shell holds, when the last edit did not parse. */\n error: string | undefined\n /** Report one edit: a parsed draft, or the reason it did not parse. */\n onJson?: ((draft: EntryDraft | undefined, error: string | undefined) => void) | undefined\n t: Translate\n}): ReactNode {\n const t = props.t\n const [text, setText] = useState(() => jsonBodyOf(props.draft))\n /** The draft this pane produced last, so its own echo does not overwrite the text. */\n const adopted = useRef<EntryDraft | undefined>(props.draft)\n useEffect(() => {\n if (props.draft === adopted.current) return\n adopted.current = props.draft\n setText(jsonBodyOf(props.draft))\n }, [props.draft])\n const change = (next: string): void => {\n setText(next)\n const answer = draftFromJson(next, props.draft)\n if ('error' in answer) {\n props.onJson?.(undefined, answer.error)\n return\n }\n adopted.current = answer.draft\n props.onJson?.(answer.draft, undefined)\n }\n return h(\n 'div',\n null,\n h('textarea', {\n style: props.editable ? STYLE.jsonArea : { ...STYLE.jsonArea, opacity: 0.75 },\n value: text,\n readOnly: !props.editable,\n spellCheck: false,\n 'aria-label': props.label,\n // The same marking the form's controls carry: this is a write control of\n // the document, and on a tier that may not be written it is disabled with\n // the host's own reason as its title.\n 'data-write': true,\n title: props.editable ? t('jsonEditHint') : props.reason,\n ...(props.editable ? {} : { disabled: true }),\n onChange: (event: { target: { value: string } }) => change(event.target.value),\n }),\n props.error === undefined\n ? null\n : h('div', { style: STYLE.noteError }, t('jsonInvalid', { reason: props.error })),\n )\n}\n\n/**\n * The split editor: the project's servers on the left, and the entry on the\n * right — its fields, and the document body under them.\n *\n * One entry, two editors: the form's fields and the JSON pane both write the same\n * draft, and the pane parses every keystroke back into it. That is the one thing\n * the pane cannot delegate: text the pane cannot read leaves the draft alone and\n * blocks the write (the shell holds the reason), so a document is never saved\n * from something nobody parsed. A `readonly` tier keeps every control disabled\n * with `writeBlockedReason`. Nothing reaches the host before the confirmation\n * step: Save only opens it, and the confirm button inside it is the write. The\n * list and the entry column share the width they are given until `narrow` says\n * there is too little of it, and then everything stacks.\n */\nexport function EditorSplit(props: EditorProps): ReactNode {\n const t = props.t\n const narrow = props.narrow === true\n const { project, row } = props\n const { draft } = props\n const declared = row.entry\n const edited = draft === undefined ? undefined : draftEntry(draft)\n const dirty = declared !== undefined && edited !== undefined && entryDirty(declared, edited)\n const parsed = draft !== undefined && edited !== undefined\n const editable = parsed && writable(row)\n const reason = blockedReason(row, t, props.hostT)\n const timeoutBad = draft !== undefined && timeoutInvalid(draft.connectTimeoutMs)\n const request = edited === undefined ? undefined : saveRequestOf(project, row, edited, props.consent)\n const jsonBad = props.jsonError !== undefined\n const saveEnabled =\n !props.saving && editable && dirty && !timeoutBad && !jsonBad && request !== undefined\n // The Save control is never silently dead: whatever disables it is its title.\n const saveReason = ((): string => {\n if (!parsed) return t('entryUnavailable')\n if (jsonBad) return t('saveJsonInvalid')\n if (!writable(row)) return reason\n if (timeoutBad) return t('saveTimeoutInvalid')\n if (request === undefined) return t('saveUnavailable')\n if (props.saving) return t('saving')\n if (!dirty) return t('saveNoChange')\n return t('saveHint')\n })()\n const global = row.writeScope === 'global'\n const confirmReady = !props.saving && (!global || props.consent)\n const source = row.source\n const label = source === undefined ? t('documentUnknown') : documentLabel(source, project.projectRoot)\n const backup = source === undefined ? undefined : `${source}.bak`\n const backupLabel =\n backup === undefined ? t('documentUnknown') : documentLabel(backup, project.projectRoot)\n const state = !parsed\n ? t('entryUnavailable')\n : writable(row)\n ? t('editableNote', { document: label, backup: backupLabel })\n : t('writeBlocked', { reason })\n return h(\n 'div',\n null,\n h(\n 'div',\n { style: STYLE.splitBar },\n h(\n 'button',\n {\n style: STYLE.button,\n title: t('backHint'),\n onClick: () => props.onSelectServer(undefined),\n },\n `‹ ${t('back')}`,\n ),\n h('span', { style: STYLE.hint, title: source ?? project.projectRoot }, state),\n ),\n h(\n 'div',\n { style: paneStyle(STYLE.split, STYLE.splitNarrow, narrow) },\n h(\n 'div',\n {\n style: paneStyle(STYLE.paneList, STYLE.paneListNarrow, narrow),\n 'data-pane': 'list',\n },\n h('div', { style: STYLE.paneHead }, t('servers')),\n project.rows.map((entry) =>\n h(\n 'div',\n {\n key: entry.name,\n style:\n entry.name === row.name\n ? { ...STYLE.listItem, ...STYLE.listItemActive }\n : STYLE.listItem,\n },\n statusDot(entry.status, t),\n serverButton(entry, entry.name === row.name, props.onSelectServer, t, props.hostT),\n ),\n ),\n ),\n h(\n 'div',\n { style: paneStyle(STYLE.paneColumn, STYLE.paneColumnNarrow, narrow) },\n h(\n 'div',\n {\n style: paneStyle(STYLE.paneForm, STYLE.paneFormNarrow, narrow),\n 'data-pane': 'form',\n },\n // The form's own head: the pane below it holds the same entry in the\n // shape the document keeps, and the list is every declared server.\n h('div', { style: STYLE.paneHead }, t('paneEntry')),\n hostField(t('name'), row.name, t('nameReason')),\n ...(draft === undefined\n ? []\n : draftFields(draft, declared, editable, reason, t, props.onDraft)),\n hostField(t('status'), t(STATUS_KEYS[row.status]), t('statusReason')),\n hostField(t('source'), source ?? t('documentUnknown'), t('sourceReason')),\n hostDetailField(t('detail'), rowDetail(row, props.hostT) ?? '—', t('detailReason')),\n ),\n h(\n 'div',\n {\n style: paneStyle(STYLE.paneJson, STYLE.paneJsonNarrow, narrow),\n 'data-pane': 'json',\n },\n h(\n 'div',\n { style: STYLE.paneHead },\n draft === undefined || edited === undefined\n ? label\n : `${label} · ${dirty ? t('jsonDiff') : t('jsonClean')}`,\n ),\n draft === undefined || declared === undefined || edited === undefined\n ? h('div', { style: STYLE.json }, t('jsonUnavailable'))\n : h(JsonPane, {\n draft,\n editable,\n reason,\n label,\n error: props.jsonError,\n onJson: props.onJsonEdit,\n t,\n }),\n ),\n ),\n ),\n h(\n 'div',\n null,\n h(\n 'div',\n { style: STYLE.splitFooter },\n formControl(\n 'button',\n { style: STYLE.buttonPrimary, onClick: props.onAskSave },\n saveEnabled,\n saveReason,\n t('save'),\n ),\n h(\n 'button',\n {\n style: STYLE.button,\n disabled: !dirty,\n title: dirty ? t('discardHint') : t('discardReason'),\n onClick: props.onDiscard,\n },\n t('discard'),\n ),\n dirty ? h('span', { style: STYLE.tag }, t('unsaved')) : null,\n h('span', { style: { flex: 1 } }),\n h(\n 'span',\n {\n style: STYLE.hint,\n title: source ?? project.projectRoot,\n },\n t(writable(row) ? 'footerWrite' : 'footerReadonly', { document: label }),\n ),\n ),\n props.confirming\n ? confirmation({\n label,\n backupLabel,\n server: row.name,\n global,\n consent: props.consent,\n ready: confirmReady,\n saving: props.saving,\n t,\n onConsent: props.onConsent,\n onConfirm: props.onConfirmSave,\n onCancel: props.onCancelSave,\n })\n : null,\n props.saveState === undefined ? null : noticeBlock(props.saveState, t, props.onReRead, props.hostT),\n ),\n )\n}\n\n/** The entry's own fields, for the transport the draft currently declares. */\nfunction draftFields(\n draft: EntryDraft,\n declared: EntrySnapshot | undefined,\n editable: boolean,\n reason: string,\n t: Translate,\n onDraft: (draft: EntryDraft) => void,\n): ReactNode[] {\n const clearable = (value: string): string | undefined => (value === '' ? undefined : value)\n const transport = transportField(draft, editable, reason, t, onDraft)\n if (draft.transport === 'streamable-http') {\n return [\n transport,\n textField(t('urlField'), draft.url ?? '', editable, reason, (value) =>\n onDraft({ ...draft, url: clearable(value) }),\n ),\n fieldList(t('headersField'), draft.headers, editable, reason, t, t('headersHint'), (headers) =>\n onDraft({ ...draft, headers }),\n ),\n ...commonFields(draft, declared, editable, reason, t, onDraft),\n ]\n }\n return [\n transport,\n textField(t('commandField'), draft.command ?? '', editable, reason, (value) =>\n onDraft({ ...draft, command: clearable(value) }),\n ),\n textField(\n t('argsField'),\n (draft.args ?? []).join('\\n'),\n editable,\n reason,\n (value) => onDraft({ ...draft, args: value === '' ? undefined : value.split('\\n') }),\n t('argsHint'),\n ),\n textField(t('cwdField'), draft.cwd ?? '', editable, reason, (value) =>\n onDraft({ ...draft, cwd: clearable(value) }),\n ),\n fieldList(t('envField'), draft.env, editable, reason, t, t('envHint'), (env) =>\n onDraft({ ...draft, env }),\n ),\n ...commonFields(draft, declared, editable, reason, t, onDraft),\n ]\n}\n\n/** Fields both transports carry: `enabled` and the connect timeout. */\nfunction commonFields(\n draft: EntryDraft,\n declared: EntrySnapshot | undefined,\n editable: boolean,\n reason: string,\n t: Translate,\n onDraft: (draft: EntryDraft) => void,\n): ReactNode[] {\n const value = draft.enabled === undefined ? t('absent') : String(draft.enabled)\n return [\n h(\n 'div',\n { style: STYLE.field, key: 'enabled' },\n h('span', { style: STYLE.fieldLabel }, t('enabledField')),\n h(\n 'label',\n { style: { display: 'flex', alignItems: 'center', gap: 6 } },\n formControl(\n 'input',\n {\n type: 'checkbox',\n checked: draft.enabled !== false,\n style: STYLE.switch,\n 'aria-label': t('enabledField'),\n ...(editable\n ? {\n onChange: (event: { target: { checked: boolean } }) =>\n onDraft({\n ...draft,\n enabled: event.target.checked ? (declared?.enabled === true ? true : undefined) : false,\n }),\n }\n : {}),\n },\n editable,\n reason,\n ),\n h('span', { style: STYLE.hint }, t('enabledValue', { value })),\n ),\n ),\n textField(\n t('timeoutField'),\n draft.connectTimeoutMs,\n editable,\n reason,\n (value) => onDraft({ ...draft, connectTimeoutMs: value }),\n timeoutInvalid(draft.connectTimeoutMs) ? t('saveTimeoutInvalid') : t('timeoutHint'),\n ),\n ]\n}\n\n/** The confirmation step: what is written where, and the consent it may need. */\nfunction confirmation(props: {\n label: string\n backupLabel: string\n server: string\n global: boolean\n consent: boolean\n ready: boolean\n saving: boolean\n t: Translate\n onConsent: (consent: boolean) => void\n onConfirm: () => void\n onCancel: () => void\n}): ReactNode {\n const { t } = props\n return h(\n 'div',\n { style: STYLE.confirm },\n h('div', { style: STYLE.stateTitle }, t('confirmTitle', { document: props.label })),\n h('div', { style: STYLE.hint }, t('confirmBackup', { backup: props.backupLabel })),\n h('div', { style: STYLE.hint }, t('confirmFormat', { server: props.server })),\n props.global ? h('div', { style: STYLE.hint }, t('confirmConsent')) : null,\n props.global\n ? h(\n 'label',\n { style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: '0.85em' } },\n h('input', {\n type: 'checkbox',\n checked: props.consent,\n style: STYLE.switch,\n 'aria-label': t('consentLabel'),\n onChange: (event: { target: { checked: boolean } }) =>\n props.onConsent(event.target.checked),\n }),\n t('consentLabel'),\n )\n : null,\n h(\n 'div',\n { style: STYLE.splitFooter },\n formControl(\n 'button',\n { style: STYLE.buttonPrimary, onClick: props.onConfirm },\n props.ready,\n props.ready ? t('confirmWriteHint') : props.saving ? t('saving') : t('confirmBlocked'),\n t('confirmWrite'),\n ),\n h('button', { style: STYLE.button, onClick: props.onCancel }, t('cancel')),\n ),\n )\n}\n\n/** The sentence the last save answer gets, plus the actions it offers. */\nfunction noticeBlock(answer: SaveAnswer, t: Translate, onReRead: () => void, hostT?: Translate | undefined): ReactNode {\n const notice = saveNotice(answer, t, hostT)\n return h(\n 'div',\n { style: notice.written ? STYLE.noteOk : STYLE.noteError },\n notice.text,\n // The detail arrives ready to render: saveNotice applied the hostMessage\n // wrapper to an uncoded answer and the host seat to a coded one.\n notice.detail === undefined ? null : h('div', { style: STYLE.hint }, notice.detail),\n notice.reRead\n ? h('button', { style: STYLE.button, title: t('reReadHint'), onClick: onReRead }, t('reRead'))\n : null,\n )\n}\n\n/** The transport field: the two transports the host maps. */\nfunction transportField(\n draft: EntryDraft,\n editable: boolean,\n reason: string,\n t: Translate,\n onDraft: (draft: EntryDraft) => void,\n): ReactNode {\n return h(\n 'div',\n { style: STYLE.field, key: 'transport' },\n h('span', { style: STYLE.fieldLabel }, t('transport')),\n formControl(\n 'select',\n {\n style: STYLE.input,\n value: draft.transport,\n 'aria-label': t('transport'),\n ...(editable\n ? {\n onChange: (event: { target: { value: string } }) =>\n onDraft({\n ...draft,\n transport: event.target.value === 'streamable-http' ? 'streamable-http' : 'stdio',\n }),\n }\n : {}),\n },\n editable,\n reason,\n ['stdio', 'streamable-http'].map((option) => h('option', { key: option, value: option }, option)),\n ),\n )\n}\n\n/** The Source column: the declaring document, or the project root fallback. */\nfunction sourceLabel(row: ServerRow, project: ProjectSnapshot, t: Translate): ReactNode {\n const label =\n row.source === undefined ? t('documentUnknown') : documentLabel(row.source, project.projectRoot)\n return h('span', { style: { ...STYLE.muted, fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)' }, title: row.source ?? project.projectRoot }, label)\n}\n\n/** The row's `enabled` switch: the table edits nothing, so it opens the editor. */\nfunction enabledSwitch(row: ServerRow, t: Translate, hostT?: Translate | undefined): ReactNode {\n // The mockups draw the On column as their switch, not as a checkbox: the two\n // live states are the same fact (`enabled: false` is what `disabled` means),\n // and the switch is the shape the rest of the page's controls use. It is not\n // an editor either way — the click that opens the entry is the row's own.\n const on = row.status !== 'disabled'\n return formControl(\n 'button',\n {\n type: 'button',\n style: on ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n 'aria-checked': on,\n 'aria-label': t('on'),\n },\n false,\n writable(row) ? t('openToEdit') : blockedReason(row, t, hostT),\n h('span', {\n style: on ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob,\n 'aria-hidden': true,\n }),\n )\n}\n\n/** A status dot; the colour and the wording both come from the shared vocabulary. */\nfunction statusDot(status: ServerStatus, t: Translate): ReactNode {\n return h('span', {\n style: { ...STYLE.dot, background: STATUS_COLOR[status] },\n title: t(STATUS_HINT[status]),\n 'aria-hidden': true,\n })\n}\n\n/** A server name that selects it; selection is not a write. */\nfunction serverButton(\n row: ServerRow,\n selected: boolean,\n onSelect: (name: string | undefined) => void,\n t: Translate,\n hostT?: Translate | undefined,\n): ReactNode {\n return h(\n 'button',\n {\n style: selected\n ? { ...STYLE.serverButton, ...STYLE.serverButtonActive }\n : STYLE.serverButton,\n title: rowDetail(row, hostT) ?? t(STATUS_HINT[row.status]),\n onClick: () => onSelect(selected ? undefined : row.name),\n },\n row.name,\n )\n}\n","/**\n * The plugin's own configuration card (F-54): a `plugins.bundle.config` entry\n * that edits the volatile configuration the host serves over `configForms`.\n *\n * The card is deliberately thin: the host owns the schema, the revision dance\n * and the write path; this module renders the eighteen volatile fields as two\n * groups of setting rows, commits valid edits through `form.set`, and offers a\n * per-field reset (`form.unset`) only for fields the user layer overrides.\n *\n * Two host facts are mirrored here on purpose, because host code must never\n * enter the client bundle: the volatile-field defaults (`src/index.ts`\n * `DEFAULTS`, module-private and host-side) and the local-prefix rule\n * (`src/naming.ts` `isValidLocalPrefix`). Both mirrors carry a comment at the\n * copy.\n */\n\nimport { createElement as h, useMemo, useState, useSyncExternalStore } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { PACKAGE_NAME } from '../shared.ts'\n// settings.ts owns the locale namespace and the row/switch styles. Both are\n// read inside function bodies only, never at module scope: `locales/ui.ts`\n// imports this module while settings.ts imports `locales/ui.ts`, so a value\n// read here during evaluation could land inside settings.ts's TDZ window.\nimport { NS, STYLE } from './settings.ts'\n\n// ---------------------------------------------------------------------------\n// Local faces — the vendored contracts, so the client never imports host types\n// ---------------------------------------------------------------------------\n\n/** The slice of `ConfigForm`'s snapshot the card reads. */\nexport interface ConfigFormSnapshotLike {\n readonly status: 'loading' | 'ready' | 'unavailable'\n readonly value: Record<string, unknown> | undefined\n /** The user layer of the layered configuration; a field's PRESENCE marks an override. */\n readonly user: unknown\n readonly writable: boolean\n}\n\n/** The slice of the host's `ConfigForm` service object the card uses. */\nexport interface ConfigFormLike {\n getSnapshot(): ConfigFormSnapshotLike\n subscribe(listener: () => void): () => void\n set(field: string, value: unknown): Promise<boolean>\n unset(field: string): Promise<boolean>\n}\n\n/** The slice of the `configForms` service the registration block uses. */\nexport interface ConfigFormsLike {\n get<T>(namespace: string): ConfigFormLike\n whileServed(\n namespaces: readonly string[],\n register: (served: ReadonlySet<string>) => () => void,\n ): () => void\n}\n\n/**\n * The props the slot contract declares for `plugins.bundle.config`\n * (`PluginConfigViewProps`), with `form` widened to `unknown`: this\n * registration injects a factory under `form`, but the contract also lets an\n * owner pass its own page form, and a card must survive every shape quietly.\n */\nexport interface PluginConfigViewPropsLike {\n readonly view: 'summary' | 'page'\n readonly form?: unknown\n readonly t?: Translate\n}\n\n// ---------------------------------------------------------------------------\n// English dictionary (zh/ru live in `./locales/ui.ts`, which merges this table)\n// ---------------------------------------------------------------------------\n\nexport const EN = {\n configSummary: 'Edit this plugin’s activation and runtime configuration',\n configGroupActivation: 'Activation',\n configGroupRuntime: 'Runtime',\n configLoading: 'Loading the configuration…',\n configUnavailable: 'The host does not serve this plugin’s configuration to this client.',\n configReadOnly: 'This client keeps its preferences process-local, so these values are read-only here.',\n configOverridden: 'overridden',\n configReset: 'Reset',\n configResetHint: 'Clear this override and inherit the default',\n configInvalidInteger: 'Enter a whole number ≥ {min}',\n configInvalidRange: 'Enter a whole number between {min} and {max}',\n configInvalidPrefix: 'Up to {max} characters: letters, digits, “_” or “-”',\n // The Activation group: the tool-activation surface of `src/activation.ts`.\n configActivationEnabled: 'Tool activation',\n configActivationEnabledHint: 'Offer MCP tools progressively — counters, disclosure and the search gate',\n configActivationSeeded: 'Seeded tools',\n configActivationSeededHint: 'Tools offered from the first step, before any counter accrues; 0 seeds none',\n configActivationMinCalls: 'Calls to pin',\n configActivationMinCallsHint: 'Calls after which the counters pin a tool directly; 0 pins any tool with a recorded call',\n configToolIdleMs: 'Tool idle timeout (ms)',\n configToolIdleMsHint: 'A tool unused for this long drops back out of the request; 0 keeps it for the whole session',\n configGuidanceEnabled: 'System-prompt guidance',\n configGuidanceEnabledHint: 'Inject the plugin’s operating notes into the session prompt',\n configActivationAutoLimit: 'Auto-activation limit',\n configActivationAutoLimitHint: 'Most tools the counters may add on their own (0–50)',\n configActivationAutoStickySteps: 'Sticky steps',\n configActivationAutoStickyStepsHint: 'Extra user messages a context offer stays offered; 0 keeps it for that message only (0–1000)',\n configActivationToolBudgetChars: 'Tool budget (chars)',\n configActivationToolBudgetCharsHint: 'Character budget for the tool schemas one request carries (≥ 1000)',\n // The Runtime group: mounting, precedence and timeouts.\n configAllowGlobalWrite: 'Global writes',\n configAllowGlobalWriteHint: 'Allow saving into the user-level (~/.dsh) configuration',\n configEnvFiles: '.env files',\n configEnvFilesHint: 'Load .env files for server environment variables',\n configLazy: 'Lazy mounting',\n configLazyHint: 'Start project servers on the session’s first step, not at boot',\n configLocalPrefix: 'Local prefix',\n configLocalPrefixHint: 'Prefix for local tool names — up to 5 characters of A–Z, 0–9, _ or -; empty disables it',\n configProfileWins: 'Profile wins',\n configProfileWinsHint: 'Profile-level servers override project declarations of the same name',\n configConnectTimeoutMs: 'Connect timeout (ms)',\n configConnectTimeoutMsHint: 'How long starting one server may take',\n configToolCallTimeoutMs: 'Call timeout (ms)',\n configToolCallTimeoutMsHint: 'How long one tool call may take',\n configIdleTimeoutMs: 'Server idle timeout (ms)',\n configIdleTimeoutMsHint: 'A server idle for this long is stopped',\n configDebounceMs: 'Watch debounce (ms)',\n configDebounceMsHint: 'Quiet period before a config change triggers a rescan',\n configActivationWaitMs: 'Activation wait (ms)',\n configActivationWaitMsHint: 'How long the first step may wait for lazy servers',\n} satisfies Record<string, string>\n\n/** A dictionary key of this module's half of the namespace. */\nexport type LocaleKey = keyof typeof EN\n\n/** Translate one key, with optional `{name}` template params (the DSH seat). */\nexport type Translate = (key: string, params?: Record<string, unknown>) => string\n\n/**\n * Bind the translate seat the framework injects, falling back to this module's\n * own English dictionary when the card renders outside a DSH shell (tests, or\n * a browser half newer than the host).\n * @param t - the `t` seat of the composed props, when the framework passes one.\n * @returns a translate function that always answers.\n */\nexport function translateOf(t?: Translate): Translate {\n return t ?? fallbackTranslate\n}\n\nfunction fallbackTranslate(key: string, params?: Record<string, unknown>): string {\n const template = (EN as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in params ? String(params[name]) : match,\n )\n}\n\n// ---------------------------------------------------------------------------\n// The volatile fields — a mirror of the host table, with the card's own bounds\n// ---------------------------------------------------------------------------\n\n/** The eighteen keys of `VOLATILE_CONFIG_KEYS` (`src/index.ts`), redeclared. */\nexport type VolatileConfigKey =\n | 'activationEnabled'\n | 'activationSeeded'\n | 'activationMinCalls'\n | 'toolIdleMs'\n | 'guidanceEnabled'\n | 'activationAutoLimit'\n | 'activationAutoStickySteps'\n | 'activationToolBudgetChars'\n | 'allowGlobalWrite'\n | 'envFiles'\n | 'lazy'\n | 'localPrefix'\n | 'profileWins'\n | 'connectTimeoutMs'\n | 'toolCallTimeoutMs'\n | 'idleTimeoutMs'\n | 'debounceMs'\n | 'activationWaitMs'\n\n/**\n * The defaults the card displays when the served snapshot has no value for a\n * field. Mirror of the host's module-private `DEFAULTS` (`src/index.ts`) and\n * the activation constants (`src/activation.ts`): the host table cannot cross\n * into the client bundle, so the copy lives here and the schema's own defaults\n * remain the source of truth at write time.\n */\nexport const CONFIG_DEFAULTS: Record<VolatileConfigKey, boolean | number | string> = {\n activationEnabled: true,\n activationSeeded: 16,\n activationMinCalls: 1,\n toolIdleMs: 0,\n guidanceEnabled: true,\n activationAutoLimit: 12,\n activationAutoStickySteps: 100,\n activationToolBudgetChars: 40_000,\n allowGlobalWrite: false,\n envFiles: true,\n lazy: true,\n localPrefix: '',\n profileWins: true,\n connectTimeoutMs: 60_000,\n toolCallTimeoutMs: 60_000,\n idleTimeoutMs: 300_000,\n debounceMs: 300,\n activationWaitMs: 2_000,\n}\n\n/**\n * The local-prefix rule, mirrored from `src/naming.ts` (`MAX_LOCAL_PREFIX_LENGTH`\n * and `PREFIX_SHAPE`, in `isValidLocalPrefix`): empty disables the prefix,\n * otherwise at most five characters of letters, digits, `_` or `-`.\n */\nconst LOCAL_PREFIX_MAX = 5\nconst LOCAL_PREFIX_SHAPE = /^[A-Za-z0-9_-]+$/\n\n/** Client-side replica of the host's `isValidLocalPrefix`; see the note above. */\nexport function isValidLocalPrefix(value: string): boolean {\n if (value === '') return true\n return value.length <= LOCAL_PREFIX_MAX && LOCAL_PREFIX_SHAPE.test(value)\n}\n\n/** One editable field: how it is grouped, edited and bounded. */\ninterface FieldDef {\n readonly key: VolatileConfigKey\n readonly kind: 'boolean' | 'integer' | 'text'\n readonly min?: number\n readonly max?: number\n readonly label: LocaleKey\n readonly hint: LocaleKey\n}\n\nconst ACTIVATION_FIELDS: readonly FieldDef[] = [\n { key: 'activationEnabled', kind: 'boolean', label: 'configActivationEnabled', hint: 'configActivationEnabledHint' },\n { key: 'activationSeeded', kind: 'integer', min: 0, label: 'configActivationSeeded', hint: 'configActivationSeededHint' },\n { key: 'activationMinCalls', kind: 'integer', min: 0, label: 'configActivationMinCalls', hint: 'configActivationMinCallsHint' },\n { key: 'toolIdleMs', kind: 'integer', min: 0, label: 'configToolIdleMs', hint: 'configToolIdleMsHint' },\n { key: 'guidanceEnabled', kind: 'boolean', label: 'configGuidanceEnabled', hint: 'configGuidanceEnabledHint' },\n { key: 'activationAutoLimit', kind: 'integer', min: 0, max: 50, label: 'configActivationAutoLimit', hint: 'configActivationAutoLimitHint' },\n { key: 'activationAutoStickySteps', kind: 'integer', min: 0, max: 1000, label: 'configActivationAutoStickySteps', hint: 'configActivationAutoStickyStepsHint' },\n { key: 'activationToolBudgetChars', kind: 'integer', min: 1000, label: 'configActivationToolBudgetChars', hint: 'configActivationToolBudgetCharsHint' },\n]\n\nconst RUNTIME_FIELDS: readonly FieldDef[] = [\n { key: 'allowGlobalWrite', kind: 'boolean', label: 'configAllowGlobalWrite', hint: 'configAllowGlobalWriteHint' },\n { key: 'envFiles', kind: 'boolean', label: 'configEnvFiles', hint: 'configEnvFilesHint' },\n { key: 'lazy', kind: 'boolean', label: 'configLazy', hint: 'configLazyHint' },\n { key: 'localPrefix', kind: 'text', label: 'configLocalPrefix', hint: 'configLocalPrefixHint' },\n { key: 'profileWins', kind: 'boolean', label: 'configProfileWins', hint: 'configProfileWinsHint' },\n { key: 'connectTimeoutMs', kind: 'integer', min: 0, label: 'configConnectTimeoutMs', hint: 'configConnectTimeoutMsHint' },\n { key: 'toolCallTimeoutMs', kind: 'integer', min: 0, label: 'configToolCallTimeoutMs', hint: 'configToolCallTimeoutMsHint' },\n { key: 'idleTimeoutMs', kind: 'integer', min: 0, label: 'configIdleTimeoutMs', hint: 'configIdleTimeoutMsHint' },\n { key: 'debounceMs', kind: 'integer', min: 0, label: 'configDebounceMs', hint: 'configDebounceMsHint' },\n { key: 'activationWaitMs', kind: 'integer', min: 0, label: 'configActivationWaitMs', hint: 'configActivationWaitMsHint' },\n]\n\n// ---------------------------------------------------------------------------\n// The card\n// ---------------------------------------------------------------------------\n\nconst QUIET: CSSProperties = {\n fontSize: '0.85em',\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n}\n\nconst OVERRIDDEN_CHIP: CSSProperties = {\n marginLeft: 8,\n padding: '0 6px',\n borderRadius: 8,\n border: '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.4))',\n fontSize: '0.75em',\n fontWeight: 400,\n color: 'var(--dsw-alias-label-tertiary, inherit)',\n verticalAlign: '1px',\n}\n\nconst RESET_BUTTON: CSSProperties = {\n border: 'none',\n background: 'none',\n padding: 0,\n cursor: 'pointer',\n font: 'inherit',\n fontSize: '0.85em',\n color: 'var(--dsw-alias-state-business-primary, #2563eb)',\n}\n\nconst INPUT_WIDTH: CSSProperties = { width: 96 }\n\nconst INPUT_INVALID: CSSProperties = {\n borderColor: 'var(--dsw-alias-state-error-primary, #ef4444)',\n}\n\nconst INVALID_NOTE: CSSProperties = {\n fontSize: '0.8em',\n color: 'var(--dsw-alias-state-error-primary, #ef4444)',\n}\n\n/** The snapshot used while there is no form at all: the unavailable note. */\nconst NO_FORM_SNAPSHOT: ConfigFormSnapshotLike = {\n status: 'unavailable',\n value: undefined,\n user: undefined,\n writable: false,\n}\n\nconst noFormSnapshot = (): ConfigFormSnapshotLike => NO_FORM_SNAPSHOT\nconst subscribeNone = (): (() => void) => () => undefined\n\n/** The memoized store pair `useSyncExternalStore` needs, plus the form itself. */\ninterface FormSource {\n readonly form: ConfigFormLike\n readonly subscribe: (listener: () => void) => () => void\n readonly getSnapshot: () => ConfigFormSnapshotLike\n}\n\n/**\n * Resolve the `form` prop into a store the card can subscribe to. The\n * registration injects a factory (`() => forms.get(ns)`); a direct\n * `ConfigForm`-shaped object is accepted as well. Anything else — an absent\n * prop, a factory that throws, an owner-provided page form the card cannot\n * write through — resolves to `null`, and the card renders its quiet\n * unavailable note instead of failing.\n */\nfunction formSourceOf(raw: unknown): FormSource | null {\n let candidate: unknown = raw\n if (typeof candidate === 'function') {\n try {\n candidate = (candidate as () => unknown)()\n } catch {\n return null\n }\n }\n if (candidate === null || typeof candidate !== 'object') return null\n const form = candidate as ConfigFormLike\n if (\n typeof form.getSnapshot !== 'function' ||\n typeof form.subscribe !== 'function' ||\n typeof form.set !== 'function' ||\n typeof form.unset !== 'function'\n ) {\n return null\n }\n return {\n form,\n subscribe: (listener) => form.subscribe(listener),\n getSnapshot: () => form.getSnapshot(),\n }\n}\n\n/** A field is overridden when it is PRESENT in the user layer, whatever its value. */\nfunction hasOverride(user: unknown, field: string): boolean {\n return typeof user === 'object' && user !== null && Object.prototype.hasOwnProperty.call(user, field)\n}\n\n/** The displayed value: the served one, falling back to the mirrored default. */\nfunction fieldValue(def: FieldDef, snapshot: ConfigFormSnapshotLike): boolean | number | string {\n const raw = snapshot.value?.[def.key]\n const fallback = CONFIG_DEFAULTS[def.key]\n if (def.kind === 'boolean') return typeof raw === 'boolean' ? raw : (fallback as boolean)\n if (def.kind === 'integer') {\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : (fallback as number)\n }\n return typeof raw === 'string' ? raw : (fallback as string)\n}\n\n/** Parse a draft into a bounded whole number; `undefined` means \"do not write\". */\nfunction parseInteger(raw: string, min: number, max: number | undefined): number | undefined {\n const trimmed = raw.trim()\n if (!/^-?\\d+$/.test(trimmed)) return undefined\n const parsed = Number(trimmed)\n if (!Number.isSafeInteger(parsed) || parsed < min || (max !== undefined && parsed > max)) return undefined\n return parsed\n}\n\n/**\n * The plugin's configuration card. `view: 'summary'` is the one-liner the\n * contract allows an owner to ask for; the Plugins page today only ever asks\n * for `'page'`, which is the full two-group form.\n */\nexport function PluginConfigCard(props: PluginConfigViewPropsLike): ReactNode {\n const t = translateOf(props.t)\n // The injected face is cached per entry, so `props.form` is stable and this\n // memo resolves the factory exactly once per entry.\n const source = useMemo(() => formSourceOf(props.form), [props.form])\n const snapshot = useSyncExternalStore(\n source === null ? subscribeNone : source.subscribe,\n source === null ? noFormSnapshot : source.getSnapshot,\n )\n if (props.view === 'summary') {\n return h('div', { style: QUIET }, t('configSummary'))\n }\n if (source === null || snapshot.status === 'unavailable') {\n return h('div', { style: QUIET }, t('configUnavailable'))\n }\n if (snapshot.status === 'loading') {\n return h('div', { style: QUIET }, t('configLoading'))\n }\n const disabled = !snapshot.writable\n return h(\n 'div',\n null,\n disabled ? h('div', { style: { ...QUIET, marginBottom: 8 } }, t('configReadOnly')) : null,\n fieldGroup('activation', 'configGroupActivation', ACTIVATION_FIELDS, snapshot, source.form, t, disabled),\n fieldGroup('runtime', 'configGroupRuntime', RUNTIME_FIELDS, snapshot, source.form, t, disabled),\n )\n}\n\n/** One titled group of setting rows, in the shape DSH's own settings pages use. */\nfunction fieldGroup(\n group: string,\n titleKey: LocaleKey,\n fields: readonly FieldDef[],\n snapshot: ConfigFormSnapshotLike,\n form: ConfigFormLike,\n t: Translate,\n disabled: boolean,\n): ReactNode {\n return h(\n 'section',\n { key: group, style: group === 'activation' ? undefined : STYLE.settingGroup },\n h('div', { style: STYLE.settingGroupHead }, t(titleKey)),\n fields.map((def, index) =>\n h(FieldRow, {\n key: def.key,\n def,\n snapshot,\n form,\n t,\n disabled,\n last: index === fields.length - 1,\n }),\n ),\n )\n}\n\ninterface FieldRowProps {\n readonly def: FieldDef\n readonly snapshot: ConfigFormSnapshotLike\n readonly form: ConfigFormLike\n readonly t: Translate\n readonly disabled: boolean\n readonly last: boolean\n}\n\n/** One setting row: label and hint left, control right, reset when overridden. */\nfunction FieldRow(props: FieldRowProps): ReactNode {\n const { def, snapshot, form, t, disabled, last } = props\n const overridden = hasOverride(snapshot.user, def.key)\n const value = fieldValue(def, snapshot)\n const label = t(def.label)\n const control =\n def.kind === 'boolean'\n ? h(BooleanControl, {\n label,\n value: value as boolean,\n disabled,\n onToggle: (next: boolean) => void form.set(def.key, next),\n })\n : def.kind === 'integer'\n ? h(IntegerControl, {\n label,\n value: value as number,\n disabled,\n min: def.min ?? 0,\n max: def.max,\n t,\n onCommit: (next: number) => void form.set(def.key, next),\n })\n : h(TextControl, {\n label,\n value: value as string,\n disabled,\n t,\n onCommit: (next: string) => void form.set(def.key, next),\n })\n return h(\n 'div',\n { style: last ? { ...STYLE.settingRow, ...STYLE.lastRow } : STYLE.settingRow },\n h(\n 'div',\n { style: STYLE.settingRowText },\n h(\n 'span',\n { style: STYLE.settingRowLabel },\n label,\n overridden ? h('span', { style: OVERRIDDEN_CHIP }, t('configOverridden')) : null,\n ),\n h('span', { style: STYLE.settingRowDesc }, t(def.hint)),\n ),\n h(\n 'div',\n { style: STYLE.settingRowControl },\n control,\n overridden\n ? h(\n 'button',\n {\n type: 'button',\n style: RESET_BUTTON,\n disabled,\n title: t('configResetHint'),\n 'aria-label': `${t('configReset')}: ${label}`,\n onClick: () => void form.unset(def.key),\n },\n t('configReset'),\n )\n : null,\n ),\n )\n}\n\ninterface BooleanControlProps {\n readonly label: string\n readonly value: boolean\n readonly disabled: boolean\n readonly onToggle: (next: boolean) => void\n}\n\n/** The settings pages' sliding switch, bound to one boolean field. */\nfunction BooleanControl(props: BooleanControlProps): ReactNode {\n return h(\n 'button',\n {\n type: 'button',\n role: 'switch',\n 'aria-checked': props.value,\n 'aria-label': props.label,\n disabled: props.disabled,\n style: props.value ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },\n onClick: () => props.onToggle(!props.value),\n },\n h('span', {\n style: props.value ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob,\n 'aria-hidden': true,\n }),\n )\n}\n\ninterface IntegerControlProps {\n readonly label: string\n readonly value: number\n readonly disabled: boolean\n readonly min: number\n readonly max: number | undefined\n readonly t: Translate\n readonly onCommit: (next: number) => void\n}\n\n/**\n * A bounded whole-number input. The draft is local; only a dirty draft commits,\n * on blur or Enter — a blur with no edit writes nothing. An invalid draft\n * never reaches `form.set` — it marks the control and explains the bound\n * instead. Escape abandons the draft.\n */\nfunction IntegerControl(props: IntegerControlProps): ReactNode {\n const [draft, setDraft] = useState<string | undefined>(undefined)\n const [invalid, setInvalid] = useState(false)\n const invalidText =\n props.max === undefined\n ? props.t('configInvalidInteger', { min: props.min })\n : props.t('configInvalidRange', { min: props.min, max: props.max })\n const commit = (raw: string): void => {\n const parsed = parseInteger(raw, props.min, props.max)\n if (parsed === undefined) {\n setInvalid(true)\n return\n }\n setInvalid(false)\n setDraft(undefined)\n props.onCommit(parsed)\n }\n return h(\n 'span',\n { style: { display: 'inline-flex', flexDirection: 'column', gap: 2 } },\n h('input', {\n type: 'number',\n inputMode: 'numeric',\n step: 1,\n min: props.min,\n ...(props.max === undefined ? {} : { max: props.max }),\n style: invalid ? { ...STYLE.input, ...INPUT_WIDTH, ...INPUT_INVALID } : { ...STYLE.input, ...INPUT_WIDTH },\n value: draft ?? String(props.value),\n disabled: props.disabled,\n 'aria-label': props.label,\n 'aria-invalid': invalid || undefined,\n onChange: (event: { target: { value: string } }) => {\n setDraft(String(event.target.value))\n if (invalid) setInvalid(false)\n },\n onBlur: () => {\n // Commit only a dirty draft: a blur with no edit must not write the\n // displayed snapshot value (it would pin a phantom override), and the\n // Enter path clears the draft, so an Enter-then-blur no-ops instead of\n // committing the stale value the input fell back to.\n if (draft !== undefined) commit(draft)\n },\n onKeyDown: (event: { key: string }) => {\n if (event.key === 'Enter') {\n if (draft !== undefined) commit(draft)\n } else if (event.key === 'Escape') {\n setDraft(undefined)\n setInvalid(false)\n }\n },\n }),\n invalid ? h('span', { role: 'alert', style: INVALID_NOTE }, invalidText) : null,\n )\n}\n\ninterface TextControlProps {\n readonly label: string\n readonly value: string\n readonly disabled: boolean\n readonly t: Translate\n readonly onCommit: (next: string) => void\n}\n\n/** The local-prefix input: same commit discipline as the numbers, prefix rule. */\nfunction TextControl(props: TextControlProps): ReactNode {\n const [draft, setDraft] = useState<string | undefined>(undefined)\n const [invalid, setInvalid] = useState(false)\n const commit = (raw: string): void => {\n if (!isValidLocalPrefix(raw)) {\n setInvalid(true)\n return\n }\n setInvalid(false)\n setDraft(undefined)\n props.onCommit(raw)\n }\n return h(\n 'span',\n { style: { display: 'inline-flex', flexDirection: 'column', gap: 2 } },\n h('input', {\n type: 'text',\n maxLength: LOCAL_PREFIX_MAX,\n style: invalid ? { ...STYLE.input, ...INPUT_WIDTH, ...INPUT_INVALID } : { ...STYLE.input, ...INPUT_WIDTH },\n value: draft ?? props.value,\n placeholder: '—',\n disabled: props.disabled,\n 'aria-label': props.label,\n 'aria-invalid': invalid || undefined,\n onChange: (event: { target: { value: string } }) => {\n setDraft(String(event.target.value))\n if (invalid) setInvalid(false)\n },\n onBlur: () => {\n // Same commit discipline as the number input: dirty drafts only.\n if (draft !== undefined) commit(draft)\n },\n onKeyDown: (event: { key: string }) => {\n if (event.key === 'Enter') {\n if (draft !== undefined) commit(draft)\n } else if (event.key === 'Escape') {\n setDraft(undefined)\n setInvalid(false)\n }\n },\n }),\n invalid\n ? h('span', { role: 'alert', style: INVALID_NOTE }, props.t('configInvalidPrefix', { max: LOCAL_PREFIX_MAX }))\n : null,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Registration — the `plugins.bundle.config` entry, parked on the configForms\n// service so the card appears exactly when the host serves the namespace\n// ---------------------------------------------------------------------------\n\nconst PLUGIN_CONFIG_SLOT = 'plugins.bundle.config'\nconst PRIMARY_CONFIG_NS = 'dsh-project-mcp'\nconst LEGACY_CONFIG_NS = 'project-mcp'\n\n/** The slot-services slice the registration needs, mirroring settings.ts. */\nexport interface PluginConfigSlotServices {\n effect(execute: () => unknown, label?: string): unknown\n slots: {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(\n options: {\n name: string\n key: string\n locale: string\n inject: () => Record<string, unknown>\n },\n component: (props: Props) => ReactNode,\n ): unknown\n }\n configForms: ConfigFormsLike\n}\n\n/**\n * Register the card on the Plugins page.\n *\n * The keyed slot's options are exactly `{ name, key, locale, inject }` — the\n * `id`/`order`/`label` options of list slots do not exist here. `whileServed`\n * watches both config namespaces and prefers the plugin's own; the register\n * callback fires once, when the first watched namespace becomes served (there\n * is no re-fire while any of them stays served), and its returned disposer —\n * the one `slots.inject` hands back — runs when the last one disappears.\n */\nexport function registerPluginConfigCard(services: PluginConfigSlotServices): void {\n const forms = services.configForms\n services.effect(\n () =>\n forms.whileServed([PRIMARY_CONFIG_NS, LEGACY_CONFIG_NS], (served) => {\n const ns = served.has(PRIMARY_CONFIG_NS) ? PRIMARY_CONFIG_NS : LEGACY_CONFIG_NS\n // `slots.inject` keeps registration a no-op on a composition whose\n // slots registry does not declare the slot (an older host) — the card\n // is simply absent there, nothing throws.\n const dispose = services.slots.inject(PLUGIN_CONFIG_SLOT, () =>\n services.slots.register(\n {\n name: PLUGIN_CONFIG_SLOT,\n key: PACKAGE_NAME,\n locale: NS,\n inject: () => ({ form: () => forms.get(ns) }),\n },\n (props: PluginConfigViewPropsLike) => h(PluginConfigCard, props),\n ),\n )\n return typeof dispose === 'function' ? (dispose as () => void) : (): void => undefined\n }),\n 'project-mcp: plugin config card',\n )\n}\n","/**\n * Every word the plugin's client half shows a person, in the three languages it\n * ships. The tables in `view.ts` and `settings.ts` stay where they are — they are\n * the runtime's English fallback and their key types are what makes a missing\n * translation a compile error here:\n *\n * `en` is the merge of both halves (`settings.ts` first, the panel last — the\n * order the runtime registration registers it), `UiKey` is the union of both key\n * types, and all three tables are declared `Record<UiKey, string>` — as an\n * annotated object literal, so the compiler reads every key of the union off the\n * literal itself and a key that exists in one language and not another does not\n * build.\n *\n * Composed here rather than at the registration site, so the merge sits at the\n * source of the two halves and is read against their own key types. That is a\n * preference, not the gate: the gate is whichever form a table is written in,\n * and both forms the translation tasks use — the annotated literal above and\n * `{ … } satisfies Record<UiKey, string>` — reject a short table the same way\n * (probed: identical `TS2740`, `… and 266 more`).\n *\n * The `zh` and `ru` tables are authored by the maintainers, not by a native\n * speaker, and are pending review: see the release notes for 0.2.0.\n *\n * @module src/client/locales/ui\n */\n\nimport { EN as configEn } from '../plugin-config.ts'\nimport type { LocaleKey as PluginConfigLocaleKey } from '../plugin-config.ts'\nimport { EN, NS } from '../settings.ts'\nimport type { LocaleKey as SettingsLocaleKey } from '../settings.ts'\nimport type { TabLocale } from '../tab-locale.ts'\nimport { en as viewEn } from '../view.ts'\nimport type { LocaleKey as ViewLocaleKey, Translate } from '../view.ts'\n\n/** Every key the `settings.projectMcp` namespace carries. */\nexport type UiKey = ViewLocaleKey | SettingsLocaleKey | PluginConfigLocaleKey\n\n/**\n * The merged English table, built on first read rather than at module\n * evaluation. `settings.ts` imports this module for {@link uiTranslate} while\n * this module imports `EN` from `settings.ts`, so which of the two evaluates\n * first depends on the entry point — and a spread of the not-yet-initialized\n * half would silently drop every settings key from the fallback. Deferring the\n * merge past module evaluation keeps the table complete in either order.\n */\nlet english: Record<UiKey, string> | undefined\nfunction mergedEnglish(): Record<UiKey, string> {\n return (english ??= { ...EN, ...viewEn, ...configEn })\n}\n\n/** English, and the runtime fallback for any language that lacks a key. */\nexport const en: Record<UiKey, string> = new Proxy({} as Record<UiKey, string>, {\n get: (_target, property) => Reflect.get(mergedEnglish(), property),\n has: (_target, property) => Reflect.has(mergedEnglish(), property),\n ownKeys: () => Reflect.ownKeys(mergedEnglish()),\n getOwnPropertyDescriptor: (_target, property) =>\n Object.getOwnPropertyDescriptor(mergedEnglish(), property),\n})\n\n/**\n * Chinese, complete across the namespace: every key of `UiKey` is written out\n * below — the view half (the tab and its blocks) first, then the settings half\n * in `settings.ts` order — so the `Record<UiKey, string>` annotation itself\n * proves completeness. Its key order is the canonical one for future\n * additions.\n */\nexport const zh: Record<UiKey, string> = {\n // The tab itself: its label in the sidebar and the line under it.\n tab: '项目 MCP',\n tabDescription: '各项目声明的 MCP 服务器,以及为其会话挂载的内容',\n sync: '同步',\n retryFailed: '重试失败项',\n // Tool presentation: the tab's tools block and the settings page's Tools rows.\n toolsSeeModel: '模型所见',\n toolsPinned: '已置顶',\n toolsByCounters: '按计数器',\n toolsDisclosed: '已披露',\n toolsHidden: '已隐藏',\n toolsNotMounted: '暂无可隐藏的工具',\n toolsNotMountedHint:\n '惰性挂载:项目的服务器在会话的第一步才启动,因此工具目录在此之前为空',\n toolsNotMountedCode: 'tools[] = built-ins only · mcp__* not registered yet',\n // The declared servers of this session, on the tools block: the reason an\n // apparently empty catalog is empty.\n toolsServers: '服务器',\n toolsServersUp: '{up}/{total} 运行中',\n toolsGroupPinned: '已置顶 · 始终在请求中',\n toolsGroupCounters: '由计数器提供',\n toolsGroupDisclosed: '由模型披露 · 直至会话结束',\n toolsGroupHidden: '已隐藏',\n toolsPin: '置顶',\n toolsPinHint: '让此工具保留在此项目的每次请求中',\n toolsUnpin: '取消置顶',\n toolsUnpinHint: '取消在此项目的每次请求中置顶此工具',\n toolsHide: '隐藏',\n toolsHideHint: '放弃此次披露,不再提供此工具',\n toolsHiddenVia: '模型只能通过 mcp_search_tools 使用',\n // The tools block's own filter (F-43): the counter chips above the list stop\n // being a reading and become the tier switch, and a query narrows by name.\n toolsFilterPlaceholder: '按名称过滤…',\n toolsFilterLabel: '按注册表名过滤此会话的工具',\n toolsFilterTier: '只显示此层级;再按一次显示全部层级',\n toolsFilterClear: '清除',\n toolsFilterClearHint: '显示全部层级并清空查询',\n toolsFilterShown: '显示 {shown}/{total}',\n toolsFilterNone: '此会话没有符合过滤条件的工具。',\n // The server-level pin (F-44): one press for a whole server's names, since a\n // server is how the hidden tier and the settings page both group them.\n toolsPinAll: '全部置顶',\n toolsPinAllHint: '在每次请求中置顶此服务器的所有隐藏工具',\n // The other direction of the same press, said by both surfaces when the set\n // is already wholly pinned.\n toolsUnpinAll: '全部取消置顶',\n toolsUnpinAllHint: '取消置顶此服务器的所有隐藏工具',\n // The same press on the pinned tier, where the names it releases are the ones\n // the user pinned rather than the ones the host hid.\n toolsUnpinServerHint: '取消置顶此服务器的所有工具',\n toolsBudget: '{used}/{total} 字符 · ≈ {tokens} token',\n toolsBudgetExhausted: '预算已用尽:后续披露将被拒绝并说明原因',\n toolsBudgetFree: '腾出预算空间,或在项目设置中置顶此工具',\n toolsBudgetGateOff: '披露门控已关闭:所有已挂载的工具都会进入请求',\n toolsBudgetBreakdown: '{used}/{total}({percent}%)',\n toolsModeOff: '此项目的 MCP 工具已关闭',\n toolsModeOffCounters: '已挂载 {mounted} 个 · 均未提供',\n toolsModeOffHint:\n '此项目的工具都不会提供给模型。在「工具」页将模式设为「披露」即可重新提供。',\n toolsModeDirect: '全部直接:所有已挂载的工具都会进入请求',\n toolsPresentationOwner: '另一个插件正在主导请求的呈现',\n toolsOtherOwner: '其他呈现所有者',\n toolsDemo: '演示',\n toolsStep: '第 {step} 步',\n // The host's own usage counters: how often one tool was called, and how\n // long one server has gone unused.\n callsOne: '1 次调用',\n callsMany: '{count} 次调用',\n callsNone: '从未调用',\n callsProject: '项目中 {count} 次',\n idleDay: '闲置 {count} 天',\n idleHour: '闲置 {count} 小时',\n idleMinute: '闲置 {count} 分钟',\n // One tool row's detail block (F-56): the serving server with its state, the\n // tier as a sentence, the two counter readings, then the host's own answer\n // about the definition. The header keeps the name, the clock and the step, and the\n // body prints them again in its fact line: that is what the contract's own probe reads\n // out of the open disclosure (`contracts/surfaces.md` §1.5).\n toolServer: '服务器 {server}',\n toolServerState: '{server} · {state}',\n toolTierPinned: '已置顶 — 始终在请求中',\n toolTierSession: '由本次会话提供',\n toolTierContext: '由上下文排序提供',\n showTool: '显示此工具的服务器、说明、字段及其提供方式',\n hideTool: '隐藏此工具的详细信息',\n toolCallsSession: '本次会话 {count} 次',\n toolLoading: '正在从宿主读取此定义…',\n toolFailed: '宿主没有对此定义作答',\n toolFieldsLabel: '接受',\n toolFieldRequiredHint: '必填字段',\n toolReasonBudget: '未提供:{chars} 字符,超出 {budget} 字符的预算',\n toolReasonChars: '{chars} 字符',\n toolReasonBudgetOnly: '{budget} 字符的预算',\n toolReasonUsed: '已提供 {used}',\n toolReason: '未提供',\n // The errors and logs blocks, under their own disclosures: the event ring is\n // the plugin's own, one project at a time.\n errorsSection: '问题',\n showErrors: '显示需要查看的服务器',\n hideErrors: '隐藏需要查看的服务器',\n logsSection: '日志',\n showLogs: '显示此项目的事件',\n hideLogs: '隐藏此项目的事件',\n logsThisSession: '本会话',\n logsAllSessions: '全部会话',\n logsAllLevels: '全部级别',\n logsErrorsOnly: '错误',\n logsLevelInfo: 'info',\n logsLevelUp: 'up',\n logsLevelWarn: 'warn',\n logsLevelError: 'error',\n logsClear: '清除',\n logsClearHint: '隐藏目前已记录的所有事件;新事件仍会出现',\n logsEmptyTitle: '暂无事件',\n logsEmptyHint:\n '项目的服务器会在会话的第一步启动,或在你按下「同步」时启动;挂载、启动和停止都会显示在这里。',\n logsNoErrorsTitle: '没有错误',\n logsNoErrorsHint:\n '本项目的事件环中存有其他事件;把级别过滤器切到「全部级别」即可查看。',\n logsMore: '显示更早',\n logsMoreHint: '加载比当前屏幕上更早的事件',\n logsShown: '显示 {shown}/{total}',\n logsProjectCount: '本项目 {count} 条',\n logsLoading: '正在加载更早的事件…',\n logsLoadFailed: '无法读取更早的事件',\n // The tab's own states, in the same table for the same reason.\n noSession: '此标签页没有关联会话。',\n noSessionHint: '面板读取的是它所在会话的项目。',\n noProject: '此会话的文件夹还不在任何项目内。',\n noProjectHint:\n '宿主会从此会话的 cwd 向上查找 .git · .dsh · .kimi-code · package.json · *.sln。',\n nothingNeedsAttention: '无需关注。',\n noServersDeclared: '此项目未声明任何 MCP 服务器。',\n noServersDeclaredHint: '添加 {documents}。',\n noServersDeclaredUnknown: '请向项目添加一份 MCP 文档。',\n noServersDeclaredNowhere:\n '此部署不读取任何项目文档,因此无处声明——请在插件配置(`localFiles`)中列出一个。',\n // Surface A's own header and the vocabulary its rows are built from. The\n // segment bar is gone (F-26): the toolbar names the project and carries one\n // phrase on its right edge, and every count a mode segment used to badge lives\n // on the block it describes.\n thisSession: '本会话',\n noProjectLabel: '无项目',\n retry: '重试',\n retryHint: '立即重试此项目失败的挂载',\n sessionsSection: '会话',\n // The `sessions` section is the project's *disagreement* view: its chip counts\n // the sessions whose own reading differs from the merged rows, not the\n // sessions that exist.\n differsOne: '1 个会话不一致',\n differsMany: '{count} 个会话不一致',\n sessionsOne: '1 个会话',\n sessionsMany: '{count} 个会话',\n serversOne: '1 个服务器',\n serversMany: '{count} 个服务器',\n mergedAcrossSessions: '跨会话合并',\n release: '释放',\n nothingDeclared: '无声明',\n showSessions: '显示此项目的会话',\n hideSessions: '隐藏此项目的会话',\n showSession: '显示此会话的服务器',\n hideSession: '隐藏此会话的服务器',\n mountedPerProject: '按项目挂载',\n projectsCount: '{count} 个项目',\n nothingMounted: '尚未挂载任何内容。',\n // The status vocabulary (F-47): the word a row wears and the one-line\n // explanation its tooltip carries.\n statusActive: '运行中',\n statusConnecting: '连接中',\n statusConflict: '冲突',\n statusError: '错误',\n statusIdle: '闲置',\n statusDisabled: '已禁用',\n statusHintActive: '已挂载,其工具在本会话中可见',\n statusHintConnecting: '已挂载,尚未发布任何工具',\n statusHintIdle: '已声明但未挂载——将在下一轮挂载',\n statusHintDisabled: '以 enabled: false 声明',\n statusHintConflict: '同名 serverName 已被配置文件级实例占用',\n statusHintError: '查看详情',\n // The status line of a project or session: one template per status, the\n // count always a `{count}` placeholder.\n summaryActive: '{count} 个运行中',\n summaryConnecting: '{count} 个连接中',\n summaryIdle: '{count} 个闲置',\n summaryDisabled: '{count} 个已禁用',\n summaryError: '{count} 个错误',\n summaryConflict: '{count} 个冲突',\n summaryNone: '无声明',\n close: '关闭',\n // The frame-wide toasts (F-47): one keyed line per lifecycle moment, and the\n // quieter line weaving the project around the fact behind it.\n toastUp: '{server} 已启动',\n toastFailed: '{server} 失败',\n toastReleased: '{server} 已释放',\n toastDetail: '{project} · {detail}',\n // The poll interval's row in the tab's settings panel.\n refreshTitle: '刷新间隔',\n refreshDesc: '面板重新读取宿主快照的频率',\n // The tab's actions menu: the row that opens the settings popup.\n settingsMenuItem: '面板设置…',\n // The design stand's own tab title and description.\n designTitle: '项目 MCP · 设计 ({variant})',\n designDesc: '设计模式:{variant} 夹具,背后没有宿主',\n // Settings half, in `settings.ts` order: the overview table, its states and\n // the read-only reasons of its rows.\n project: '项目',\n projectsOne: '1 个项目有活动会话',\n projectsMany: '{count} 个项目有活动会话',\n viewTable: '表格',\n viewFiles: '按文件',\n syncHint: '立即重新读取宿主快照',\n server: '服务器',\n transport: '传输',\n status: '状态',\n source: '来源',\n on: '开',\n servers: '服务器',\n paneEntry: '条目',\n name: '名称',\n detail: '详情',\n loading: '正在读取宿主快照…',\n loadingHint: '页面一打开就会轮询 /project-mcp/snapshot。',\n hostUnavailable: '页面没有收到插件宿主的应答。',\n hostUnavailableHint:\n '宿主侧提供 {route};它只在 dsh web 重启后才拾取变更——请查看日志。',\n noSessions: '还没有会话关联到任何项目。',\n noSessionsHint:\n '当会话开始在项目文件夹内工作时服务器才会启动——没有会话的项目不会挂载任何内容。',\n noSessionsPaths: '读取:{paths}',\n noSessionsNoPaths:\n '此部署不读取任何 MCP 文档——请在插件配置(`localFiles`、`globalFiles`)中列出要读取的文档',\n noServers: '此项目未声明任何 MCP 服务器。',\n noServersHint: '没有任何声明,因此不会为其会话挂载任何内容。',\n noServersNoPath: '此部署不读取任何项目文档,因此无处声明。',\n documentUnknown: '声明文档未知',\n global: '全局',\n priority: '优先级 {tier}/{total}',\n overrideFrom: '↳ 覆盖来自 {from} 的 {name}',\n overrideUnpinned: '↳ 覆盖在更低优先级文档中声明的 {name}',\n nameReason: '只读:服务器名是宿主报告的声明键。',\n statusReason: '只读:状态来自运行中的宿主,而非文档。',\n sourceReason: '只读:声明文档的路径来自宿主。',\n detailReason: '只读:宿主会隐去这段文本,且从不包含参数。',\n openToEdit: '此处只读:打开服务器以编辑其条目。',\n rowActionsMore: '…',\n rowActionsHint: '在编辑器中打开此条目',\n showJson: '显示 JSON',\n hideJson: '隐藏 JSON',\n jsonPreview: '快照 JSON',\n jsonPreviewHint: '读取自宿主快照;磁盘上的文档不会被触碰。',\n back: '返回列表',\n backHint: '返回概览,不做任何更改',\n // Editor: the fields of the parsed entry.\n entryUnavailable: '宿主未能解析此条目,因此没有可编辑的内容。',\n commandField: '命令',\n argsField: '参数',\n cwdField: 'CWD',\n urlField: 'URL',\n envField: 'Env',\n headersField: '请求头',\n enabledField: '启用',\n timeoutField: '超时',\n keyField: '键',\n valueField: '值',\n argsHint: '每行一个参数;每一行都原样写入。',\n envHint: '每个键一个值;表单中删去的键会从条目中移除。',\n headersHint: '每个请求头一个值;表单中删去的键会从条目中移除。',\n timeoutHint: '毫秒;留空表示声明不设置超时。',\n enabledValue: '启用:{value}',\n absent: '未设置',\n maskedValue: '•••• 未更改——输入以替换',\n valuePlaceholder: '值',\n keyPlaceholder: 'KEY',\n credentialsNote:\n '来自外部来源——项目的 .env 或凭据文件——而非此文档:它会被原样显示并原样写回。',\n credentialValue: '来自项目的 .env 或凭据文件',\n addKey: '添加键',\n addKeyHint: '追加一个空键;未命名的键不会被写入。',\n removeKey: '✕',\n removeKeyHint: '删去此键;被删去的键会从条目中移除。',\n // Writing.\n editableNote:\n '正在编辑 {document}:「保存」会要求确认、先备份到 {backup} 并整体重写该条目。',\n writeBlocked: '只读:{reason}',\n writeBlockedUnknown: '宿主未报告此文档为何不可写入。',\n save: '保存…',\n saveHint: '打开此次写入的确认',\n saveNoChange: '还没有可保存的更改。',\n saveUnavailable: '快照没有携带可写回的声明文档或修订版本。',\n saveTimeoutInvalid: '超时不是以毫秒为单位的整数。',\n saving: '正在写入…',\n discard: '放弃',\n discardHint: '从快照恢复所有字段,不写入任何内容',\n discardReason: '还没有可恢复的更改。',\n unsaved: '未保存',\n jsonDiff: 'diff',\n jsonClean: '无更改',\n jsonUnavailable: '无已解析的条目',\n jsonInvalid: 'JSON 无法解析为条目:{reason}',\n jsonEditHint: '按文档声明的形式编辑条目',\n saveJsonInvalid: '请先修复 JSON 窗格:它无法解析为条目。',\n footerWrite: '→ {document} · .bak 副本 · 确认',\n footerReadonly: '→ {document} · 只读',\n confirmTitle: '写入 {document}?',\n confirmBackup: '当前文档会先被复制到 {backup}。',\n confirmFormat:\n '该条目会整体替换 mcpServers[{server}]。文档将以两空格缩进和末尾换行重新序列化,因此文档其余部分的缩进和键顺序会被规范化。',\n confirmConsent:\n '这是一个全局文档:每个项目都会读取它,因此写入需要明确同意。',\n consentLabel: '我理解这会重写一个所有项目共享的全局文档。',\n confirmWrite: '写入文档',\n confirmWriteHint: '通过上述检查后写入文档',\n confirmBlocked: '请先勾选同意框:没有它的全局写入会被拒绝。',\n cancel: '取消',\n saveOk: '已保存:文档已写入并重新读取。',\n saveErrorInvalid:\n '宿主拒绝了该条目:它不是此插件会挂载的条目。未写入任何内容。',\n saveErrorBlocked:\n '此层级不允许写入该文档,或缺少同意。未写入任何内容。',\n saveErrorConflict: '自此快照取得以来文档已更改。未写入任何内容。',\n saveErrorNotFound: '文档或服务器已不存在。未写入任何内容。',\n saveErrorFailed: '写入本身失败;文档保持原样。未写入任何内容。',\n hostMessage: '宿主返回:{message}',\n reRead: '重新读取',\n reReadHint: '重新获取宿主快照并据此重建表单',\n // Our own two pages, and the disclosure policy page next to `Servers`.\n tabServers: '服务器',\n tabTools: '工具',\n policyNote: '此项目遵循的模式,以及为它置顶的工具',\n checkConflicts: '检查冲突',\n checkConflictsHint:\n '宿主为此项目报告的冲突服务器名读取自其快照;此按钮会立即重新读取快照',\n conflictsNone: '此项目没有冲突的服务器名',\n conflictProfile: '配置文件级名称',\n conflictDuplicate: '重复声明',\n conflictSources: '声明于 {sources}',\n choiceLabel: '显示',\n choiceLocal: '此项目的副本,作为 {alias}',\n choiceProfileHint: '保持配置文件实例的工具原样不变',\n choiceLocalHint:\n '将此项目自己的声明挂载在配置文件声明旁边,使用本地名 {alias}',\n choiceNative: '此项目的声明,使用其自身名称',\n choiceNativeHint:\n '将此项目自己的声明按其声明的名称挂载:它在此项目中更近,因此在此它会遮蔽配置文件实例的工具,而其他所有项目仍照常看到它们',\n choiceRefused: '宿主拒绝了该选择:',\n toolsCount: '工具',\n pinned: '已置顶',\n mode: '模式',\n modeDisclosure: '披露',\n modeDirect: '全部直接',\n modeOff: 'off',\n modeHint: '立即写入,在宿主组装的下一个请求上生效',\n modeRefused: '宿主拒绝了该模式:',\n pinRefused: '宿主拒绝了该置顶:',\n pinList: '已置顶 · 手写维护,在每次请求中提供',\n pinListEmpty: '还没有置顶——在下方工具列表中开启一个',\n serverAllOffered: '其全部 {count} 个工具都直接提供',\n serverPartlyOffered: '{total} 个工具中 {offered} 个直接提供',\n // The server-level pin (F-44): one switch for the whole server row, above the\n // per-name rows it stands for.\n serverPin: '置顶此服务器的工具',\n serverPinHint: '置顶此服务器挂载的每个工具——包括隐藏的——让每个请求都携带它们',\n serverUnpin: '取消置顶此服务器的工具',\n serverUnpinHint: '停止置顶此服务器的工具',\n prefixFact: 'mcp__<server>__<tool>;前缀由注册表添加,而非本页',\n pinTag: 'pin',\n moreTools: '… 还有 {count} 个',\n requestPreview: '请求预览',\n requestPreviewTools: 'tools[] = {count}',\n requestPreviewTokens: '≈ {tokens} token',\n requestPreviewHidden: '已隐藏 {count} 个',\n requestPreviewSaved: '已隐藏 {count} 个 · 节省 ≈ {tokens} token',\n requestPreviewNoOffer: '此会话尚未向模型提供任何工具',\n // The plugin's own configuration card (F-54), the newest keys last.\n configSummary: '编辑本插件的激活与运行时配置',\n configGroupActivation: '激活',\n configGroupRuntime: '运行时',\n configLoading: '正在加载配置…',\n configUnavailable: '宿主未向此客户端提供本插件的配置。',\n configReadOnly: '此客户端的偏好为进程内有效,因此此处这些值为只读。',\n configOverridden: '已覆盖',\n configReset: '重置',\n configResetHint: '清除此覆盖,恢复默认值',\n configInvalidInteger: '请输入 ≥ {min} 的整数',\n configInvalidRange: '请输入 {min} 到 {max} 之间的整数',\n configInvalidPrefix: '最多 {max} 个字符:字母、数字、“_” 或 “-”',\n configActivationEnabled: '工具激活',\n configActivationEnabledHint: '渐进式提供 MCP 工具——计数、披露与搜索门控',\n configActivationSeeded: '预置工具数',\n configActivationSeededHint: '在计数累计之前,从第一步就提供的工具数;0 表示不预置',\n configActivationMinCalls: '固定所需调用次数',\n configActivationMinCallsHint: '调用达到此次数后,计数器会直接固定该工具;0 表示只要有过调用就固定',\n configToolIdleMs: '工具闲置超时(毫秒)',\n configToolIdleMsHint: '工具超过此时长未使用将从请求中移除;0 表示整个会话都保留',\n configGuidanceEnabled: '系统提示指引',\n configGuidanceEnabledHint: '将本插件的使用说明注入会话提示',\n configActivationAutoLimit: '自动激活上限',\n configActivationAutoLimitHint: '计数器最多可自行加入的工具数(0–50)',\n configActivationAutoStickySteps: '黏滞步数',\n configActivationAutoStickyStepsHint: '按任务上下文提供的工具额外保留多少条用户消息;0 表示仅保留当前消息(0–1000)',\n configActivationToolBudgetChars: '工具预算(字符)',\n configActivationToolBudgetCharsHint: '单次请求携带的工具模式字符预算(≥ 1000)',\n configAllowGlobalWrite: '允许全局写入',\n configAllowGlobalWriteHint: '允许保存到用户级(~/.dsh)配置',\n configEnvFiles: '.env 文件',\n configEnvFilesHint: '为服务器环境变量加载 .env 文件',\n configLazy: '惰性挂载',\n configLazyHint: '在会话的第一步启动项目服务器,而非启动时',\n configLocalPrefix: '本地前缀',\n configLocalPrefixHint: '本地工具名前缀——最多 5 个字符,仅限 A–Z、0–9、_ 或 -;留空则禁用',\n configProfileWins: '配置档优先',\n configProfileWinsHint: '同名服务器以配置档级覆盖项目声明',\n configConnectTimeoutMs: '连接超时(毫秒)',\n configConnectTimeoutMsHint: '启动单个服务器允许的最长时长',\n configToolCallTimeoutMs: '调用超时(毫秒)',\n configToolCallTimeoutMsHint: '单次工具调用允许的最长时长',\n configIdleTimeoutMs: '服务器闲置超时(毫秒)',\n configIdleTimeoutMsHint: '服务器闲置超过此时长将被停止',\n configDebounceMs: '监听去抖(毫秒)',\n configDebounceMsHint: '配置变更触发重新扫描前的静默时长',\n configActivationWaitMs: '激活等待(毫秒)',\n configActivationWaitMsHint: '第一步等待惰性服务器就绪的最长时长',\n}\n\n/**\n * Russian, complete across the namespace: every key of `UiKey` is written out\n * below, so the `Record<UiKey, string>` annotation itself proves completeness.\n */\nexport const ru: Record<UiKey, string> = {\n // The tab itself: its label in the sidebar and the line under it.\n tab: 'MCP проекта',\n tabDescription:\n 'MCP-серверы, которые объявляет проект, и что смонтировано для его сессий',\n sync: 'Синхронизировать',\n retryFailed: 'Повторить неудачные',\n // Tool presentation: the tab's tools block and the settings page's Tools rows.\n toolsSeeModel: 'что видит модель',\n toolsPinned: 'закреплённые',\n toolsByCounters: 'по счётчикам',\n toolsDisclosed: 'раскрытые',\n toolsHidden: 'скрытые',\n toolsNotMounted: 'Пока скрывать нечего',\n toolsNotMountedHint:\n 'ленивое монтирование: серверы проекта поднимаются на первом шаге сессии, поэтому каталог пока пуст',\n toolsNotMountedCode: 'tools[] = built-ins only · mcp__* not registered yet',\n // The declared servers of this session, on the tools block.\n toolsServers: 'Серверы',\n toolsServersUp: '{up}/{total} работают',\n toolsGroupPinned: 'закреплённые · всегда в запросе',\n toolsGroupCounters: 'предлагаются счётчиками',\n toolsGroupDisclosed: 'раскрыты моделью · до конца сессии',\n toolsGroupHidden: 'скрытые',\n toolsPin: 'Закрепить',\n toolsPinHint: 'Держать этот инструмент в каждом запросе проекта',\n toolsUnpin: 'Открепить',\n toolsUnpinHint: 'Больше не закреплять этот инструмент в запросах проекта',\n toolsHide: 'Скрыть',\n toolsHideHint: 'Снять это раскрытие и перестать предлагать инструмент',\n toolsHiddenVia: 'доступен модели только через mcp_search_tools',\n // The tools block's own filter: the tier switch and the name query.\n toolsFilterPlaceholder: 'фильтр по имени…',\n toolsFilterLabel: 'фильтр инструментов сессии по имени в реестре',\n toolsFilterTier: 'Показать только этот уровень; ещё раз — все уровни',\n toolsFilterClear: 'Сбросить',\n toolsFilterClearHint: 'Показать все уровни и убрать запрос',\n toolsFilterShown: 'показано {shown} из {total}',\n toolsFilterNone: 'Ни один инструмент сессии не подходит под фильтр.',\n // The server-level pin: one press for a whole server's names.\n toolsPinAll: 'Закрепить все',\n toolsPinAllHint: 'Закрепить каждый скрытый инструмент этого сервера в каждом запросе',\n // The other direction of the same press.\n toolsUnpinAll: 'Открепить все',\n toolsUnpinAllHint: 'Открепить все скрытые инструменты этого сервера',\n // The same press on the pinned tier.\n toolsUnpinServerHint: 'Открепить все инструменты этого сервера',\n toolsBudget: '{used} симв. из {total} · ≈ {tokens} токенов',\n toolsBudgetExhausted: 'бюджет исчерпан: дальнейшие раскрытия отклоняются с указанием причины',\n toolsBudgetFree: 'освободите место в бюджете или закрепите инструмент в настройках проекта',\n toolsBudgetGateOff: 'контроль раскрытий выключен: каждый смонтированный инструмент попадает в запрос',\n toolsBudgetBreakdown: '{used} из {total} ({percent}%)',\n toolsModeOff: 'MCP-инструменты этого проекта выключены',\n toolsModeOffCounters: 'смонтировано: {mounted} · не предлагаются',\n toolsModeOffHint:\n 'Ничто из этого проекта не предлагается модели. Включите режим «Раскрытие» на странице инструментов, чтобы снова их предлагать.',\n toolsModeDirect: 'ничего не откладывается: каждый смонтированный инструмент попадает в запрос',\n toolsPresentationOwner: 'Другой плагин формирует запрос',\n toolsOtherOwner: 'Другой владелец представления',\n toolsDemo: 'демо',\n toolsStep: 'шаг {step}',\n // The host's own usage counters: how often one tool was called, and how\n // long one server has gone unused.\n callsOne: '1 вызов',\n callsMany: 'вызовов: {count}',\n callsNone: 'ни разу не вызывался',\n callsProject: '{count} в проекте',\n idleDay: 'простой {count}д',\n idleHour: 'простой {count}ч',\n idleMinute: 'простой {count}мин',\n // One tool row's detail block (F-56): the serving server with its state, the\n // tier as a sentence, the two counter readings, then the host's own answer\n // about the definition. The header keeps the name, the clock and the step, and the\n // body prints them again in its fact line: that is what the contract's own probe reads\n // out of the open disclosure (`contracts/surfaces.md` §1.5).\n toolServer: 'сервер {server}',\n toolServerState: '{server} · {state}',\n toolTierPinned: 'закреплён — всегда в запросе',\n toolTierSession: 'предложен этой сессией',\n toolTierContext: 'предложен ранжированием контекста',\n showTool: 'показать сервер инструмента, описание, поля и способ предложения',\n hideTool: 'скрыть подробности инструмента',\n toolCallsSession: '{count} в этой сессии',\n toolLoading: 'читаем это определение у хоста…',\n toolFailed: 'хост не ответил на это определение',\n toolFieldsLabel: 'принимает',\n toolFieldRequiredHint: 'обязательное поле',\n toolReasonBudget: 'не предложен: {chars} символов при бюджете {budget}',\n toolReasonChars: '{chars} символов',\n toolReasonBudgetOnly: 'бюджет {budget} символов',\n toolReasonUsed: 'уже предложено {used}',\n toolReason: 'не предложен',\n // The errors and logs blocks, under their own disclosures.\n errorsSection: 'Проблемы',\n showErrors: 'показать серверы, требующие внимания',\n hideErrors: 'скрыть серверы, требующие внимания',\n logsSection: 'Журнал',\n showLogs: 'показать события проекта',\n hideLogs: 'скрыть события проекта',\n logsThisSession: 'эта сессия',\n logsAllSessions: 'все сессии',\n logsAllLevels: 'все уровни',\n logsErrorsOnly: 'ошибки',\n logsLevelInfo: 'info',\n logsLevelUp: 'up',\n logsLevelWarn: 'warn',\n logsLevelError: 'error',\n logsClear: 'Очистить',\n logsClearHint: 'Скрыть все записанные события; новые всё равно появятся',\n logsEmptyTitle: 'Событий пока нет',\n logsEmptyHint:\n 'Серверы проекта поднимаются на первом шаге сессии или при нажатии «Синхронизировать»; монтирование, запуск и остановка появятся здесь.',\n logsNoErrorsTitle: 'Ошибок нет',\n logsNoErrorsHint:\n 'Кольцо проекта содержит другие события; переключите фильтр уровней на «все уровни», чтобы их увидеть.',\n logsMore: 'Показать более ранние',\n logsMoreHint: 'Загрузить события старше показанных',\n logsShown: 'показано {shown} из {total}',\n logsProjectCount: '{count} в этом проекте',\n logsLoading: 'загрузка старых событий…',\n logsLoadFailed: 'старые события не удалось прочитать',\n // The tab's own states.\n noSession: 'К этой вкладке не привязана сессия.',\n noSessionHint: 'Панель читает проект сессии, в которой открыта.',\n noProject: 'Папка этой сессии пока не входит в проект.',\n noProjectHint:\n 'Хост поднимается от cwd сессии в поисках .git · .dsh · .kimi-code · package.json · *.sln.',\n nothingNeedsAttention: 'Внимания не требуется.',\n noServersDeclared: 'Этот проект не объявляет MCP-серверы.',\n noServersDeclaredHint: 'Добавьте {documents}.',\n noServersDeclaredUnknown: 'Добавьте в проект MCP-документ.',\n noServersDeclaredNowhere:\n 'Эта установка не читает документы проекта, так что объявлять некуда — укажите один в конфигурации плагина (`localFiles`).',\n // Surface A's own header and the vocabulary its rows are built from.\n thisSession: 'эта сессия',\n noProjectLabel: 'нет проекта',\n retry: 'Повторить',\n retryHint: 'Повторить неудачные монтирования проекта сейчас',\n sessionsSection: 'сессии',\n // The `sessions` section is the project's *disagreement* view.\n differsOne: '1 расходится',\n differsMany: '{count} расходятся',\n sessionsOne: '1 сессия',\n sessionsMany: 'сессий: {count}',\n serversOne: '1 сервер',\n serversMany: 'серверов: {count}',\n mergedAcrossSessions: 'объединено между сессиями',\n release: 'Освободить',\n nothingDeclared: 'ничего не объявлено',\n showSessions: 'показать сессии этого проекта',\n hideSessions: 'скрыть сессии этого проекта',\n showSession: 'показать серверы этой сессии',\n hideSession: 'скрыть серверы этой сессии',\n mountedPerProject: 'Смонтировано по проектам',\n projectsCount: '{count} проект(ов)',\n nothingMounted: 'Пока ничего не смонтировано.',\n // The status vocabulary (F-47): the word a row wears and the one-line\n // explanation its tooltip carries.\n statusActive: 'активен',\n statusConnecting: 'подключается',\n statusConflict: 'конфликт',\n statusError: 'ошибка',\n statusIdle: 'простой',\n statusDisabled: 'отключён',\n statusHintActive: 'смонтирован, его инструменты видны в этой сессии',\n statusHintConnecting: 'смонтирован, инструменты ещё не опубликованы',\n statusHintIdle: 'объявлен, но не смонтирован — смонтируется на следующем шаге',\n statusHintDisabled: 'объявлен с enabled: false',\n statusHintConflict: 'то же имя serverName занято экземпляром уровня профиля',\n statusHintError: 'см. подробности',\n // The status line of a project or session: one template per status, the\n // count always a `{count}` placeholder. The counted forms are the genitive\n // plural or an invariant construction — the documented 2–4 compromise.\n summaryActive: '{count} активных',\n summaryConnecting: '{count} подключающихся',\n summaryIdle: '{count} в простое',\n summaryDisabled: '{count} отключено',\n summaryError: '{count} с ошибкой',\n summaryConflict: '{count} в конфликте',\n summaryNone: 'ничего не объявлено',\n close: 'Закрыть',\n // The frame-wide toasts (F-47): one keyed line per lifecycle moment, and the\n // quieter line weaving the project around the fact behind it.\n toastUp: '{server} поднят',\n toastFailed: '{server}: сбой',\n toastReleased: '{server} освобождён',\n toastDetail: '{project} · {detail}',\n // The poll interval's row in the tab's settings panel.\n refreshTitle: 'Интервал обновления',\n refreshDesc: 'Как часто панель перечитывает снимок хоста',\n // The tab's actions menu: the row that opens the settings popup.\n settingsMenuItem: 'Настройки панели…',\n // The design stand's own tab title and description.\n designTitle: 'MCP проекта · дизайн ({variant})',\n designDesc: 'режим дизайна: фикстура {variant}, хоста за ней нет',\n // Settings half, in `settings.ts` order: the overview table, its states and\n // the read-only reasons of its rows.\n project: 'Проект',\n projectsOne: '1 проект с активной сессией',\n projectsMany: 'проектов с активными сессиями: {count}',\n viewTable: 'Таблица',\n viewFiles: 'По файлам',\n syncHint: 'Перечитать снимок хоста сейчас',\n server: 'Сервер',\n transport: 'Транспорт',\n status: 'Статус',\n source: 'Источник',\n on: 'Вкл',\n servers: 'Серверы',\n paneEntry: 'Запись',\n name: 'Имя',\n detail: 'Подробности',\n loading: 'Чтение снимка хоста…',\n loadingHint: 'Страница опрашивает /project-mcp/snapshot сразу после открытия.',\n hostUnavailable: 'Страница не получила ответа от хоста плагина.',\n hostUnavailableHint:\n 'Хостовая половина обслуживает {route}; изменения она подхватывает только после перезапуска dsh web — проверьте журнал.',\n noSessions: 'К проекту пока не привязана ни одна сессия.',\n noSessionsHint:\n 'Серверы поднимаются, когда сессия начинает работать в папке проекта, — без сессии для проекта ничего не монтируется.',\n noSessionsPaths: 'читаются: {paths}',\n noSessionsNoPaths:\n 'эта установка не читает ни одного MCP-документа — перечислите документы для чтения в конфигурации плагина (`localFiles`, `globalFiles`)',\n noServers: 'Этот проект не объявляет MCP-серверы.',\n noServersHint: 'Ничего не объявлено, поэтому для его сессий ничего не монтируется.',\n noServersNoPath: 'Эта установка не читает документы проекта, так что объявлять некуда.',\n documentUnknown: 'документ объявления неизвестен',\n global: 'глобальный',\n priority: 'приоритет {tier}/{total}',\n overrideFrom: '↳ переопределяет {name} из {from}',\n overrideUnpinned: '↳ переопределяет {name}, объявленное в документе с более низким приоритетом',\n nameReason: 'Только чтение: имя сервера — ключ объявления, который сообщает хост.',\n statusReason: 'Только чтение: статус приходит от работающего хоста, а не из документа.',\n sourceReason: 'Только чтение: путь объявляющего документа приходит от хоста.',\n detailReason: 'Только чтение: хост скрывает этот текст и никогда не включает аргументы.',\n openToEdit: 'Здесь только чтение: откройте сервер, чтобы изменить его запись.',\n rowActionsMore: '…',\n rowActionsHint: 'Открыть эту запись в редакторе',\n showJson: 'Показать JSON',\n hideJson: 'Скрыть JSON',\n jsonPreview: 'JSON снимка',\n jsonPreviewHint: 'Читается из снимка хоста; документ на диске не затрагивается.',\n back: 'Назад к списку',\n backHint: 'Вернуться к обзору, ничего не меняя',\n // Editor: the fields of the parsed entry.\n entryUnavailable: 'Хост не смог разобрать эту запись, так что редактировать нечего.',\n commandField: 'Команда',\n argsField: 'Аргументы',\n cwdField: 'CWD',\n urlField: 'URL',\n envField: 'Env',\n headersField: 'Заголовки',\n enabledField: 'Включён',\n timeoutField: 'Таймаут',\n keyField: 'Ключ',\n valueField: 'Значение',\n argsHint: 'Один аргумент на строку; каждая строка записывается как есть.',\n envHint: 'Одно значение на ключ; ключ, убранный в форме, удаляется из записи.',\n headersHint: 'Одно значение на заголовок; заголовок, убранный в форме, удаляется из записи.',\n timeoutHint: 'Миллисекунды; пусто — объявление не задаёт таймаут.',\n enabledValue: 'включён: {value}',\n absent: 'отсутствует',\n maskedValue: '•••• без изменений — введите текст, чтобы заменить',\n valuePlaceholder: 'значение',\n keyPlaceholder: 'KEY',\n credentialsNote:\n 'Приходит из внешнего источника — из .env проекта или файла учётных данных, — а не из этого документа: показывается и записывается обратно без изменений.',\n credentialValue: 'из .env проекта или файла учётных данных',\n addKey: 'Добавить ключ',\n addKeyHint: 'Добавить пустой ключ; безымянный ключ не записывается.',\n removeKey: '✕',\n removeKeyHint: 'Убрать этот ключ; убранный ключ удаляется из записи.',\n // Writing.\n editableNote:\n 'Редактируется {document}: «Сохранить» попросит подтверждение, сохранит резервную копию в {backup} и перезапишет запись целиком.',\n writeBlocked: 'Только чтение: {reason}',\n writeBlockedUnknown: 'хост не сообщил, почему этот документ нельзя записывать.',\n save: 'Сохранить…',\n saveHint: 'Открыть подтверждение этой записи',\n saveNoChange: 'Пока нечего сохранять.',\n saveUnavailable: 'В снимке нет ни объявляющего документа, ни ревизии, в которую можно было бы записать.',\n saveTimeoutInvalid: 'Таймаут — не целое число миллисекунд.',\n saving: 'Запись…',\n discard: 'Отменить',\n discardHint: 'Восстановить все поля из снимка и ничего не записывать',\n discardReason: 'Пока нечего восстанавливать.',\n unsaved: 'не сохранено',\n jsonDiff: 'diff',\n jsonClean: 'нет изменений',\n jsonUnavailable: 'нет разобранной записи',\n jsonInvalid: 'JSON не разбирается в запись: {reason}',\n jsonEditHint: 'Редактировать запись в том виде, в каком её объявляет документ',\n saveJsonInvalid: 'Сначала исправьте панель JSON: она не разбирается в запись.',\n footerWrite: '→ {document} · копия .bak · подтверждение',\n footerReadonly: '→ {document} · только чтение',\n confirmTitle: 'Записать {document}?',\n confirmBackup: 'Сначала текущий документ копируется в {backup}.',\n confirmFormat:\n 'Запись заменяет mcpServers[{server}] целиком. Документ сериализуется заново с отступом в два пробела и завершающим переводом строки, поэтому отступы и порядок ключей в остальной части документа нормализуются.',\n confirmConsent:\n 'Это глобальный документ: его читает каждый проект, поэтому запись требует явного согласия.',\n consentLabel: 'Я понимаю, что это перезапишет глобальный документ, общий для всех проектов.',\n confirmWrite: 'Записать документ',\n confirmWriteHint: 'Записать документ после проверок выше',\n confirmBlocked: 'Сначала отметьте согласие: глобальная запись без него отклоняется.',\n cancel: 'Отмена',\n saveOk: 'Сохранено: документ записан и перечитан.',\n saveErrorInvalid:\n 'Хост отклонил запись: этот плагин не стал бы монтировать такую. Ничего не записано.',\n saveErrorBlocked:\n 'Документ нельзя записать на этом уровне, либо нет согласия. Ничего не записано.',\n saveErrorConflict: 'Документ изменился с момента снятия этого снимка. Ничего не записано.',\n saveErrorNotFound: 'Документа или сервера больше нет. Ничего не записано.',\n saveErrorFailed: 'Сама запись не удалась; документ оставлен как был. Ничего не записано.',\n hostMessage: 'Хост ответил: {message}',\n reRead: 'Перечитать',\n reReadHint: 'Заново запросить снимок хоста и перестроить по нему форму',\n // Our own two pages, and the disclosure policy page next to `Servers`.\n tabServers: 'Серверы',\n tabTools: 'Инструменты',\n policyNote: 'режим, которому следует проект, и закреплённые для него инструменты',\n checkConflicts: 'Проверить конфликты',\n checkConflictsHint:\n 'конфликтующие имена серверов, которые хост сообщает для этого проекта, читаются из его снимка; кнопка перечитывает его сейчас',\n conflictsNone: 'в этом проекте нет конфликтующих имён серверов',\n conflictProfile: 'имя из профиля',\n conflictDuplicate: 'дубликат объявления',\n conflictSources: 'объявлено в {sources}',\n choiceLabel: 'показать',\n choiceLocal: 'копию этого проекта как {alias}',\n choiceProfileHint: 'оставить инструменты экземпляра профиля как есть',\n choiceLocalHint:\n 'смонтировать собственное объявление этого проекта рядом с профильным, под локальным именем {alias}',\n choiceNative: 'объявление этого проекта под его собственным именем',\n choiceNativeHint:\n 'смонтировать собственное объявление этого проекта под именем, которое оно объявляет: в этом проекте оно ближе, поэтому здесь оно затеняет инструменты экземпляра профиля, а все остальные проекты продолжают их видеть',\n choiceRefused: 'Хост отклонил выбор:',\n toolsCount: 'инструменты',\n pinned: 'Закреплённые',\n mode: 'Режим',\n modeDisclosure: 'раскрытие',\n modeDirect: 'все напрямую',\n modeOff: 'off',\n modeHint: 'записывается сразу, в следующий запрос, который соберёт хост',\n modeRefused: 'Хост отклонил режим:',\n pinRefused: 'Хост отклонил закрепление:',\n pinList: 'закреплённые · записаны вручную, предлагаются в каждом запросе',\n pinListEmpty: 'закреплений пока нет — включите одно в списке инструментов ниже',\n serverAllOffered: 'все {count} его инструментов предлагаются напрямую',\n serverPartlyOffered: '{offered} из {total} инструментов предлагаются напрямую',\n // The server-level pin (F-44): one switch for the whole server row, above the\n // per-name rows it stands for.\n serverPin: 'закрепить инструменты этого сервера',\n serverPinHint: 'Закрепить каждый инструмент, который монтирует этот сервер, — и скрытые тоже, — чтобы их нёс каждый запрос',\n serverUnpin: 'открепить инструменты этого сервера',\n serverUnpinHint: 'Перестать закреплять инструменты этого сервера',\n prefixFact: 'mcp__<server>__<tool>; префикс добавляет реестр, а не эта страница',\n pinTag: 'pin',\n moreTools: '… ещё {count}',\n requestPreview: 'предпросмотр запроса',\n requestPreviewTools: 'tools[] = {count}',\n requestPreviewTokens: '≈ {tokens} токенов',\n requestPreviewHidden: 'скрыто {count}',\n requestPreviewSaved: 'скрыто {count} · сэкономлено ≈ {tokens} токенов',\n requestPreviewNoOffer: 'эта сессия пока ничего не предложила',\n // The plugin's own configuration card (F-54), the newest keys last.\n configSummary: 'Настройка активации и параметров времени выполнения плагина',\n configGroupActivation: 'Активация',\n configGroupRuntime: 'Время выполнения',\n configLoading: 'Загрузка конфигурации…',\n configUnavailable: 'Хост не предоставляет конфигурацию этого плагина данному клиенту.',\n configReadOnly: 'Этот клиент хранит настройки в пределах процесса, поэтому здесь эти значения доступны только для чтения.',\n configOverridden: 'переопределено',\n configReset: 'Сбросить',\n configResetHint: 'Убрать переопределение и вернуть значение по умолчанию',\n configInvalidInteger: 'Введите целое число ≥ {min}',\n configInvalidRange: 'Введите целое число от {min} до {max}',\n configInvalidPrefix: 'Не более {max} символов: буквы, цифры, «_» или «-»',\n configActivationEnabled: 'Активация инструментов',\n configActivationEnabledHint: 'Постепенно предлагать MCP-инструменты — счётчики, раскрытие и поисковый шлюз',\n configActivationSeeded: 'Предустановленные инструменты',\n configActivationSeededHint: 'Инструменты, предлагаемые с первого шага, до накопления счётчиков; 0 — не предлагать',\n configActivationMinCalls: 'Вызовов до закрепления',\n configActivationMinCallsHint: 'После стольких вызовов счётчики закрепляют инструмент напрямую; 0 — закрепить любой инструмент с записанным вызовом',\n configToolIdleMs: 'Тайм-аут простоя инструмента (мс)',\n configToolIdleMsHint: 'Инструмент, не использованный за это время, исключается из запроса; 0 — оставить его на всю сессию',\n configGuidanceEnabled: 'Подсказки в системном промпте',\n configGuidanceEnabledHint: 'Добавлять рабочие заметки плагина в промпт сессии',\n configActivationAutoLimit: 'Лимит автоактивации',\n configActivationAutoLimitHint: 'Максимум инструментов, которые счётчики могут добавить сами (0–50)',\n configActivationAutoStickySteps: 'Шагов закрепления',\n configActivationAutoStickyStepsHint: 'Сколько пользовательских сообщений предложенный по контексту инструмент остаётся предложенным; 0 — только для этого сообщения (0–1000)',\n configActivationToolBudgetChars: 'Бюджет инструментов (символы)',\n configActivationToolBudgetCharsHint: 'Бюджет в символах на схемы инструментов в одном запросе (≥ 1000)',\n configAllowGlobalWrite: 'Глобальная запись',\n configAllowGlobalWriteHint: 'Разрешить сохранение в пользовательскую (~/.dsh) конфигурацию',\n configEnvFiles: 'Файлы .env',\n configEnvFilesHint: 'Загружать .env-файлы для переменных окружения серверов',\n configLazy: 'Ленивое монтирование',\n configLazyHint: 'Запускать серверы проекта на первом шаге сессии, а не при загрузке',\n configLocalPrefix: 'Локальный префикс',\n configLocalPrefixHint: 'Префикс имён локальных инструментов — до 5 символов: A–Z, 0–9, _ или -; пусто — отключён',\n configProfileWins: 'Профиль приоритетнее',\n configProfileWinsHint: 'Серверы уровня профиля переопределяют одноимённые объявления проекта',\n configConnectTimeoutMs: 'Тайм-аут подключения (мс)',\n configConnectTimeoutMsHint: 'Сколько может длиться запуск одного сервера',\n configToolCallTimeoutMs: 'Тайм-аут вызова (мс)',\n configToolCallTimeoutMsHint: 'Сколько может длиться один вызов инструмента',\n configIdleTimeoutMs: 'Тайм-аут простоя сервера (мс)',\n configIdleTimeoutMsHint: 'Сервер, простаивающий дольше этого срока, останавливается',\n configDebounceMs: 'Антидребезг наблюдения (мс)',\n configDebounceMsHint: 'Пауза перед тем, как изменение конфигурации запустит повторное сканирование',\n configActivationWaitMs: 'Ожидание активации (мс)',\n configActivationWaitMsHint: 'Сколько первый шаг может ждать ленивые серверы',\n}\n\n/** English text for a key, with `{name}` placeholders substituted. */\nexport function uiFallback(key: string, params?: Record<string, unknown>): string {\n const template = (en as Record<string, string>)[key] ?? key\n if (params === undefined) return template\n return template.replace(/\\{(\\w+)\\}/gu, (whole, name: string) =>\n name in params ? String(params[name]) : whole,\n )\n}\n\n/**\n * A translator bound to this namespace that never shows a raw key when English\n * knows it.\n *\n * Both translate seats route through here — the sidebar tab's `tabTranslate`\n * and the settings page's label — so the fallback is one code path: the bound\n * seat answers first, and when it can only echo the key (the active language's\n * dictionary lacks it) the merged English table of this module answers instead.\n * A key even English lacks renders as itself — a documented last resort, made\n * unreachable by construction (compile-time completeness of the three tables,\n * plus the parity spec), not by hiding the branch.\n * @param locale - the shell's locale service, when there is one.\n * @returns a translate function that always answers.\n */\nexport function uiTranslate(locale: TabLocale | undefined): Translate {\n if (locale === undefined) return uiFallback\n let bound: Translate\n try {\n bound = locale.bind(NS) as Translate\n } catch {\n // A service that refuses the namespace leaves the surface its own English.\n return uiFallback\n }\n return (key, params) => {\n const text = bound(key, params)\n return text === key ? uiFallback(key, params) : text\n }\n}\n","/**\n * The translate seat of the sidebar tab.\n *\n * The native Settings page registers through `settings.section` / `slots`,\n * which hands its component the framework's own `t` seat. The tab has neither:\n * it is created by the sidebar service, so its\n * panel used to render the module's English dictionary while the rest of the\n * shell followed the language preference.\n *\n * The tab's translator is built here, out of the one locale face the shell\n * publishes on the client context (`ctx.get('locale')` — the DSH `LocaleRuntime`\n * every dictionary registers into): the component binds the plugin's namespace\n * to it, subscribes to the locale snapshot, and repaints on a language switch.\n * The same namespace is registered from `./index.ts` with the merged\n * three-language dictionary, so a key the shell translates wins, and the\n * fallback inside {@link uiTranslate} is only the last resort for a composition\n * without a locale service — a test, or a browser half newer than the host.\n *\n * @module dsh-project-mcp/client/tab-locale\n */\n\nimport { useEffect, useState } from 'react'\nimport { uiTranslate } from './locales/ui.ts'\nimport type { Translate } from './view.ts'\n\n/**\n * The slice of the client locale service the tab needs, mirrored structurally.\n *\n * The DSH client packages are provided by the web shell and are not dependencies\n * of this one, so the seat is bound by shape rather than by import — the same\n * reason the settings page mirrors its slot services. `subscribe` is optional:\n * a service that publishes no snapshot never notifies, and the tab then renders\n * whatever language it was opened in.\n */\nexport interface TabLocale {\n /** Bind one namespace to a translate function that follows the active locale. */\n bind(namespace: string): Translate\n /** Subscribe to locale changes (a language switch or a late registration). */\n subscribe?(listener: () => void): () => void\n}\n\n/**\n * The locale service out of the client context, when the composition has one.\n *\n * The read goes through `ctx.get`, never through a property: Cordis throws\n * `cannot get property \"locale\" without inject` for a service this fiber did not\n * declare, and that throw takes the whole web client boot down with it. A\n * composition without a locale service answers `undefined`, and the tab keeps\n * its own English table.\n * @param ctx - the client context `apply` was called with.\n * @returns the locale service, or undefined when there is none.\n */\nexport function localeServiceOf(ctx: unknown): TabLocale | undefined {\n if (ctx === null || typeof ctx !== 'object') return undefined\n const get = (ctx as { get?: unknown }).get\n if (typeof get !== 'function') return undefined\n const candidate = (get as (name: string) => unknown).call(ctx, 'locale')\n if (candidate === null || typeof candidate !== 'object') return undefined\n return typeof (candidate as Partial<TabLocale>).bind === 'function'\n ? (candidate as TabLocale)\n : undefined\n}\n\n/**\n * The tab's translator, bound to the shell's locale service.\n *\n * A thin delegate to {@link uiTranslate}, the one translator both seats share:\n * the bound namespace answers first, the merged English table answers a key\n * the active language lacks, and the raw key shows only when even English has\n * nothing for it.\n * @param locale - the locale service, when there is one.\n * @returns a translate function that always answers.\n */\nexport function tabTranslate(locale: TabLocale | undefined): Translate {\n return uiTranslate(locale)\n}\n\n/**\n * The tab's translator as a hook: bound once, re-bound when the language\n * changes.\n *\n * The tab component is the one surface of this plugin rendered outside the slot\n * framework, so it is the one place a repaint has to be asked for explicitly.\n * @param locale - the locale service, when there is one.\n * @returns the translate seat the panel renders through.\n */\nexport function useTabTranslate(locale: TabLocale | undefined): Translate {\n const [seat, setSeat] = useState<Translate>(() => tabTranslate(locale))\n useEffect(() => {\n setSeat(tabTranslate(locale))\n return locale?.subscribe?.(() => setSeat(tabTranslate(locale)))\n }, [locale])\n return seat\n}\n","/**\n * The plugin's tab in DSH's **own** right sidebar, and the settings it carries.\n *\n * The panel used to be a tab of `dsh-better-sidebar`, a third-party registry\n * that re-exports DSH's right sidebar with its own descriptor API (and with its\n * own builtin tabs, its own `+` menu and its own side card settings). This module\n * speaks to the shipped surface directly, so the plugin depends on nothing\n * outside the harness:\n *\n * - the type itself goes into `sidebarRightTabs` (stage one: what the type *is* —\n * its id, its kind, and one guide entry, which is the only way a user can open\n * a page type at all);\n * - its body and its chip title go into the keyed `sidebar.right.pane.tab` /\n * `sidebar.right.pane.tab.title` seats under that same id, which is what the\n * sidebar dispatches on for every tab of the kind;\n * - the chip's actions menu gains one row (`sidebar.right.tab.menu.item`) that\n * opens the plugin's settings, and the settings themselves render as an entry\n * of the frame-wide `shell.overlay` layer — because a menu item that acts must\n * dismiss the menu it was pressed in, and the popup cannot live inside the row\n * that opened it. One store drives both halves.\n *\n * The DSH client packages are provided by the web shell and are not dependencies\n * of this package, so each of those contracts is **mirrored structurally** here —\n * the choice `./settings.ts` and `./tab-locale.ts` already make for\n * `settings.section` and the locale service. Nothing in this module imports a\n * `@deepseek-ai/dsh-client-*` package; the slot keys and the service name are\n * the only names it needs from the checkout, and they are dialled as strings.\n *\n * What the port changes for a user: the tab is listed by the shell's own guide\n * page instead of the sidebar's `+` menu, and the side card's plugin settings\n * page is gone — the poll interval and the per-project release panel now sit\n * behind the row this module adds to the tab's actions menu.\n *\n * @module dsh-project-mcp/client/sidebar-tab\n */\n\nimport { createElement as h, useEffect, useState } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { PACKAGE_NAME, TAB_ID } from '../shared.ts'\nimport { hostTranslate } from './locales/host.ts'\nimport { tabTranslate, useTabTranslate } from './tab-locale.ts'\nimport type { TabLocale } from './tab-locale.ts'\nimport type { RefreshStore, Translate } from './view.ts'\n\n/** Type discriminator of the panel's page: what `openTab` names and what the sidebar dispatches on. */\nexport const TAB_KIND = 'project-mcp'\n\n/** Keyed seat a tab type registers its body under. */\nexport const TAB_SLOT = 'sidebar.right.pane.tab'\n\n/** Keyed seat the same type registers its chip title under. */\nexport const TAB_TITLE_SLOT = 'sidebar.right.pane.tab.title'\n\n/** List seat a tab type adds its own entries to: the actions menu of the chip. */\nexport const TAB_MENU_SLOT = 'sidebar.right.tab.menu.item'\n\n/** Frame-wide floating layer the settings popup renders into. */\nexport const SETTINGS_DIALOG_SLOT = 'shell.overlay'\n\n/** Registration id of the actions-menu row, unique within that menu. */\nexport const TAB_MENU_ID = `${PACKAGE_NAME}:settings`\n\n/** Position of the row among the menu's entries, after the kit's own close item. */\nexport const TAB_MENU_ORDER = 60\n\n/** Registration id of the settings popup in the floating layer. */\nexport const SETTINGS_DIALOG_ID = `${PACKAGE_NAME}:settings-dialog`\n\n/** Position of the popup among the layer's entries, after the toast stack. */\nexport const SETTINGS_DIALOG_ORDER = 61\n\n/** Identity of the type's guide entry: the box the guide page offers to open a tab. */\nexport const TAB_GUIDE_ENTRY_ID = 'servers'\n\n/** Position of the guide entry among every registered type's entries; the tab's own descriptor order. */\nexport const TAB_GUIDE_ORDER = 55\n\n/**\n * One box the guide page offers, contributed by the type it opens.\n *\n * `title` and `description` are thunks read on every render, so a language\n * switch needs no re-registration — the rule the old descriptor's own copy\n * followed. A guide that lists too many entries drops descriptions and shows\n * titles alone, so the title has to stand on its own.\n */\nexport interface SidebarRightGuideEntry {\n readonly id: string\n readonly order: number\n readonly title: () => string\n readonly description?: (() => string) | undefined\n}\n\n/**\n * Stage one of a tab type: what it is, and nothing per-tab.\n *\n * `patterns` is omitted on purpose — the panel is a *page* type, opened by kind\n * (from the guide page, or from another surface's `openTab`), not a viewer that\n * claims an address. `multiple` is omitted too: one project panel per pane is\n * what `single: true` meant in the sidebar the tab came from.\n */\nexport interface SidebarRightTabDefinition {\n readonly id: string\n readonly kind: string\n /** Defaults to `extension` in the shipped registry: a type from outside the product. */\n readonly priority?: 'extension' | 'builtin' | 'fallback' | undefined\n /** Chip text captured when a tab opens. */\n readonly title: (address: string) => string\n readonly guide?: readonly SidebarRightGuideEntry[] | undefined\n}\n\n/** The registry service (stage one), as a registrant uses it. */\nexport interface SidebarRightTabsService {\n /** Register one type; the returned disposer removes it and is idempotent. */\n register(definition: SidebarRightTabDefinition): () => void\n}\n\n/** Live tab information the framework binds for a body: the presentation and the record. */\nexport interface SidebarTabInfo {\n readonly tab: {\n /** Only a tab on screen is visible: a docked body requires expansion and selection, a float survives a collapse. */\n readonly visible: boolean\n }\n}\n\n/**\n * The framework's own props for a `sidebar.right.pane.tab` body.\n *\n * `sessionId` is the slot's session scope; `useTabInfo` is the slot-owned hook\n * the framework injects (declared as `inject.hooks.tabInfo` in the slot map and\n * delivered flattened under that `use…` name). Both are optional here because a\n * composition — or a test — may hand the body neither, and this module falls\n * back rather than throwing.\n */\nexport interface SidebarTabFrameworkProps {\n readonly sessionId?: string | undefined\n readonly useTabInfo?: (() => SidebarTabInfo) | undefined\n}\n\n/** Owner share of one actions-menu occurrence: the menu's own dismiss seat. */\nexport interface SidebarTabMenuOwnerProps {\n readonly dismiss?: (() => void) | undefined\n}\n\n/**\n * Options one `slots.register` accepts, as far as this module uses them.\n *\n * `key` addresses a keyed seat; `id` and `order` place a list entry.\n */\nexport interface SidebarTabSlotOptions {\n name: string\n key?: string | undefined\n id?: string | undefined\n order?: number | undefined\n}\n\n/** The slot service, as this module's registrants use it. */\nexport interface SidebarTabSlots {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(options: SidebarTabSlotOptions, component: (props: Props) => ReactNode): unknown\n}\n\n/** The client services the tab's registration needs; each may be absent from a composition. */\nexport interface SidebarTabServices {\n effect(execute: () => unknown, label?: string): unknown\n slots: SidebarTabSlots\n sidebarRightTabs: SidebarRightTabsService\n}\n\n/** The tab body's props: the framework's own, plus the seats this module binds. */\nexport interface SidebarTabBodyProps {\n /** The session the tab belongs to — the panel shows that session's project only. */\n sessionId: string | undefined\n /** Whether the tab is on screen; an off-screen panel stops polling. */\n visible: boolean\n /** The poll interval, followed live so a change in the settings popup reaches the panel. */\n refreshMs: number\n t: Translate\n hostT: Translate\n}\n\n/** The settings popup's content, with the seats it needs. */\nexport interface SidebarSettingsProps {\n refreshMs: number\n /** Write a new interval; the popup's own row is the only writer. */\n onRefreshMs: (value: number) => void\n onClose: () => void\n t: Translate\n hostT: Translate\n}\n\n/**\n * Whether the settings popup is on screen, and how the menu row reaches it.\n *\n * The row and the popup are not in one tree: an actions-menu item that acts must\n * dismiss the menu, so the row cannot render the popup itself — it opens this\n * store, the menu closes, and the popup's own entry in the floating layer renders\n * from the same value. It is a store rather than a state setter because exactly\n * one side opens and the other subscribes.\n */\nexport interface SettingsDialogStore {\n isOpen(): boolean\n open(): void\n close(): void\n subscribe(listener: () => void): () => void\n}\n\n/**\n * Build a {@link SettingsDialogStore}, closed.\n * @returns the store the menu row and the popup share.\n */\nexport function createSettingsDialogStore(): SettingsDialogStore {\n let open = false\n const listeners = new Set<() => void>()\n const publish = (next: boolean): void => {\n if (next === open) return\n open = next\n for (const listener of listeners) listener()\n }\n return {\n isOpen: () => open,\n open: () => publish(true),\n close: () => publish(false),\n subscribe: (listener: () => void): (() => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\n/** Run one render when `open` flips, so a closed popup draws nothing at all. */\nfunction useSettingsOpen(store: SettingsDialogStore): boolean {\n const [open, setOpen] = useState(() => store.isOpen())\n useEffect(() => store.subscribe(() => setOpen(store.isOpen())), [store])\n return open\n}\n\n/** Follow the interval store so both the body and the popup re-render on a change. */\nfunction useRefreshMs(store: RefreshStore): number {\n const [value, setValue] = useState(() => store.get())\n useEffect(() => store.subscribe(() => setValue(store.get())), [store])\n return value\n}\n\n/** Copy the type publishes to the guide page; overridable so the design stand can name its picture. */\nexport interface SidebarTabCopy {\n title: () => string\n description: () => string\n}\n\n/** What {@link registerSidebarTab} wires up; the product and the design stand differ only here. */\nexport interface RegisterSidebarTabOptions {\n /** The shell's locale service, when the composition has one. */\n locale: TabLocale | undefined\n /** The poll interval shared by the body and the popup. */\n refresh: RefreshStore\n /** The tab body. */\n body: (props: SidebarTabBodyProps) => ReactNode\n /** The popup's content. */\n settings: (props: SidebarSettingsProps) => ReactNode\n /** The guide page's copy for this type; the product's own by default. */\n copy?: SidebarTabCopy | undefined\n}\n\n/** Nothing on screen when no tab information arrives: the frame renders every entry, hidden or not. */\nconst ALWAYS_VISIBLE: SidebarTabInfo = { tab: { visible: true } }\n\nfunction useAlwaysVisible(): SidebarTabInfo {\n return ALWAYS_VISIBLE\n}\n\n/**\n * Register the panel as a tab type of DSH's own right sidebar.\n *\n * Five registrations, all disposed with the fiber: the type in the registry, its\n * body and its chip title under their keyed seats, the settings row in the chip's\n * actions menu, and the settings popup in the frame-wide floating layer. A\n * composition that lacks any of the services keeps the surfaces it has — the\n * settings page, the toasts and the host half never depend on this module.\n * @param services - the injected `slots` registry, the right-sidebar tab registry, and `effect`.\n * @param options - the two surfaces to draw, the interval they share, and the guide copy.\n */\nexport function registerSidebarTab(\n services: SidebarTabServices,\n options: RegisterSidebarTabOptions,\n): void {\n const t = tabTranslate(options.locale)\n const copy: SidebarTabCopy = options.copy ?? {\n title: () => t('tab'),\n description: () => t('tabDescription'),\n }\n const store = createSettingsDialogStore()\n\n services.effect(\n () =>\n services.sidebarRightTabs.register({\n id: TAB_ID,\n kind: TAB_KIND,\n title: () => copy.title(),\n guide: [\n {\n id: TAB_GUIDE_ENTRY_ID,\n order: TAB_GUIDE_ORDER,\n title: () => copy.title(),\n description: () => copy.description(),\n },\n ],\n }),\n 'dsh-project-mcp: sidebar tab type',\n )\n\n services.slots.inject(TAB_SLOT, () =>\n services.slots.register({ name: TAB_SLOT, key: TAB_ID }, (props: SidebarTabFrameworkProps) =>\n h(TabBody, { framework: props, locale: options.locale, refresh: options.refresh, body: options.body }),\n ),\n )\n\n // The chip's title is re-read here on every render, which is what makes the\n // tab's own label follow a language switch. The registry's `title` thunk above\n // only covers the moment a tab opens: a record keeps the text it was minted\n // with until this seat overrides it.\n services.slots.inject(TAB_TITLE_SLOT, () =>\n services.slots.register({ name: TAB_TITLE_SLOT, key: TAB_ID }, () => h(TabChipTitle, { copy })),\n )\n\n services.slots.inject(TAB_MENU_SLOT, () =>\n services.slots.register(\n { name: TAB_MENU_SLOT, id: TAB_MENU_ID, order: TAB_MENU_ORDER },\n (props: SidebarTabMenuOwnerProps) =>\n h(MenuRow, { locale: options.locale, store, dismiss: props.dismiss }),\n ),\n )\n\n services.slots.inject(SETTINGS_DIALOG_SLOT, () =>\n services.slots.register(\n { name: SETTINGS_DIALOG_SLOT, id: SETTINGS_DIALOG_ID, order: SETTINGS_DIALOG_ORDER },\n () =>\n h(SettingsDialog, {\n locale: options.locale,\n store,\n refresh: options.refresh,\n settings: options.settings,\n }),\n ),\n )\n}\n\n/**\n * The tab body: the framework's props, the two translate seats and the live\n * interval, handed to the surface the entry supplied.\n * @param props - the framework's share plus the registration's own options.\n * @returns the panel element tree.\n */\nexport function TabBody(props: {\n framework: SidebarTabFrameworkProps\n locale: TabLocale | undefined\n refresh: RefreshStore\n body: (props: SidebarTabBodyProps) => ReactNode\n}): ReactNode {\n const t = useTabTranslate(props.locale)\n const hostT = hostTranslate(props.locale)\n const refreshMs = useRefreshMs(props.refresh)\n // Called unconditionally — the framework injects this hook for the seat. A\n // composition that somehow hands none is drawn as an on-screen tab rather than\n // as an error: `visible` only paces the panel's own polling.\n const info = (props.framework.useTabInfo ?? useAlwaysVisible)()\n // An element, not a bare call: the body is a component of its own, so its\n // hooks belong to its own fiber rather than to this adapter's.\n return h(props.body, {\n sessionId: props.framework.sessionId,\n visible: info.tab.visible,\n refreshMs,\n t,\n hostT,\n })\n}\n\n/**\n * The chip's title: the type's own name, read through the entry's copy thunk on\n * every render.\n *\n * The registry captures a title when a tab opens, and a record keeps that text\n * until this seat replaces it — so without this registration an open tab would\n * keep whatever language it was opened in. The component takes nothing from the\n * tab: the panel's label is the same for every occurrence.\n * @param props - the type's copy.\n * @returns the title text.\n */\nexport function TabChipTitle(props: { copy: SidebarTabCopy }): ReactNode {\n return props.copy.title()\n}\n\n/**\n * The row this plugin adds to a tab chip's actions menu.\n *\n * It dismisses the menu first — the contract for an item that acts, and the\n * reason the popup is not drawn here: the menu unmounts on dismiss, so a popup\n * inside the item would go with it. The row reads the plugin's own dictionary and\n * follows the language like every other surface.\n * @param props - the locale seat, the store the popup subscribes to, and the menu's dismiss seat.\n * @returns the menu item.\n */\nexport function MenuRow(props: {\n locale: TabLocale | undefined\n store: SettingsDialogStore\n dismiss?: (() => void) | undefined\n}): ReactNode {\n const t = useTabTranslate(props.locale)\n return h(\n 'button',\n {\n type: 'button',\n role: 'menuitem',\n style: STYLE.menuItem,\n onClick: () => {\n props.dismiss?.()\n props.store.open()\n },\n },\n t('settingsMenuItem'),\n )\n}\n\n/**\n * The settings popup: the tab's own settings, rendered as an entry of the\n * frame-wide floating layer.\n *\n * Nothing is drawn while the popup is closed, so the layer holds an empty cell\n * and the frame's click-through is untouched. The backdrop is the entry's own\n * element, which is what makes the layer's `pointer-events: auto` rule apply to\n * it.\n * @param props - the locale seat, the open/closed store, the interval and the content.\n * @returns the backdrop with the popup card, or `null` while it is closed.\n */\nexport function SettingsDialog(props: {\n locale: TabLocale | undefined\n store: SettingsDialogStore\n refresh: RefreshStore\n settings: (props: SidebarSettingsProps) => ReactNode\n}): ReactNode {\n const t = useTabTranslate(props.locale)\n const hostT = hostTranslate(props.locale)\n const refreshMs = useRefreshMs(props.refresh)\n const open = useSettingsOpen(props.store)\n if (!open) return null\n const close = (): void => props.store.close()\n return h(\n 'div',\n { style: STYLE.backdrop, onClick: close },\n h(\n 'div',\n {\n style: STYLE.dialog,\n role: 'dialog',\n 'aria-modal': true,\n 'aria-label': t('settingsMenuItem'),\n // A press inside the card must not reach the backdrop's close.\n onClick: (event: { stopPropagation: () => void }) => event.stopPropagation(),\n },\n // An element too: the popup's content is a component with hooks of its\n // own — the panel polls, and a bare call would fold them into this frame.\n h(props.settings, {\n refreshMs,\n onRefreshMs: (value: number) => props.refresh.set(value),\n onClose: close,\n t,\n hostT,\n }),\n ),\n )\n}\n\n/**\n * The entries' own style.\n *\n * The popup is deliberately not the panel's `STYLE`: it draws a menu row and a\n * frame-wide card, and neither is part of the tab's surface contract. The tokens\n * are the same alias variables every other surface uses, so the card follows the\n * theme — including the design stand's, which renders the same components.\n */\nconst STYLE = {\n /**\n * The menu row. The kit's own items are hashed CSS the plugin cannot borrow,\n * so the row is drawn the way the plugin draws every other control: an inline\n * style over the alias tokens, matching the kit's item in size and weight.\n */\n menuItem: {\n display: 'block',\n width: '100%',\n padding: '4px 10px',\n border: 'none',\n borderRadius: 4,\n background: 'transparent',\n color: 'inherit',\n font: 'inherit',\n textAlign: 'left',\n cursor: 'pointer',\n } satisfies CSSProperties,\n /** The layer spans the frame, so the backdrop does too; the card is centred over the whole application. */\n backdrop: {\n position: 'absolute',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: 'rgba(0, 0, 0, 0.4)',\n } satisfies CSSProperties,\n /**\n * The card, which scrolls its own content: the panel lists every project with\n * a live session, and a project with many servers is taller than any window.\n */\n dialog: {\n maxWidth: 'min(560px, 92vw)',\n maxHeight: '80vh',\n overflowY: 'auto',\n borderRadius: 8,\n border: '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.25))',\n background: 'var(--dsw-alias-bg-layer-2, #1f1f22)',\n color: 'var(--dsw-alias-label-primary, inherit)',\n boxShadow: '0 12px 32px rgba(0, 0, 0, 0.45)',\n } satisfies CSSProperties,\n} as const\n","/**\n * `dsh-project-mcp`, frame-wide toasts: one banner per MCP server that comes\n * up, fails, or is released — announced wherever the user is, rather than only\n * inside the sidebar tab's «Logs» mode.\n *\n * The seat is `shell.overlay` (`kind: 'list'`, `scope: 'root'`), DSH's\n * frame-wide floating layer: additive, owned by no feature, and click-through\n * until an entry opts into pointer events. Its catalog names a toast stack as\n * one of the things that belong there, so this module adds an entry **beside**\n * the shipped ones and declares no slot of its own. The composer dock that\n * F-05 removed is not coming back: nothing here paints into a surface this\n * plugin does not own.\n *\n * The source is the host's status channel, `GET /project-mcp/events` (see\n * `createEventStream` in `src/ui.ts`), the same stream the sidebar panel falls\n * back from polling to. A toast is not a second source of truth: every frame\n * carries the whole snapshot, and this module only diffs the picture it already\n * had for {@link ServerRow.status} transitions, so a missed frame costs one\n * banner rather than a wrong one.\n *\n * What a toast cannot say: a **stall** is not a lifecycle transition in the\n * snapshot — the row stays `connecting` and only its `detail` wording changes —\n * so stalls stay in the «Logs» tab and in the DSH log instead of becoming\n * banners.\n *\n * A draft carries dictionary keys and parameters, never a finished sentence:\n * the stack resolves them at render through the tab's translate seat\n * (`useTabTranslate`), so a language switch repaints the banners already on\n * screen instead of freezing the language of whatever the store holds (F-47).\n *\n * @module dsh-project-mcp/client/toasts\n */\n\nimport { createElement as h, useEffect, useState } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { ROUTE_ACTIONS, ROUTE_PREFIX } from '../shared.ts'\nimport type { McpSnapshot, ServerRow, SnapshotChange } from '../types.ts'\nimport type { UiKey } from './locales/ui.ts'\nimport { hostTranslate, resolveHost } from './locales/host.ts'\nimport { useTabTranslate } from './tab-locale.ts'\nimport type { TabLocale } from './tab-locale.ts'\nimport { STATUS_COLOR, STATUS_HINT, basename, translateOf } from './view.ts'\nimport type { Translate } from './view.ts'\n\n/** Slot the stack registers into: DSH's frame-wide floating layer. */\nexport const TOASTS_SLOT = 'shell.overlay'\n\n/** Registration id, unique among the layer's entries, and the cell it owns. */\nexport const TOASTS_ID = 'dsh-project-mcp:toasts'\n\n/** Position among the layer's entries, ascending. */\nexport const TOASTS_ORDER = 60\n\n/** Full-opacity hold before a banner starts to fade, matching DSH's own toast. */\nexport const TOAST_HOLD_MS = 3_000\n\n/** Fade duration, matching the `transition` the banner carries. */\nexport const TOAST_FADE_MS = 1_000\n\n/**\n * Banners kept on screen at once.\n *\n * A pass can start every server of a project in one go, and a stack taller than\n * the window is a stack nobody reads: the newest {@link MAX_TOASTS} are kept\n * and older ones drop, the same way a notification centre ages out its tail.\n */\nexport const MAX_TOASTS = 3\n\n/** Which lifecycle moment a banner reports. */\nexport type ToastLevel =\n /** The server reached `active`: mounted, its tools are visible. */\n | 'up'\n /** The server landed in `error`: the entry or its mount failed. */\n | 'error'\n /** An active server went back to `idle`: its mounts were dropped. */\n | 'released'\n\n/** One banner before the store stamps it with an identity. */\nexport interface ToastDraft {\n readonly level: ToastLevel\n /** `serverName` the transition belongs to. */\n readonly server: string\n /** Basename of the project root, so a banner fits on one line. */\n readonly project: string\n /**\n * Dictionary key of the one line — what happened to the server — resolved\n * through the seat at render, so a stored banner follows a language switch.\n */\n readonly textKey: UiKey\n /** Parameters of that line (`{server}`). */\n readonly textParams?: Record<string, unknown> | undefined\n /**\n * Dictionary key of the fact the quieter line explains — a status hint —\n * with the project woven around it (`toastDetail`). Absent, the quieter line\n * is just {@link ToastDraft.detail}, a language-neutral string.\n */\n readonly detailKey?: UiKey | undefined\n /**\n * The host's own fact sentence, shown instead of the keyed hint when the row\n * carries one; when {@link ToastDraft.detailKey} is absent, the whole\n * quieter line (the project basename).\n */\n readonly detail?: string | undefined\n /**\n * Wire companions of {@link ToastDraft.detail} (F-48): the row's\n * `detailCode`/`detailParams`, carried through so the quieter line resolves\n * through the host namespace at render and falls back to the prose when the\n * code is absent or unknown.\n */\n readonly detailCode?: string | undefined\n /** Flat params of {@link ToastDraft.detailCode}. */\n readonly detailParams?: Record<string, string> | undefined\n}\n\n/** One banner on screen. */\nexport interface Toast extends ToastDraft {\n /** Identity the store mints; also the React key and the dismiss handle. */\n readonly id: number\n}\n\n/**\n * The stack's own state.\n *\n * A plain observable rather than React state, because the writer is the status\n * channel and the reader is the slot entry: they are not in one component tree,\n * and only the store has to survive the slot re-registering.\n */\nexport interface ToastStore {\n /** Current banners, newest first. */\n getSnapshot(): readonly Toast[]\n /** Listen for changes; returns the unsubscribe. */\n subscribe(listener: () => void): () => void\n /** Add one banner, dropping the tail beyond the limit. */\n push(draft: ToastDraft): void\n /** Retire one banner; an unknown id is a no-op. */\n dismiss(id: number): void\n}\n\n/**\n * Build one stack's store.\n * @param limit - banners kept at once; defaults to {@link MAX_TOASTS}.\n * @returns the store the entry renders from.\n */\nexport function createToastStore(limit: number = MAX_TOASTS): ToastStore {\n let toasts: readonly Toast[] = []\n let minted = 0\n const listeners = new Set<() => void>()\n /** Publish one new array: the snapshot identity is what React compares. */\n const publish = (next: readonly Toast[]): void => {\n toasts = next\n for (const listener of [...listeners]) listener()\n }\n return {\n getSnapshot: () => toasts,\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n push(draft) {\n minted += 1\n publish([{ ...draft, id: minted }, ...toasts].slice(0, Math.max(0, limit)))\n },\n dismiss(id) {\n const next = toasts.filter((toast) => toast.id !== id)\n if (next.length !== toasts.length) publish(next)\n },\n }\n}\n\n/** Identity of one row across frames: a server name is unique per project. */\nfunction keyOf(row: ServerRow): string {\n return `${row.projectRoot}\\u0000${row.name}`\n}\n\n/**\n * Every row of one picture, keyed by project and server.\n * @param snapshot - a picture.\n * @returns the keyed rows.\n */\nfunction rowsOf(snapshot: McpSnapshot): Map<string, ServerRow> {\n const rows = new Map<string, ServerRow>()\n for (const project of snapshot.projects) {\n for (const row of project.rows) rows.set(keyOf(row), row)\n }\n return rows\n}\n\n/** The banner one row's new state earns, when it earns one. */\nfunction transitionToast(was: ServerRow | undefined, row: ServerRow): ToastDraft | undefined {\n const project = basename(row.projectRoot)\n if (row.status === 'active') {\n return {\n level: 'up',\n server: row.name,\n project,\n textKey: 'toastUp',\n textParams: { server: row.name },\n detail: project,\n }\n }\n if (row.status === 'error') {\n return {\n level: 'error',\n server: row.name,\n project,\n textKey: 'toastFailed',\n textParams: { server: row.name },\n detailKey: STATUS_HINT.error,\n detail: row.detail,\n ...(row.detailCode === undefined ? {} : { detailCode: row.detailCode }),\n ...(row.detailParams === undefined ? {} : { detailParams: row.detailParams }),\n }\n }\n // Only an active server *loses* mounts; `idle` reached from `connecting` or\n // `disabled` is a picture of a server that never came up, not a release.\n if (row.status === 'idle' && was?.status === 'active') {\n return {\n level: 'released',\n server: row.name,\n project,\n textKey: 'toastReleased',\n textParams: { server: row.name },\n detailKey: STATUS_HINT.idle,\n }\n }\n return undefined\n}\n\n/**\n * The banners two consecutive pictures earn.\n *\n * Read from status alone, and only when the status actually changed: a rescan\n * that re-derives the same rows announces nothing, and a row that moves between\n * two non-terminal states (`idle → connecting` on the next turn's lazy mount)\n * is not a lifecycle moment worth a banner.\n * @param previous - the picture already applied; `undefined` makes `next` the baseline.\n * @param next - the picture a `change` frame just delivered.\n * @returns banners, oldest transition first; empty for a baseline or a quiet frame.\n */\nexport function serverTransitions(previous: McpSnapshot | undefined, next: McpSnapshot): ToastDraft[] {\n if (previous === undefined) return []\n const before = rowsOf(previous)\n const drafts: ToastDraft[] = []\n for (const [key, row] of rowsOf(next)) {\n const was = before.get(key)\n if (was?.status === row.status) continue\n const draft = transitionToast(was, row)\n if (draft !== undefined) drafts.push(draft)\n }\n return drafts\n}\n\n/**\n * Read one frame's payload.\n *\n * A frame this plugin cannot read is dropped, not guessed at: the stream is\n * whole-picture, so the next frame is a complete answer, and a half-parsed\n * snapshot would produce phantom transitions.\n * @param data - `MessageEvent.data` of a `hello`/`change` frame.\n * @returns the change, or `undefined` when the payload is not one.\n */\nexport function parseChange(data: unknown): SnapshotChange | undefined {\n if (typeof data !== 'string') return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return undefined\n }\n if (parsed === null || typeof parsed !== 'object') return undefined\n const { revision, snapshot } = parsed as { revision?: unknown; snapshot?: unknown }\n if (typeof revision !== 'number') return undefined\n if (snapshot === null || typeof snapshot !== 'object') return undefined\n if (!Array.isArray((snapshot as { projects?: unknown }).projects)) return undefined\n return { revision, snapshot: snapshot as McpSnapshot }\n}\n\n/** The part of `EventSource` this module uses, so a test can hand it a stand-in. */\nexport interface FollowSource {\n addEventListener(type: string, listener: (event: Event) => void): void\n close(): void\n}\n\n/**\n * How the channel is opened.\n *\n * A seam for tests: the channel is the one thing in this module that talks to\n * the browser, so a test hands it a stand-in rather than patching a global, and\n * the default is the only place that reaches for `EventSource`.\n */\nexport type OpenSource = (url: string) => FollowSource | undefined\n\n/** Open the status channel, or nothing in an environment without `EventSource`. */\nfunction defaultOpen(url: string): FollowSource | undefined {\n return typeof EventSource === 'undefined' ? undefined : new EventSource(url)\n}\n\n/**\n * Follow the host's status channel and raise one banner per transition.\n *\n * The stream carries two frame kinds: `hello` is the picture as it is — on\n * open and on every reconnect the browser's `EventSource` performs — and\n * `change` is one announced change. `hello` only resets the baseline, so a page\n * load, a dropped connection and a late join never read as twenty servers\n * starting at once. A frame whose revision is not newer than the last applied\n * one is repeated or replayed, and is ignored for the same reason.\n * @param store - the stack to push banners into.\n * @param open - channel factory; defaults to a real `EventSource`.\n * @returns the disposer that closes the channel.\n */\nexport function followServers(store: ToastStore, open: OpenSource = defaultOpen): () => void {\n const source = open(`${ROUTE_PREFIX}/${ROUTE_ACTIONS.events}`)\n if (source === undefined) return () => undefined\n let previous: McpSnapshot | undefined\n let revision = Number.NEGATIVE_INFINITY\n /** Apply one frame's picture; `raise` is false for the baseline `hello`. */\n const apply = (event: Event, raise: boolean): void => {\n const change = parseChange((event as MessageEvent).data)\n if (change === undefined || change.revision <= revision) return\n if (raise) {\n for (const draft of serverTransitions(previous, change.snapshot)) store.push(draft)\n }\n previous = change.snapshot\n revision = change.revision\n }\n source.addEventListener('hello', (event) => apply(event, false))\n source.addEventListener('change', (event) => apply(event, true))\n return () => source.close()\n}\n\n/** The slot service, as this registrant uses it; mirrored structurally, not imported. */\nexport interface ToastSlots {\n inject(slot: string, callback: () => unknown): unknown\n register<Props>(\n options: { name: string; id: string; order: number },\n component: (props: Props) => ReactNode,\n ): () => void\n}\n\n/**\n * The one client service the stack needs.\n *\n * It is optional in a composition — a shell without the floating layer simply\n * has no banners — which is why registration goes through `ctx.inject` rather\n * than a module-level `inject` list: a composition without `slots` must keep\n * the sidebar tab and the settings page, and must not leave this entry pending.\n * The locale service is the tab's own seat: with it, a language switch repaints\n * the banners on screen; without it, the stack renders its English fallback.\n */\nexport interface ToastsServices {\n slots: ToastSlots\n /** The shell's locale service, when the composition has one. */\n locale?: TabLocale | undefined\n}\n\n/**\n * Contribute the stack to the frame's floating layer.\n *\n * `slots.register` throws on a duplicate list id, so the entry and the channel\n * are installed behind one disposer and that disposer is returned to\n * `slots.inject`: a second run — the layer's declaration collapsing and coming\n * back, or an HMR reload — tears the first activation down before the second\n * registers, instead of throwing away the whole entry or following the channel\n * twice.\n * @param services - the injected `slots` service, and the locale seat.\n */\nexport function registerToasts(services: ToastsServices): void {\n const store = createToastStore()\n /** The live activation, so a repeat of the injection can never leave two. */\n let stop: (() => void) | undefined\n services.slots.inject(TOASTS_SLOT, () => {\n stop?.()\n const entry = services.slots.register({ name: TOASTS_SLOT, id: TOASTS_ID, order: TOASTS_ORDER }, () =>\n h(ToastStack, { store, locale: services.locale }),\n )\n const channel = followServers(store)\n stop = () => {\n channel()\n entry()\n stop = undefined\n }\n return stop\n })\n}\n\n/** The tones a banner's dot takes, from the panel's own status palette. */\nconst LEVEL_COLOR: Record<ToastLevel, string> = {\n up: STATUS_COLOR.active,\n error: STATUS_COLOR.error,\n released: STATUS_COLOR.idle,\n}\n\n/**\n * The stack's own styles.\n *\n * The banner mirrors DSH's shipped `Toast` (`ui-primitives`): the same alias\n * variables, radius, padding and type, so a banner reads as a shell surface\n * rather than a plugin's own invention. The difference is placement — that\n * toast portals to the body and centers itself on the viewport, while this one\n * is an entry of the floating layer, which spans the frame and already sits\n * above every column.\n */\nconst STYLE = {\n stack: {\n position: 'absolute',\n top: 12,\n left: '50%',\n transform: 'translateX(-50%)',\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n gap: 8,\n // Same bound as one banner: the frame's center is where a long failure\n // sentence would otherwise size itself against half the window.\n maxWidth: 'min(640px, calc(100vw - 48px))',\n // Announcements never intercept clicks: the layer is click-through until an\n // entry opts in, and this entry opts back out for its whole subtree.\n pointerEvents: 'none',\n } satisfies CSSProperties,\n banner: {\n display: 'flex',\n alignItems: 'center',\n gap: 10,\n width: 'max-content',\n maxWidth: 'min(640px, calc(100vw - 48px))',\n padding: '12px 16px',\n borderRadius: 14,\n background: 'var(--dsw-alias-button-contrast-fill, rgba(20, 22, 26, 0.92))',\n color: 'var(--dsw-alias-label-primary-inverted, #fff)',\n fontSize: 14,\n lineHeight: '22px',\n boxShadow: 'var(--dsw-shadow-lv3, 0 8px 24px rgba(0, 0, 0, 0.28))',\n transition: `opacity ${TOAST_FADE_MS}ms ease`,\n } satisfies CSSProperties,\n /** The tail of a banner's life: it is already retired, only the fade is left. */\n fading: { opacity: 0 } satisfies CSSProperties,\n dot: {\n flex: 'none',\n width: 8,\n height: 8,\n borderRadius: 999,\n } satisfies CSSProperties,\n body: { minWidth: 0 } satisfies CSSProperties,\n detail: { opacity: 0.75, fontSize: 12, lineHeight: '18px' } satisfies CSSProperties,\n} as const\n\n/** Read one banner off the store and follow it while the entry is mounted. */\nfunction useToasts(store: ToastStore): readonly Toast[] {\n const [toasts, setToasts] = useState<readonly Toast[]>(store.getSnapshot())\n useEffect(() => store.subscribe(() => setToasts(store.getSnapshot())), [store])\n return toasts\n}\n\n/**\n * The stack the floating layer renders.\n *\n * Nothing is rendered while there is nothing to say, so the layer holds no\n * empty box between banners. The live-region role is on the stack rather than\n * on a banner, because a banner mounts and unmounts on its own timer. The\n * translate seat is bound here: drafts carry keys, and `useTabTranslate`\n * re-reads them when the shell's language changes, so the banners on screen\n * repaint without the store re-deriving anything.\n * @param props.store - the stack's state.\n * @param props.locale - the shell's locale service, when there is one.\n * @returns the banners, newest first, or `null`.\n */\nexport function ToastStack(props: { store: ToastStore; locale?: TabLocale | undefined }): ReactNode {\n const toasts = useToasts(props.store)\n const t = useTabTranslate(props.locale)\n // The host namespace beside the UI one: a banner whose row carried a coded\n // detail (F-48) resolves it through this seat, and the repaint still rides\n // on `t`'s re-bind.\n const hostT = hostTranslate(props.locale)\n if (toasts.length === 0) return null\n return h(\n 'div',\n { style: STYLE.stack, role: 'status', 'aria-live': 'polite' },\n toasts.map((toast) => h(ToastRow, { key: toast.id, toast, store: props.store, t, hostT })),\n )\n}\n\n/**\n * The quieter line of one banner, resolved through the seat at render time.\n *\n * A keyed fact is a status hint the project is woven around (`toastDetail`);\n * the host's own detail sentence wins over the hint when the row carries one;\n * a draft with no key at all shows its language-neutral line as it is. A coded\n * detail (F-48) resolves through the host seat first and falls back to its\n * prose when the code is absent or unknown, so an uncoded banner reads exactly\n * as before.\n * @param toast - the banner to read.\n * @param t - the translate seat.\n * @param hostT - the host-namespace seat; the echo seat answers without one.\n * @returns the line, or `undefined` when the banner has none.\n */\nfunction detailLine(toast: ToastDraft, t: Translate, hostT: Translate): string | undefined {\n if (toast.detailKey === undefined) {\n if (toast.detail === undefined && toast.detailCode === undefined) return undefined\n return resolveHost(hostT, toast.detailCode, toast.detailParams, toast.detail)\n }\n const fact =\n toast.detailCode === undefined\n ? toast.detail ?? t(toast.detailKey)\n : resolveHost(hostT, toast.detailCode, toast.detailParams, toast.detail ?? t(toast.detailKey))\n return t('toastDetail', { project: toast.project, detail: fact })\n}\n\n/**\n * One banner: full opacity for {@link TOAST_HOLD_MS}, then a fade of\n * {@link TOAST_FADE_MS}, then retired from the store.\n *\n * Two timers rather than one, because the fade is a real transition the user\n * sees; a single timer would drop the banner from full opacity to nothing.\n * @param props.toast - the banner to draw.\n * @param props.store - the stack it belongs to, so it can retire itself.\n * @param props.t - the translate seat the stack bound; the panel's English\n * fallback answers without one.\n * @returns the banner element.\n */\nexport function ToastRow(props: {\n toast: Toast\n store: ToastStore\n t?: Translate | undefined\n /** Host-namespace seat for a coded detail (F-48); the echo seat answers without one. */\n hostT?: Translate | undefined\n}): ReactNode {\n const [fading, setFading] = useState(false)\n const { store, toast } = props\n const t = translateOf(props.t)\n const detail = detailLine(toast, t, props.hostT ?? hostTranslate(undefined))\n useEffect(() => {\n const hold = setTimeout(() => setFading(true), TOAST_HOLD_MS)\n return () => clearTimeout(hold)\n }, [])\n useEffect(() => {\n if (!fading) return\n const fade = setTimeout(() => store.dismiss(props.toast.id), TOAST_FADE_MS)\n return () => clearTimeout(fade)\n }, [fading, store, props.toast.id])\n return h(\n 'div',\n { style: fading ? { ...STYLE.banner, ...STYLE.fading } : STYLE.banner },\n h('span', { style: { ...STYLE.dot, background: LEVEL_COLOR[toast.level] } }),\n h(\n 'span',\n { style: STYLE.body },\n h('div', null, t(toast.textKey, toast.textParams)),\n detail === undefined ? null : h('div', { style: STYLE.detail }, detail),\n ),\n )\n}\n","/**\n * The pictures the design surfaces draw.\n *\n * `./design.ts` mounts the three browser surfaces with **no host half at all**:\n * nothing is mounted, no route is called, and the sidebar tab, its settings\n * popover and the settings page are rendered from the fixtures below. That keeps\n * the interface reviewable on a machine with no live project and no MCP server,\n * which is the whole point of the mode.\n *\n * Every field here is the shape the host really publishes (`src/types.ts`), and\n * the `full` picture is the same one the parity gate feeds the live panel\n * (`scripts/design-parity.mjs`): seven servers covering all four status tones, a\n * session that disagrees with its project, a failure with its detail, four\n * events in the ring and a tool offer with pinned, disclosed and hidden names.\n * The other pictures isolate one state each, so a designer can look at it alone.\n *\n * @module dsh-project-mcp/client/design-fixtures\n */\n\nimport type {\n LogEvent,\n McpSnapshot,\n ProjectSnapshot,\n ServerRow,\n ServerStatus,\n ServerUsage,\n SessionSnapshot,\n SessionTools,\n ToolFacts,\n ToolPolicy,\n} from '../types.ts'\nimport type { ToastDraft } from './toasts.ts'\nimport { STATUS_HINT, seedToolFacts } from './view.ts'\n\n/** Session the fixtures belong to; `shortSessionId` renders it as `8fce1c`. */\nexport const DESIGN_SESSION = 'session-8fce1c-4a3f-4d0b-9c11-2f6a7b8c9d10'\n\n/** Neutral placeholder project, as the repository's conventions require. */\nexport const DESIGN_PROJECT_ROOT = '/example/service'\n\n/** The declaring document of every fixture row. */\nexport const DESIGN_DOCUMENT = `${DESIGN_PROJECT_ROOT}/.dsh/mcp.json`\n\n/** The detail a failed mount carries: three facts, no advice (`F-03`). */\nexport const DESIGN_FAILURE =\n `no tool appeared within 60.2s; endpoint stdio docker; declared in ${DESIGN_DOCUMENT}`\n\n/** How long the quiet fixture server has been unused, as the stand shows it. */\nconst DESIGN_IDLE_MS = 3 * 24 * 60 * 60 * 1000\n\n/**\n * The host's usage counters for the picture (`ProjectSnapshot.usage`).\n *\n * The three states the panel can draw are all here, because a stand that shows\n * only the happy one hides the rule that matters: `tglider` has counts for both\n * its tools, `grafana-local` has a record whose `tools` came back empty — the\n * row prints `never called` rather than a zero nobody counted — and every other\n * server has no record at all, so its rows carry no figure. `graph` is quiet\n * with a three-day-old date, which is the one row that draws `idle 3d`; the\n * figure is computed at module load so the stand always shows the same reading.\n *\n * The split is the other half of the rule (F-34): this session called\n * `workspace` 3 times while the project counted 182, so the row shows both, and\n * it never called `catalog`, so that row reads `never called · 96 in the\n * project`. A project whose host publishes no split draws one number, which is\n * what the other pictures show.\n */\nexport const DESIGN_USAGE: Record<string, ServerUsage> = {\n tglider: {\n calls: 182,\n errors: 0,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS / 3).toISOString(),\n tools: { workspace: 182, catalog: 96 },\n sessions: {\n [DESIGN_SESSION]: {\n calls: 3,\n errors: 0,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS / 3).toISOString(),\n tools: { workspace: 3 },\n },\n },\n },\n 'grafana-local': {\n calls: 0,\n errors: 0,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS).toISOString(),\n tools: {},\n },\n context7: {\n calls: 12,\n errors: 1,\n lastUsedAt: new Date(Date.now() - DESIGN_IDLE_MS * 2).toISOString(),\n tools: { docs: 12 },\n },\n}\n\n/**\n * The definitions the stand's own host publishes (F-56).\n *\n * The body of an opened row is answered by `GET tool`, a route the stand has no\n * host behind: without these records every open row of the design surfaces would\n * sit on a read that never lands. The records are the picture's own — they agree\n * with {@link DESIGN_USAGE} (`workspace` was called, `catalog` never) and with\n * {@link designTools} — so the stand draws the real body: a description, a field\n * list with one required field and one nested object drawn as its type, and the\n * reason a deferred name is not in the request.\n *\n * They are seeded into the panel's own cache ({@link designProject} calls\n * {@link seedDesignToolFacts}), not branched on inside the row: `view.ts` has no\n * code path that knows whether an answer came from a socket, and the stand must\n * render the product's body rather than a second drawing of it.\n */\nexport const DESIGN_TOOL_FACTS: Record<string, ToolFacts> = {\n 'mcp__tglider__workspace': {\n name: 'mcp__tglider__workspace',\n description:\n 'Workspace overview: changed symbols, diagnostics and the files that carry them, as one page.',\n fields: [\n {\n name: 'path',\n type: 'string',\n required: true,\n description: 'Directory to read, relative to the project root.',\n },\n {\n name: 'depth',\n type: 'number',\n required: false,\n description: 'How deep the dependency walk may go.',\n },\n {\n // An object field is drawn as its own type and not expanded: the panel\n // lists what a call takes, it does not mirror the schema.\n name: 'filters',\n type: 'object',\n required: false,\n description: 'Per-file overrides; the server documents their shape.',\n },\n ],\n },\n // No fields at all, so the stand also shows the rule that an empty group draws\n // no heading rather than an empty list under it.\n 'mcp__tglider__catalog': {\n name: 'mcp__tglider__catalog',\n description: 'Every tool the server declares, with the size of each definition.',\n fields: [],\n },\n 'mcp__grafana-local__query': {\n name: 'mcp__grafana-local__query',\n description: 'Run one PromQL query against a dashboard’s data source.',\n fields: [\n { name: 'query', type: 'string', required: true, description: 'The PromQL expression.' },\n { name: 'range', type: 'string', required: false },\n ],\n },\n 'mcp__context7__docs': {\n name: 'mcp__context7__docs',\n description: 'Documentation pages for one library, ranked by the question asked.',\n fields: [],\n },\n 'mcp__playwright__navigate': {\n name: 'mcp__playwright__navigate',\n description: 'Open a URL in the browser and wait for the page to settle.',\n fields: [{ name: 'url', type: 'string', required: true, description: 'Absolute URL to open.' }],\n // Every figure is one the picture's own host measured, which is the whole\n // point of the reason line: the panel prints no size it computed itself.\n reason: { kind: 'budget', chars: 1_240, budget: 8_000, used: 6_900 },\n },\n 'mcp__rider__open': {\n name: 'mcp__rider__open',\n description: 'Open one file in the IDE at a line.',\n fields: [{ name: 'path', type: 'string', required: true }],\n reason: { kind: 'budget', chars: 640, budget: 8_000 },\n },\n}\n\n/**\n * Publish the picture's definitions into the panel's cache.\n *\n * Idempotent and cheap: called from {@link designProject}, which every design\n * surface renders through, so a fixture body is always seeded before the first\n * row can be opened. Seeding the same record twice is the same record.\n */\nexport function seedDesignToolFacts(): void {\n for (const [name, facts] of Object.entries(DESIGN_TOOL_FACTS)) seedToolFacts(name, facts)\n}\n\n/** One lifecycle event, as the ring stores it. */\nfunction event(\n at: number,\n level: LogEvent['level'],\n server: string,\n message: string,\n detail?: string,\n): LogEvent {\n return detail === undefined\n ? { at, level, projectRoot: DESIGN_PROJECT_ROOT, sessionId: DESIGN_SESSION, server, message }\n : { at, level, projectRoot: DESIGN_PROJECT_ROOT, sessionId: DESIGN_SESSION, server, message, detail }\n}\n\n/** The four events the `full` picture holds, oldest first. */\nexport const DESIGN_EVENTS: readonly LogEvent[] = [\n event(1_789_000_000_000, 'info', 'tglider', `mounting for session ${DESIGN_SESSION} (trigger: turn)`),\n event(1_789_000_001_000, 'up', 'tglider', `is up — tools visible to session ${DESIGN_SESSION} after 812ms`),\n event(1_789_000_002_000, 'warn', 'grafana-local', 'unmounting — the session went idle (it ran for 8m 03s)'),\n event(1_789_000_003_000, 'error', 'gateway', 'no tool appeared in 4m 27s', `endpoint: stdio docker · declared in ${DESIGN_DOCUMENT}`),\n]\n\n/** The one event the `tools-absent` picture holds: a declaration waiting for a turn. */\nexport const DESIGN_PENDING_EVENT: readonly LogEvent[] = [\n event(1_789_000_030_000, 'info', 'tglider', 'declared, waiting for the session’s first step'),\n]\n\n/** One row of a picture. */\nfunction row(\n name: string,\n status: ServerStatus,\n transport: 'stdio' | 'streamable-http',\n detail?: string,\n): ServerRow {\n return detail === undefined\n ? { name, status, projectRoot: DESIGN_PROJECT_ROOT, source: DESIGN_DOCUMENT, transport }\n : { name, status, projectRoot: DESIGN_PROJECT_ROOT, source: DESIGN_DOCUMENT, transport, detail }\n}\n\n/**\n * Every picture the design mode can draw.\n *\n * `full` is the default and the one the docs' own mock (`mockups/harness.html`)\n * mirrors; the rest isolate a single state so it can be reviewed on its own.\n */\nexport type DesignVariant =\n /** All states at once: four tones, a disagreement, a failure, a full tool offer. */\n | 'full'\n /** The quiet project: sessions agree, nothing failed, the ring is empty. */\n | 'quiet'\n /** The project declares nothing. */\n | 'empty'\n /** The session declares one server and the host published no offer yet. */\n | 'tools-absent'\n /** The tools page is switched off for this project. */\n | 'off'\n /** Nothing is deferred: every mounted tool goes into the request. */\n | 'direct'\n /** The session's folder is not inside a project. */\n | 'no-project'\n /** No session is attached to the tab. */\n | 'no-session'\n\n/** The variants, in the order the docs present them. */\nexport const DESIGN_VARIANTS: readonly DesignVariant[] = [\n 'full',\n 'quiet',\n 'empty',\n 'tools-absent',\n 'off',\n 'direct',\n 'no-project',\n 'no-session',\n]\n\n/** Narrow `unknown` to a variant, so a stored string can never switch the mode blind. */\nexport function isDesignVariant(value: unknown): value is DesignVariant {\n return typeof value === 'string' && (DESIGN_VARIANTS as readonly string[]).includes(value)\n}\n\n/** The merged rows of the project, per picture. */\nfunction mergedRows(variant: DesignVariant): ServerRow[] {\n switch (variant) {\n case 'full':\n return [\n row('tglider', 'active', 'streamable-http'),\n row('grafana-local', 'active', 'streamable-http'),\n row('gateway', 'error', 'stdio', DESIGN_FAILURE),\n row('playwright', 'connecting', 'stdio'),\n row('context7', 'conflict', 'streamable-http', 'the name is taken by a live profile-level instance'),\n row('rider', 'idle', 'stdio', 'not mounted yet — this session has not started a turn (lazy mounting is on)'),\n row('legacy-gh', 'disabled', 'stdio'),\n ]\n case 'quiet':\n case 'off':\n return [row('tglider', 'active', 'streamable-http'), row('grafana-local', 'active', 'streamable-http')]\n case 'direct':\n return [row('tglider', 'active', 'streamable-http')]\n case 'tools-absent':\n return [row('tglider', 'idle', 'streamable-http', 'not mounted yet — this session has not started a turn (lazy mounting is on)')]\n case 'empty':\n case 'no-project':\n case 'no-session':\n return []\n }\n}\n\n/**\n * This session's own rows.\n *\n * The `full` picture is the one the panel's project-first view exists for: the\n * project merges `grafana-local` as `active`, while this session — whose ring\n * says it went idle — reads it as `idle`. Every other picture agrees with its\n * project, so the panel draws no `sessions` section at all.\n */\nfunction sessionOwnRows(variant: DesignVariant): ServerRow[] {\n const rows = mergedRows(variant)\n if (variant !== 'full') return rows\n return rows.map((entry) =>\n entry.name === 'grafana-local' ? { ...entry, status: 'idle' as const } : entry,\n )\n}\n\n/** The tool policy in force for the picture. */\nexport function designPolicy(variant: DesignVariant): ToolPolicy {\n switch (variant) {\n case 'off':\n return { mode: 'off', pins: [] }\n case 'direct':\n return { mode: 'direct', pins: ['mcp__tglider__workspace'] }\n case 'quiet':\n return { mode: 'disclosure', pins: ['mcp__tglider__workspace', 'mcp__grafana-local__query'] }\n default:\n return { mode: 'disclosure', pins: ['mcp__tglider__workspace'] }\n }\n}\n\n/**\n * One session's tool offer, or `undefined` for the pictures where the host has\n * published none.\n *\n * `undefined` is the host's only \"not mounted yet\" signal, and it is a different\n * state from an offer whose counters are real zeroes — the panel prints two\n * different blocks for the two.\n */\nexport function designTools(variant: DesignVariant): SessionTools | undefined {\n const base = { sessionId: DESIGN_SESSION, mounted: 5, budgetChars: 20_000, deferring: false }\n switch (variant) {\n case 'full':\n return {\n ...base,\n baseline: ['mcp__tglider__workspace', 'mcp__tglider__catalog'],\n activated: [{ name: 'mcp__grafana-local__query', via: 'session', at: 1_789_000_004_000, step: 3 }],\n context: [{ name: 'mcp__context7__docs', via: 'context' }],\n deferred: ['mcp__playwright__navigate', 'mcp__rider__open'],\n surfaceChars: 12_800,\n visibleChars: 4_200,\n deferredChars: 8_600,\n deferring: true,\n }\n case 'quiet':\n return {\n ...base,\n mounted: 2,\n baseline: ['mcp__tglider__workspace', 'mcp__grafana-local__query'],\n activated: [],\n context: [],\n deferred: [],\n surfaceChars: 6_400,\n visibleChars: 6_400,\n deferredChars: 0,\n }\n case 'off':\n return {\n ...base,\n mounted: 1,\n baseline: [],\n activated: [],\n context: [],\n deferred: ['mcp__tglider__workspace'],\n surfaceChars: 3_200,\n visibleChars: 0,\n deferredChars: 3_200,\n }\n case 'direct':\n return {\n ...base,\n mounted: 1,\n baseline: ['mcp__tglider__workspace'],\n activated: [],\n context: [],\n deferred: [],\n surfaceChars: 3_200,\n visibleChars: 3_200,\n deferredChars: 0,\n }\n case 'empty':\n case 'tools-absent':\n case 'no-project':\n case 'no-session':\n return undefined\n }\n}\n\n/** One session of the picture, or `undefined` when the picture has no session. */\nfunction sessionOf(variant: DesignVariant): SessionSnapshot[] {\n if (variant === 'no-project' || variant === 'no-session') return []\n const rows = sessionOwnRows(variant)\n const tools = designTools(variant)\n const logs = variant === 'full' ? DESIGN_EVENTS : variant === 'tools-absent' ? DESIGN_PENDING_EVENT : []\n const session: SessionSnapshot = {\n id: DESIGN_SESSION,\n rows,\n issues: [],\n logCount: logs.length,\n ...(tools === undefined ? {} : { tools }),\n }\n return [session]\n}\n\n/**\n * The one project of the picture, or `undefined` for the two that resolve to\n * none — a folder that is not inside a project, and a tab with no session at\n * all (the panel reads the project of the session it is open in, so neither\n * resolves).\n */\nexport function designProject(variant: DesignVariant): ProjectSnapshot | undefined {\n if (variant === 'no-project' || variant === 'no-session') return undefined\n // The stand's own host answers (F-56): an opened row reads the definitions\n // from the cache the product reads, seeded here because there is no route.\n seedDesignToolFacts()\n const rows = mergedRows(variant)\n const logs = variant === 'full' ? DESIGN_EVENTS : variant === 'tools-absent' ? DESIGN_PENDING_EVENT : []\n const sessions = sessionOf(variant)\n return {\n projectRoot: DESIGN_PROJECT_ROOT,\n policy: designPolicy(variant),\n sessionIds: [DESIGN_SESSION],\n // The read order of this deployment, as the host publishes it: the fixture\n // project is declared in the DSH document, and no global document is read.\n files: [{ path: DESIGN_DOCUMENT, scope: 'project' }],\n rows,\n issues: [],\n sessions,\n conflicts: [],\n ...(logs.length === 0 ? {} : { logs, logCount: logs.length }),\n // The counters belong to the two pictures that publish a tool offer: a\n // project the host never counted (every other picture) draws no figures at\n // all, which is a state worth being able to look at.\n ...(variant === 'full' || variant === 'quiet' ? { usage: DESIGN_USAGE } : {}),\n }\n}\n\n/** The whole picture, in the envelope's own shape. */\nexport function designPicture(variant: DesignVariant): McpSnapshot {\n const project = designProject(variant)\n return {\n ready: true,\n projects: project === undefined ? [] : [project],\n sources: { local: ['.dsh/mcp.json'], global: [] },\n watchedFiles: project === undefined ? [] : [DESIGN_DOCUMENT],\n }\n}\n\n/**\n * The session id the tab should read for this picture.\n *\n * `no-session` is the state the shell itself can be in — a tab with no session\n * attached — and the one the panel answers with its own empty state.\n * @param variant - the picture on screen.\n * @returns the fixture session id, or `undefined` for `no-session`.\n */\nexport function designSessionId(variant: DesignVariant): string | undefined {\n return variant === 'no-session' ? undefined : DESIGN_SESSION\n}\n\n/**\n * The banners the design toast stack shows, one per lifecycle moment. Keyed\n * like the real drafts (`src/client/toasts.ts`), so the stand repaints its\n * banners in the shell's active language the same way the product does.\n */\nexport const DESIGN_TOASTS: readonly ToastDraft[] = [\n {\n level: 'up',\n server: 'playwright',\n project: 'service',\n textKey: 'toastUp',\n textParams: { server: 'playwright' },\n detail: 'service',\n },\n {\n level: 'error',\n server: 'gateway',\n project: 'service',\n textKey: 'toastFailed',\n textParams: { server: 'gateway' },\n detailKey: STATUS_HINT.error,\n detail: DESIGN_FAILURE,\n },\n {\n level: 'released',\n server: 'rider',\n project: 'service',\n textKey: 'toastReleased',\n textParams: { server: 'rider' },\n detailKey: STATUS_HINT.idle,\n },\n]\n","/**\n * Design-only render mode: the browser half drawn from fixtures.\n *\n * This module exists so the interface can be reviewed **as the shell renders\n * it** on a machine where nothing is mounted: no project, no MCP server, no host\n * route. When the design flag is set (see {@link DESIGN_FLAG_KEY}) `./index.ts`\n * registers *these* surfaces instead of the real ones, and every one of them\n * renders the same components the product renders — `PanelHeader`, `tabBody`,\n * `SettingsPage`, `ProjectBlock`, `ToastStack` — fed from `./design-fixtures.ts`.\n *\n * What the mode is not: it is not a second UI. There is no markup here that the\n * real surfaces do not also produce; the only thing it swaps is where the\n * picture comes from. The host half is untouched, so a profile that has this\n * flag set still mounts whatever the project declares — the *drawing* is a\n * fixture, the *runtime* is real.\n *\n * Turning it on, from the web client's own console:\n *\n * ```js\n * localStorage.setItem('dsh-project-mcp:design', 'full') // or quiet | empty | …\n * location.reload() // back to the product\n * localStorage.removeItem('dsh-project-mcp:design')\n * ```\n *\n * @module dsh-project-mcp/client/design\n */\n\nimport { createElement as h, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { en, ru, zh } from './locales/ui.ts'\nimport { NS_HOST, en as hostEn, ru as hostRu, zh as hostZh, hostTranslate } from './locales/host.ts'\nimport { registerSidebarTab } from './sidebar-tab.ts'\nimport type { SidebarSettingsProps, SidebarTabBodyProps, SidebarTabServices } from './sidebar-tab.ts'\nimport {\n DEFAULT_SETTINGS_VIEW,\n NS,\n SETTINGS_TAB_ID,\n SETTINGS_TAB_ORDER,\n SettingsPage,\n registerSettingsTab,\n useNarrowSettings,\n} from './settings.ts'\nimport type { SettingsSlotServices, SettingsTabProps, SettingsView } from './settings.ts'\nimport { DEFAULT_SETTINGS_PAGE } from './settings-tools.ts'\nimport type { SettingsPageKey } from './settings-tools.ts'\nimport { localeServiceOf, tabTranslate, useTabTranslate } from './tab-locale.ts'\nimport type { TabLocale } from './tab-locale.ts'\nimport { TOASTS_ID, TOASTS_ORDER, TOASTS_SLOT, ToastStack, createToastStore } from './toasts.ts'\nimport type { ToastsServices } from './toasts.ts'\nimport {\n PanelHeader,\n ProjectBlock,\n RefreshRow,\n STYLE,\n browserStorage,\n createRefreshStore,\n sessionLogCount,\n statusGroups,\n storedString,\n tabBody,\n translateOf,\n} from './view.ts'\nimport type { PanelStorage, Translate } from './view.ts'\nimport {\n DESIGN_TOASTS,\n designPicture,\n designPolicy,\n designProject,\n designSessionId,\n isDesignVariant,\n} from './design-fixtures.ts'\nimport type { DesignVariant } from './design-fixtures.ts'\n\n/**\n * Where the design mode is asked for.\n *\n * A browser-local preference rather than a build flag, for the same reason the\n * panel's own view and filters are: it must be switchable without a rebuild, and\n * it must be readable by the bundle that is already loaded.\n */\nexport const DESIGN_FLAG_KEY = 'dsh-project-mcp:design'\n\n/** Values that mean \"on\" without naming a picture. */\nconst DESIGN_FLAG_ALIASES: readonly string[] = ['on', 'true', 'yes', '1']\n\n/** How often the fixture stack repeats its three banners. */\nconst DESIGN_TOAST_ROTATE_MS = 2_500\n\n/** A set that never changes, for the read-only props of the fixture settings page. */\nconst NO_PENDING: ReadonlySet<string> = new Set()\n\n/** Do nothing: the fixture surfaces have no host to call. */\nfunction noop(): void {\n // Intentionally empty: a design surface answers no route.\n}\n\n/**\n * The picture the flag asks for.\n *\n * The flag holds a variant name (`full`, `quiet`, …) or one of the plain \"on\"\n * spellings, which mean the all-states picture. Anything else — including a\n * value from a newer build — leaves the mode **off**, so a typo can never swap\n * the real interface for a fixture.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns the variant, or undefined when the mode is off.\n */\nexport function designVariantOf(storage?: PanelStorage): DesignVariant | undefined {\n const value = storedString(DESIGN_FLAG_KEY, storage)\n if (value === undefined) return undefined\n if (DESIGN_FLAG_ALIASES.includes(value)) return 'full'\n return isDesignVariant(value) ? value : undefined\n}\n\n/**\n * `true` when the flag names a picture the mode can draw.\n * @param storage - storage to read; defaults to the browser's own.\n * @returns whether the design surfaces should be registered instead of the real ones.\n */\nexport function designModeEnabled(storage?: PanelStorage): boolean {\n return designVariantOf(storage) !== undefined\n}\n\n/**\n * The sidebar tab, drawn from a picture.\n *\n * The same two elements the real panel renders, in the same order: the toolbar\n * and the one body of the single surface. Nothing here fetches, so nothing here\n * needs the shell to be connected.\n * @param props - the picture, the tab's session and the translate seat.\n * @returns the panel element tree.\n */\nexport function DesignPanel(props: {\n variant: DesignVariant\n sessionId: string | undefined\n t?: Translate | undefined\n /** Host-namespace seat for the fixtures' coded events (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const project = designProject(props.variant)\n const sessionId = designSessionId(props.variant)\n const groups = project === undefined ? [] : statusGroups(project.rows)\n const session = (project?.sessions ?? []).find((entry) => entry.id === sessionId)\n return h(\n 'div',\n { style: STYLE.root },\n h(PanelHeader, {\n project,\n sessions: project?.sessionIds.length ?? 0,\n busy: false,\n onSync: noop,\n t,\n }),\n h(\n 'div',\n { style: STYLE.body },\n tabBody({\n project,\n sessionId,\n groups,\n busy: false,\n policy: project === undefined ? undefined : designPolicy(props.variant),\n onRelease: noop,\n sessionLogCount: sessionLogCount(session),\n t,\n hostT: props.hostT,\n }),\n ),\n )\n}\n\n/**\n * The tab's own settings popup, drawn from a picture.\n *\n * Same shape as `ProjectMcpSettings`: the poll-interval row first, then the bar\n * that names the surface, counts the projects and offers `Sync`/`Close`, and a\n * body rendering one `ProjectBlock` per project — the product's own components,\n * fed here. The row is shared with the product rather than redrawn, so the two\n * cannot drift on the control this port moved into the popup.\n * @param props - the picture, the interval, the close seat and the translate seats.\n * @returns the popup element tree.\n */\nexport function DesignPopup(props: {\n variant: DesignVariant\n refreshMs: number\n onRefreshMs?: ((value: number) => void) | undefined\n onClose?: (() => void) | undefined\n t?: Translate | undefined\n /** Host-namespace seat for the fixtures' coded payload fields (F-48). */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const projects = designPicture(props.variant).projects\n return h(\n 'div',\n { style: STYLE.root },\n h(\n 'div',\n { style: STYLE.bar },\n h('span', { style: STYLE.name }, t('mountedPerProject')),\n h('span', { style: STYLE.muted }, t('projectsCount', { count: projects.length })),\n h('span', { style: { flex: 1 } }),\n h('button', { style: STYLE.button, onClick: noop }, t('sync')),\n props.onClose === undefined\n ? null\n : h('button', { style: STYLE.button, onClick: () => props.onClose?.() }, t('close')),\n ),\n h(RefreshRow, { refreshMs: props.refreshMs, onRefreshMs: props.onRefreshMs, t }),\n h(\n 'div',\n { style: STYLE.body },\n projects.length === 0\n ? h('div', { style: { ...STYLE.muted, padding: 8 } }, t('nothingMounted'))\n : projects.map((project) =>\n h(ProjectBlock, {\n key: project.projectRoot,\n project,\n busy: false,\n onRelease: noop,\n t: props.t,\n hostT: props.hostT,\n }),\n ),\n ),\n )\n}\n\n/**\n * The native Settings page, drawn from a picture.\n *\n * `SettingsPage` is a pure function of its props, so the design mode supplies\n * the state the real `SettingsTab` owns — view, page, selection, JSON — and the\n * fixture snapshot, and lets the page render itself. The editor's write path is\n * the one thing the mode does not simulate: there is no host to write to, so the\n * draft stays empty and `Save…` never becomes live.\n * @param props - the picture and the translate seat.\n * @returns the settings page element tree.\n */\nexport function DesignSettingsTab(props: {\n variant: DesignVariant\n t?: Translate | undefined\n /** The host namespace's seat, forwarded to the page like the product does. */\n hostT?: Translate | undefined\n}): ReactNode {\n const t = translateOf(props.t)\n const [view, setView] = useState<SettingsView>(DEFAULT_SETTINGS_VIEW)\n const [page, setPage] = useState<SettingsPageKey>(DEFAULT_SETTINGS_PAGE)\n const [selectedServer, setSelectedServer] = useState<string | undefined>(undefined)\n const [json, setJson] = useState(false)\n const narrow = useNarrowSettings()\n const snapshot = designPicture(props.variant)\n const project = snapshot.projects[0]\n return h(SettingsPage, {\n snapshot,\n error: undefined,\n busy: false,\n view,\n onView: setView,\n page,\n onPage: setPage,\n onMode: noop,\n modePending: NO_PENDING,\n modeError: undefined,\n selectedRoot: project?.projectRoot,\n onSelectProject: noop,\n selectedServer,\n onSelectServer: setSelectedServer,\n onSync: noop,\n onRetry: noop,\n json,\n onJson: setJson,\n draft: undefined,\n confirming: false,\n consent: false,\n saveState: undefined,\n saving: false,\n onDraft: noop,\n onDiscard: noop,\n onAskSave: noop,\n onCancelSave: noop,\n onConsent: noop,\n onConfirmSave: noop,\n onReRead: noop,\n narrow,\n t,\n hostT: props.hostT,\n })\n}\n\n/**\n * The tab body the entry hands to {@link registerSidebarTab}.\n *\n * The entry already bound both translate seats, so the adapter only forwards the\n * framework's own session and the fixture the mode was started with — the\n * product's own adapter (`LocalizedPanel` in `./index.ts`) does the same with the\n * real panel.\n * @param props - the body's props, seats included.\n * @returns the fixture panel.\n */\nexport function LocalizedDesignPanel(props: SidebarTabBodyProps & { variant?: DesignVariant }): ReactNode {\n const variant = props.variant ?? 'full'\n return h(DesignPanel, { variant, sessionId: props.sessionId, t: props.t, hostT: props.hostT })\n}\n\n/**\n * The settings popup's fixture content.\n *\n * Same chrome as the product's popup — the poll-interval row first, then the\n * per-project blocks — with the stand's fixtures behind it. The interval row is\n * the shared {@link RefreshRow}, so the stand cannot drift from the product on\n * the control the port moved here.\n * @param props - the popup's props, seats included, plus the fixture variant.\n * @returns the fixture popup.\n */\nexport function LocalizedDesignPopup(props: SidebarSettingsProps & { variant?: DesignVariant }): ReactNode {\n const variant = props.variant ?? 'full'\n return h(DesignPopup, {\n variant,\n refreshMs: props.refreshMs,\n onRefreshMs: props.onRefreshMs,\n onClose: props.onClose,\n t: props.t,\n hostT: props.hostT,\n })\n}\n\n\n/**\n * The frame-wide toast stack, repeating its three fixture banners.\n *\n * The product's stack reads a status channel; here the store is filled directly\n * from {@link DESIGN_TOASTS} and refilled on a timer, because a banner lives\n * three seconds and a design surface has to still be on screen when someone\n * looks at it.\n * @param services - the injected `slots` service, and the locale seat.\n */\nexport function registerDesignToasts(services: ToastsServices): void {\n const store = createToastStore()\n services.slots.inject(TOASTS_SLOT, () => {\n const entry = services.slots.register(\n { name: TOASTS_SLOT, id: TOASTS_ID, order: TOASTS_ORDER },\n () => h(ToastStack, { store, locale: services.locale }),\n )\n let index = 0\n const push = (): void => {\n const draft = DESIGN_TOASTS[index % DESIGN_TOASTS.length]\n index += 1\n if (draft !== undefined) store.push(draft)\n }\n push()\n const timer = setInterval(push, DESIGN_TOAST_ROTATE_MS)\n return () => {\n clearInterval(timer)\n entry()\n }\n })\n}\n\n/**\n * Register the fixture surfaces on the browser half.\n *\n * Mirrors `apply`'s own wiring exactly — the tab behind the right sidebar's\n * settings page behind `slots` + `locale`, the toasts behind `slots` alone — so\n * the design mode is a drop-in replacement for the real one and a composition\n * missing a service behaves the same way in both.\n * @param ctx - client root context.\n * @param variant - the picture to draw; read from the flag when omitted.\n */\nexport function registerDesignSurfaces(\n ctx: Context,\n variant: DesignVariant = designVariantOf(browserStorage()) ?? 'full',\n): void {\n const locale = localeServiceOf(ctx)\n const t = tabTranslate(locale)\n\n // The same four seats the product registers, from the fixtures: the stand has\n // to draw the surface the port produced — a right-sidebar tab, one actions-menu\n // row and the popup in the frame-wide floating layer — or it would be comparing\n // the product against a surface that no longer exists.\n ctx.inject(['slots', 'sidebarRightTabs'], (scope) => {\n registerSidebarTab(scope as unknown as SidebarTabServices, {\n locale,\n // The stand reads and writes the same browser-local interval the product\n // does, so the row a designer presses there behaves exactly like the row\n // the product shows.\n refresh: createRefreshStore(),\n body: (props) =>\n h(LocalizedDesignPanel, { ...props, variant }),\n settings: (props) =>\n h(LocalizedDesignPopup, { ...props, variant }),\n copy: {\n title: () => t('designTitle', { variant }),\n description: () => t('designDesc', { variant }),\n },\n })\n })\n\n ctx.inject(['slots', 'locale'], (scope) => {\n const services = scope as unknown as SettingsSlotServices\n // The same one call with all three tables as the product entry. No\n // `addLanguage` of its own: `apply()` returns early in design mode, so\n // the entry — the only place that names Russian to the shell — never runs\n // in this mode. The registration alone is still valid: its `ru` keys are\n // simply unused, and anything unresolved falls back to English.\n services.effect(\n () => services.locale.register(NS, { zh, en, ru }),\n 'dsh-project-mcp: design settings dictionary',\n )\n services.effect(\n // The host-code namespace, beside the UI one as in the product entry.\n () => services.locale.register(NS_HOST, { zh: hostZh, en: hostEn, ru: hostRu }),\n 'dsh-project-mcp: design host dictionary',\n )\n registerSettingsTab(services, (props: SettingsTabProps) =>\n h(DesignSettingsTab, { variant, t: props.t, hostT: props.hostT }),\n )\n })\n\n ctx.inject(['slots', 'locale'], (scope) => {\n registerDesignToasts(scope as unknown as ToastsServices)\n })\n}\n","/**\n * `dsh-project-mcp`, browser half: a DSH right-sidebar tab that shows which MCP\n * servers each project declares and what is currently mounted for its sessions,\n * its own settings popup in the tab chip's actions menu, a page in DSH's native\n * Settings listing every project with a live session, and a frame-wide toast\n * stack for the servers that come up, fail or are released.\n *\n * The tab is a type of DSH's own right sidebar (`./sidebar-tab.ts`, which mirrors\n * the shipped contract structurally), and the popup is an entry of the frame-wide\n * floating layer. The other three seats are the browser-shell slots\n * `settings.section`, `plugins.bundle.config` and `shell.overlay`. Every seat\n * exists in the browser half only. The host half publishes the same data over\n * `/project-mcp/*` (see `src/ui.ts`), so this module never imports host code at\n * runtime.\n *\n * @module dsh-project-mcp/client\n */\n\nimport { createElement } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { PACKAGE_NAME } from '../shared.ts'\nimport { designModeEnabled, registerDesignSurfaces } from './design.ts'\nimport { en, ru, zh } from './locales/ui.ts'\nimport { NS_HOST, en as hostEn, ru as hostRu, zh as hostZh } from './locales/host.ts'\nimport { registerPluginConfigCard } from './plugin-config.ts'\nimport type { PluginConfigSlotServices } from './plugin-config.ts'\nimport { NS, registerSettingsTab } from './settings.ts'\nimport type { SettingsSlotServices } from './settings.ts'\nimport { localeServiceOf } from './tab-locale.ts'\nimport { registerSidebarTab } from './sidebar-tab.ts'\nimport type { SidebarSettingsProps, SidebarTabBodyProps, SidebarTabServices } from './sidebar-tab.ts'\nimport { registerToasts } from './toasts.ts'\nimport type { ToastsServices } from './toasts.ts'\nimport { ProjectMcpPanel, ProjectMcpSettings, createRefreshStore } from './view.ts'\n\n/** Plugin name: matches the package name and the host half. */\nexport const name = PACKAGE_NAME\n\n/**\n * Register the surfaces, each behind the services it actually needs.\n *\n * No module-level dependency is declared, because every one of them is optional:\n * a module-level `inject` would leave this entry **pending** for good in a\n * composition without the right sidebar, and DSH's web boot audit refuses to\n * start while an entry is pending. `ctx.inject(name, …)` waits for the same\n * services without gating the entry, so a composition without the sidebar keeps\n * the native Settings page, the config card and the toast stack.\n *\n * A service this fiber did not declare must never be read as a property: Cordis\n * throws `cannot get property \"…\" without inject`, and that throw fails the\n * entry, which takes the whole web client boot down. Optional reads go through\n * {@link Context.get}.\n */\nexport const inject: string[] = []\n\n/**\n * Register the browser half's surfaces. Every registration returns a disposer and\n * Cordis runs them on fiber disposal, which is what keeps HMR and plugin\n * disabling free of \"already registered\" failures.\n * @param ctx - client root context.\n */\nexport function apply(ctx: Context): void {\n // The design-only render mode: when the flag names a picture, the four\n // surfaces below are registered from fixtures instead (`./design.ts`). It is a\n // replacement, never an addition — two registrations of one tab type id would\n // fight over the same sidebar cell. The flag is a browser-local preference, so\n // the product and the fixture mode are one bundle apart, not one build apart.\n if (designModeEnabled()) {\n registerDesignSurfaces(ctx)\n return\n }\n\n // The plugin's own translate seat: the slots below are registered without a\n // locale namespace of their own, because the plugin registers its dictionaries\n // itself and wants the tab to repaint on a language switch either way. The\n // shell's locale service is read with `ctx.get` — this fiber does not declare\n // it — and without one the seat falls back to the merged English table\n // composed in ./locales/ui.ts.\n const locale = localeServiceOf(ctx)\n\n // The panel's poll interval, shared by the tab it paces and the popup that\n // changes it. One store for both, because the two are not in one tree.\n const refresh = createRefreshStore()\n\n // The sidebar tab, its chip's settings row and the settings popup itself:\n // `./sidebar-tab.ts` holds the structural contract of DSH's own right sidebar\n // and registers all four seats behind the services they need. `ctx.inject`\n // parks this callback until the slot registry and the tab registry exist, so a\n // composition without a right sidebar still boots everything below.\n ctx.inject(['slots', 'sidebarRightTabs'], (scope) => {\n registerSidebarTab(scope as unknown as SidebarTabServices, {\n locale,\n refresh,\n body: LocalizedPanel,\n settings: LocalizedSettings,\n })\n })\n\n // The native Settings page. `ctx.inject` runs this callback only once both\n // services exist and unloads it when either goes away: a composition without\n // the web settings shell keeps the sidebar tab above and the toast stack\n // below, it just has no page to add.\n ctx.inject(['slots', 'locale'], (scope) => {\n const services = scope as unknown as SettingsSlotServices\n // The shell ships only `zh` and `en`: Russian is added at runtime, and the\n // add must precede the dictionary registration that uses it. `addLanguage`\n // is read optionally — a shell whose locale service predates the method\n // must still boot, with `ru` keys simply falling back to English.\n services.effect(\n () => services.locale.addLanguage?.({ id: 'ru', label: 'Русский', fallback: 'en' }),\n 'dsh-project-mcp: ru language',\n )\n services.effect(\n // One namespace for the whole plugin, one call carrying all three\n // languages: the runtime throws when the same (namespace, locale) pair is\n // registered twice, so three calls are not an option. The tables are the\n // complete ones from ./locales/ui.ts — `en` is the merge of the panel's\n // and the settings page's halves, composed there.\n () => services.locale.register(NS, { zh, en, ru }),\n 'dsh-project-mcp: settings dictionaries',\n )\n services.effect(\n // The second namespace, beside the first: the host's coded messages\n // (F-48). Same one-call shape — a duplicate (namespace, locale) pair\n // throws, so the three languages ride a single registration.\n () => services.locale.register(NS_HOST, { zh: hostZh, en: hostEn, ru: hostRu }),\n 'dsh-project-mcp: host dictionaries',\n )\n registerSettingsTab(services)\n })\n\n // The plugin's own configuration card on the Plugins page (F-54), in an\n // inject of its own: `configForms` is optional (DSH before the service's\n // introduction, or a composition without it), and the settings tab above must\n // not depend on it. `locale` rides along because the card declares the\n // plugin's namespace — the dictionaries themselves stay registered by the\n // settings block, whose inject list is a subset of this one's.\n ctx.inject(['slots', 'locale', 'configForms'], (scope) => {\n const services = scope as unknown as PluginConfigSlotServices\n const forms = services.configForms\n // A service that predates `get`/`whileServed` leaves the card absent\n // rather than failing the entry — the same rule the whole file follows.\n if (typeof forms?.get !== 'function' || typeof forms.whileServed !== 'function') return\n registerPluginConfigCard(services)\n })\n\n // The frame-wide toast stack, in its own inject: a composition without the\n // sidebar still floats banners, and one without the slot registry keeps every\n // other surface. The locale service rides along so a language switch repaints\n // the banners on screen; `shell.overlay` is declared by the layout frame, so\n // `registerToasts` waits for it through `slots.inject` and simply has nothing\n // to register in a shell without a frame.\n ctx.inject(['slots', 'locale'], (scope) => {\n registerToasts(scope as unknown as ToastsServices)\n })\n}\n\n/**\n * The sidebar panel.\n *\n * `./sidebar-tab.ts` already bound the two translate seats — the UI namespace and\n * the host-message one — before calling this, so the adapter has nothing left to\n * do but name the component and let React render it as an element rather than as\n * a bare call.\n * @param props - the body's props, seats included.\n * @returns the panel element.\n */\nexport function LocalizedPanel(props: SidebarTabBodyProps): ReactNode {\n return createElement(ProjectMcpPanel, {\n visible: props.visible,\n sessionId: props.sessionId,\n refreshMs: props.refreshMs,\n t: props.t,\n hostT: props.hostT,\n })\n}\n\n/**\n * The settings popup's content, with the same two seats.\n *\n * The popup is an entry of the frame-wide floating layer, so its chrome has to\n * repaint on a language switch exactly like the tab's: the seats are bound per\n * render by `./sidebar-tab.ts`, and this adapter only names the component.\n * @param props - the popup's props, seats included.\n * @returns the settings panel element.\n */\nexport function LocalizedSettings(props: SidebarSettingsProps): ReactNode {\n return createElement(ProjectMcpSettings, {\n refreshMs: props.refreshMs,\n onRefreshMs: props.onRefreshMs,\n onClose: props.onClose,\n t: props.t,\n hostT: props.hostT,\n })\n}\n"],"mappings":";;;;AAaA,MAAa,eAAe;;AAG5B,MAAa,SAAS;;AAGtB,MAAa,eAAe;;AAG5B,MAAa,gBAAgB;;CAE3B,UAAU;;CAEV,MAAM;;CAEN,OAAO;;CAEP,QAAQ;;CAER,MAAM;;;;;;CAMN,MAAM;;CAEN,SAAS;;CAET,MAAM;;CAEN,KAAK;;CAEL,QAAQ;;CAER,UAAU;AACZ;;;;AClBA,MAAa,UAAU;;;;;;AAoGvB,MAAaA,OAA+B;CAE1C,+BACE;CAEF,6BACE;CAEF,gCACE;CAEF,sBAAsB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