@klarkxy/dsh-current-title 0.3.3 → 0.3.4
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/README.md +2 -0
- package/docs/README.zh-CN.md +2 -0
- package/lib/client.inner.cjs +567 -88
- package/lib/client.inner.cjs.map +1 -1
- package/lib/client.js +567 -88
- package/lib/index.js +3 -2
- package/lib/index.js.map +1 -1
- package/package.json +10 -9
package/lib/client.inner.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.inner.cjs","names":["useSyncExternalStore","useCallback","useRef","createElement","useRef","useState","useCallback","useMemo","Button","useRef","useState","useId","useMemo","rankByName","observeStickyMenuGroups","createPortal","MenuSurface","IconChevronRightOutlineRegular","Input","IconCloseFillRegular","IconCheckOutlineRegular","MenuGroup","isValidElement","cloneElement","useCallback","useSyncExternalStore","useState","useRef","Button","IconChevronDownOutlineRegular","useState","useCallback","useRef","Button","IconChevronDownOutlineRegular"],"sources":["../../dsh-model-route/src/catalog.ts","../../dsh-model-route/src/menu.ts","../../dsh-plugin-kit/src/contracts.ts","../../dsh-plugin-kit/src/client-utils.ts","../../dsh-plugin-kit/src/official-ui.ts","../../dsh-plugin-kit/src/model-settings-client.ts","../../dsh-model-route/src/catalog-ui.tsx","../../dsh-model-route/src/ui.tsx","../../dsh-plugin-kit/src/auxiliary-model-client.tsx","../src/contracts.ts","../src/client-work.ts","../src/marker.ts","../src/client.tsx"],"sourcesContent":["/**\n * Host model-catalog parsing shared by plugin settings UIs and model hubs.\n * Pure and browser-safe: no React, no host imports. The catalog envelope is\n * structural so hosts may add fields without breaking consumers.\n */\nimport { modelRouteKey, type ModelRoute } from './route.ts'\n\n/** One selectable model. `efforts` are the advertised reasoning efforts. */\nexport interface ModelMenuChoice {\n readonly provider: string\n readonly model: string\n readonly label: string\n readonly efforts: ReadonlyArray<{ id: string; name: string }>\n}\n\n/** Both services are required: Cordis checks the nested namespace separately. */\nexport const MODEL_CATALOG_INJECT = ['remote', 'remote.session'] as const\n\nexport interface ModelCatalogFailure {\n readonly id: string\n readonly name: string\n readonly message: string\n}\n\n/** The catalog face this helper needs; stays structural so hosts may add more. */\nexport interface ModelCatalogClient {\n readonly remote?: {\n readonly session?: { readonly modelCatalog?: () => Promise<unknown> }\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined\n}\n\nfunction asText(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\n/** A useful diagnostic even when a transport rejects with a plain object. */\nexport function modelCatalogErrorMessage(value: unknown): string {\n if (value instanceof Error && value.message) return value.message\n const row = asRecord(value)\n return asText(row?.message) ?? asText(value) ?? 'Unable to load the model catalog.'\n}\n\n/**\n * Validate and unwrap a successful catalog without discarding provider failures\n * or newer host metadata. Names and metadata remain optional for older hosts.\n * A broken response is never presented as a successfully loaded empty menu.\n */\nexport function checkedModelCatalog(value: unknown): unknown {\n const envelope = asRecord(value)\n if (envelope?.ok === false) throw new Error(modelCatalogErrorMessage(envelope.error ?? envelope))\n const root = envelope?.ok === true ? asRecord(envelope.value) : envelope\n const malformed = (field: string): never => { throw new Error(`Invalid model catalog: ${field}.`) }\n if (!root || !Array.isArray(root.groups)) return malformed('groups must be an array')\n for (const value of root.groups) {\n const group = asRecord(value)\n if (!group || !asText(group.id) || !Array.isArray(group.models)) return malformed('each group needs an id and models array')\n for (const value of group.models) {\n const model = asRecord(value)\n if (!model || !asText(model.id)) return malformed('each model needs an id')\n if (model.reasoning !== undefined) {\n const reasoning = asRecord(model.reasoning)\n if (!reasoning || !Array.isArray(reasoning.efforts) || reasoning.efforts.some(value => !parseEffort(value))) {\n return malformed('reasoning efforts must be an array of identified efforts')\n }\n }\n }\n }\n if (root.failures !== undefined && (!Array.isArray(root.failures) || root.failures.some(value => {\n const failure = asRecord(value)\n return !failure || !asText(failure.id) || typeof failure.name !== 'string' || typeof failure.message !== 'string'\n }))) return malformed('failures must be an array of provider failures')\n return root\n}\n\n/** Read through the injected session namespace; absence and rejection are errors. */\nexport async function readModelCatalog(client: ModelCatalogClient): Promise<unknown> {\n const session = client.remote?.session\n if (typeof session?.modelCatalog !== 'function') {\n throw new Error('Model catalog unavailable: inject both remote and remote.session.')\n }\n return checkedModelCatalog(await session.modelCatalog())\n}\n\n/** Provider failures are partial results, not a transport failure. */\nexport function modelCatalogFailures(value: unknown): readonly ModelCatalogFailure[] {\n // Rendering can precede the checked load boundary (for example hub owner\n // snapshots). Invalid or absent data must not crash the whole settings page.\n try {\n const root = checkedModelCatalog(value) as { failures?: readonly ModelCatalogFailure[] }\n return root.failures ?? []\n } catch { return [] }\n}\n\n/** Text adapter for existing model-hub status messages. */\nexport function catalogFailures(value: unknown): string[] {\n return modelCatalogFailures(value).map(failure => `${failure.name || failure.id}: ${failure.message}`)\n}\n\nfunction parseEffort(value: unknown): { id: string; name: string } | undefined {\n const row = asRecord(value)\n const id = row ? asText(row.id) : undefined\n if (!id) return undefined\n return { id, name: row ? asText(row.name) ?? id : id }\n}\n\n/** Parse the host session catalog into flat choices, keeping a saved route selectable. */\nexport function parseModelMenuChoices(value: unknown, bound?: ModelRoute): ModelMenuChoice[] {\n const envelope = asRecord(value)\n // Host remote calls resolve to a result envelope ({ ok, value }); older hosts\n // and unit tests hand over the bare catalog. Accept both.\n const root = (envelope && envelope.ok === true ? asRecord(envelope.value) : undefined) ?? envelope ?? {}\n const groups = Array.isArray(root.groups) ? root.groups : []\n const choices: ModelMenuChoice[] = []\n for (const group of groups) {\n const groupRow = asRecord(group)\n const provider = groupRow ? asText(groupRow.id) : undefined\n if (!provider || !groupRow || !Array.isArray(groupRow.models)) continue\n const providerName = asText(groupRow.name) ?? provider\n for (const entry of groupRow.models) {\n const modelRow = asRecord(entry)\n const model = modelRow ? asText(modelRow.id) : undefined\n if (!model || !modelRow) continue\n const name = asText(modelRow.name) ?? model\n const reasoning = asRecord(modelRow.reasoning)\n const efforts = reasoning && Array.isArray(reasoning.efforts)\n ? reasoning.efforts.flatMap(effort => { const parsed = parseEffort(effort); return parsed ? [parsed] : [] })\n : []\n choices.push({ provider, model, label: `${providerName} / ${name}`, efforts })\n }\n }\n if (bound?.provider && bound.model && !choices.some(item => item.provider === bound.provider && item.model === bound.model)) {\n choices.push({ provider: bound.provider, model: bound.model, label: `${bound.provider} / ${bound.model}`, efforts: [] })\n }\n return choices\n}\n\n/** Reasoning-effort options for one choice; the saved value stays selectable. */\nexport function modelMenuEffortOptions(\n choice: ModelMenuChoice | undefined,\n current?: string,\n): Array<{ id: string; name: string }> {\n const listed = (choice?.efforts ?? []).map(item => ({ ...item }))\n if (current && !listed.some(item => item.id === current)) listed.push({ id: current, name: current })\n return listed\n}\n\n/** Flat set of known routes for DetectModelFieldsOptions.knownModel. */\nexport function knownModelFromChoices(choices: readonly ModelMenuChoice[]): (route: ModelRoute) => boolean {\n const known = new Set(choices.map(choice => modelRouteKey(choice.provider, choice.model)))\n return route => known.has(modelRouteKey(route.provider, route.model))\n}\n","/**\n * Pure menu helpers over parsed catalog choices: provider grouping, display\n * names and search filtering. Pure and browser-safe like the rest of the core\n * entry — no React, no host imports. The popover component lives in `./ui.tsx`.\n */\nimport type { ModelMenuChoice } from './catalog.ts'\n\n/** Localize standard effort ids only when the provider has not supplied a display name. */\nexport function modelMenuEffortLabel(effort: { id: string; name: string }, locale?: string): string {\n if (effort.name !== effort.id) return effort.name\n const labels: Record<string, readonly [string, string]> = {\n off: ['关闭', 'Off'], none: ['无', 'None'], minimal: ['最低', 'Minimal'], low: ['低', 'Low'],\n medium: ['中', 'Medium'], high: ['高', 'High'], xhigh: ['极高', 'Extra high'],\n max: ['最高', 'Maximum'], ultra: ['超高', 'Ultra'],\n }\n return labels[effort.id]?.[locale?.toLowerCase().startsWith('zh') ? 0 : 1] ?? effort.name\n}\n\n/** One provider group in the menu, in catalog order, after applying the search query. */\nexport interface ModelMenuGroup {\n readonly provider: string\n /** Provider display name, split from the catalog \"Provider / Model\" label. */\n readonly name: string\n readonly items: readonly ModelMenuChoice[]\n}\n\n/** The short model label shown inside a provider group. */\nexport function modelMenuShortName(choice: ModelMenuChoice): string {\n const sep = choice.label.indexOf(' / ')\n return sep > 0 ? choice.label.slice(sep + 3) : choice.model\n}\n\n/** Group catalog choices by provider and filter them by a case-insensitive query. */\nexport function groupModelMenuChoices(choices: readonly ModelMenuChoice[], query: string): ModelMenuGroup[] {\n const needle = query.trim().toLowerCase()\n const matched = needle\n ? choices.filter(choice => choice.label.toLowerCase().includes(needle)\n || choice.model.toLowerCase().includes(needle)\n || choice.provider.toLowerCase().includes(needle))\n : choices\n const groups: Array<{ provider: string; name: string; items: ModelMenuChoice[] }> = []\n for (const choice of matched) {\n const sep = choice.label.indexOf(' / ')\n const name = sep > 0 ? choice.label.slice(0, sep) : choice.provider\n const last = groups.at(-1)\n if (last && last.provider === choice.provider) last.items.push(choice)\n else groups.push({ provider: choice.provider, name, items: [choice] })\n }\n return groups\n}\n","import type { ContextFormed } from '@deepseek-ai/dsh-llm'\nimport { modelRouteOverride, type ModelRoute } from '@klarkxy/dsh-model-route'\n\n/**\n * The canonical home is @klarkxy/dsh-model-route; re-exported here so existing\n * plugin-kit consumers keep compiling.\n */\nexport type { ModelRoute }\n\n/** Public, browser-safe contracts. Host implementations stay in their owning packages. */\nexport type ProducerSourceKind = `plugin:${string}`\nexport type ProducerMessageSource = { kind: ProducerSourceKind; plugin: string } & ContextFormed\n\n/**\n * V4 sessions persist the producing extension in `kind`; the retired generic\n * `plugin` wrapper is not admitted. Each feature plugin declares its own kind.\n */\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n [kind: ProducerSourceKind]: ProducerMessageSource\n }\n}\n\nexport function producerMessageSource(plugin: string): ProducerMessageSource {\n return { kind: `plugin:${plugin}`, plugin }\n}\n\nexport type RpcResult<T = unknown> = { ok: true; value: T } | { ok: false; error: { code: string; message: string } }\nexport const CHAT_EVENTS_SLOT = 'dsh-editor.chat.events'\nexport interface EvidenceRef { sessionId: string; seq: number; kind: 'user' | 'tool' | 'turn' | 'manual'; excerpt?: string }\nexport interface TaskContract {\n id: string\n sessionId: string\n sourceVersion: string\n revision: number\n goal: string\n deliverables: string[]\n inScope: string[]\n outOfScope: string[]\n constraints: string[]\n acceptance: string[]\n assumptions: string[]\n questions: string[]\n evidence: EvidenceRef[]\n readiness: 'pending' | 'clear-request' | 'user-confirmed' | 'disclosed-assumptions' | 'cancelled' | 'stale'\n updatedAt: number\n}\nexport interface TaskCheckpoint {\n id: string\n sessionId: string\n sourceVersion: string\n contractVersion?: number\n fromSeq: number\n toSeq: number\n revision: number\n status: 'running' | 'completed' | 'failed' | 'cancelled'\n items: Array<{ label: string; state: 'pending' | 'verified' | 'failed'; evidence: EvidenceRef[] }>\n constraints: string[]\n nextAction: string\n createdAt: number\n}\nexport type KnowledgeScope = { kind: 'global' } | { kind: 'project'; projectId: string }\nexport type KnowledgeKind = 'preference' | 'project-fact' | 'decision' | 'vocabulary' | 'activity' | 'lesson'\n/** Descriptive context, never an executable instruction or authorization. */\nexport interface ContextKnowledge {\n subject: string\n domain: string\n key: string\n aliases: string[]\n observedAt: number\n /** The user's own time expression, not an inferred completion date. */\n eventTime?: string\n activityStatus?: 'planned' | 'in-progress' | 'blocked' | 'paused' | 'completed' | 'cancelled' | 'unknown'\n}\n/** A scoped method. Observations remain candidates until explicitly accepted. */\nexport interface ProcedureKnowledge {\n origin: 'instruction' | 'observation'\n goal: string\n when: string[]\n steps: string[]\n avoid: string[]\n verify: string[]\n}\nexport interface MemoryRecord {\n id: string\n revision: number\n scope: KnowledgeScope\n kind: KnowledgeKind\n status: 'candidate' | 'active' | 'rejected' | 'superseded' | 'revoked' | 'deleted'\n title: string\n content: string\n tags: string[]\n evidence: EvidenceRef[]\n exceptions: string[]\n source: 'user' | 'memory' | 'dream' | 'self-improvement'\n context?: ContextKnowledge\n procedure?: ProcedureKnowledge\n createdAt: number\n updatedAt: number\n expiresAt?: number\n supersedes?: string[]\n /** Exact record revisions behind a derived candidate; revalidated on adoption. */\n basis?: Array<{ id: string; revision: number }>\n}\nexport type NewMemoryRecord = Omit<MemoryRecord, 'id' | 'revision' | 'createdAt' | 'updatedAt'>\nexport interface MemoryQuery { scope: KnowledgeScope; query?: string; kinds?: KnowledgeKind[]; statuses?: MemoryRecord['status'][]; limit?: number }\nexport interface MemoryMutationOptions { signal?: AbortSignal; isCurrent?: () => boolean }\nexport interface MemoryService {\n list(query: MemoryQuery): Promise<MemoryRecord[]>\n create(record: NewMemoryRecord, options?: MemoryMutationOptions): Promise<MemoryRecord>\n update(id: string, patch: Partial<Pick<MemoryRecord, 'title' | 'content' | 'tags' | 'exceptions' | 'status' | 'expiresAt'>>, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n /** Explicit user promotion, persisted atomically on the same record; preserves expiry and evidence. */\n promoteToGlobal(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n remove(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<void>\n recall(query: MemoryQuery): Promise<MemoryRecord[]>\n}\n\n/**\n * The session creation metadata the host snapshots when it creates a delegated child\n * thread. Mirrors `CreateAgentOptions.meta` in `@deepseek-ai/dsh-agent`; it is durable\n * session data, so it survives a restart and needs no ancestry walk.\n */\nexport interface SubagentSessionLike {\n readonly header?: {\n readonly parentSession?: unknown\n readonly origin?: unknown\n readonly delegationDepth?: unknown\n readonly isSeeded?: unknown\n readonly classification?: unknown\n }\n}\n\n/**\n * True when `session` is a delegated child thread rather than a human-driven top-level\n * conversation.\n *\n * A message's `source.kind === 'user'` cannot answer this: a lead agent's dispatch prompt\n * is delivered as the child's own user message, so delegated work is indistinguishable\n * from a person typing once you only look at the message. Plugins use this to keep\n * automatic writes and derived model calls on top-level sessions.\n */\nexport function isSubagentSession(session: unknown): boolean {\n const header = (session as SubagentSessionLike | null | undefined)?.header\n if (!header || typeof header !== 'object') return false\n if (header.origin === 'subagent' || Number(header.delegationDepth ?? 0) > 0) return true\n // Native human forks also persist parentSession for history lineage. A fork's\n // seeded header distinguishes it from legacy children whose parent is the\n // only marker. Native rc.2 forks omit depth; patched hosts may persist zero.\n // Explicit delegation and unknown metadata still keep the child guard.\n const humanFork = header.isSeeded === true\n && (header.delegationDepth === undefined || header.delegationDepth === 0)\n && header.origin === undefined\n && (header.classification === undefined || header.classification === 'ordinary' || header.classification === 'free')\n return Boolean(header.parentSession) && !humanFork\n}\n\n/** Project keys come only from the host-validated session directory, never client input. */\nexport function projectIdFromCwd(cwd: string | undefined): string | undefined {\n if (typeof cwd !== 'string') return undefined\n const normalized = cwd.trim().replaceAll('\\\\', '/')\n if (!normalized) return undefined\n return normalized === '/' || /^[A-Za-z]:\\/$/.test(normalized) ? normalized : normalized.replace(/\\/+$/, '')\n}\n\n/**\n * One settings owner's Remote stream. Typert accepts either case in an RPC\n * segment, so the Cordis service key and the wire namespace use the same\n * Pascal segment. The scope's first letter stays uppercase.\n */\nexport interface ModelSettingsChangesIdentity {\n readonly service: string\n readonly namespace: string\n}\n\n/** `@klarkxy/dsh-git-commit` becomes `KlarkxyDshGitCommitModelSettingsChanges`. */\nexport function modelSettingsChangesIdentity(packageName: string): ModelSettingsChangesIdentity {\n const scoped = /^@([^/]+)\\/(.+)$/.exec(packageName)\n const body = scoped ? `${scoped[1]}/${scoped[2]}` : packageName\n const parts = body.split(/[^A-Za-z0-9]+/).filter(Boolean)\n if (!parts.length) throw new Error('Model settings package name has no RPC segment')\n const segment = `${parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('')}ModelSettingsChanges`\n if (!/^[A-Z][A-Za-z0-9]*$/.test(segment)) throw new Error(`Model settings sync name is not an RPC segment: ${segment}`)\n return { service: segment, namespace: segment }\n}\n\n/**\n * Repository extension: a native web provider announces that its local\n * availability changed. Kind is `search` or `fetch`; id is the provider id.\n * Listeners refresh management state and must not treat this as a network probe.\n */\nexport const WEB_PROVIDER_AVAILABILITY_EVENT = 'web/provider-availability-updated' as const\n\n/**\n * Optional display metadata a provider may attach when it registers directly\n * with `ctx.web`. Execution and credentials stay with the provider; this object\n * is display-only and must never carry secret values.\n */\nexport interface DshWebManagementDescriptor {\n readonly id: string\n readonly label: string\n readonly description: string\n readonly defaultBaseURL?: string\n readonly credentialRef?: string\n /** True when the key is shared with another surface. The page must not delete it. */\n readonly credentialShared?: boolean\n /** Optional notice naming the settings surface that owns a shared credential. */\n readonly credentialHint?: string\n readonly billing: 'request' | 'model-and-tools' | 'none' | 'unknown'\n /** Optional provider-supplied billing summary. */\n readonly pricing?: string\n /** Public HTTPS page explaining provider charges. */\n readonly pricingUrl?: string\n /** Public HTTPS page where the user can create an API key. */\n readonly signupUrl?: string\n /** Plugin that owns configuration. Native providers keep their settings there. */\n readonly configurationOwner?: string\n /** Explicit settings link supplied by the provider, never inferred from its id. */\n readonly configurationUrl?: string\n /** Fixed legacy route migrated by a bundle-owned adapter; not used by native plugins. */\n readonly legacyId?: string\n}\n\n/**\n * Host Creator agent-preset id (`agentPresets.composedPreset`).\n * Plugins that gate Creator-only tools or prompt sections compare against this.\n */\nexport const CREATOR_PRESET_ID = 'cordis'\n\n/**\n * Shared \"Session Management\" settings section id. The section is provided by\n * shared infrastructure (see `registerSessionSettingsItem` in `client-utils`),\n * not by any one business plugin: every participant registers only a row into\n * {@link SESSION_SETTINGS_ITEM_SLOT}, so any enabled subset yields the same page.\n */\nexport const SESSION_SETTINGS_SECTION_ID = 'session-manager'\n\n/**\n * Child list slot declared by the shared Session Management page. Neutral\n * naming on purpose: participants never import each other, they only\n * contribute `{id, order}` rows into this slot while the page is alive.\n */\nexport const SESSION_SETTINGS_ITEM_SLOT = 'dsh.session-settings.item'\n\n/**\n * Host-owned nav icon seat: a root-scoped list where each entry's `id` must\n * equal the `settings.section` id it decorates. Owner props are\n * `{size, active}`; icons stay `aria-hidden` so the section label remains the\n * accessible name. Contributors into a shared section may register the same\n * icon `id` with different priorities — the ledger keeps every entry while the\n * host renders one icon per section.\n */\nexport const SETTINGS_SECTION_ICON_SLOT = 'settings.section.icon'\n\n/* Shared auxiliary-model default. Feature plugins may store a global default\n * route that fills the tier between their own saved override and the live\n * session model. The durable state is a root-context singleton (like the\n * shared session-settings page): it exists while any participant retains it\n * and is never owned by a business plugin. See `auxiliary-model.ts`. */\n\n/** Root context service key holding the shared auxiliary-model state. */\nexport const AUXILIARY_MODEL_SERVICE = 'dshAuxiliaryModel'\n\n/** Authenticated host-RPC channel for get/set of the shared default. */\nexport const AUXILIARY_MODEL_CHANNEL = '/dsh-auxiliary-model'\n\n/** Model-settings namespace under which the shared default is published. */\nexport const AUXILIARY_MODEL_NS = '@klarkxy/dsh-plugin-kit/auxiliary-model'\n\n/**\n * Typert identity of the shared change stream. Mounted on the root context\n * with ownerNs filtering, so frames only carry {@link AUXILIARY_MODEL_NS}.\n */\nexport const AUXILIARY_MODEL_CHANGES_IDENTITY = modelSettingsChangesIdentity('@klarkxy/dsh-plugin-kit')\n\n/** The value the shared default persists: `model: null` means follow the live session/host model. */\nexport interface AuxiliaryModelDefaults {\n readonly revision: number\n readonly model: ModelRoute | null\n}\n\n/** Shape of the root singleton; produced and owned by `auxiliary-model.ts`. */\nexport interface AuxiliaryModelShared {\n readonly ready: Promise<void>\n snapshot(): AuxiliaryModelDefaults\n}\n\nfunction sharedAuxiliaryModel(host: unknown): AuxiliaryModelShared | undefined {\n const root = (host as { root?: unknown } | undefined)?.root as { get?(name: string, strict?: boolean): unknown } | undefined\n try {\n const shared = root?.get?.(AUXILIARY_MODEL_SERVICE, false) as AuxiliaryModelShared | undefined\n return shared && typeof shared.snapshot === 'function' ? shared : undefined\n } catch { return undefined }\n}\n\n/**\n * Synchronously read the shared auxiliary default; `undefined` only when no\n * participant retains the singleton or the default is legitimately unset.\n * An initialization or snapshot failure propagates: silently falling back to\n * a different model after a storage error would spend the wrong budget.\n */\nexport function getAuxiliaryModel(host: unknown): ModelRoute | undefined {\n const shared = sharedAuxiliaryModel(host)\n if (!shared) return undefined\n return modelRouteOverride(shared.snapshot().model ?? undefined)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { createElement, useCallback, useEffect, useRef, useSyncExternalStore, type ReactNode } from 'react'\nimport { SESSION_SETTINGS_ITEM_SLOT, SESSION_SETTINGS_SECTION_ID, SETTINGS_SECTION_ICON_SLOT } from './contracts.ts'\n\n/** Fixed pause for failing background reads; manual work is never replayed. */\nexport function createPluginReadGate(now: () => number = Date.now) {\n let pausedUntil = 0\n let epoch = 0\n return {\n canRead: () => now() >= pausedUntil,\n reset: () => { epoch++; pausedUntil = 0 },\n async run<T>(read: () => Promise<T>): Promise<T> {\n const current = epoch\n try {\n const value = await read()\n if (current === epoch) pausedUntil = 0\n return value\n } catch (error) {\n // The native Connection error is an Error with this exact HTTP text.\n // Authentication, application failures, and cancellation stay distinct.\n const message = error instanceof Error ? error.message : ''\n if (current === epoch && (/(?:^|\\s)transport failure for .+: HTTP (?:404|405|503)\\b/.test(message)\n || (error instanceof TypeError && /^(?:Failed to fetch|fetch failed|NetworkError when attempting to fetch resource\\.?)$/i.test(message)))) {\n pausedUntil = now() + 30_000\n }\n throw error\n }\n },\n }\n}\n\nexport interface NativeSurfaceClient {\n sessions: {\n binding?(sessionId: string): { eventSource: { subscribe(listener: () => void): () => void } } | undefined\n }\n uiWorkspace: { current?: { getSnapshot(): { sessionId: string } | undefined; subscribe(listener: () => void): () => void } }\n uiSession: { adapter: { current: { getSnapshot(): { key?: string }; subscribe(listener: () => void): () => void } } }\n locale: { getSnapshot(): { active: string }; subscribe(listener: () => void): () => void }\n connection?: { generation?: { subscribe(listener: () => void): () => void } }\n}\n\n/** The Editor retains its manuscript session separately; native DSH exposes the main-view binding. */\nexport function selectedSessionId(client: Pick<NativeSurfaceClient, 'uiWorkspace' | 'uiSession'>): string {\n const workspace = client.uiWorkspace?.current\n return workspace\n ? workspace.getSnapshot()?.sessionId ?? ''\n : client.uiSession.adapter.current.getSnapshot().key ?? ''\n}\n\n/**\n * Owner props are data the host composed, never a Cordis context: reading an\n * undeclared property off one throws instead of returning undefined, which\n * would crash the slot entry and abdicate its cell for good. Tolerate a\n * throwing read so a mistaken prop degrades to \"not supplied\".\n */\nfunction read(source: unknown, key: string): unknown {\n if (source === null || typeof source !== 'object') return undefined\n try {\n return (source as Record<string, unknown>)[key]\n } catch {\n return undefined\n }\n}\n\nfunction readString(source: unknown, key: string): string | undefined {\n const value = read(source, key)\n return typeof value === 'string' ? value : undefined\n}\n\n/** Owner props win; native settings only supplies close, so resolve its selected session. */\nexport function useNativeSeat(client: NativeSurfaceClient, props?: unknown) {\n const current = useSyncExternalStore(\n useCallback((fn: () => void) => (client.uiWorkspace?.current ?? client.uiSession.adapter.current).subscribe(fn), [client]),\n useCallback(() => selectedSessionId(client), [client]),\n () => '',\n )\n const language = useSyncExternalStore(\n useCallback((fn: () => void) => client.locale.subscribe(fn), [client]),\n useCallback(() => client.locale.getSnapshot().active, [client]),\n () => 'en',\n )\n const sessionId = readString(props, 'sessionId') ?? readString(read(props, 'owner'), 'sessionId') ?? current\n const requestedLocale = read(props, 'locale') ?? read(read(props, 'owner'), 'locale') ?? language\n return { sessionId, locale: (String(requestedLocale).startsWith('zh') ? 'zh' : 'en') as 'zh' | 'en',\n hidden: read(props, 'hidden') === true || read(read(props, 'owner'), 'hidden') === true }\n}\n\n/** Refresh on native log boundaries/reconnect/focus. Read-only settling is bounded to an observed job. */\nexport function useFeatureRefresh(\n client: NativeSurfaceClient, sessionId: string, refresh: () => void,\n working = false, enabled = true,\n): void {\n const refreshRef = useRef(refresh)\n refreshRef.current = refresh\n useEffect(() => {\n if (!enabled) return\n let timer: ReturnType<typeof setTimeout> | undefined\n const queue = () => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return\n clearTimeout(timer)\n timer = setTimeout(() => refreshRef.current(), 150)\n }\n const source = sessionId ? client.sessions.binding?.(sessionId)?.eventSource : undefined\n const stopEvents = source?.subscribe(queue)\n const stopConnection = client.connection?.generation?.subscribe(queue)\n const visibility = () => { if (document.visibilityState === 'visible') queue() }\n window.addEventListener('focus', queue)\n document.addEventListener('visibilitychange', visibility)\n // Details are collapsed by default; opening an existing panel must get current state.\n document.addEventListener('toggle', queue, true)\n return () => {\n clearTimeout(timer)\n stopEvents?.(); stopConnection?.()\n window.removeEventListener('focus', queue)\n document.removeEventListener('visibilitychange', visibility)\n document.removeEventListener('toggle', queue, true)\n }\n }, [client, sessionId, enabled])\n useEffect(() => {\n if (!enabled || !working) return\n let delay = 250\n const until = Date.now() + 300_000\n let timer: ReturnType<typeof setTimeout>\n const tick = () => {\n if (Date.now() >= until) return\n if (document.visibilityState !== 'hidden') refreshRef.current()\n delay = Math.min(delay * 2, 2000)\n timer = setTimeout(tick, delay)\n }\n timer = setTimeout(tick, delay)\n return () => clearTimeout(timer)\n }, [client, sessionId, working, enabled])\n}\n\n/* Shared \"Session Management\" settings page. The page is root-owned shared\n * infrastructure, not a business plugin: any participant alone yields the same\n * section, and participants never import each other. Synchronization crosses\n * separately bundled copies of this helper through the Cordis root context —\n * `root.get`/`root.provide` is the only rendezvous, so no window global or\n * module singleton is needed and no participant depends on another being enabled.\n */\n\n/** A row contributed into the shared Session Management page. */\nexport interface SessionSettingsItemSpec {\n readonly id: string\n readonly order: number\n}\n\n/* Original line icons for settings-section navigation seats. The official\n * `dsh-client-ui-primitives` icon set covers generic glyphs only; these keep\n * the same conventions (16×16 viewBox, 1px stroke, round caps, currentColor)\n * so the plugin set stays visually consistent with the native nav. Colors\n * never appear here: `currentColor` lets the host style the active state, and\n * `aria-hidden` keeps the section label the single accessible name. */\n\n/** Owner props the host's `settings.section.icon` seat hands to its cell. */\nexport interface SettingsSectionIconProps {\n readonly size?: number\n /** Selection state; the nav styles active icons through color, not geometry. */\n readonly active?: boolean\n}\n\ntype IconChild = readonly [tag: string, attrs: Record<string, string | number>]\n\n/** One `<svg>` with the shared icon chrome; children are plain elements. */\nfunction lineIcon(children: IconChild[]) {\n return function SettingsSectionIcon(props: SettingsSectionIconProps): ReactNode {\n return createElement('svg', {\n 'aria-hidden': 'true',\n width: props.size ?? 16,\n height: props.size ?? 16,\n viewBox: '0 0 16 16',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 1,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n }, ...children.map(([tag, attrs], index) => createElement(tag, { key: index, ...attrs })))\n }\n}\n\n/** Chat bubble for the shared Session Management section. */\nexport const IconSessionSettings = lineIcon([\n ['path', { d: 'M8.5 13a5.5 5.5 0 0 0 5.5-5.5A5.5 5.5 0 0 0 8.5 2 5.5 5.5 0 0 0 3 7.5a5.48 5.48 0 0 0 .9 3L2.8 12.6a.5.5 0 0 0 .62.62l2.9-.98a5.48 5.48 0 0 0 2.18.76Z' }],\n])\n\n/** Serif-flavoured letter A for the Font section. */\nexport const IconFontSettings = lineIcon([\n ['path', { d: 'M3.3 12.6 7.9 3.1a.5.5 0 0 1 .9 0l4.6 9.5' }],\n ['path', { d: 'M5.2 9.4h6.3' }],\n ['path', { d: 'M2.4 12.6h2.4' }],\n ['path', { d: 'M11.9 12.6h2.4' }],\n])\n\n/** Keyboard for the Shortcuts section. */\nexport const IconKeyboardSettings = lineIcon([\n ['rect', { x: 1.75, y: 4.75, width: 12.5, height: 7.5, rx: 1.2 }],\n ['path', { d: 'M4.5 7.25h0' }],\n ['path', { d: 'M8 7.25h0' }],\n ['path', { d: 'M11.5 7.25h0' }],\n ['path', { d: 'M5.25 9.75h5.5' }],\n])\n\n/** Linked model nodes for the Model Management section. */\nexport const IconModelNetworkSettings = lineIcon([\n ['line', { x1: 10.6, y1: 5.3, x2: 8.8, y2: 7.1 }],\n ['line', { x1: 7.2, y1: 8.9, x2: 5.4, y2: 10.7 }],\n ['circle', { cx: 12, cy: 4, r: 1.9 }],\n ['circle', { cx: 4, cy: 12, r: 1.9 }],\n ['circle', { cx: 8, cy: 8, r: 1.5 }],\n])\n\n/**\n * Contribute the nav icon of a `settings.section` entry. The `settings\n * .section.icon` seat is declared by the host independently of the section\n * list, so the wait runs in parallel: the icon appears as soon as both seats\n * exist and unloading removes it again, restoring the host's default glyph.\n * The `id` must equal the section id; `order`/`priority` mirror `order` so the\n * icon cell sorts like its section and, for shared sections, several\n * contributors can register the same icon id under different priorities\n * without duplicating nav entries.\n */\nexport function registerSettingsSectionIcon(\n ctx: Context,\n sectionId: string,\n order: number,\n component: (props: SettingsSectionIconProps) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n return slots.inject(SETTINGS_SECTION_ICON_SLOT, () =>\n slots.register({ name: SETTINGS_SECTION_ICON_SLOT, id: sectionId, order, priority: order }, component))\n}\n\ninterface SessionSettingsSlots {\n inject(key: string, callback: () => Iterable<(() => void) | void> | (() => void) | void): () => void\n register(spec: Record<string, unknown>, render: unknown): () => void\n}\n\ninterface SessionSettingsRoot {\n get(name: string, strict?: boolean): unknown\n provide(name: string, value: unknown): () => void\n readonly slots?: SessionSettingsSlots\n}\n\n/** Private Cordis rendezvous; every bundled copy of this helper resolves the same root service. */\nconst SESSION_SETTINGS_PAGE_SERVICE = 'dshSessionSettingsPage'\n\ninterface SessionSettingsPage {\n retain(): void\n release(): void\n}\n\n/** The page component renders only its declared child list: items paint their own titles and styles. */\nfunction SessionSettingsPageView(props: { renderSlot: (key: string, owner: Record<string, never>) => ReactNode }): ReactNode {\n return props.renderSlot(SESSION_SETTINGS_ITEM_SLOT, {})\n}\n\n/**\n * Acquire the root-owned page service, creating and providing it on first use.\n * One counter covers participants, the section wait and the provider: the last\n * release removes the wait and then the provider synchronously (Cordis deletes\n * the impl before its async disposer awaits), so a later acquire sees a clean\n * get() miss and can re-establish the page.\n */\nfunction acquireSessionSettingsPage(root: SessionSettingsRoot): SessionSettingsPage {\n const existing = root.get(SESSION_SETTINGS_PAGE_SERVICE, false) as SessionSettingsPage | undefined\n if (existing) return existing\n const slots = root.slots as SessionSettingsSlots\n let users = 0\n let stopPage: (() => void) | undefined\n let unprovide: (() => void) | undefined\n const page: SessionSettingsPage = {\n retain() {\n // The reservation is counted before the throwing install, so a failure\n // lets the caller's release() undo it fully instead of leaking the service.\n users += 1\n if (!stopPage) {\n stopPage = slots.inject('settings.section', () => slots.register(\n {\n name: 'settings.section',\n id: SESSION_SETTINGS_SECTION_ID,\n order: 30,\n label: () => {\n const locale = root.get('locale', false) as { getSnapshot?(): { active?: unknown } } | undefined\n return String(locale?.getSnapshot?.().active ?? '').startsWith('zh') ? '会话管理' : 'Session Management'\n },\n children: { [SESSION_SETTINGS_ITEM_SLOT]: { kind: 'list', scope: 'root' } },\n },\n SessionSettingsPageView,\n ))\n }\n },\n release() {\n if (users <= 0) return\n users -= 1\n if (users > 0) return\n // The last contributor tears the section down; collapsing its children\n // declaration clears the item slot for every other bundle as well.\n stopPage?.()\n stopPage = undefined\n unprovide?.()\n },\n }\n unprovide = root.provide(SESSION_SETTINGS_PAGE_SERVICE, page)\n return page\n}\n\n/**\n * Contribute one row to the shared Session Management settings page.\n *\n * `ctx` is the plugin's own context: the row's slot wait unloads with the\n * plugin, while the page itself is retained on the shared root context for as\n * long as any contributor lives. There is no fallback seat — when every\n * contributor is gone the section disappears with the page. Returns a disposer.\n * Shared root-owned infrastructure (the auxiliary-model card) calls this on\n * `ctx.root` so its row, icon and page share are owned by the root lifetime\n * and released by the returned disposer, not by any plugin fiber.\n */\nexport function registerSessionSettingsItem(\n ctx: Context,\n item: SessionSettingsItemSpec,\n component: (props: never) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n const root = ctx.root as unknown as SessionSettingsRoot\n const page = acquireSessionSettingsPage(root)\n let stopItem: (() => void) | undefined\n let stopIcon: (() => void) | undefined\n try {\n page.retain()\n stopItem = slots.inject(SESSION_SETTINGS_ITEM_SLOT, () => slots.register({ name: SESSION_SETTINGS_ITEM_SLOT, ...item }, component))\n // Every contributor also waits on the nav-icon seat, registering the same\n // section icon id under its own priority (its row order). Same-id entries\n // coexist on the ledger while the host renders one icon, so no contributor\n // owns the icon and none depends on another for it; the wait lives with\n // this ctx, so it fires now on fresh loads and retro-fills on HMR.\n stopIcon = slots.inject(SETTINGS_SECTION_ICON_SLOT, () => slots.register(\n { name: SETTINGS_SECTION_ICON_SLOT, id: SESSION_SETTINGS_SECTION_ID, order: item.order, priority: item.order },\n IconSessionSettings,\n ))\n } catch (error) {\n // A synchronous failure (for example a duplicate row id or a failing page\n // install) must not pin the shared page for a contributor that never joined.\n stopIcon?.()\n stopItem?.()\n page.release()\n throw error\n }\n // The disposer may be invoked by both ctx.effect and an explicit caller;\n // releasing twice would unbalance the shared refcount.\n let disposed = false\n return () => {\n if (disposed) return\n disposed = true\n stopIcon?.()\n stopItem?.()\n page.release()\n }\n}\n","/**\n * Shared contract that keeps every plugin's browser-side UI on the official\n * DeepSeek Harness Web design language.\n *\n * Two rules produce that language, and both are load-bearing here:\n *\n * 1. Colour, radius, elevation and focus come from the host theme's real\n * `--dsw-*` tokens, written under their own names. Plugins never invent a\n * token, never alias the official ones behind a private palette (a private\n * alias is just a second, diverging theme), and never carries a literal\n * fallback — the host publishes light and dark, and a literal would pin one\n * of them. The only non-colour custom properties used are the host's own\n * content-font axis and frame clearance.\n *\n * 2. Anything the host already ships is used, not reimplemented. Controls come\n * from `@deepseek-ai/dsh-client-ui-primitives` (`Button`, `Input`,\n * `Checkbox`, `Switch`, `Tag`, `Pill`, `SegmentedControl`, `Menu`, `Modal`,\n * `Tooltip`, `Toast`, `DisclosureRow`, `StateDot`, `PathLabel`, the settings\n * form suite). This module only styles what primitives do not cover: page\n * scaffolding, field layout, banners, empty states and scroll regions.\n *\n * The metrics below are transcribed from the primitives' own CSS modules so a\n * feature panel lines up pixel-for-pixel with a native one: the 14/22 body and\n * 13/20 compact type tiers, the 0.5px hairline scale, and the elevation family\n * that draws a surface's edge in its shadow (`border: 0`) instead of a border.\n */\n\n/**\n * Every `--dsw-*` token this repo is allowed to reference, grouped by role.\n *\n * Plugins may only colour through this list. It is exported so the guard test\n * can fail a build when a stylesheet reaches for anything else — the failure\n * mode this prevents is silent: an unknown token resolves to nothing, so a\n * border disappears or a label inherits the wrong colour with no error anywhere.\n */\nexport const OFFICIAL_THEME_TOKENS = {\n /** Surfaces, from the page up to the topmost nested card. */\n surface: [\n '--dsw-alias-bg-base',\n '--dsw-alias-bg-layer-1',\n '--dsw-alias-bg-layer-2',\n '--dsw-alias-bg-layer-3',\n '--dsw-alias-bg-layer-4',\n '--dsw-alias-bg-module-platform',\n '--dsw-alias-bg-overlay',\n ],\n /** Hairlines. l1 is near-invisible on a menu surface, so menus use l2+. */\n border: ['--dsw-alias-border-l1', '--dsw-alias-border-l2', '--dsw-alias-border-l3', '--dsw-alias-border-l4'],\n /** Text. `caption` is menu shortcut text, `dimmed` is placeholder text. */\n label: [\n '--dsw-alias-label-primary',\n '--dsw-alias-label-secondary',\n '--dsw-alias-label-tertiary',\n '--dsw-alias-label-caption',\n '--dsw-alias-label-dimmed',\n '--dsw-alias-label-error',\n '--dsw-alias-label-primary-foreground',\n ],\n /** Interactive fills. The `-danger` hover belongs to destructive rows. */\n interactive: [\n '--dsw-alias-interactive-bg-hover',\n '--dsw-alias-interactive-bg-active',\n '--dsw-alias-interactive-bg-hover-danger',\n ],\n /** Accent and status. `business` is the focus ring's default colour. */\n accent: [\n '--dsw-alias-brand-primary',\n '--dsw-alias-button-primary-fill',\n '--dsw-alias-button-primary-hover',\n '--dsw-alias-button-tool-bar-fill',\n '--dsw-alias-button-tool-bar-hover',\n '--dsw-alias-button-ghost-active-fill',\n '--dsw-alias-button-ghost-active-border',\n ],\n state: [\n '--dsw-alias-state-business-primary',\n '--dsw-alias-state-success-primary',\n '--dsw-alias-state-warn-primary',\n '--dsw-alias-state-error-primary',\n '--dsw-alias-state-idle-primary',\n ],\n /** Corner scale: sm 8, md 12, lg the large card, panel the modal. */\n radius: ['--dsw-radius-sm', '--dsw-radius-md', '--dsw-radius-lg', '--dsw-radius-panel'],\n /** An elevated surface draws its edge in the shadow, so it keeps border: 0. */\n elevation: [\n '--dsw-elevation-soft',\n '--dsw-elevation-stroke',\n '--dsw-elevation-stroke-color',\n '--dsw-elevation-panel',\n '--dsw-elevation-prominent',\n ],\n /** Floats, masks and scrollbars. */\n overlay: [\n '--dsw-menu-surface-fill',\n '--dsw-menu-backdrop-filter',\n '--dsw-mask-blur',\n '--dsw-alias-bg-mask-1',\n '--dsw-alias-menu-icon',\n '--dsw-alias-scrollbar-bg-l2',\n '--dsw-alias-scrollbar-hover-l2',\n '--dsw-shadow-lv3',\n ],\n /** Motion, focus and type axis, published by the host rather than by a component. */\n system: [\n '--dsw-focus-ring-width',\n '--dsw-focus-ring-color',\n '--dsw-font-markdown-code-font-family',\n '--ds-transition-duration',\n '--ds-ease-in-out',\n '--ds-font-family-code',\n '--dsh-scrollbar-thumb',\n '--dsh-scrollbar-thumb-hover',\n '--dsh-content-font-size-secondary',\n '--dsh-content-font-delta',\n '--dsh-frame-top-clearance',\n ],\n} as const\n\n/** Every official token name, flat. Used by the token guard test. */\nexport const OFFICIAL_THEME_TOKEN_NAMES: readonly string[] = Object.values(OFFICIAL_THEME_TOKENS).flat()\n\n/** The elevation steps a surface can be raised by, softest first. */\nexport type OfficialElevation = 'soft' | 'stroke' | 'panel' | 'prominent'\n\n/**\n * The host's focus ring shorthand, verbatim. Writing this per control is how\n * rings drift apart; a stylesheet that draws its own focus style should use\n * {@link officialFocus} instead. The colour fallback is the host's own default.\n */\nexport const OFFICIAL_FOCUS_RING =\n 'var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))'\n\n/**\n * A complete `outline` declaration at the official geometry. `offset` defaults\n * to the 2px the native controls use; the host's inline field rules sit at 1px\n * and a segmented tab pulls the ring inside itself at -2px.\n */\nexport function officialFocus(offset = '2px'): string {\n return `outline: ${OFFICIAL_FOCUS_RING}; outline-offset: ${offset}`\n}\n\n/**\n * An elevated surface. The host draws a raised surface's edge inside its\n * shadow rather than as a border, so a card sets `border: 0` and takes the edge\n * from the elevation — which is also why its border stays off the alias-border\n * set that a flat, non-elevated rule would use.\n */\nexport function officialElevation(level: OfficialElevation): string {\n return `border: 0; box-shadow: var(--dsw-elevation-${level})`\n}\n\n/**\n * An elevated surface whose edge should read as a specific hairline. Rebinding\n * the stroke colour is how a menu card picks l1 while a panel picks l3, without\n * the two growing apart by hand.\n */\nexport function officialStrokedElevation(level: OfficialElevation, color: string): string {\n return `--dsw-elevation-stroke-color: ${color}; ${officialElevation(level)}`\n}\n\n/**\n * The shared stylesheet for a plugin UI, scoped under that plugin's root class.\n *\n * Scoping is what keeps this safe to always-bundle into every client: the rules\n * can only match inside the plugin's own subtree, so two plugins can both mount\n * `dsh-ui-card` without either styling the other's markup.\n *\n * Each recipe matches the root element *and* its descendants, because the\n * commonest arrangement is one element that is both — a surface that carries\n * the root class and `dsh-ui-card`, or a portaled dialog that is the root and\n * the `dsh-ui-surface`. A descendant-only scope would silently leave those\n * unstyled, with no error anywhere.\n *\n * A caveat worth knowing: `Modal` and `Menu` portal to `document.body`, so their\n * content leaves the plugin's subtree entirely. A portaled surface therefore\n * needs its own root class on an element inside the portal.\n *\n * Only patterns that primitives do not provide live here. If a control appears\n * below that `Button`/`Input`/`Switch`/`Tag`/`Menu` already covers, that is a\n * bug in this file: use the primitive and delete the recipe.\n */\nexport function officialUiCss(roots: string | readonly string[]): string {\n // One plugin often mounts several unrelated surfaces (a settings seat, a chat\n // card, a header menu), so the caller names every root. The rules below are\n // nested under a single selector list and use `&`, which the browser expands\n // per root — so one stylesheet covers all of them without duplicating itself.\n const scope = (typeof roots === 'string' ? [roots] : roots).map(root => `.${root}`).join(', ')\n const sheet = `\n/* Official DSH Web UI contract. Generated by @klarkxy/dsh-plugin-kit/official-ui.\n * Do not hand-edit the copy inside a plugin: change this module so every plugin\n * moves together. Scope: ${scope} */\n/* The scope rule below stays open for the whole sheet: every rule after it\n * nests with the parent selector, so one stylesheet can cover several unrelated\n * roots without leaking into a neighbouring plugin. Its closing brace is last. */\n${scope} {\n color: var(--dsw-alias-label-primary);\n font-family: inherit;\n font-size: 14px;\n line-height: 22px;\n min-width: 0;\n\n& *, & *::before, & *::after { box-sizing: border-box; }\n& h1, & h2, & h3, & h4, & p, & figure { margin: 0; }\n/* Keyboard focus only: pointer input keeps the native resting appearance. The\n * ring needs no radius of its own — the outline already follows the control's\n * own border-radius, and overriding it here would flatten every control. */\n& :focus-visible { ${officialFocus()}; }\n& [hidden] { display: none !important; }\n\n/* --- Type tiers. The same 14/22 and 13/20 steps the primitives use. --- */\n& .dsh-ui-title { font-size: 16px; line-height: 24px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-heading { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-compact { font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-meta { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-hint { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-error { font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-warn { color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-success { color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-muted { color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n& .dsh-ui-wrap { min-width: 0; overflow-wrap: anywhere; }\n\n/* --- Layout scaffolding. --- */\n& .dsh-ui-stack { display: flex; flex-direction: column; gap: 12px; }\n& .dsh-ui-stack-lg { display: flex; flex-direction: column; gap: 20px; }\n/* Plugin detail pages share one reading column. These are layout recipes;\n * controls keep their own primitive styles. Form spacing follows the host's\n * settings-form/fields.module.css and SettingsForm.module.css. */\n& .dsh-ui-page { display: flex; flex-direction: column; gap: 16px; width: 100%; max-width: 760px; min-width: 0; }\n& .dsh-ui-form { display: flex; flex-direction: column; gap: 0; min-width: 0; }\n&.dsh-ui-form > .dsh-ui-field, & .dsh-ui-form > .dsh-ui-field { padding: 12px 0; }\n& .dsh-ui-form-footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding-top: 16px; min-width: 0; }\n& .dsh-ui-fields-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 20px; min-width: 0; margin: 0; padding: 0; border: 0; }\n@media (max-width: 560px) {\n & .dsh-ui-fields-grid { grid-template-columns: minmax(0, 1fr); }\n}\n& .dsh-ui-row { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-row-wrap { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }\n& .dsh-ui-spacer { flex: 1; min-width: 0; }\n/* A 0.5px l2 rule is the host's section divider; reserve the same rhythm. */\n& .dsh-ui-divider { height: 0.5px; background: var(--dsw-alias-border-l2); }\n& .dsh-ui-section { display: flex; flex-direction: column; gap: 12px; padding-top: 16px; border-top: 0.5px solid var(--dsw-alias-border-l2); }\n\n/* --- Card: a raised surface whose edge lives in the shadow. --- */\n& .dsh-ui-card {\n ${officialElevation('stroke')}\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 16px;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-alias-bg-layer-1);\n color: var(--dsw-alias-label-primary);\n min-width: 0;\n}\n& .dsh-ui-card--flat { border: 0.5px solid var(--dsw-alias-border-l3); box-shadow: none; }\n& .dsh-ui-card--nested { background: var(--dsw-alias-bg-layer-2); }\n& .dsh-ui-card--plain { background: none; }\n\n/* --- Field: label, control, help, error. The control itself is an\n * official primitive, so this only owns the vertical rhythm. --- */\n& .dsh-ui-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }\n& .dsh-ui-field + .dsh-ui-field { border-top: 0.5px solid var(--dsw-alias-border-l2); padding-top: 12px; }\n/* Grid fields share a row, so the stacked-field divider must not win later in\n * the cascade. Reset it here, after the field recipe. */\n& .dsh-ui-fields-grid > .dsh-ui-field { padding: 0; border: 0; }\n& .dsh-ui-label { display: flex; align-items: center; gap: 6px; font-size: 13px; line-height: 20px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-label-row { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }\n& .dsh-ui-help { font-size: 12px; line-height: 1.6; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-help p { margin: 0; }\n& .dsh-ui-help p + p { margin-top: 8px; }\n& .dsh-ui-required { color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-control { width: 100%; min-width: 0; }\n/* An invalid control is marked on the control, not only in the message. */\n& .dsh-ui-control[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-readonly { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-readonly > dt { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-readonly > dd { margin: 0; font-size: 13px; line-height: 20px; overflow-wrap: anywhere; }\n\n/* --- Buttons row. A no-op container: it exists so actions line up on the\n * trailing edge the way every native panel does. --- */\n& .dsh-ui-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 4px; }\n& .dsh-ui-actions-end { justify-content: flex-end; }\n\n/* --- Banners. A banner is a left-rail notice, the shape used for warnings,\n * deprecations and blocking instructions. --- */\n& .dsh-ui-banner {\n display: flex;\n flex-direction: column;\n gap: 8px;\n padding: 10px 14px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-left: 3px solid var(--dsw-alias-state-warn-primary);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-banner-title { font-weight: 500; color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-banner--info { border-left-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-banner--danger { border-left-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-banner--success { border-left-color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-banner p { margin: 0; }\n\n/* --- Inline notice: a transient confirmation with no chrome of its own. --- */\n& .dsh-ui-notice { display: flex; align-items: center; gap: 6px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-notice--error { color: var(--dsw-alias-state-error-primary); }\n\n/* --- Empty and loading states. Both sit in a dashed well so an empty panel\n * reads as \"nothing here yet\" rather than as a broken layout. --- */\n& .dsh-ui-empty {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 6px;\n padding: 20px 16px;\n border: 0.5px dashed var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-loading { display: flex; align-items: center; gap: 8px; padding: 20px 0; font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-secondary); }\n\n/* --- Selectable list. A row is a button-sized target with a hover fill and\n * a selected fill; the name carries the weight, the description does not. --- */\n& .dsh-ui-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; min-width: 0; }\n& .dsh-ui-list-scroll { max-height: min(66vh, 760px); overflow-y: auto; overflow-x: hidden; }\n& .dsh-ui-list-row { border-radius: var(--dsw-radius-md); }\n& .dsh-ui-list-row:hover { background: var(--dsw-alias-interactive-bg-hover); }\n& .dsh-ui-list-row[aria-selected='true'], & .dsh-ui-list-row[data-selected] { background: var(--dsw-alias-interactive-bg-active); }\n& .dsh-ui-list-item {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 4px;\n width: 100%;\n min-width: 0;\n padding: 10px 12px;\n border: 0;\n border-radius: var(--dsw-radius-md);\n background: none;\n font: inherit;\n color: inherit;\n text-align: start;\n cursor: pointer;\n}\n& .dsh-ui-list-item:disabled { cursor: default; }\n& .dsh-ui-list-item:disabled:hover { background: none; }\n& .dsh-ui-list-name { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); overflow-wrap: anywhere; }\n& .dsh-ui-list-desc { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n\n/* --- Code and structured output. Wraps rather than scrolls, because a\n * feature panel is read rather than scanned. --- */\n& .dsh-ui-code {\n padding: 10px 12px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-family: var(--ds-font-family-code);\n font-size: 12px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n overflow-wrap: anywhere;\n white-space: pre-wrap;\n}\n& .dsh-ui-scroll { max-height: 60vh; overflow: auto; overscroll-behavior: contain; }\n\n/* --- A toggle row: label on the left, switch on the trailing edge. This is\n * layout only; the switch itself is the official primitive. --- */\n& .dsh-ui-toggle-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; padding: 12px 0; }\n& .dsh-ui-toggle-row + .dsh-ui-toggle-row { border-top: 0.5px solid var(--dsw-alias-border-l2); }\n& .dsh-ui-toggle-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-toggle-label { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Floating surface: a panel anchored to a trigger. This is the material\n * a menu card is made of — the translucent fill plus its backdrop blur, with\n * the edge riding inside the prominent elevation. A plugin that hand-rolls this\n * is how tokens like --dsw-specific-menu get invented; use this instead. --- */\n& .dsh-ui-surface {\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l1);\n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n position: relative;\n display: flex;\n flex-direction: column;\n border: 0;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-menu-surface-fill);\n backdrop-filter: var(--dsw-menu-backdrop-filter);\n box-shadow: var(--dsw-elevation-prominent);\n color: var(--dsw-alias-label-primary);\n font-size: 13px;\n line-height: 20px;\n min-width: 0;\n}\n& .dsh-ui-surface-body { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px 14px; overflow-y: auto; }\n& .dsh-ui-surface-head { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-surface-title { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Native select. The primitives ship no select, so a plugin that offers a\n * closed list of choices keeps the platform control and matches the official\n * settings field geometry exactly (34px, 0.5px l4, radius-md, layer-3). A\n * SegmentedControl is the primitive to reach for when the choices are few\n * enough to show at once. --- */\n& .dsh-ui-select {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n height: 34px;\n padding: 0 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n cursor: pointer;\n}\n& .dsh-ui-select:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-select:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-select[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* --- Native textarea. The primitives ship no textarea either, so a settings\n * prompt keeps the platform element and the same field shell as the select:\n * 0.5px l4, radius-md, layer-3, 13/1.5 type. It grows vertically instead of\n * locking to the select's 34px row. --- */\n& .dsh-ui-textarea {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n resize: vertical;\n padding: 8px 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n}\n& .dsh-ui-textarea:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-textarea:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-textarea::placeholder { color: var(--dsw-alias-label-dimmed); }\n& .dsh-ui-textarea[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* Long panels scroll inside themselves instead of growing the host page. */\n& .dsh-ui-panel { display: flex; flex-direction: column; gap: 16px; min-width: 0; }\n& .dsh-ui-panel-wide { max-width: 100%; }\n\n@media (prefers-reduced-motion: reduce) {\n & *, & *::before, & *::after { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; }\n}\n}\n`\n // Widen every recipe from \"a descendant of the root\" to \"the root, or one of\n // its descendants\". Written as a transform rather than by hand so no recipe\n // can be added later with only the descendant form. The pattern is narrow on\n // purpose: a leading `&` followed by one recipe class and no combinator, so\n // sibling and child rules such as `.dsh-ui-field + .dsh-ui-field` keep their\n // own meaning and are left alone.\n return sheet.replace(/^& (\\.dsh-ui-[a-z0-9-]+)(?=\\s*\\{)/gm, (_match, className: string) =>\n `&${className}, & ${className}`)\n}\n","import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'\nimport { modelSettingsChangesIdentity, type ModelSettingsChangesIdentity } from './contracts.ts'\n\nexport type ModelSettingsChangeFrame = { kind: 'ready' } | { kind: 'changed'; ns: string; revision: number }\n\n/** This stream carries invalidations only; ready is never a settings snapshot. */\nexport function parseModelSettingsChangeFrame(value: unknown): ModelSettingsChangeFrame {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid model settings change frame')\n const frame = value as Record<string, unknown>\n if (frame.kind === 'ready' && Object.keys(frame).length === 1) return { kind: 'ready' }\n if (frame.kind === 'changed' && Object.keys(frame).length === 3 && typeof frame.ns === 'string' && frame.ns.length > 0\n && typeof frame.revision === 'number' && Number.isSafeInteger(frame.revision) && frame.revision >= 0) {\n return { kind: 'changed', ns: frame.ns, revision: frame.revision }\n }\n throw new Error('Invalid model settings change frame')\n}\n\n/** One owner's contribution. Each package mounts only its own endpoint. */\nexport function modelSettingsChangesRemote(packageName: string, identity: ModelSettingsChangesIdentity = modelSettingsChangesIdentity(packageName)): TypertRemoteContribution {\n return {\n package: packageName,\n descriptors: [{\n id: `${identity.namespace}/watch`,\n service: identity.service,\n namespace: identity.namespace,\n method: 'watch',\n mode: 'stream' as const,\n invocation: { kind: 'direct' as const },\n parameters: [],\n cancellation: { parameter: 'signal' as const },\n result: { mode: 'strict' as const, typeSymbol: 'ModelSettings.ChangeFrame', create: () => ({ parse: parseModelSettingsChangeFrame }) },\n }],\n }\n}\n\ninterface RemoteMountScope {\n remote: { $mount(contribution: TypertRemoteContribution): Promise<() => Promise<void>> }\n effect(callback: () => () => void | Promise<void>): unknown\n}\ninterface RemoteMountContext {\n inject(dependencies: string[], callback: (scope: unknown) => void): unknown\n}\n\n/** Mount from a synchronous apply. Disposal waits for an in-flight mount and\n * then withdraws it, so the contribution cannot outlive the plugin. */\nexport function mountModelSettingsChanges(ctx: RemoteMountContext, packageName: string): void {\n const contribution = modelSettingsChangesRemote(packageName)\n ctx.inject(['remote'], injected => {\n const scope = injected as RemoteMountScope\n const mounting = scope.remote.$mount(contribution)\n void mounting.catch(() => {})\n scope.effect(() => async () => {\n const unmount = await mounting.catch(() => undefined)\n await unmount?.()\n })\n })\n}\n\ninterface StreamItem {\n generation: number\n value: unknown\n signal: AbortSignal\n accept(): void\n}\ninterface ChangeStream extends AsyncIterable<StreamItem> { dispose(): Promise<void> }\ntype OpenChangeStream = (options: {\n name: string\n open(signal: AbortSignal): AsyncIterable<unknown>\n ended(accepted: boolean): Error\n}) => ChangeStream\nexport interface ModelSettingsSubscriberScope {\n remote: { $stream: OpenChangeStream } & Record<string, { watch?(signal: AbortSignal): AsyncIterable<unknown> } | OpenChangeStream | undefined>\n effect(callback: () => () => void | Promise<void>): unknown\n}\nexport interface ModelSettingsSubscriberContext {\n inject(dependencies: string[], callback: (scope: unknown) => void): unknown\n}\nexport interface ModelSettingsSubscriber {\n subscribe(onChange: () => void, onError?: (message: string) => void): () => void\n}\n\n/** Native RemoteStream owns carrier reconnects; no timers or browser transport.\n * A factory shares one logical stream while at least one subscriber remains. */\nexport function createModelSettingsSubscriber(\n ctx: ModelSettingsSubscriberContext,\n packageName: string,\n identity: ModelSettingsChangesIdentity = modelSettingsChangesIdentity(packageName),\n accept: (ns: string) => boolean = ns => ns === packageName,\n): ModelSettingsSubscriber {\n const endpoint = identity\n const listeners = new Set<{ change: () => void; error?: (message: string) => void }>()\n let injection: { dispose(): void | Promise<void> } | undefined\n let current: { stream: ChangeStream; active: boolean } | undefined\n let lifecycle = 0\n let failureMessage: string | undefined\n const report = (message: string) => {\n failureMessage = message\n for (const listener of [...listeners]) {\n try { listener.error?.(message) } catch { /* Isolate page callbacks. */ }\n }\n }\n const invalidate = () => {\n for (const listener of [...listeners]) {\n if (!listeners.has(listener)) continue\n try { listener.change() } catch (error) {\n try { listener.error?.(error instanceof Error ? error.message : String(error)) } catch { /* Isolate callbacks. */ }\n }\n }\n }\n const start = () => {\n const life = ++lifecycle\n injection = ctx.inject(['remote', `remote.${endpoint.namespace}`], injected => {\n if (life !== lifecycle || !listeners.size) return\n const scope = injected as ModelSettingsSubscriberScope\n const service = scope.remote[endpoint.namespace]\n if (!service || !('watch' in service) || !service.watch) { report('Model settings sync service unavailable'); return }\n const watch = service.watch\n const stream = scope.remote.$stream({\n name: 'Model settings sync',\n open: signal => watch(signal),\n ended: accepted => new Error(`Model settings sync stream ended ${accepted ? 'after' : 'before'} ready; refresh or reopen the page`),\n })\n const session = { stream, active: true }\n current = session\n scope.effect(() => () => {\n session.active = false\n if (current === session) {\n current = undefined\n if (life === lifecycle && listeners.size) report('Model settings sync service unavailable')\n }\n return stream.dispose()\n })\n void (async () => {\n let generation: number | undefined\n let ready = false\n try {\n for await (const item of stream) {\n if (!session.active || life !== lifecycle || !listeners.size) break\n if (item.signal.aborted) continue\n if (generation !== item.generation) { generation = item.generation; ready = false }\n const frame = parseModelSettingsChangeFrame(item.value)\n if (frame.kind === 'ready') {\n ready = true\n failureMessage = undefined\n // Accept the validated invalidation baseline, not fetched data.\n // Every current listener queues its own latest settings read.\n item.accept()\n invalidate()\n } else {\n if (!ready) throw new Error('Model settings sync change arrived before ready')\n if (accept(frame.ns)) invalidate()\n }\n }\n } catch (error) {\n if (session.active && life === lifecycle) report(error instanceof Error ? error.message : String(error))\n } finally {\n if (current === session) current = undefined\n session.active = false\n await stream.dispose().catch(() => {})\n }\n })()\n }) as { dispose(): void | Promise<void> }\n queueMicrotask(() => {\n if (life === lifecycle && listeners.size && !current) report('Model settings sync service unavailable')\n })\n }\n return Object.freeze({ subscribe(onChange: () => void, onError?: (message: string) => void) {\n const listener = { change: onChange, error: onError }\n listeners.add(listener)\n if (!injection) start()\n else if (failureMessage) queueMicrotask(() => {\n if (listeners.has(listener) && failureMessage) {\n try { listener.error?.(failureMessage) } catch { /* Isolate callbacks. */ }\n }\n })\n return () => {\n if (!listeners.delete(listener) || listeners.size) return\n lifecycle++\n if (current) { current.active = false; void current.stream.dispose().catch(() => {}) }\n current = undefined\n failureMessage = undefined\n const previous = injection\n injection = undefined\n try { void Promise.resolve(previous?.dispose()).catch(() => {}) } catch { /* Already unloaded. */ }\n }\n } })\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { Button } from '@deepseek-ai/dsh-client-ui-primitives'\nimport {\n checkedModelCatalog, modelCatalogErrorMessage, modelCatalogFailures, parseModelMenuChoices,\n type ModelCatalogFailure, type ModelMenuChoice,\n} from './catalog.ts'\n\nexport interface UseModelCatalogOptions {\n /** Used only on mount; subsequent changes come from load(). */\n readonly initialCatalog?: unknown\n /** Disables initial, focus, subscription, and manual refreshes. */\n readonly enabled?: boolean\n readonly subscribe?: (onChange: () => void) => (() => void) | undefined\n}\n\nexport interface ModelCatalogState {\n readonly catalog: unknown\n readonly choices: ModelMenuChoice[]\n readonly loading: boolean\n readonly error: string\n readonly failures: readonly ModelCatalogFailure[]\n readonly refresh: () => Promise<void>\n}\n\ntype Snapshot = Pick<ModelCatalogState, 'catalog' | 'loading' | 'error'>\n\n/**\n * Latest refresh wins, including retries while a previous request is pending.\n * Keep load stable (for example with useCallback); changing it invalidates the\n * previous source and fetches again, so switching clients cannot publish stale data.\n */\nexport function useModelCatalog(load: () => Promise<unknown>, options: UseModelCatalogOptions = {}): ModelCatalogState {\n const enabled = options.enabled !== false\n const enabledRef = useRef(enabled)\n enabledRef.current = enabled\n const live = useRef(false)\n const source = useRef(load)\n const revision = useRef(0)\n const [state, setState] = useState<Snapshot>(() => {\n try {\n return { catalog: options.initialCatalog === undefined ? undefined : checkedModelCatalog(options.initialCatalog), loading: enabled, error: '' }\n } catch (error) {\n return { catalog: undefined, loading: enabled, error: modelCatalogErrorMessage(error) }\n }\n })\n const refresh = useCallback(async (): Promise<void> => {\n if (!live.current || !enabledRef.current) return\n const request = ++revision.current\n setState(previous => ({ ...previous, loading: true, error: '' }))\n try {\n const catalog = checkedModelCatalog(await load())\n if (live.current && request === revision.current) setState({ catalog, loading: false, error: '' })\n } catch (error) {\n if (live.current && request === revision.current) {\n setState(previous => ({ ...previous, loading: false, error: modelCatalogErrorMessage(error) }))\n }\n }\n }, [load, enabled])\n\n useEffect(() => {\n live.current = true\n if (source.current !== load) {\n source.current = load\n // Last-good retention belongs to one source; a new client must not\n // inherit another client's models if its initial request fails.\n setState({ catalog: undefined, loading: enabled, error: '' })\n }\n if (enabled) void refresh()\n else setState(previous => ({ ...previous, loading: false }))\n return () => { live.current = false; ++revision.current }\n }, [enabled, refresh])\n\n useEffect(() => {\n if (!enabled) return\n const reload = (): void => { void refresh() }\n // No polling: the host owns catalog production, and focus is a cheap\n // recovery path for missed ordinary notifications or changed credentials.\n if (typeof window !== 'undefined') window.addEventListener('focus', reload)\n let unsubscribe: (() => void) | undefined\n try { unsubscribe = options.subscribe?.(reload) } catch (error) {\n setState(previous => ({ ...previous, error: modelCatalogErrorMessage(error) }))\n }\n return () => {\n if (typeof window !== 'undefined') window.removeEventListener('focus', reload)\n unsubscribe?.()\n }\n }, [enabled, refresh, options.subscribe])\n\n const choices = useMemo(() => parseModelMenuChoices(state.catalog), [state.catalog])\n const failures = useMemo(() => state.catalog === undefined ? [] : modelCatalogFailures(state.catalog), [state.catalog])\n return { ...state, choices, failures, refresh }\n}\n\nexport interface ModelCatalogStatusProps {\n readonly state: Pick<ModelCatalogState, 'loading' | 'error' | 'failures' | 'refresh'>\n readonly locale?: string\n}\n\n/**\n * Also accepts a mapped state from a caller that owns broader async orchestration.\n *\n * The dsh-ui-* classes carry the styling and resolve through the consuming\n * plugin's own officialUiCss scope (every consumer mounts its root class, so\n * e.g. `.dsh-model-hub .dsh-ui-loading` paints this); dsh-model-catalog-status\n * stays as a structural hook for tests and layout, never a colour source.\n */\nexport function ModelCatalogStatus({ state, locale }: ModelCatalogStatusProps) {\n const zh = locale?.toLowerCase().startsWith('zh') === true\n const copy = zh\n ? { loading: '正在加载模型…', error: '模型列表加载失败', partial: '部分提供商的模型未能加载', retry: '重试' }\n : { loading: 'Loading models…', error: 'Unable to load models', partial: 'Some providers could not load their models', retry: 'Retry' }\n if (!state.loading && !state.error && state.failures.length === 0) return null\n return <div className=\"dsh-model-catalog-status dsh-ui-stack\" lang={zh ? 'zh' : 'en'}>\n {state.loading ? <p role=\"status\" className=\"dsh-ui-loading\">{copy.loading}</p> : null}\n {state.error ? <p role=\"alert\" className=\"dsh-ui-error dsh-ui-wrap\">{copy.error}: {state.error}</p> : null}\n {state.failures.length > 0 ? <div role=\"status\" className=\"dsh-ui-meta\">\n <p>{copy.partial}</p>\n <ul className=\"dsh-ui-list\">{state.failures.map((failure, index) => <li key={`${failure.id}:${index}`}>{failure.name || failure.id}: {failure.message}</li>)}</ul>\n </div> : null}\n {state.error || state.failures.length > 0\n ? <div className=\"dsh-ui-actions\"><Button type=\"button\" size=\"sm\" disabled={state.loading} onClick={() => { void state.refresh() }}>{copy.retry}</Button></div>\n : null}\n </div>\n}\n","/**\n * ModelMenu: the standard editor of one model-route field — the visible half\n * of the x-model-route contract. A feature plugin's settings page renders it\n * for its own marked field; the model hub renders one per detected field.\n *\n * It is a plugin-side copy of the host's composer model picker\n * (dsh-client-ui-model-selection's ModelSelect), rebuilt from the official\n * primitives and the published bundle's behavior: one card that opens on the\n * root pane (Model / Effort cells), drills into the provider-grouped,\n * searchable model list or the effort list, and Escapes back before closing.\n * Sticky group headings, subsequence ranking, highlight walking and focus\n * hand-back all match the host. SYNC POINT: when the host's ModelSelect or\n * ModelSelect.module.css changes, this copy must be re-transcribed; styles\n * below may only reference allowlisted theme tokens (the --dsw-* set plus the\n * host's --ds-* motion tokens), never literal colors.\n *\n * It statically imports the primitives, so only browser clients should load\n * this entry; host code and node tests use the core entry (`./index.ts`).\n */\nimport { cloneElement, isValidElement, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconCloseFillRegular, Input, MenuGroup, MenuSurface,\n observeStickyMenuGroups, rankByName,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nexport { useModelCatalog, ModelCatalogStatus } from './catalog-ui.tsx'\nexport type { UseModelCatalogOptions, ModelCatalogState, ModelCatalogStatusProps } from './catalog-ui.tsx'\nimport type { ModelMenuChoice } from './catalog.ts'\nimport { groupModelMenuChoices, modelMenuEffortLabel, modelMenuShortName } from './menu.ts'\n\n/** Extra rows rendered above the model groups (e.g. a plugin's \"follow\"/\"off\" modes). */\nexport interface ModelMenuLeadingItem {\n readonly id: string\n readonly label: ReactNode\n readonly selected?: boolean\n}\n\nexport interface ModelMenuProps {\n /** Active host locale, supplied by the owning plugin's live locale subscription. */\n readonly locale?: string\n readonly open: boolean\n readonly onOpenChange: (open: boolean) => void\n /** Trigger rendered in place; the menu anchors to it and returns focus to it. */\n readonly anchor: ReactNode\n readonly choices: readonly ModelMenuChoice[]\n readonly selected?: { readonly provider: string; readonly model: string }\n readonly onPick: (route: { provider: string; model: string }) => void\n readonly leading?: readonly ModelMenuLeadingItem[]\n readonly onPickLeading?: (id: string) => void\n /** Effort pane rows; the root Effort cell is hidden while this is empty. */\n readonly efforts?: ReadonlyArray<{ id: string; name: string }>\n readonly selectedEffort?: string\n readonly onPickEffort?: (effort: string | undefined) => void\n /** Root-cell labels and the values shown trailing them. */\n readonly modelLabel?: string\n readonly modelValue?: string\n readonly effortLabel?: string\n readonly effortValue?: string\n readonly defaultEffortLabel?: string\n readonly searchPlaceholder?: string\n readonly emptyLabel?: string\n readonly clearSearchLabel?: string\n readonly className?: string\n /** Extra class on the portaled menu card, which renders under document.body. */\n readonly listClassName?: string\n}\n\ntype Pane = 'root' | 'model' | 'effort'\n\n/** Unplaced portal card: hidden but laid out at a fixed origin so measurements are real. */\nconst MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }\n\nexport function ModelMenu(props: ModelMenuProps) {\n const language = props.locale?.toLowerCase().startsWith('zh') ? 'zh' : 'en'\n const copy = language === 'zh'\n ? { model: '模型', effort: '思考强度', default: '默认', search: '搜索模型…', empty: '没有匹配的模型', clear: '清除搜索' }\n : { model: 'Model', effort: 'Reasoning', default: 'Default', search: 'Search models…', empty: 'No matching models', clear: 'Clear search' }\n const {\n open, onOpenChange, anchor, choices, selected, onPick,\n leading = [], onPickLeading, efforts = [], selectedEffort, onPickEffort,\n modelLabel = copy.model, modelValue = '—', effortLabel = copy.effort, effortValue, defaultEffortLabel = copy.default,\n searchPlaceholder = copy.search, emptyLabel = copy.empty, clearSearchLabel = copy.clear,\n className, listClassName,\n } = props\n const rootRef = useRef<HTMLSpanElement | null>(null)\n const openRef = useRef(open)\n openRef.current = open\n const pendingOpenRef = useRef(false)\n const pendingRestoreFocus = useRef(false)\n const [requestedOpen, setRequestedOpen] = useState(false)\n const menuRef = useRef<HTMLDivElement | null>(null)\n const groupsRef = useRef<HTMLDivElement | null>(null)\n const searchRef = useRef<HTMLInputElement | null>(null)\n const itemRefs = useRef<Array<HTMLButtonElement | null>>([])\n const paneFocus = useRef<Pane | 'drill' | null>(null)\n const [pane, setPane] = useState<Pane>('root')\n const [query, setQuery] = useState('')\n const [highlightedIndex, setHighlightedIndex] = useState<number | null>(null)\n const [menuPos, setMenuPos] = useState<CSSProperties | null>(null)\n const id = useId()\n const showSearch = choices.length > 4\n const effortRows = useMemo(() => [{ id: '', name: defaultEffortLabel }, ...efforts.map(effort => ({ ...effort, name: modelMenuEffortLabel(effort, language) }))], [defaultEffortLabel, efforts, language])\n /* The official ranks each provider group by a case-insensitive ordered\n * subsequence (prefix hits first, then alignment score, then catalog order);\n * groups left empty by the query drop out. */\n const filteredGroups = useMemo(() => groupModelMenuChoices(choices, '').map(group => ({\n ...group,\n items: rankByName(group.items.map(choice => ({ choice, name: modelMenuShortName(choice), label: choice.model })), showSearch ? query.trim() : ''),\n })).filter(group => group.items.length > 0), [choices, query, showSearch])\n const visibleModels = useMemo(() => filteredGroups.flatMap(group => group.items.map(item => item.choice)), [filteredGroups])\n const currentVisibleIndex = visibleModels.findIndex(choice => choice.provider === selected?.provider && choice.model === selected.model)\n const activeModelIndex = Math.min(highlightedIndex ?? Math.max(0, currentVisibleIndex), visibleModels.length - 1)\n const changeOpen = (next: boolean): void => {\n if (openRef.current === next) return\n openRef.current = next\n onOpenChange(next)\n }\n const requestOpen = (): void => {\n if (open || pendingOpenRef.current) return\n pendingOpenRef.current = true\n pendingRestoreFocus.current = false\n setRequestedOpen(true)\n }\n const close = (restoreFocus = false): void => {\n const active = document.activeElement\n pendingRestoreFocus.current = restoreFocus && (active === document.body\n || rootRef.current?.contains(active) === true || menuRef.current?.contains(active) === true)\n changeOpen(false)\n }\n const drill = (next: Pane): void => {\n setQuery('')\n setHighlightedIndex(null)\n paneFocus.current = 'drill'\n setPane(next)\n }\n /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */\n const back = (from: Pane): void => {\n paneFocus.current = from\n setPane('root')\n }\n const moveFocus = (offset: number): void => {\n const items = itemRefs.current.filter((item): item is HTMLButtonElement => item !== null && !item.disabled)\n if (!items.length) return\n const active = items.findIndex(item => item === document.activeElement)\n items[active === -1 ? (offset > 0 ? 0 : items.length - 1) : (active + offset + items.length) % items.length]?.focus()\n }\n\n // A selection can synchronously disable its trigger while the owner writes.\n // Retry on the owner's next render, once the native button can take focus.\n useLayoutEffect(() => {\n if (open || !pendingRestoreFocus.current) return\n const active = document.activeElement\n if (active !== document.body && !rootRef.current?.contains(active)) {\n pendingRestoreFocus.current = false\n return\n }\n const trigger = rootRef.current?.querySelector('button')\n if (!trigger || trigger.disabled) return\n trigger.focus()\n if (document.activeElement === trigger) pendingRestoreFocus.current = false\n })\n useEffect(() => {\n if (open || !pendingRestoreFocus.current) return\n const cancelOutside = (event: Event): void => {\n if (event.target instanceof Node && !rootRef.current?.contains(event.target)) pendingRestoreFocus.current = false\n }\n document.addEventListener('focusin', cancelOutside)\n document.addEventListener('pointerdown', cancelOutside)\n return () => {\n document.removeEventListener('focusin', cancelOutside)\n document.removeEventListener('pointerdown', cancelOutside)\n }\n })\n\n useEffect(() => {\n if (!requestedOpen) return\n pendingOpenRef.current = false\n setRequestedOpen(false)\n // The caller's trigger handler may also update the controlled open prop.\n // Check the committed state before supplying the missing open callback.\n if (!open) changeOpen(true)\n }, [requestedOpen, open])\n\n useEffect(() => {\n if (!open) return\n setPane('root')\n setQuery('')\n setHighlightedIndex(null)\n }, [open])\n useEffect(() => {\n if (!open) return\n const closeOutside = (event: MouseEvent): void => {\n const target = event.target as Node\n if (rootRef.current?.contains(target) || menuRef.current?.contains(target)) return\n changeOpen(false)\n }\n document.addEventListener('mousedown', closeOutside)\n return () => document.removeEventListener('mousedown', closeOutside)\n }, [open, onOpenChange])\n /* Focus intent after a pane change: the model pane takes the search field when\n * it has one, every other drill takes the checked row, and going back takes\n * the cell that opened the pane. */\n useEffect(() => {\n const intent = paneFocus.current\n // MenuSurface forwards the measurement visibility:hidden style. Browsers\n // refuse focus there, so keep intent until placement has made it visible.\n if (!open || menuPos === null || intent === null) return\n // Reopening resets a previously drilled pane in a separate commit. Entry\n // and return intent belong to the root cells, never the outgoing rows.\n if (intent !== 'drill' && pane !== 'root') return\n paneFocus.current = null\n if (intent === 'drill') {\n if (pane === 'model' && showSearch) { searchRef.current?.focus(); return }\n (menuRef.current?.querySelector<HTMLButtonElement>('[role=\"menuitemradio\"][aria-checked=\"true\"]:not([disabled])')\n ?? itemRefs.current.find(item => item !== null && !item.disabled))?.focus()\n return\n }\n itemRefs.current[intent === 'effort' ? 1 : 0]?.focus()\n }, [open, pane, showSearch, menuPos])\n useEffect(() => {\n const viewport = groupsRef.current\n if (viewport === null) return\n return observeStickyMenuGroups(viewport)\n }, [open, pane, filteredGroups])\n useLayoutEffect(() => {\n if (open && pane === 'model' && activeModelIndex >= 0) itemRefs.current[leading.length + activeModelIndex]?.scrollIntoView({ block: 'nearest' })\n }, [open, pane, activeModelIndex, visibleModels, leading.length])\n /* The card hangs above the trigger, right-aligned, inside 12px viewport\n * margins — the official placement formula, re-run on scroll and resize. */\n useLayoutEffect(() => {\n if (!open) { setMenuPos(null); return }\n const place = (): void => {\n const rect = rootRef.current?.getBoundingClientRect()\n if (!rect) return\n const margin = 12, lw = menuRef.current?.offsetWidth ?? 0, lh = menuRef.current?.offsetHeight ?? 0\n let x = rect.right - lw, y = rect.top - 8 - lh\n if (lw > 0) x = Math.min(Math.max(x, margin), window.innerWidth - lw - margin)\n if (lh > 0) y = Math.min(Math.max(y, margin), window.innerHeight - lh - margin)\n setMenuPos({ left: x, top: y })\n }\n place()\n window.addEventListener('scroll', place, true)\n window.addEventListener('resize', place)\n return () => {\n window.removeEventListener('scroll', place, true)\n window.removeEventListener('resize', place)\n }\n }, [open, pane, choices, query])\n\n function onKeyDown(event: React.KeyboardEvent): void {\n if (event.defaultPrevented || event.nativeEvent.isComposing) return\n if (!open && ['Enter', ' ', 'ArrowDown', 'ArrowUp'].includes(event.key)) {\n const button = event.target instanceof Element ? event.target.closest('button') : null\n if (!(button instanceof HTMLButtonElement) || button.disabled || !rootRef.current?.contains(button)) return\n // Prevent the native Enter/Space click from opening a second time.\n event.preventDefault()\n paneFocus.current = 'model'\n requestOpen()\n return\n }\n if (event.key === 'Escape' && open) {\n event.preventDefault()\n if (pane !== 'root') back(pane)\n else close(true)\n return\n }\n if (!open) return\n if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {\n event.preventDefault()\n if (visibleModels.length > 0) {\n setHighlightedIndex((activeModelIndex + (event.key === 'ArrowDown' ? 1 : -1) + visibleModels.length) % visibleModels.length)\n searchRef.current?.focus()\n }\n return\n }\n if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) {\n if (event.key === 'Tab' && visibleModels.length === 0) return\n event.preventDefault()\n const highlighted = visibleModels[activeModelIndex]\n if (highlighted) { onPick({ provider: highlighted.provider, model: highlighted.model }); close(true) }\n return\n }\n if (event.key === 'Tab') {\n if (event.shiftKey) {\n event.preventDefault()\n if (pane !== 'root') back(pane)\n else close(true)\n return\n }\n const focused = document.activeElement\n const rows = itemRefs.current.filter((item): item is HTMLButtonElement => item !== null)\n if (focused instanceof HTMLButtonElement && rows.includes(focused)) {\n event.preventDefault()\n focused.click()\n return\n }\n if (pane === 'model' && showSearch) {\n event.preventDefault()\n setHighlightedIndex(null)\n searchRef.current?.focus()\n }\n return\n }\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n moveFocus(event.key === 'ArrowDown' ? 1 : -1)\n }\n }\n\n function onBlur(event: React.FocusEvent): void {\n if (event.relatedTarget instanceof Node && (rootRef.current?.contains(event.relatedTarget) || menuRef.current?.contains(event.relatedTarget))) return\n if (open) changeOpen(false)\n }\n\n itemRefs.current = []\n let itemIndex = 0\n let modelIndex = 0\n const itemRef = () => {\n const at = itemIndex++\n return (node: HTMLButtonElement | null): void => { itemRefs.current[at] = node }\n }\n\n const menu = open && typeof document !== 'undefined'\n ? createPortal(\n <MenuSurface\n ref={menuRef}\n id={`${id}-menu`}\n className={`dsh-model-menu-menu${listClassName ? ` ${listClassName}` : ''}`}\n style={menuPos ?? MEASURE_STYLE}\n role={pane === 'model' ? 'group' : 'menu'}\n aria-label={modelLabel}\n lang={language}\n >\n {pane === 'root' ? <>\n <button ref={itemRef()} type=\"button\" role=\"menuitem\" className=\"dsh-model-menu-cell\" onClick={() => drill('model')}>\n <span className=\"dsh-model-menu-cellLabel\">{modelLabel}</span>\n <span className=\"dsh-model-menu-cellValue\">{modelValue}</span>\n <IconChevronRightOutlineRegular className=\"dsh-model-menu-cellChevron\" />\n </button>\n {efforts.length > 0 ? <button ref={itemRef()} type=\"button\" role=\"menuitem\" className=\"dsh-model-menu-cell\" onClick={() => drill('effort')}>\n <span className=\"dsh-model-menu-cellLabel\">{effortLabel}</span>\n <span className=\"dsh-model-menu-cellValue\">{effortValue ?? effortRows.find(row => row.id === (selectedEffort ?? ''))?.name ?? defaultEffortLabel}</span>\n <IconChevronRightOutlineRegular className=\"dsh-model-menu-cellChevron\" />\n </button> : null}\n </> : null}\n {pane === 'model' ? <>\n {showSearch ? <div className=\"dsh-model-menu-searchRow\">\n <Input\n ref={searchRef}\n className={`dsh-model-menu-search${query !== '' ? ' dsh-model-menu-searchWithQuery' : ''}`}\n type=\"text\"\n role=\"searchbox\"\n aria-label={searchPlaceholder}\n aria-controls={`${id}-models`}\n aria-activedescendant={activeModelIndex < 0 ? undefined : `${id}-model-${activeModelIndex}`}\n placeholder={searchPlaceholder}\n value={query}\n onChange={event => { setQuery(event.target.value); setHighlightedIndex(0) }}\n />\n {query !== '' ? <button type=\"button\" className=\"dsh-model-menu-searchClear\" aria-label={clearSearchLabel}\n onClick={() => { setQuery(''); setHighlightedIndex(null); searchRef.current?.focus() }}>\n <IconCloseFillRegular />\n </button> : null}\n </div> : null}\n <div ref={groupsRef} id={`${id}-models`} className=\"dsh-model-menu-groups scrollable\" role=\"menu\" aria-label={modelLabel}\n hidden={filteredGroups.length === 0}>\n {leading.length > 0 ? <div className=\"dsh-model-menu-leading\">\n {leading.map(item => (\n <button key={item.id} ref={itemRef()} type=\"button\" role=\"menuitemradio\" aria-checked={item.selected === true}\n className={`dsh-model-menu-option${item.selected === true ? ' dsh-model-menu-selected' : ''}`}\n onClick={() => { onPickLeading?.(item.id); close(true) }}>\n <span className=\"dsh-model-menu-optionCopy\"><span className=\"dsh-model-menu-modelName\">{item.label}</span></span>\n <span className=\"dsh-model-menu-check\">{item.selected === true ? <IconCheckOutlineRegular /> : null}</span>\n </button>\n ))}\n </div> : null}\n {filteredGroups.map(group => (\n <MenuGroup key={group.provider} label={group.name}>\n {group.items.map(item => {\n const index = modelIndex++\n const choice = item.choice\n const checked = selected?.provider === choice.provider && selected.model === choice.model\n return <button\n key={`${choice.provider}/${choice.model}`}\n ref={itemRef()}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={checked}\n id={`${id}-model-${index}`}\n tabIndex={showSearch ? -1 : 0}\n onFocus={() => setHighlightedIndex(index)}\n data-highlighted={index === activeModelIndex ? '' : undefined}\n className={`dsh-model-menu-option dsh-model-menu-modelOption${checked ? ' dsh-model-menu-selected' : ''}${index === activeModelIndex ? ' dsh-model-menu-optionActive' : ''}`}\n onMouseMove={index === activeModelIndex ? undefined : () => {\n if (showSearch) setHighlightedIndex(index)\n else itemRefs.current[leading.length + index]?.focus()\n }}\n title={choice.label}\n onClick={() => { onPick({ provider: choice.provider, model: choice.model }); close(true) }}\n >\n <span className=\"dsh-model-menu-optionCopy\"><span className=\"dsh-model-menu-modelName\">{modelMenuShortName(choice)}</span></span>\n <span className=\"dsh-model-menu-check\">{checked ? <IconCheckOutlineRegular /> : null}</span>\n </button>\n })}\n </MenuGroup>\n ))}\n </div>\n {filteredGroups.length === 0 ? <div className=\"dsh-model-menu-empty\" role=\"status\">{emptyLabel}</div> : null}\n </> : null}\n {pane === 'effort' ? <>\n {effortRows.map(row => {\n const checked = (selectedEffort ?? '') === row.id\n return <button key={row.id || '__default'} ref={itemRef()} type=\"button\" role=\"menuitemradio\" aria-checked={checked}\n className={`dsh-model-menu-option${checked ? ' dsh-model-menu-selected' : ''}`}\n onClick={() => { onPickEffort?.(row.id || undefined); close(true) }}>\n <span className=\"dsh-model-menu-optionCopy\"><span className=\"dsh-model-menu-modelName\">{row.name}</span></span>\n <span className=\"dsh-model-menu-check\">{checked ? <IconCheckOutlineRegular /> : null}</span>\n </button>\n })}\n </> : null}\n </MenuSurface>,\n document.body,\n )\n : null\n const trigger = isValidElement<Record<string, unknown>>(anchor)\n ? cloneElement(anchor, { 'aria-haspopup': 'menu', 'aria-expanded': open, 'aria-controls': open ? `${id}-menu` : undefined })\n : anchor\n return <span ref={rootRef} className={`dsh-model-menu-root${className ? ` ${className}` : ''}`} onKeyDown={onKeyDown} onBlur={onBlur}\n onClick={event => {\n if (event.defaultPrevented) return\n const button = event.target instanceof Element ? event.target.closest('button') : null\n if (!(button instanceof HTMLButtonElement) || button.disabled || !rootRef.current?.contains(button)) return\n requestOpen()\n }}\n onMouseDown={event => { if (event.target instanceof Element && menuRef.current?.contains(event.target) && event.target.closest('button') !== null) event.preventDefault() }}>\n {trigger}{menu}\n </span>\n}\n\n/**\n * ModelMenu styles, transcribed from the official ModelSelect.module.css (the\n * published dsh-client-ui-model-selection bundle): card capped at\n * min(360px, 100vh - 96px), 34px option cells at 13/18 with 5px 7px padding,\n * 34px root cells at 13/20, a borderless 12px search row with a clear button,\n * sticky group headings (MenuGroup's own CSS), and the l1-stroke prominent\n * elevation at portal z-index 1100. The trigger mirrors the composer's 28px\n * model pill, chevron rotating open. MenuSurface paints fill and backdrop.\n * Only allowlisted --dsw- and --ds- theme tokens may appear here — a literal\n * color is a bug.\n */\nexport const modelMenuCss = `\n.dsh-model-menu-root { min-width: 0; position: relative; display: inline-flex; }\n.dsh-model-menu-trigger {\n border-radius: var(--dsw-radius-sm);\n min-width: 0;\n max-width: min(360px, 45cqw);\n height: 28px;\n color: var(--dsw-alias-label-secondary);\n cursor: pointer;\n background: none;\n border: none;\n outline: none;\n align-items: center;\n gap: 4px;\n padding: 0 4px 0 8px;\n font-size: 13px;\n font-weight: 400;\n line-height: 20px;\n display: flex;\n}\n.dsh-model-menu-trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-trigger:focus-visible:not([data-selection-focus]) { box-shadow: 0 0 0 var(--dsw-focus-ring-width) var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }\n.dsh-model-menu-trigger:disabled { color: var(--dsw-alias-label-dimmed); cursor: default; }\n.dsh-model-menu-triggerLabel { text-overflow: ellipsis; white-space: nowrap; min-width: 0; overflow: hidden; }\n.dsh-model-menu-triggerEffort { text-overflow: ellipsis; white-space: nowrap; min-width: 0; color: var(--dsw-alias-label-caption); flex-shrink: 1000; overflow: hidden; }\n.dsh-model-menu-chevron { color: var(--dsw-alias-label-caption); flex: none; transition: transform var(--ds-transition-duration) var(--ds-ease-in-out); }\n.dsh-model-menu-chevronOpen { transform: rotate(180deg); }\n/* Portal overlay: the host publishes no z-index token, so the card keeps the\n * native menu layer's 1100 verbatim. */\n.dsh-model-menu-menu {\n z-index: 1100;\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l1);\n width: max-content;\n min-width: min(240px, 100vw - 32px);\n max-width: min(420px, 100vw - 32px);\n max-height: min(360px, 100vh - 96px);\n box-shadow: var(--dsw-elevation-prominent);\n color: var(--dsw-alias-label-primary);\n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n border: 0;\n flex-direction: column;\n padding: 4px;\n display: flex;\n position: fixed;\n overflow: hidden;\n}\n.dsh-model-menu-status, .dsh-model-menu-empty { color: var(--dsw-alias-label-tertiary); padding: 8px; font-size: 12px; line-height: 18px; }\n.dsh-model-menu-searchRow { flex-shrink: 0; margin: 2px 0 3px; position: relative; }\n.dsh-model-menu-searchRow .dsh-model-menu-search { border-radius: var(--dsw-radius-md); background: none; border: 0 solid transparent; height: auto; padding: 5px 7px; display: flex; }\n.dsh-model-menu-searchRow .dsh-model-menu-search:focus-within { border-color: transparent; }\n.dsh-model-menu-searchWithQuery { padding-right: 34px; }\n.dsh-model-menu-searchRow .dsh-model-menu-search input { padding: 0; font-size: 12px; line-height: normal; }\n.dsh-model-menu-searchRow .dsh-model-menu-search input::placeholder { color: var(--dsw-alias-label-caption); }\n/* The clear button is a circle by geometry (border-radius: 50%), a shape the\n * radius token scale does not describe. */\n.dsh-model-menu-searchClear {\n width: 24px;\n height: 24px;\n color: var(--dsw-alias-label-secondary);\n cursor: pointer;\n background: none;\n border: none;\n border-radius: 50%;\n justify-content: center;\n align-items: center;\n padding: 0;\n display: inline-flex;\n position: absolute;\n top: 50%;\n right: 4px;\n transform: translateY(-50%);\n}\n.dsh-model-menu-searchClear:hover, .dsh-model-menu-searchClear:focus-visible { background: var(--dsw-alias-interactive-bg-hover); outline: none; }\n.dsh-model-menu-groups { min-height: 0; overflow-y: auto; }\n.dsh-model-menu-leading { border-bottom: 0.5px solid var(--dsw-alias-border-l2); margin-bottom: 3px; padding-bottom: 3px; }\n.dsh-model-menu-option {\n box-sizing: border-box;\n border-radius: var(--dsw-radius-md);\n width: auto;\n min-width: 100%;\n min-height: 34px;\n color: inherit;\n text-align: left;\n cursor: pointer;\n background: none;\n border: none;\n outline: none;\n align-items: center;\n gap: 6px;\n padding: 5px 7px;\n display: flex;\n}\n.dsh-model-menu-option:not(.dsh-model-menu-modelOption):hover:not(:disabled),\n.dsh-model-menu-option:focus-visible,\n.dsh-model-menu-optionActive:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-modelOption:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-selected { background: none; }\n.dsh-model-menu-option:disabled { color: var(--dsw-alias-label-dimmed); cursor: default; }\n.dsh-model-menu-optionCopy { flex-direction: column; flex: 1; min-width: 0; display: flex; }\n.dsh-model-menu-modelName { color: inherit; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 400; line-height: 18px; overflow: hidden; }\n.dsh-model-menu-check { color: var(--dsw-alias-label-primary); flex: 0 0 14px; place-items: center; display: grid; }\n.dsh-model-menu-check svg { width: 14px; height: 14px; }\n.dsh-model-menu-cell {\n box-sizing: border-box;\n border-radius: var(--dsw-radius-md);\n width: auto;\n min-width: 100%;\n height: 34px;\n color: var(--dsw-alias-label-primary);\n cursor: pointer;\n text-align: left;\n background: none;\n border: none;\n outline: none;\n align-items: center;\n gap: 6px;\n padding: 0 8px;\n font-size: 13px;\n line-height: 20px;\n display: flex;\n}\n.dsh-model-menu-cell:hover, .dsh-model-menu-cell:focus-visible { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-cellLabel { white-space: nowrap; flex: none; }\n.dsh-model-menu-cellValue { text-overflow: ellipsis; white-space: nowrap; text-align: right; min-width: 0; color: var(--dsw-alias-label-tertiary); flex: auto; overflow: hidden; }\n.dsh-model-menu-cellChevron { width: 12px; height: 12px; color: var(--dsw-alias-menu-icon); flex: none; }\n`\n","/**\n * Shared \"default auxiliary model\" settings card.\n *\n * Any number of feature plugins call `registerAuxiliaryModelSettings(ctx)`\n * from their client half; a single card appears as the `auxiliary-model` row\n * of the shared Session Management settings column for as long as at least\n * one participant lives. The card is root-owned shared infrastructure, not a\n * business plugin: every bundled copy of this helper rendezvouses on the same\n * Cordis root service, so no participant depends on another being enabled, the\n * card is mounted once (duplicate row ids would throw), and the last\n * `release()` removes it. The card also retains the shared page itself, so a\n * lone auxiliary plugin still yields the column — participants never depend\n * on another business plugin providing their settings page.\n *\n * The storage side lives in the shared host service behind the plugin-kit RPC\n * channel: `defaults.get` returns `{revision, model}` and `defaults.set`\n * carries `{model, expectedRevision}` with an empty provider/model clearing\n * the override. Cross-window invalidation rides the existing model-settings\n * change stream — no polling is added anywhere in this file.\n */\nimport type { Context } from '@deepseek-ai/cordis'\nimport { Button, IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'\nimport {\n readModelCatalog, modelMenuEffortLabel, modelMenuEffortOptions, parseModelMenuChoices, type ModelRoute,\n} from '@klarkxy/dsh-model-route'\nimport { ModelCatalogStatus, ModelMenu, modelMenuCss, useModelCatalog } from '@klarkxy/dsh-model-route/ui'\nimport { officialUiCss } from './official-ui.ts'\nimport {\n createModelSettingsSubscriber, modelSettingsChangesRemote, type ModelSettingsSubscriber,\n} from './model-settings-client.ts'\nimport { registerSessionSettingsItem } from './client-utils.ts'\nimport {\n AUXILIARY_MODEL_CHANNEL, AUXILIARY_MODEL_CHANGES_IDENTITY, AUXILIARY_MODEL_NS,\n type AuxiliaryModelDefaults, type RpcResult,\n} from './contracts.ts'\n\nconst AUXILIARY_MODEL_PACKAGE = '@klarkxy/dsh-plugin-kit'\n\n/** The stored row; re-exported so card consumers share the contract shape. */\nexport type AuxiliaryModelSnapshot = AuxiliaryModelDefaults\n\n/* The card is one row of the shared Session Management column: the item slot\n * is a root-scope list declared by the shared page, and row ids must be\n * unique. The row sorts ahead of every business participant. */\nexport const AUXILIARY_MODEL_SEAT_ID = 'auxiliary-model'\nexport const AUXILIARY_MODEL_SEAT_ORDER = 55\n\n/** Private Cordis rendezvous; every bundled copy resolves the same root service. */\nconst AUXILIARY_MODEL_CARD_SERVICE = 'dshAuxiliaryModelSettingsCard'\n\n/** Theme-token-only stylesheet: officialUiCss scope plus the shared ModelMenu recipe. */\nexport const auxiliaryModelCss = `${officialUiCss('ams-root')}${modelMenuCss}\n.ams-root .ams-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }\n`\n\nconst auxiliaryCopy = {\n zh: {\n title: '默认辅助模型',\n help: '各辅助功能(如标题生成、摘要)没有单独指定模型时使用的模型;仅影响声明使用它的功能。',\n model: '辅助模型',\n modelDefault: '跟随会话或宿主默认',\n modelHint: '不选择模型时,各功能按自己的规则决定对话模型。',\n effortDefault: '跟随模型默认',\n loading: '正在读取设置…',\n failed: '无法读取模型设置。',\n stale: '设置已被其他窗口更新,请刷新后重试。',\n saveFailed: '保存失败,原设置未更改。请重试。',\n saved: '已保存。',\n retry: '重试',\n refresh: '刷新设置',\n syncUnavailable: '自动刷新不可用,请手动刷新设置。',\n },\n en: {\n title: 'Default Auxiliary Model',\n help: 'The model used by auxiliary features (such as title generation or summarizing) that do not name their own model; only features that opted in are affected.',\n model: 'Auxiliary model',\n modelDefault: 'Follow session or host default',\n modelHint: 'With no model selected, each feature follows its own rules for the conversation model.',\n effortDefault: 'Follow model default',\n loading: 'Loading settings…',\n failed: 'Could not load model settings.',\n stale: 'Settings were changed elsewhere; refresh and retry.',\n saveFailed: 'Save failed; the previous setting was not changed. Try again.',\n saved: 'Saved.',\n retry: 'Retry',\n refresh: 'Refresh settings',\n syncUnavailable: 'Automatic refresh unavailable; refresh settings manually.',\n },\n} as const\ntype AuxiliaryCopy = (typeof auxiliaryCopy)['zh'] | (typeof auxiliaryCopy)['en']\n\n/** A failed RPC keeps its code so the card can translate known rejections. */\nclass AuxiliaryRpcError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = 'AuxiliaryRpcError' }\n}\n\n/** The client services this card reads; the shared service passes ctx.root. */\nexport interface AuxiliaryModelClient {\n connection: {\n rpc: { call(channel: string, endpoint: string, payload: unknown): Promise<unknown> }\n generation?: { subscribe(listener: () => void): () => void }\n }\n remote?: { session?: { modelCatalog?: () => Promise<unknown> } }\n locale?: { getSnapshot(): { active: string }; subscribe(listener: () => void): () => void }\n}\n\n/** Host UI language, following live switches with the host's English fallback. */\nfunction useAuxiliaryLocale(client: AuxiliaryModelClient): 'zh' | 'en' {\n const subscribe = useCallback((listener: () => void) => client.locale?.subscribe(listener) ?? (() => {}), [client])\n const snapshot = useCallback(() => client.locale?.getSnapshot().active ?? 'en', [client])\n return String(useSyncExternalStore(subscribe, snapshot, snapshot)).startsWith('zh') ? 'zh' : 'en'\n}\n\nfunction isAbort(error: unknown): boolean {\n return error instanceof Error && (error.name === 'AbortError' || /abort|cancel/i.test(error.message))\n}\n\n/* A revision mismatch is a lost race, not a broken save: the stored row moved\n * past the one the user edited. The host reports it as auxiliary-model/conflict;\n * the message fallback covers older hosts that surfaced it as internal. */\nfunction isStaleRejection(error: unknown): boolean {\n if (!(error instanceof AuxiliaryRpcError)) return false\n return error.code === 'stale' || error.code === 'auxiliary-model/conflict'\n || /changed|revision|reload|stale|conflict/i.test(error.message)\n}\n\nasync function callAuxiliaryRpc<T>(\n client: AuxiliaryModelClient, endpoint: string, payload: unknown = {},\n): Promise<T> {\n const result = await client.connection.rpc.call(AUXILIARY_MODEL_CHANNEL, endpoint, payload) as RpcResult<T> | undefined\n if (!result || result.ok !== true) {\n const error = result && 'error' in result ? result.error : undefined\n throw new AuxiliaryRpcError(error?.code ?? 'unknown', error?.message ?? `RPC ${endpoint} failed`)\n }\n return result.value\n}\n\n/**\n * The shared card. All state comes from the shared host service over the\n * plugin-kit RPC channel; the card only renders the stored row.\n */\nexport function AuxiliaryModelCard({ client, subscribe }: {\n client: AuxiliaryModelClient\n /** Settings-change invalidation; injected for tests without a live stream. */\n subscribe?: (change: () => void, error?: (message: string) => void) => () => void\n}): ReactNode {\n const language = useAuxiliaryLocale(client)\n const text: AuxiliaryCopy = auxiliaryCopy[language]\n const [settings, setSettings] = useState<AuxiliaryModelSnapshot>()\n const loadCatalog = useCallback(() => readModelCatalog(client), [client])\n const subscribeCatalog = useCallback(\n (change: () => void) => client.connection.generation?.subscribe(change), [client])\n const catalogState = useModelCatalog(loadCatalog, { subscribe: subscribeCatalog })\n const { refresh: refreshCatalog } = catalogState\n const choices = parseModelMenuChoices(catalogState.catalog, settings?.model ?? undefined)\n const [menuOpen, setMenuOpen] = useState(false)\n const [error, setError] = useState<'' | 'failed' | 'stale' | 'saveFailed'>('')\n const [note, setNote] = useState(false)\n const [busy, setBusy] = useState(false)\n const [syncError, setSyncError] = useState('')\n const operation = useRef({ epoch: 0, active: false, reading: false, writing: false, pending: false })\n const refreshRef = useRef<() => void>(() => {})\n\n const refresh = () => {\n const state = operation.current\n if (!state.active) return\n if (state.reading || state.writing) { state.pending = true; return }\n state.pending = false; state.reading = true; setBusy(true)\n const epoch = state.epoch\n void callAuxiliaryRpc<AuxiliaryModelSnapshot>(client, 'defaults.get').then(next => {\n if (state.active && state.epoch === epoch && !state.pending) {\n setSettings(next); setError('')\n }\n }).catch(reason => {\n if (state.active && state.epoch === epoch && !state.pending && !isAbort(reason)) setError('failed')\n }).finally(() => {\n if (!state.active || state.epoch !== epoch) return\n state.reading = false; setBusy(false)\n if (state.pending) refreshRef.current()\n })\n }\n refreshRef.current = refresh\n useEffect(() => {\n const state = operation.current\n state.epoch++; state.active = true; state.reading = false; state.writing = false; state.pending = false\n setBusy(false); setSettings(undefined); setError(''); setNote(false)\n refreshRef.current()\n return () => { state.active = false; state.epoch++ }\n }, [client])\n // Cross-window invalidation rides the shared model-settings change stream.\n useEffect(() => {\n setSyncError('')\n let live = true\n let stop: (() => void) | undefined\n try {\n stop = subscribe?.(() => {\n if (live) { setSyncError(''); refreshCatalog(); refreshRef.current() }\n }, message => { if (live) setSyncError(message) })\n } catch {\n // A subscriber that cannot even attach degrades to manual refresh.\n if (live) setSyncError('Model settings sync service unavailable')\n }\n return () => { live = false; try { stop?.() } catch { /* detach is best-effort */ } }\n }, [subscribe, refreshCatalog])\n\n const save = useCallback((model: ModelRoute | null) => {\n const state = operation.current\n if (!settings || !state.active || state.writing || state.reading) return\n state.writing = true\n const epoch = state.epoch\n setBusy(true); setNote(false); setError('')\n void callAuxiliaryRpc<AuxiliaryModelSnapshot>(client, 'defaults.set', {\n model: model ?? { provider: '', model: '' },\n expectedRevision: settings.revision,\n }).then(next => {\n if (state.active && state.epoch === epoch) { setSettings(next); setNote(true); refreshCatalog() }\n }).catch(reason => {\n if (state.active && state.epoch === epoch) {\n setError(isStaleRejection(reason) ? 'stale' : 'saveFailed')\n }\n }).finally(() => {\n if (!state.active || state.epoch !== epoch) return\n state.writing = false; setBusy(false)\n if (state.pending) refreshRef.current()\n })\n }, [client, settings, refreshCatalog])\n\n const locked = busy\n if (!settings) {\n return <section className=\"ams-root dsh-ui-card\" data-testid=\"auxiliary-model-settings\">\n <span className=\"dsh-ui-heading\">{text.title}</span>\n <p className=\"dsh-ui-help\">{text.help}</p>\n {error\n ? <p role=\"alert\" className=\"dsh-ui-error\">{text[error]}</p>\n : <p role=\"status\" className=\"dsh-ui-hint\">{text.loading}</p>}\n {syncError && <p role=\"status\" className=\"dsh-ui-hint\">{text.syncUnavailable}</p>}\n <div className=\"dsh-ui-actions\">\n <Button variant=\"ghost\" size=\"sm\" disabled={locked} onClick={() => refreshRef.current()}>{text.retry}</Button>\n </div>\n </section>\n }\n\n const current = settings.model ?? { provider: '', model: '' }\n const follow = !current.provider || !current.model\n const selected = follow ? undefined : choices.find(item => item.provider === current.provider && item.model === current.model)\n const efforts = follow ? [] : modelMenuEffortOptions(selected, current.reasoningEffort)\n const currentLabel = follow ? text.modelDefault : selected?.label ?? `${current.provider} / ${current.model}`\n const selectedEffort = efforts.find(item => item.id === (current.reasoningEffort || ''))\n const effortName = selectedEffort ? modelMenuEffortLabel(selectedEffort, language) : undefined\n\n return <section className=\"ams-root dsh-ui-card\" data-testid=\"auxiliary-model-settings\">\n <span className=\"dsh-ui-heading\">{text.title}</span>\n <p className=\"dsh-ui-help\">{text.help}</p>\n <div className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.model}</span>\n <ModelCatalogStatus state={catalogState} locale={language} />\n <ModelMenu\n locale={language}\n open={menuOpen && !locked}\n onOpenChange={next => setMenuOpen(next && !locked)}\n listClassName=\"ams-root ams-menu-portal\"\n anchor={<button type=\"button\" className=\"dsh-model-menu-trigger\" disabled={locked}\n aria-label={`${text.model}: ${currentLabel}`}>\n <span className=\"dsh-model-menu-triggerLabel\">{currentLabel}</span>\n {!follow && efforts.length ? <span className=\"dsh-model-menu-triggerEffort\">{effortName ?? text.effortDefault}</span> : null}\n <IconChevronDownOutlineRegular className={`dsh-model-menu-chevron${menuOpen && !locked ? ' dsh-model-menu-chevronOpen' : ''}`} />\n </button>}\n choices={choices}\n selected={follow ? undefined : { provider: current.provider, model: current.model }}\n onPick={picked => save({ provider: picked.provider, model: picked.model })}\n leading={[{ id: 'default', label: text.modelDefault, selected: follow }]}\n onPickLeading={() => save(null)}\n efforts={efforts}\n selectedEffort={current.reasoningEffort || ''}\n onPickEffort={effort => save(follow\n ? null\n : { provider: current.provider, model: current.model, ...(effort ? { reasoningEffort: effort } : {}) })}\n modelLabel={text.model}\n modelValue={currentLabel}\n defaultEffortLabel={text.effortDefault}\n />\n <span className=\"dsh-ui-hint\">{text.modelHint}</span>\n </div>\n <div className=\"ams-row\">\n {syncError && <p role=\"status\" className=\"dsh-ui-hint\">{text.syncUnavailable}</p>}\n {error && <p role=\"alert\" className=\"dsh-ui-error\">{text[error]}</p>}\n {note && <p role=\"status\" className=\"dsh-ui-notice\">{text.saved}</p>}\n {error || syncError ? (\n <Button variant=\"ghost\" size=\"sm\" disabled={locked} onClick={() => refreshRef.current()}>{text.refresh}</Button>\n ) : null}\n </div>\n </section>\n}\n\ninterface AuxiliaryRoot {\n get(name: string, strict?: boolean): unknown\n provide(name: string, value: unknown): () => void\n inject(deps: string[], callback: (scope: unknown) => void): AuxiliaryFiber\n}\ninterface AuxiliaryFiber {\n dispose(): void | Promise<void>\n}\ninterface AuxiliaryRemoteMountScope {\n remote: { $mount(contribution: unknown): Promise<unknown> }\n effect(cb: () => () => void | Promise<void>): unknown\n}\n\n/* The client-side stream descriptor mount, serialized through one root\n * coordinator. Its tail carries mounts and unmounts in strict order: a new\n * mount cannot start while a previous fiber's unmount is in flight, and a\n * lease that closes before its continuation runs never mounts at all. The\n * coordinator leaves the store only when the queue is drained and no lease\n * is active — a fast teardown→re-acquire chains onto the same tail instead\n * of hitting \"already registered\" or overlapping a second mount. */\ninterface AuxiliaryWatchLease {\n fiber: AuxiliaryFiber | undefined\n closed: boolean\n done(): void\n}\ninterface AuxiliaryWatchCoordinator {\n tail: Promise<void>\n active: number\n mount(): AuxiliaryWatchLease\n}\nconst AUXILIARY_MODEL_WATCH_COORDINATOR = 'dshAuxiliaryModelWatchCoordinator'\n\nfunction acquireWatchCoordinator(root: AuxiliaryRoot): AuxiliaryWatchCoordinator {\n const existing = root.get(AUXILIARY_MODEL_WATCH_COORDINATOR, false) as AuxiliaryWatchCoordinator | undefined\n if (existing) return existing\n let unprovide: (() => void) | undefined\n const coordinator: AuxiliaryWatchCoordinator = {\n tail: Promise.resolve(),\n active: 0,\n mount() {\n coordinator.active += 1\n const previousTail = coordinator.tail\n const lease: AuxiliaryWatchLease = {\n closed: false,\n done() {\n if (lease.closed) return\n lease.closed = true\n coordinator.active -= 1\n const owned = lease.fiber\n lease.fiber = undefined\n // The unmount joins the tail every later mount waits on.\n coordinator.tail = coordinator.tail\n .then(() => Promise.resolve(owned?.dispose()).catch(() => {}))\n // Unprovide only once the queue is really drained: a newer lease\n // already queued on this coordinator must keep it alive.\n void coordinator.tail.then(() => {\n if (coordinator.active > 0) return\n try {\n if (root.get(AUXILIARY_MODEL_WATCH_COORDINATOR, false) === coordinator) {\n void Promise.resolve(unprovide?.()).catch(() => {})\n }\n } catch { /* Root already unloading. */ }\n })\n },\n fiber: undefined,\n }\n void previousTail.then(() => {\n // A release that beat the mount ends here: nothing mounted, nothing\n // to unmount, and the tail already moved on.\n if (lease.closed) return\n // mountModelSettingsChanges performs this exact inject/$mount pair;\n // it is repeated here only because that helper returns void and the\n // fiber must be captured for symmetric teardown.\n try {\n lease.fiber = root.inject(['remote'], injected => {\n const scope = injected as AuxiliaryRemoteMountScope\n const mounting = scope.remote.$mount(\n modelSettingsChangesRemote(AUXILIARY_MODEL_PACKAGE, AUXILIARY_MODEL_CHANGES_IDENTITY),\n ) as Promise<(() => Promise<void>) | undefined>\n void mounting.catch(() => {})\n scope.effect(() => async () => {\n const unmount = await mounting.catch(() => undefined)\n await unmount?.()\n })\n })\n } catch { /* remote unavailable: the card degrades to manual refresh */ }\n })\n return lease\n },\n }\n unprovide = root.provide(AUXILIARY_MODEL_WATCH_COORDINATOR, coordinator)\n return coordinator\n}\n\ninterface AuxiliaryCardService {\n retain(): void\n release(): void\n}\n\n/**\n * Acquire the root-owned card service, creating it on first use. One counter\n * covers participants, the seat wait and the change-stream mount: the last\n * release removes the wait, then the watch contribution, then the provider\n * itself synchronously (Cordis deletes the impl before its async disposer\n * awaits), so a later acquire sees a clean get() miss and can re-establish.\n */\nfunction acquireAuxiliaryModelCard(root: AuxiliaryRoot, ctx: Context): AuxiliaryCardService {\n const existing = root.get(AUXILIARY_MODEL_CARD_SERVICE, false) as AuxiliaryCardService | undefined\n if (existing) return existing\n let users = 0\n let styleElement: HTMLStyleElement | undefined\n let stopItem: (() => void) | undefined\n let unprovide: (() => void) | undefined\n // The client-side stream descriptor hangs off the shared root context —\n // never a plugin fiber — so the first participant's unload cannot take the\n // card's change stream down. The coordinator still unmounts it, in tail\n // order, on the last release.\n const watchLease = acquireWatchCoordinator(root).mount()\n const subscriber: ModelSettingsSubscriber = createModelSettingsSubscriber(\n ctx.root as unknown as Parameters<typeof createModelSettingsSubscriber>[0],\n AUXILIARY_MODEL_PACKAGE,\n AUXILIARY_MODEL_CHANGES_IDENTITY,\n ns => ns === AUXILIARY_MODEL_NS,\n )\n const render = () => <AuxiliaryModelCard client={root as unknown as AuxiliaryModelClient}\n subscribe={subscriber.subscribe} />\n const service: AuxiliaryCardService = {\n retain() {\n // The reservation is counted before the throwing installs, so a failure\n // lets the caller's release() undo it fully instead of leaking the service.\n users += 1\n if (styleElement === undefined && typeof document !== 'undefined') {\n styleElement = document.createElement('style')\n styleElement.setAttribute('data-plugin', 'dsh-auxiliary-model-shared')\n styleElement.textContent = auxiliaryModelCss\n document.head.appendChild(styleElement)\n }\n /* The card is a participant of the shared column too: the root-owned\n * call contributes its row AND retains the page and nav icon, which is\n * what guarantees a lone auxiliary plugin still creates the Session\n * Management section — no business plugin has to provide it. The waits\n * sit on the root context, so they live exactly as long as the card. */\n if (!stopItem) {\n stopItem = registerSessionSettingsItem(ctx.root, {\n id: AUXILIARY_MODEL_SEAT_ID,\n order: AUXILIARY_MODEL_SEAT_ORDER,\n }, render)\n }\n },\n release() {\n if (users <= 0) return\n users -= 1\n if (users > 0) return\n stopItem?.()\n stopItem = undefined\n styleElement?.remove()\n styleElement = undefined\n watchLease.done()\n // The store entry leaves synchronously, like the shared page service:\n // the next acquire must not see a stale \"already registered\" marker.\n try { void Promise.resolve(unprovide?.()).catch(() => {}) } catch { /* Root already unloading. */ }\n unprovide = undefined\n },\n }\n unprovide = root.provide(AUXILIARY_MODEL_CARD_SERVICE, service)\n return service\n}\n\n/**\n * Show the shared \"default auxiliary model\" card while the calling plugin is\n * enabled.\n *\n * `ctx` is the plugin's own client context: the card itself is retained on the\n * shared root context for as long as any participant lives, so an arbitrary\n * subset of enabled plugins yields the same single card. The mount's slot wait\n * and the change-stream contribution are owned by the root service — the first\n * participant's unload cannot take the card down. Returns a disposer; it may\n * be invoked by both ctx.effect and an explicit caller and releases at most\n * once, so a double call cannot unbalance the shared refcount.\n */\nexport function registerAuxiliaryModelSettings(ctx: Context): () => void {\n const root = ctx.root as unknown as AuxiliaryRoot\n const service = acquireAuxiliaryModelCard(root, ctx)\n try {\n service.retain()\n } catch (error) {\n // A synchronous failure (for example a duplicate row id) must not pin the\n // shared card for a participant that never joined.\n service.release()\n throw error\n }\n let disposed = false\n return () => {\n if (disposed) return\n disposed = true\n service.release()\n }\n}\n","import { defaultModelRoute, normalizeModelRoute, type ModelRoute } from '@klarkxy/dsh-model-route'\nexport { defaultModelRoute, normalizeModelRoute }\n\n/** Browser-safe contracts. Shared RPC/result types stay on @klarkxy/dsh-plugin-kit. */\nexport type { RpcResult } from '@klarkxy/dsh-plugin-kit/contracts'\n\nexport const PLUGIN_NAME = '@klarkxy/dsh-current-title'\nexport const FEATURE_ID = 'current-title'\nexport const PROVIDER_ID = '@klarkxy/dsh-current-title'\nexport const PURPOSE_ID = 'current-title.generate'\nexport const RPC_CHANNEL = '/dsh-current-title'\nexport const TITLE_CLIENT_SERVICE = 'dshCurrentTitleClient'\nexport const PROMPT_VERSION = 'current-title.v2'\n/** Feature id stamped on the auxiliary-context envelope for this call. */\nexport const TITLE_CALL_FEATURE = 'session-title'\nexport const SCHEMA_VERSION = 'title-json.v1'\nexport const CONTRACT_VERSION = 1\nexport const SETTINGS_KEY = 'current'\nexport const MAX_PROMPT_CHARS = 4000\n\nexport const DEFAULT_MAX_RECENT_MESSAGES = 8\nexport const DEFAULT_TARGET_WORDS = 5\nexport const DEFAULT_TARGET_CJK = 10\nexport const DEFAULT_MAX_INPUT_BYTES = 4096\nexport const DEFAULT_MAX_OUTPUT_TOKENS = 256\nexport const DEFAULT_TIMEOUT_MS = 60_000\nexport const DEFAULT_MAX_TITLE_BYTES = 80\n\nexport type TitleLocaleMode = 'auto' | 'zh' | 'en'\nexport type TitleSourceKind = 'fallback' | 'provider' | 'user'\n/** Automatic generation cadence: every eligible message, or only the first. */\nexport type TitleCadence = 'all-prompts' | 'first-prompt'\n\nexport interface TitleMessage {\n readonly seq: number\n readonly text: string\n}\n\nexport interface TitleSnapshot {\n readonly title: string\n readonly messageSeqs: readonly number[]\n readonly source: { readonly kind: TitleSourceKind; readonly provider?: string }\n readonly eventSeq: number\n readonly updatedAt: number\n}\n\n/**\n * Empty provider and model means the shared weak role. Both must be set together.\n * No title-only fields: the stored value is the shared ModelRoute (250/80 caps\n * live in @klarkxy/dsh-model-route). The alias keeps the title-specific name.\n */\nexport type TitleModelRoute = ModelRoute\n\nexport interface TitleSettings {\n revision: number\n locale: TitleLocaleMode\n /** Empty keeps the built-in title instruction. */\n prompt: string\n model: TitleModelRoute\n cadence: TitleCadence\n}\n\nexport interface TitleSupport {\n nativeOwner: string | null\n weOwn: boolean\n limitation?: string\n}\n\nexport interface TitleStatus {\n settings: TitleSettings\n support: TitleSupport\n session?: {\n sessionId: string\n title?: string\n sourceKind?: TitleSourceKind\n generating: boolean\n pinned: boolean\n }\n}\n\nexport interface TitleClientMarker {\n active: boolean\n}\n\nexport interface GenerateConfig {\n readonly maxRecentMessages: number\n readonly locale: TitleLocaleMode\n readonly targetWords: number\n readonly targetCjkCharacters: number\n readonly maxInputBytes: number\n readonly maxOutputTokens: number\n readonly timeoutMs: number\n readonly maxTitleBytes: number\n}\n\nexport function defaultSettings(locale: TitleLocaleMode = 'auto'): TitleSettings {\n return { revision: 0, locale, prompt: '', model: defaultModelRoute(), cadence: 'all-prompts' }\n}\n\nexport function normalizeCadence(value: unknown): TitleCadence {\n return value === 'first-prompt' ? 'first-prompt' : 'all-prompts'\n}\n\nexport function normalizePrompt(value: unknown): string {\n if (typeof value !== 'string') return ''\n return value.replace(/\\u0000/gu, '').trim().slice(0, MAX_PROMPT_CHARS)\n}\n\nexport function defaultGenerateConfig(locale: TitleLocaleMode = 'auto'): GenerateConfig {\n return {\n maxRecentMessages: DEFAULT_MAX_RECENT_MESSAGES,\n locale,\n targetWords: DEFAULT_TARGET_WORDS,\n targetCjkCharacters: DEFAULT_TARGET_CJK,\n maxInputBytes: DEFAULT_MAX_INPUT_BYTES,\n maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n maxTitleBytes: DEFAULT_MAX_TITLE_BYTES,\n }\n}\n\nexport function isTitleLocaleMode(value: unknown): value is TitleLocaleMode {\n return value === 'auto' || value === 'zh' || value === 'en'\n}\n","import type { RpcResult, TitleCadence, TitleModelRoute, TitleStatus } from './contracts.ts'\n\nexport const titleCopy = {\n zh: {\n label: '自动标题',\n groupHint: '标题模型、提示词与更新节奏',\n session: '当前会话',\n noSession: '没有打开的会话。打开一个会话后,可以在这里查看并重新生成标题。',\n pinned: '已手动命名',\n generating: '正在生成标题…',\n regenerate: '重新生成',\n locale: '类型标签语言',\n auto: '自动',\n prompt: '标题提示词',\n promptHint: '留空用内置说明,仍返回类型和摘要;离开输入框即保存。',\n loading: '正在读取标题设置…',\n model: '标题模型',\n modelDefault: '默认辅助模型',\n modelHint: '使用全局默认辅助模型;未设置时跟随当前会话模型,再回落到宿主默认对话模型。',\n cadence: '更新节奏',\n cadenceAll: '跟随当前任务(每条消息)',\n cadenceFirst: '仅首条消息',\n saved: '已保存。',\n failed: '无法读取标题设置。',\n inactive: '标题服务未接管,新消息暂时不会自动更新。',\n retry: '重试',\n externalChange: '设置已在别处修改。提示词草稿已保留,请重新加载后确认。',\n syncUnavailable: '自动刷新不可用,请手动重新加载设置。',\n reload: '重新加载(丢弃草稿)',\n defaults: '默认设置',\n },\n en: {\n label: 'Auto Title',\n groupHint: 'Title model, prompt and update cadence',\n session: 'Current session',\n noSession: 'No session is open. Open one to see its title and regenerate it here.',\n pinned: 'Renamed manually',\n generating: 'Generating title…',\n regenerate: 'Regenerate',\n locale: 'Type-label language',\n auto: 'Auto',\n prompt: 'Title prompt',\n promptHint: 'Empty uses the built-in instruction; a type and summary are still returned. Saves on blur.',\n loading: 'Loading title settings…',\n model: 'Title model',\n modelDefault: 'Default auxiliary model',\n modelHint: 'Uses the global default auxiliary model; when none is set, the current conversation model, then the host default chat model.',\n cadence: 'Update cadence',\n cadenceAll: 'Track the current task (every message)',\n cadenceFirst: 'First message only',\n saved: 'Saved.',\n failed: 'Could not read title settings.',\n inactive: 'Title generation is not active, so new messages will not rename this session.',\n retry: 'Retry',\n externalChange: 'Settings changed elsewhere. Prompt draft preserved; reload and review.',\n syncUnavailable: 'Automatic refresh unavailable; reload settings manually.',\n reload: 'Reload (discard draft)',\n defaults: 'Default settings',\n },\n} as const\n\n/** Only plugin-owned defaults are translated; model output and remote diagnostics stay intact. */\nconst titleMessages = [\n ['标题设置无效。', 'Invalid title settings.'],\n ['设置已更新,请刷新后重试。', 'Settings changed. Refresh and try again.'],\n ['无法保存标题设置。', 'Could not save title settings.'],\n ['缺少会话。', 'A session is required.'],\n ['找不到该会话。', 'Session not found.'],\n ['标题服务未就绪。', 'Title service is not ready.'],\n ['已取消。', 'Cancelled.'],\n ['标题生成失败。', 'Title generation failed.'],\n ['未知操作。', 'Unknown operation.'],\n ['缺少所需的宿主服务。', 'required host services are missing'],\n ['原生标题服务位置已被占用。', 'native title provider slot is occupied'],\n ['其他标题服务已接管;先前的服务未恢复。', 'another title provider owns the slot; previous owner was not restored'],\n [titleCopy.zh.saved, titleCopy.en.saved],\n [titleCopy.zh.failed, titleCopy.en.failed],\n] as const\n\nexport function titleMessage(message: string, locale: 'zh' | 'en'): string {\n const pair = titleMessages.find(pair => (pair as readonly string[]).includes(message))\n return pair?.[locale === 'zh' ? 0 : 1] ?? message\n}\n\n/** `undefined` draft = not edited; an empty string is a real edit (use built-in instruction). */\nexport function promptFieldValue(draft: string | undefined, saved: string): string {\n return draft ?? saved\n}\n\n/** The prompt to persist on blur, or `undefined` when nothing changed. */\nexport function promptToSave(draft: string | undefined, saved: string): string | undefined {\n if (draft === undefined) return undefined\n const next = draft.trim()\n return next === saved ? undefined : next\n}\n\nexport function shouldSkipTitleRefresh(input: { busy: boolean }): boolean {\n return input.busy\n}\n\nexport function createTitleClientWork() {\n let generation = 0\n let request = 0\n let disposed = false\n return {\n get disposed() { return disposed },\n beginLoad() {\n generation += 1\n request += 1\n return generation\n },\n captureLoad() {\n return generation\n },\n beginRequest() {\n request += 1\n return { generation, request }\n },\n isLoad(generationToken: number) {\n return !disposed && generation === generationToken\n },\n isRequest(token: { generation: number; request: number }) {\n return !disposed && generation === token.generation && request === token.request\n },\n dispose() {\n disposed = true\n generation += 1\n request += 1\n },\n }\n}\n\nexport type TitleClientWork = ReturnType<typeof createTitleClientWork>\nexport type TitleClientCall = (endpoint: string, payload?: unknown) => Promise<unknown>\n\nfunction unwrap<T>(result: RpcResult<T>): T {\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n}\n\nasync function invoke<T>(call: TitleClientCall, endpoint: string, payload?: unknown): Promise<T> {\n return unwrap(await call(endpoint, payload) as RpcResult<T>)\n}\n\nexport async function runTitleStatusLoad(input: {\n call: TitleClientCall\n sessionId?: string\n isCurrent: () => boolean\n failedMessage: string\n onStatus: (status: TitleStatus) => void\n onError: (message: string) => void\n onMarker: (status: TitleStatus | undefined) => void\n}): Promise<void> {\n try {\n const status = await invoke<TitleStatus>(\n input.call,\n 'status',\n input.sessionId ? { sessionId: input.sessionId } : {},\n )\n if (!input.isCurrent()) return\n input.onStatus(status)\n input.onMarker(status)\n } catch {\n if (!input.isCurrent()) return\n input.onMarker(undefined)\n input.onError(input.failedMessage)\n }\n}\n\nexport async function runTitleRegenerateFlow(input: {\n call: TitleClientCall\n sessionId: string\n isCurrent: () => boolean\n failedMessage: string\n onBusy: (busy: boolean) => void\n onStatus: (status: TitleStatus) => void\n onError: (message: string) => void\n onMarker: (status: TitleStatus | undefined) => void\n}): Promise<void> {\n if (!input.sessionId || !input.isCurrent()) return\n input.onBusy(true)\n try {\n await invoke(input.call, 'regenerate', { sessionId: input.sessionId })\n if (!input.isCurrent()) return\n const status = await invoke<TitleStatus>(input.call, 'status', { sessionId: input.sessionId })\n if (!input.isCurrent()) return\n input.onStatus(status)\n input.onMarker(status)\n } catch (cause) {\n if (!input.isCurrent()) return\n input.onError(cause instanceof Error ? cause.message : input.failedMessage)\n } finally {\n if (!input.isCurrent()) return\n input.onBusy(false)\n }\n}\n\nexport async function runTitleSettingsSave(input: {\n call: TitleClientCall\n prompt?: string\n model?: TitleModelRoute\n cadence?: TitleCadence\n expectedRevision: number\n isCurrent: () => boolean\n savedMessage: string\n failedMessage: string\n onBusy: (busy: boolean) => void\n onSettings: (settings: TitleStatus['settings']) => void\n onNote: (note: string) => void\n onError: (message: string) => void\n}): Promise<void> {\n input.onBusy(true)\n try {\n const settings = await invoke<TitleStatus['settings']>(input.call, 'settings', {\n ...(input.prompt !== undefined ? { prompt: input.prompt } : {}),\n ...(input.model !== undefined ? { model: input.model } : {}),\n ...(input.cadence !== undefined ? { cadence: input.cadence } : {}),\n expectedRevision: input.expectedRevision,\n })\n if (!input.isCurrent()) return\n input.onSettings(settings)\n input.onNote(input.savedMessage)\n } catch (cause) {\n if (!input.isCurrent()) return\n input.onError(cause instanceof Error ? cause.message : input.failedMessage)\n } finally {\n if (!input.isCurrent()) return\n input.onBusy(false)\n }\n}\n","import type { TitleClientMarker, TitleStatus } from './contracts.ts'\n\nexport function createTitleClientMarker(): TitleClientMarker {\n return { active: false }\n}\n\nexport function applyMarkerFromStatus(marker: TitleClientMarker, status: Pick<TitleStatus, 'support'> | undefined, live: boolean): void {\n if (!live) return\n marker.active = status?.support.weOwn === true\n}\n\nexport function disposeTitleClientMarker(marker: TitleClientMarker): void {\n marker.active = false\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type { NativeSurfaceClient } from '@klarkxy/dsh-plugin-kit/client-utils'\nimport { createPluginReadGate, registerSessionSettingsItem, useFeatureRefresh, useNativeSeat } from '@klarkxy/dsh-plugin-kit/client-utils'\nimport { Button, IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { officialUiCss } from '@klarkxy/dsh-plugin-kit/official-ui'\nimport { modelSettingsChangesIdentity } from '@klarkxy/dsh-plugin-kit/contracts'\nimport { createModelSettingsSubscriber, mountModelSettingsChanges } from '@klarkxy/dsh-plugin-kit/model-settings-client'\nimport { registerAuxiliaryModelSettings } from '@klarkxy/dsh-plugin-kit/auxiliary-model-client'\nimport {\n MODEL_CATALOG_INJECT, readModelCatalog, modelMenuEffortLabel, modelMenuEffortOptions, parseModelMenuChoices,\n} from '@klarkxy/dsh-model-route'\nimport { ModelCatalogStatus, ModelMenu, modelMenuCss, useModelCatalog } from '@klarkxy/dsh-model-route/ui'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { RPC_CHANNEL, TITLE_CLIENT_SERVICE, type RpcResult, type TitleCadence, type TitleModelRoute, type TitleStatus } from './contracts.ts'\nimport {\n createTitleClientWork, promptFieldValue, promptToSave, runTitleRegenerateFlow, runTitleSettingsSave, runTitleStatusLoad,\n shouldSkipTitleRefresh, titleCopy, titleMessage, type TitleClientCall, type TitleClientWork,\n} from './client-work.ts'\nimport { applyMarkerFromStatus, createTitleClientMarker, disposeTitleClientMarker } from './marker.ts'\n\nexport const name = 'dsh-current-title-client'\nexport const inject = ['slots', 'connection', ...MODEL_CATALOG_INJECT, 'sessions', 'locale', 'uiWorkspace', 'uiSession'] as const\nexport { createTitleClientMarker, disposeTitleClientMarker, applyMarkerFromStatus }\n\ntype Client = NativeSurfaceClient & {\n connection: NonNullable<NativeSurfaceClient['connection']> & {\n rpc: { call(channel: string, endpoint: string, payload: unknown): Promise<unknown> }\n }\n remote?: { session?: { modelCatalog?: () => Promise<unknown> } }\n}\n\nexport function TitleSettings(props: {\n client: Client\n marker: { active: boolean }\n subscribeSettings?: (change: () => void, error?: (message: string) => void) => () => void\n}) {\n const seat = useNativeSeat(props.client)\n const sessionId = seat.sessionId\n const text = titleCopy[seat.locale]\n // Async work stores canonical defaults; translation belongs to the current render.\n const messages = titleCopy.en\n const [status, setStatus] = useState<TitleStatus>()\n const [busy, setBusy] = useState(false)\n const [note, setNote] = useState('')\n const [error, setError] = useState('')\n // undefined = not edited; '' is a deliberate clear (built-in instruction).\n const [prompt, setPrompt] = useState<string | undefined>(undefined)\n const loadCatalog = useCallback(() => readModelCatalog(props.client), [props.client])\n const subscribeCatalog = useCallback((change: () => void) => props.client.connection.generation?.subscribe(change), [props.client])\n const catalogState = useModelCatalog(loadCatalog, { subscribe: subscribeCatalog })\n const { refresh: refreshCatalog } = catalogState\n const choices = parseModelMenuChoices(catalogState.catalog, status?.settings?.model)\n const [menuOpen, setMenuOpen] = useState(false)\n const [externalChange, setExternalChange] = useState(false)\n const [syncError, setSyncError] = useState('')\n const [loadingSettings, setLoadingSettings] = useState(true)\n const dirty = useRef(false)\n const external = useRef(false)\n const reading = useRef(false)\n const pending = useRef(false)\n const syncRef = useRef<() => void>(() => {})\n const workRef = useRef<TitleClientWork>(undefined)\n if (!workRef.current) workRef.current = createTitleClientWork()\n const work = workRef.current\n const readGateRef = useRef<ReturnType<typeof createPluginReadGate>>(undefined)\n if (!readGateRef.current) readGateRef.current = createPluginReadGate()\n const readGate = readGateRef.current\n const busyRef = useRef(busy)\n busyRef.current = busy\n const changeBusy = (value: boolean) => {\n busyRef.current = value; setBusy(value)\n if (!value && pending.current) syncRef.current()\n }\n\n const call: TitleClientCall = (endpoint, payload = {}) => (\n props.client.connection.rpc.call(RPC_CHANNEL, endpoint, payload)\n )\n const readCall: TitleClientCall = (endpoint, payload) => readGate.run(() => call(endpoint, payload))\n\n function commitMarker(next: TitleStatus | undefined) {\n applyMarkerFromStatus(props.marker, next, true)\n }\n\n useEffect(() => () => { readGate.reset(); work.dispose() }, [work, readGate])\n useEffect(() => props.client.connection.generation?.subscribe(() => {\n readGate.reset()\n work.beginLoad()\n reading.current = false\n setLoadingSettings(false)\n busyRef.current = false\n setBusy(false)\n }), [props.client, work, readGate])\n\n useEffect(() => {\n const generation = work.beginLoad()\n reading.current = true; pending.current = false\n setLoadingSettings(true)\n readGate.reset()\n const isCurrent = () => work.isLoad(generation)\n setBusy(false)\n setError('')\n setNote('')\n void runTitleStatusLoad({\n call: readCall,\n sessionId: sessionId || undefined,\n isCurrent,\n failedMessage: messages.failed,\n onStatus: next => { if (!pending.current) setStatus(current => current && external.current ? { ...next, settings: current.settings } : next) },\n onError: message => { if (!pending.current) setError(message) },\n onMarker: commitMarker,\n }).finally(() => {\n if (!work.isLoad(generation)) return\n reading.current = false\n setLoadingSettings(false)\n if (pending.current) syncRef.current()\n })\n return () => { if (work.isLoad(generation)) work.beginLoad() }\n }, [props.client, props.marker, sessionId, work])\n\n const refreshStatus = useCallback(() => {\n if (!readGate.canRead() || shouldSkipTitleRefresh({ busy: busyRef.current }) || work.disposed) return\n if (reading.current) return\n reading.current = true\n setLoadingSettings(true)\n readGate.reset()\n const token = work.beginRequest()\n void runTitleStatusLoad({\n call: readCall,\n sessionId: sessionId || undefined,\n isCurrent: () => work.isRequest(token) && !shouldSkipTitleRefresh({ busy: busyRef.current }),\n failedMessage: messages.failed,\n onStatus: next => {\n if (pending.current || shouldSkipTitleRefresh({ busy: busyRef.current })) return\n setStatus(current => current && external.current ? { ...next, settings: current.settings } : next)\n setError('')\n },\n onError: message => { if (!pending.current) setError(message) },\n onMarker: next => {\n if (!next || shouldSkipTitleRefresh({ busy: busyRef.current })) return\n commitMarker(next)\n },\n }).finally(() => {\n if (!work.isRequest(token)) return\n reading.current = false\n setLoadingSettings(false)\n if (pending.current) syncRef.current()\n })\n }, [props.client, props.marker, sessionId, work])\n\n useFeatureRefresh(\n props.client,\n sessionId,\n refreshStatus,\n status?.session?.generating === true && !busy,\n Boolean(sessionId),\n )\n syncRef.current = () => {\n if (work.disposed) return\n if (reading.current || busyRef.current) { pending.current = true; return }\n pending.current = false\n if (dirty.current) { external.current = true; setExternalChange(true); return }\n readGate.reset(); refreshStatus()\n }\n useEffect(() => {\n setSyncError('')\n let live = true\n const stop = props.subscribeSettings?.(() => {\n if (!live) return\n setSyncError('')\n refreshCatalog()\n if (dirty.current && !busyRef.current) { external.current = true; setExternalChange(true) }\n syncRef.current()\n }, message => { if (live) setSyncError(message) })\n return () => { live = false; stop?.() }\n }, [props.subscribeSettings, props.client, refreshCatalog])\n\n const savedPrompt = status?.settings?.prompt ?? ''\n const savedModel = status?.settings?.model ?? { provider: '', model: '' }\n const follow = !savedModel.provider || !savedModel.model\n const selectedModel = follow ? undefined : choices.find(choice => choice.provider === savedModel.provider && choice.model === savedModel.model)\n const efforts = follow ? [] : modelMenuEffortOptions(selectedModel, savedModel.reasoningEffort)\n const currentLabel = follow ? text.modelDefault : selectedModel?.label ?? `${savedModel.provider} / ${savedModel.model}`\n const selectedEffort = efforts.find(item => item.id === (savedModel.reasoningEffort || ''))\n const effortName = selectedEffort ? modelMenuEffortLabel(selectedEffort, seat.locale) : undefined\n const title = status?.session?.title\n const pinned = status?.session?.pinned === true\n const weOwn = status?.support?.weOwn === true\n const canRegenerate = Boolean(sessionId) && weOwn && !busy && !loadingSettings\n\n function saveSettings(patch: { model?: TitleModelRoute; cadence?: TitleCadence }) {\n if (!status || busyRef.current || reading.current || external.current) return\n readGate.reset()\n const token = work.beginRequest()\n setError('')\n setNote('')\n void runTitleSettingsSave({\n call,\n ...patch,\n expectedRevision: status.settings.revision,\n isCurrent: () => work.isRequest(token),\n savedMessage: messages.saved,\n failedMessage: messages.failed,\n onBusy: changeBusy,\n onSettings: settings => setStatus(current => current ? { ...current, settings } : current),\n onNote: setNote,\n onError: setError,\n })\n }\n\n return <section className=\"current-title-settings ct-root\" lang={seat.locale} data-testid=\"current-title-settings\">\n {!status && !error ? <p role=\"status\" className=\"dsh-ui-hint\">{text.loading}</p> : null}\n <article className=\"dsh-ui-card\" data-testid=\"current-title-session\">\n <h3 className=\"dsh-ui-heading\">{text.session}</h3>\n {title\n ? <p translate=\"no\" className=\"dsh-ui-title dsh-ui-wrap\">{title}</p>\n : <p className=\"dsh-ui-hint\">{text.noSession}</p>}\n {pinned ? <p className=\"dsh-ui-meta\">{text.pinned}</p> : null}\n {status?.session?.generating ? <p role=\"status\" className=\"dsh-ui-hint\">{text.generating}</p> : null}\n {status && !weOwn ? <p role=\"status\" className=\"dsh-ui-hint\">{text.inactive}{status.support?.limitation ? ` ${titleMessage(status.support.limitation, seat.locale)}` : ''}</p> : null}\n {error ? <>\n <p role=\"alert\" className=\"dsh-ui-error dsh-ui-wrap\">{titleMessage(error, seat.locale)}</p>\n <Button variant=\"outline\" size=\"sm\" disabled={busy} onClick={() => { readGate.reset(); refreshStatus() }}>\n {text.retry}\n </Button>\n </> : null}\n {note ? <p role=\"status\" className=\"dsh-ui-notice\">{titleMessage(note, seat.locale)}</p> : null}\n {externalChange ? <p role=\"alert\" className=\"dsh-ui-error\">{text.externalChange}</p> : null}\n {syncError ? <p role=\"status\" className=\"dsh-ui-hint\">{text.syncUnavailable}</p> : null}\n <div className=\"dsh-ui-actions\">\n <Button variant=\"ghost\" size=\"sm\" disabled={busy || loadingSettings} onClick={() => {\n setPrompt(undefined); dirty.current = false; external.current = false; setExternalChange(false)\n readGate.reset(); syncRef.current()\n }}>{text.reload}</Button>\n {sessionId ? <Button variant=\"outline\" size=\"md\" disabled={!canRegenerate}\n onClick={() => {\n if (!sessionId) return\n readGate.reset()\n const token = work.beginRequest()\n setError('')\n setNote('')\n void runTitleRegenerateFlow({\n call,\n sessionId,\n isCurrent: () => work.isRequest(token),\n failedMessage: messages.failed,\n onBusy: changeBusy,\n onStatus: setStatus,\n onError: setError,\n onMarker: commitMarker,\n })\n }}>{text.regenerate}</Button> : null}\n </div>\n </article>\n <section className=\"dsh-ui-section\" data-testid=\"current-title-defaults\">\n <h3 className=\"dsh-ui-heading\">{text.defaults}</h3>\n <label className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.prompt}</span>\n <textarea\n className=\"dsh-ui-textarea ct-prompt\"\n value={status ? promptFieldValue(prompt, savedPrompt) : ''}\n maxLength={4000}\n rows={5}\n disabled={busy || loadingSettings || !status}\n onChange={event => { dirty.current = true; setPrompt(event.target.value); setNote('') }}\n onBlur={() => {\n if (!status || busyRef.current || reading.current || external.current) return\n const next = promptToSave(prompt, savedPrompt)\n if (next === undefined) { dirty.current = false; setPrompt(undefined); return }\n readGate.reset()\n const token = work.beginRequest()\n setError('')\n void runTitleSettingsSave({\n call,\n prompt: next,\n expectedRevision: status.settings.revision,\n isCurrent: () => work.isRequest(token),\n savedMessage: messages.saved,\n failedMessage: messages.failed,\n onBusy: changeBusy,\n onSettings: settings => { setStatus(current => current ? { ...current, settings } : current); dirty.current = false; setPrompt(undefined) },\n onNote: setNote,\n onError: setError,\n })\n }}\n />\n <span className=\"dsh-ui-help\">{text.promptHint}</span>\n </label>\n <div className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.model}</span>\n <ModelCatalogStatus state={catalogState} locale={seat.locale} />\n <ModelMenu\n locale={seat.locale}\n open={menuOpen && Boolean(status) && !busy && !loadingSettings}\n onOpenChange={next => setMenuOpen(next && Boolean(status) && !busy && !loadingSettings)}\n listClassName=\"ct-root\"\n anchor={<button type=\"button\" className=\"dsh-model-menu-trigger\" disabled={busy || loadingSettings || !status} aria-label={`${text.model}: ${currentLabel}`}>\n <span className=\"dsh-model-menu-triggerLabel\">{currentLabel}</span>\n {!follow && efforts.length ? <span className=\"dsh-model-menu-triggerEffort\">{effortName ?? text.modelDefault}</span> : null}\n <IconChevronDownOutlineRegular className={`dsh-model-menu-chevron${menuOpen ? ' dsh-model-menu-chevronOpen' : ''}`} />\n </button>}\n choices={choices}\n selected={follow ? undefined : { provider: savedModel.provider, model: savedModel.model }}\n onPick={picked => saveSettings({ model: { provider: picked.provider, model: picked.model } })}\n leading={[{ id: 'default', label: text.modelDefault, selected: follow }]}\n onPickLeading={() => saveSettings({ model: { provider: '', model: '' } })}\n efforts={efforts}\n selectedEffort={savedModel.reasoningEffort || ''}\n onPickEffort={effort => saveSettings({ model: follow\n ? { provider: '', model: '' }\n : { provider: savedModel.provider, model: savedModel.model, ...(effort ? { reasoningEffort: effort } : {}) } })}\n modelLabel={text.model}\n modelValue={currentLabel}\n defaultEffortLabel={text.modelDefault}\n />\n <p className=\"dsh-ui-meta\">{text.modelHint}</p>\n </div>\n <label className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.cadence}</span>\n <select\n className=\"dsh-ui-select\"\n value={status?.settings?.cadence ?? 'all-prompts'}\n disabled={busy || loadingSettings || !status}\n onChange={event => {\n saveSettings({ cadence: event.target.value === 'first-prompt' ? 'first-prompt' : 'all-prompts' })\n }}\n >\n <option value=\"all-prompts\">{text.cadenceAll}</option>\n <option value=\"first-prompt\">{text.cadenceFirst}</option>\n </select>\n </label>\n </section>\n </section>\n}\n\n/**\n * The settings row: a named native details group. The content mounts\n * on the first expand only — the shared page must not fire every plugin's\n * model/status requests — and stays mounted afterwards so a collapsed group\n * never drops an unsaved prompt draft or an in-flight write.\n */\nexport function TitleSettingsItem(props: { client: Client; marker: { active: boolean }; subscribeSettings?: (change: () => void, error?: (message: string) => void) => () => void }) {\n const seat = useNativeSeat(props.client)\n const text = titleCopy[seat.locale]\n const [visited, setVisited] = useState(false)\n return (\n <details\n className=\"ct-root ct-item\"\n lang={seat.locale}\n data-testid=\"current-title-settings-item\"\n onToggle={event => { if ((event.currentTarget as HTMLDetailsElement).open) setVisited(true) }}\n >\n <summary className=\"ct-item-summary\">\n <span>\n <span className=\"ct-item-title\">{text.label}</span>\n <span className=\"ct-item-desc\">{text.groupHint}</span>\n </span>\n <IconChevronDownOutlineRegular className=\"ct-item-chevron\" aria-hidden=\"true\" />\n </summary>\n {visited ? (\n <div className=\"ct-item-body\">\n <TitleSettings client={props.client} marker={props.marker} subscribeSettings={props.subscribeSettings} />\n </div>\n ) : null}\n </details>\n )\n}\n\n/* The contract owns every type tier, the field rhythm, the focus ring, the\n * select shell and the textarea shell. The only geometry left here is this\n * panel's own: its reading width, a taller prompt box, and the settings\n * group's row geometry (mirroring the native item rows: 16px padding, a 0.5px\n * l2 rule the shell drops on the last item, 24px label-control gutter). */\nexport const currentTitleOwnCss = `\n.ct-root .ct-prompt { min-height: 96px; }\n.ct-root.ct-item { padding: 0; border-bottom: 0.5px solid var(--dsw-alias-border-l2); }\n.ct-root .ct-item-summary { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 16px 0; list-style: none; cursor: pointer; }\n.ct-root .ct-item-summary::-webkit-details-marker { display: none; }\n.ct-root .ct-item-summary > span:first-child { min-width: 0; }\n.ct-root .ct-item-title { display: block; font-size: 14px; line-height: 20px; color: var(--dsw-alias-label-primary); }\n.ct-root .ct-item-desc { display: block; margin-top: 4px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }\n.ct-root .ct-item-chevron { width: 14px; height: 14px; color: var(--dsw-alias-label-secondary); transition: transform 0.15s ease; }\n.ct-root.ct-item[open] > .ct-item-summary .ct-item-chevron { transform: rotate(180deg); }\n.ct-root .ct-item-body { padding: 0 0 16px; }\n`\nexport const currentTitleStyles = `${officialUiCss('ct-root')}${modelMenuCss}${currentTitleOwnCss}`\nconst styles = currentTitleStyles\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context { dshCurrentTitleClient: { active: boolean } }\n}\n\nexport function apply(ctx: Context): void {\n const client = ctx as unknown as Client\n const packageName = '@klarkxy/dsh-current-title'\n mountModelSettingsChanges(ctx, packageName)\n const settingsSubscriber = createModelSettingsSubscriber(ctx, packageName, modelSettingsChangesIdentity(packageName))\n const subscribeSettings = (change: () => void, error?: (message: string) => void) => settingsSubscriber.subscribe(change, error)\n const marker = createTitleClientMarker()\n ctx.provide(TITLE_CLIENT_SERVICE, marker)\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const style = document.createElement('style')\n style.setAttribute('data-plugin', name)\n style.textContent = styles\n document.head.appendChild(style)\n return () => style.remove()\n }, 'current-title.styles')\n // The settings group is one row on the shared Session Management page; the\n // page is root-owned shared infrastructure, so this plugin contributes only\n // its row and never depends on another plugin.\n ctx.effect(() => registerSessionSettingsItem(\n ctx,\n { id: 'current-title', order: 70 },\n // A slot component never receives `ctx`: the host composes its own props, and a\n // Cordis context throws on any undeclared property read (so feeding one back\n // through `useNativeSeat` crashed the entry and abdicated its keyed cell).\n // The client and marker stay in the apply closure instead.\n () => <TitleSettingsItem client={client} marker={marker} subscribeSettings={subscribeSettings} />,\n ), 'current-title.settings')\n // The shared \"default auxiliary model\" card is root-owned infrastructure:\n // this plugin retains one share while enabled and the card unloads with the\n // last participant, never depending on another plugin.\n ctx.effect(() => registerAuxiliaryModelSettings(ctx), 'current-title.auxiliary-model')\n ctx.effect(() => {\n let live = true\n void client.connection.rpc.call(RPC_CHANNEL, 'status', {}).then(result => {\n const row = result as RpcResult<TitleStatus>\n if (!live) return\n applyMarkerFromStatus(marker, row?.ok ? row.value : undefined, live)\n }).catch(() => { if (live) applyMarkerFromStatus(marker, undefined, live) })\n return () => { live = false; disposeTitleClientMarker(marker) }\n }, 'current-title.marker')\n}\n"],"mappings":";;;;;;;AAgBA,MAAa,uBAAuB,CAAC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Aa,4BACf,KACA;EAAE,IAAI;EAAiB,OAAO;CAAG,SAK3B,iBAAA,GAAA,kBAAA,IAAA,CAAC,mBAAD;EAA2B;EAAgB;EAA2B;CAAoB,CAAA,CAClG,GAAG,wBAAwB;CAI3B,IAAI,aAAa,+BAA+B,GAAG,GAAG,+BAA+B;CACrF,IAAI,aAAa;EACf,IAAI,OAAO;EACX,OAAY,WAAW,IAAI,KAAK,aAAa,UAAU,CAAC,CAAC,CAAC,CAAC,MAAK,WAAU;GACxE,MAAM,MAAM;GACZ,IAAI,CAAC,MAAM;GACX,sBAAsB,QAAQ,KAAK,KAAK,IAAI,QAAQ,KAAA,GAAW,IAAI;EACrE,CAAC,CAAC,CAAC,YAAY;GAAE,IAAI,MAAM,sBAAsB,QAAQ,KAAA,GAAW,IAAI;EAAE,CAAC;EAC3E,aAAa;GAAE,OAAO;GAAO,yBAAyB,MAAM;EAAE;CAChE,GAAG,sBAAsB;AAC3B"}
|
|
1
|
+
{"version":3,"file":"client.inner.cjs","names":["useSyncExternalStore","useCallback","useRef","createElement","useRef","useState","useCallback","useMemo","Button","useRef","useState","useId","useMemo","rankByName","observeStickyMenuGroups","createPortal","MenuSurface","IconChevronRightOutlineRegular","Input","IconCloseFillRegular","IconCheckOutlineRegular","MenuGroup","isValidElement","cloneElement","useRef","useMemo","IconChevronDownOutlineRegular","useCallback","useSyncExternalStore","useState","useRef","Button","IconChevronDownOutlineRegular","useState","useCallback","useRef","Button","IconChevronDownOutlineRegular"],"sources":["../../dsh-model-route/src/catalog.ts","../../dsh-model-route/src/menu.ts","../../dsh-plugin-kit/src/contracts.ts","../../dsh-plugin-kit/src/client-utils.ts","../../dsh-plugin-kit/src/official-ui.ts","../../dsh-plugin-kit/src/model-settings-client.ts","../../dsh-model-route/src/catalog-ui.tsx","../../dsh-model-route/src/ui.tsx","../../dsh-model-route/src/model-picker.ts","../../dsh-plugin-kit/src/model-picker.tsx","../../dsh-plugin-kit/src/auxiliary-model-client.tsx","../src/contracts.ts","../src/client-work.ts","../src/marker.ts","../src/client.tsx"],"sourcesContent":["/**\n * Host model-catalog parsing shared by plugin settings UIs and model hubs.\n * Pure and browser-safe: no React, no host imports. The catalog envelope is\n * structural so hosts may add fields without breaking consumers.\n */\nimport { modelRouteKey, type ModelRoute } from './route.ts'\n\n/** One selectable model. `efforts` are the advertised reasoning efforts. */\nexport interface ModelMenuChoice {\n readonly provider: string\n readonly model: string\n readonly label: string\n /**\n * Provider display name from the catalog group. Optional: synthetic entries\n * (a saved route missing from the catalog) have no group, so consumers must\n * fall back to `provider`. Search matches it alongside the provider id.\n */\n readonly providerLabel?: string\n readonly efforts: ReadonlyArray<{ id: string; name: string }>\n}\n\n/** Both services are required: Cordis checks the nested namespace separately. */\nexport const MODEL_CATALOG_INJECT = ['remote', 'remote.session'] as const\n\nexport interface ModelCatalogFailure {\n readonly id: string\n readonly name: string\n readonly message: string\n}\n\n/** The catalog face this helper needs; stays structural so hosts may add more. */\nexport interface ModelCatalogClient {\n readonly remote?: {\n readonly session?: { readonly modelCatalog?: () => Promise<unknown> }\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined\n}\n\nfunction asText(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\n/** A useful diagnostic even when a transport rejects with a plain object. */\nexport function modelCatalogErrorMessage(value: unknown): string {\n if (value instanceof Error && value.message) return value.message\n const row = asRecord(value)\n return asText(row?.message) ?? asText(value) ?? 'Unable to load the model catalog.'\n}\n\n/**\n * Validate and unwrap a successful catalog without discarding provider failures\n * or newer host metadata. Names and metadata remain optional for older hosts.\n * A broken response is never presented as a successfully loaded empty menu.\n */\nexport function checkedModelCatalog(value: unknown): unknown {\n const envelope = asRecord(value)\n if (envelope?.ok === false) throw new Error(modelCatalogErrorMessage(envelope.error ?? envelope))\n const root = envelope?.ok === true ? asRecord(envelope.value) : envelope\n const malformed = (field: string): never => { throw new Error(`Invalid model catalog: ${field}.`) }\n if (!root || !Array.isArray(root.groups)) return malformed('groups must be an array')\n for (const value of root.groups) {\n const group = asRecord(value)\n if (!group || !asText(group.id) || !Array.isArray(group.models)) return malformed('each group needs an id and models array')\n for (const value of group.models) {\n const model = asRecord(value)\n if (!model || !asText(model.id)) return malformed('each model needs an id')\n if (model.reasoning !== undefined) {\n const reasoning = asRecord(model.reasoning)\n if (!reasoning || !Array.isArray(reasoning.efforts) || reasoning.efforts.some(value => !parseEffort(value))) {\n return malformed('reasoning efforts must be an array of identified efforts')\n }\n }\n }\n }\n if (root.failures !== undefined && (!Array.isArray(root.failures) || root.failures.some(value => {\n const failure = asRecord(value)\n return !failure || !asText(failure.id) || typeof failure.name !== 'string' || typeof failure.message !== 'string'\n }))) return malformed('failures must be an array of provider failures')\n return root\n}\n\n/** Read through the injected session namespace; absence and rejection are errors. */\nexport async function readModelCatalog(client: ModelCatalogClient): Promise<unknown> {\n const session = client.remote?.session\n if (typeof session?.modelCatalog !== 'function') {\n throw new Error('Model catalog unavailable: inject both remote and remote.session.')\n }\n return checkedModelCatalog(await session.modelCatalog())\n}\n\n/** Provider failures are partial results, not a transport failure. */\nexport function modelCatalogFailures(value: unknown): readonly ModelCatalogFailure[] {\n // Rendering can precede the checked load boundary (for example hub owner\n // snapshots). Invalid or absent data must not crash the whole settings page.\n try {\n const root = checkedModelCatalog(value) as { failures?: readonly ModelCatalogFailure[] }\n return root.failures ?? []\n } catch { return [] }\n}\n\n/** Text adapter for existing model-hub status messages. */\nexport function catalogFailures(value: unknown): string[] {\n return modelCatalogFailures(value).map(failure => `${failure.name || failure.id}: ${failure.message}`)\n}\n\nfunction parseEffort(value: unknown): { id: string; name: string } | undefined {\n const row = asRecord(value)\n const id = row ? asText(row.id) : undefined\n if (!id) return undefined\n return { id, name: row ? asText(row.name) ?? id : id }\n}\n\n/** Parse the host session catalog into flat choices, keeping a saved route selectable. */\nexport function parseModelMenuChoices(value: unknown, bound?: ModelRoute): ModelMenuChoice[] {\n const envelope = asRecord(value)\n // Host remote calls resolve to a result envelope ({ ok, value }); older hosts\n // and unit tests hand over the bare catalog. Accept both.\n const root = (envelope && envelope.ok === true ? asRecord(envelope.value) : undefined) ?? envelope ?? {}\n const groups = Array.isArray(root.groups) ? root.groups : []\n const choices: ModelMenuChoice[] = []\n for (const group of groups) {\n const groupRow = asRecord(group)\n const provider = groupRow ? asText(groupRow.id) : undefined\n if (!provider || !groupRow || !Array.isArray(groupRow.models)) continue\n const providerName = asText(groupRow.name) ?? provider\n for (const entry of groupRow.models) {\n const modelRow = asRecord(entry)\n const model = modelRow ? asText(modelRow.id) : undefined\n if (!model || !modelRow) continue\n const name = asText(modelRow.name) ?? model\n const reasoning = asRecord(modelRow.reasoning)\n const efforts = reasoning && Array.isArray(reasoning.efforts)\n ? reasoning.efforts.flatMap(effort => { const parsed = parseEffort(effort); return parsed ? [parsed] : [] })\n : []\n choices.push({ provider, model, label: `${providerName} / ${name}`, providerLabel: providerName, efforts })\n }\n }\n if (bound?.provider && bound.model && !choices.some(item => item.provider === bound.provider && item.model === bound.model)) {\n choices.push({ provider: bound.provider, model: bound.model, label: `${bound.provider} / ${bound.model}`, efforts: [] })\n }\n return choices\n}\n\n/** Reasoning-effort options for one choice; the saved value stays selectable. */\nexport function modelMenuEffortOptions(\n choice: ModelMenuChoice | undefined,\n current?: string,\n): Array<{ id: string; name: string }> {\n const listed = (choice?.efforts ?? []).map(item => ({ ...item }))\n if (current && !listed.some(item => item.id === current)) listed.push({ id: current, name: current })\n return listed\n}\n\n/** Flat set of known routes for DetectModelFieldsOptions.knownModel. */\nexport function knownModelFromChoices(choices: readonly ModelMenuChoice[]): (route: ModelRoute) => boolean {\n const known = new Set(choices.map(choice => modelRouteKey(choice.provider, choice.model)))\n return route => known.has(modelRouteKey(route.provider, route.model))\n}\n","/**\n * Pure menu helpers over parsed catalog choices: provider grouping, display\n * names and search filtering. Pure and browser-safe like the rest of the core\n * entry — no React, no host imports. The popover component lives in `./ui.tsx`.\n */\nimport type { ModelMenuChoice } from './catalog.ts'\n\n/** Localize standard effort ids only when the provider has not supplied a display name. */\nexport function modelMenuEffortLabel(effort: { id: string; name: string }, locale?: string): string {\n if (effort.name !== effort.id) return effort.name\n const labels: Record<string, readonly [string, string]> = {\n off: ['关闭', 'Off'], none: ['无', 'None'], minimal: ['最低', 'Minimal'], low: ['低', 'Low'],\n medium: ['中', 'Medium'], high: ['高', 'High'], xhigh: ['极高', 'Extra high'],\n max: ['最高', 'Maximum'], ultra: ['超高', 'Ultra'],\n }\n return labels[effort.id]?.[locale?.toLowerCase().startsWith('zh') ? 0 : 1] ?? effort.name\n}\n\n/** One provider group in the menu, in catalog order, after applying the search query. */\nexport interface ModelMenuGroup {\n readonly provider: string\n /** Provider display name, from the catalog group or split from the \"Provider / Model\" label. */\n readonly name: string\n readonly items: readonly ModelMenuChoice[]\n}\n\n/** The short model label shown inside a provider group. */\nexport function modelMenuShortName(choice: ModelMenuChoice): string {\n const sep = choice.label.indexOf(' / ')\n return sep > 0 ? choice.label.slice(sep + 3) : choice.model\n}\n\n/** Group catalog choices by provider and filter them by a case-insensitive query. */\nexport function groupModelMenuChoices(choices: readonly ModelMenuChoice[], query: string): ModelMenuGroup[] {\n const needle = query.trim().toLowerCase()\n const matched = needle\n ? choices.filter(choice => choice.label.toLowerCase().includes(needle)\n || choice.model.toLowerCase().includes(needle)\n || choice.provider.toLowerCase().includes(needle)\n // The provider display name is a separate search channel: a catalog may\n // name a provider differently from its id, and callers search by name.\n || (choice.providerLabel?.toLowerCase().includes(needle) ?? false))\n : choices\n const groups: Array<{ provider: string; name: string; items: ModelMenuChoice[] }> = []\n for (const choice of matched) {\n const sep = choice.label.indexOf(' / ')\n const name = choice.providerLabel ?? (sep > 0 ? choice.label.slice(0, sep) : choice.provider)\n const last = groups.at(-1)\n if (last && last.provider === choice.provider) last.items.push(choice)\n else groups.push({ provider: choice.provider, name, items: [choice] })\n }\n return groups\n}\n","import type { ContextFormed } from '@deepseek-ai/dsh-llm'\nimport { modelRouteOverride, type ModelRoute } from '@klarkxy/dsh-model-route'\n\n/**\n * The canonical home is @klarkxy/dsh-model-route; re-exported here so existing\n * plugin-kit consumers keep compiling.\n */\nexport type { ModelRoute }\n\n/** Public, browser-safe contracts. Host implementations stay in their owning packages. */\nexport type ProducerSourceKind = `plugin:${string}`\nexport type ProducerMessageSource = { kind: ProducerSourceKind; plugin: string } & ContextFormed\n\n/**\n * V4 sessions persist the producing extension in `kind`; the retired generic\n * `plugin` wrapper is not admitted. Each feature plugin declares its own kind.\n */\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n [kind: ProducerSourceKind]: ProducerMessageSource\n }\n}\n\nexport function producerMessageSource(plugin: string): ProducerMessageSource {\n return { kind: `plugin:${plugin}`, plugin }\n}\n\nexport type RpcResult<T = unknown> = { ok: true; value: T } | { ok: false; error: { code: string; message: string } }\nexport const CHAT_EVENTS_SLOT = 'dsh-editor.chat.events'\nexport interface EvidenceRef { sessionId: string; seq: number; kind: 'user' | 'tool' | 'turn' | 'manual'; excerpt?: string }\nexport interface TaskContract {\n id: string\n sessionId: string\n sourceVersion: string\n revision: number\n goal: string\n deliverables: string[]\n inScope: string[]\n outOfScope: string[]\n constraints: string[]\n acceptance: string[]\n assumptions: string[]\n questions: string[]\n evidence: EvidenceRef[]\n readiness: 'pending' | 'clear-request' | 'user-confirmed' | 'disclosed-assumptions' | 'cancelled' | 'stale'\n updatedAt: number\n}\nexport interface TaskCheckpoint {\n id: string\n sessionId: string\n sourceVersion: string\n contractVersion?: number\n fromSeq: number\n toSeq: number\n revision: number\n status: 'running' | 'completed' | 'failed' | 'cancelled'\n items: Array<{ label: string; state: 'pending' | 'verified' | 'failed'; evidence: EvidenceRef[] }>\n constraints: string[]\n nextAction: string\n createdAt: number\n}\nexport type KnowledgeScope = { kind: 'global' } | { kind: 'project'; projectId: string }\nexport type KnowledgeKind = 'preference' | 'project-fact' | 'decision' | 'vocabulary' | 'activity' | 'lesson'\n/** Descriptive context, never an executable instruction or authorization. */\nexport interface ContextKnowledge {\n subject: string\n domain: string\n key: string\n aliases: string[]\n observedAt: number\n /** The user's own time expression, not an inferred completion date. */\n eventTime?: string\n activityStatus?: 'planned' | 'in-progress' | 'blocked' | 'paused' | 'completed' | 'cancelled' | 'unknown'\n}\n/** A scoped method. Observations remain candidates until explicitly accepted. */\nexport interface ProcedureKnowledge {\n origin: 'instruction' | 'observation'\n goal: string\n when: string[]\n steps: string[]\n avoid: string[]\n verify: string[]\n}\nexport interface MemoryRecord {\n id: string\n revision: number\n scope: KnowledgeScope\n kind: KnowledgeKind\n status: 'candidate' | 'active' | 'rejected' | 'superseded' | 'revoked' | 'deleted'\n title: string\n content: string\n tags: string[]\n evidence: EvidenceRef[]\n exceptions: string[]\n source: 'user' | 'memory' | 'dream' | 'self-improvement'\n context?: ContextKnowledge\n procedure?: ProcedureKnowledge\n createdAt: number\n updatedAt: number\n expiresAt?: number\n supersedes?: string[]\n /** Exact record revisions behind a derived candidate; revalidated on adoption. */\n basis?: Array<{ id: string; revision: number }>\n}\nexport type NewMemoryRecord = Omit<MemoryRecord, 'id' | 'revision' | 'createdAt' | 'updatedAt'>\nexport interface MemoryQuery { scope: KnowledgeScope; query?: string; kinds?: KnowledgeKind[]; statuses?: MemoryRecord['status'][]; limit?: number }\nexport interface MemoryMutationOptions { signal?: AbortSignal; isCurrent?: () => boolean }\nexport interface MemoryService {\n list(query: MemoryQuery): Promise<MemoryRecord[]>\n create(record: NewMemoryRecord, options?: MemoryMutationOptions): Promise<MemoryRecord>\n update(id: string, patch: Partial<Pick<MemoryRecord, 'title' | 'content' | 'tags' | 'exceptions' | 'status' | 'expiresAt'>>, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n /** Explicit user promotion, persisted atomically on the same record; preserves expiry and evidence. */\n promoteToGlobal(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n remove(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<void>\n recall(query: MemoryQuery): Promise<MemoryRecord[]>\n}\n\n/**\n * The session creation metadata the host snapshots when it creates a delegated child\n * thread. Mirrors `CreateAgentOptions.meta` in `@deepseek-ai/dsh-agent`; it is durable\n * session data, so it survives a restart and needs no ancestry walk.\n */\nexport interface SubagentSessionLike {\n readonly header?: {\n readonly parentSession?: unknown\n readonly origin?: unknown\n readonly delegationDepth?: unknown\n readonly isSeeded?: unknown\n readonly classification?: unknown\n }\n}\n\n/**\n * True when `session` is a delegated child thread rather than a human-driven top-level\n * conversation.\n *\n * A message's `source.kind === 'user'` cannot answer this: a lead agent's dispatch prompt\n * is delivered as the child's own user message, so delegated work is indistinguishable\n * from a person typing once you only look at the message. Plugins use this to keep\n * automatic writes and derived model calls on top-level sessions.\n */\nexport function isSubagentSession(session: unknown): boolean {\n const header = (session as SubagentSessionLike | null | undefined)?.header\n if (!header || typeof header !== 'object') return false\n if (header.origin === 'subagent' || Number(header.delegationDepth ?? 0) > 0) return true\n // Native human forks also persist parentSession for history lineage. A fork's\n // seeded header distinguishes it from legacy children whose parent is the\n // only marker. Native rc.2 forks omit depth; patched hosts may persist zero.\n // Explicit delegation and unknown metadata still keep the child guard.\n const humanFork = header.isSeeded === true\n && (header.delegationDepth === undefined || header.delegationDepth === 0)\n && header.origin === undefined\n && (header.classification === undefined || header.classification === 'ordinary' || header.classification === 'free')\n return Boolean(header.parentSession) && !humanFork\n}\n\n/** Project keys come only from the host-validated session directory, never client input. */\nexport function projectIdFromCwd(cwd: string | undefined): string | undefined {\n if (typeof cwd !== 'string') return undefined\n const normalized = cwd.trim().replaceAll('\\\\', '/')\n if (!normalized) return undefined\n return normalized === '/' || /^[A-Za-z]:\\/$/.test(normalized) ? normalized : normalized.replace(/\\/+$/, '')\n}\n\n/**\n * One settings owner's Remote stream. Typert accepts either case in an RPC\n * segment, so the Cordis service key and the wire namespace use the same\n * Pascal segment. The scope's first letter stays uppercase.\n */\nexport interface ModelSettingsChangesIdentity {\n readonly service: string\n readonly namespace: string\n}\n\n/** `@klarkxy/dsh-git-commit` becomes `KlarkxyDshGitCommitModelSettingsChanges`. */\nexport function modelSettingsChangesIdentity(packageName: string): ModelSettingsChangesIdentity {\n const scoped = /^@([^/]+)\\/(.+)$/.exec(packageName)\n const body = scoped ? `${scoped[1]}/${scoped[2]}` : packageName\n const parts = body.split(/[^A-Za-z0-9]+/).filter(Boolean)\n if (!parts.length) throw new Error('Model settings package name has no RPC segment')\n const segment = `${parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('')}ModelSettingsChanges`\n if (!/^[A-Z][A-Za-z0-9]*$/.test(segment)) throw new Error(`Model settings sync name is not an RPC segment: ${segment}`)\n return { service: segment, namespace: segment }\n}\n\n/**\n * Repository extension: a native web provider announces that its local\n * availability changed. Kind is `search` or `fetch`; id is the provider id.\n * Listeners refresh management state and must not treat this as a network probe.\n */\nexport const WEB_PROVIDER_AVAILABILITY_EVENT = 'web/provider-availability-updated' as const\n\n/**\n * Optional display metadata a provider may attach when it registers directly\n * with `ctx.web`. Execution and credentials stay with the provider; this object\n * is display-only and must never carry secret values.\n */\nexport interface DshWebManagementDescriptor {\n readonly id: string\n readonly label: string\n readonly description: string\n readonly defaultBaseURL?: string\n readonly credentialRef?: string\n /** True when the key is shared with another surface. The page must not delete it. */\n readonly credentialShared?: boolean\n /** Optional notice naming the settings surface that owns a shared credential. */\n readonly credentialHint?: string\n readonly billing: 'request' | 'model-and-tools' | 'none' | 'unknown'\n /** Optional provider-supplied billing summary. */\n readonly pricing?: string\n /** Public HTTPS page explaining provider charges. */\n readonly pricingUrl?: string\n /** Public HTTPS page where the user can create an API key. */\n readonly signupUrl?: string\n /** Plugin that owns configuration. Native providers keep their settings there. */\n readonly configurationOwner?: string\n /** Explicit settings link supplied by the provider, never inferred from its id. */\n readonly configurationUrl?: string\n /** Fixed legacy route migrated by a bundle-owned adapter; not used by native plugins. */\n readonly legacyId?: string\n}\n\n/**\n * Host Creator agent-preset id (`agentPresets.composedPreset`).\n * Plugins that gate Creator-only tools or prompt sections compare against this.\n */\nexport const CREATOR_PRESET_ID = 'cordis'\n\n/**\n * Shared \"Session Management\" settings section id. The section is provided by\n * shared infrastructure (see `registerSessionSettingsItem` in `client-utils`),\n * not by any one business plugin: every participant registers only a row into\n * {@link SESSION_SETTINGS_ITEM_SLOT}, so any enabled subset yields the same page.\n */\nexport const SESSION_SETTINGS_SECTION_ID = 'session-manager'\n\n/**\n * Child list slot declared by the shared Session Management page. Neutral\n * naming on purpose: participants never import each other, they only\n * contribute `{id, order}` rows into this slot while the page is alive.\n */\nexport const SESSION_SETTINGS_ITEM_SLOT = 'dsh.session-settings.item'\n\n/**\n * Host-owned nav icon seat: a root-scoped list where each entry's `id` must\n * equal the `settings.section` id it decorates. Owner props are\n * `{size, active}`; icons stay `aria-hidden` so the section label remains the\n * accessible name. Contributors into a shared section may register the same\n * icon `id` with different priorities — the ledger keeps every entry while the\n * host renders one icon per section.\n */\nexport const SETTINGS_SECTION_ICON_SLOT = 'settings.section.icon'\n\n/* Shared auxiliary-model default. Feature plugins may store a global default\n * route that fills the tier between their own saved override and the live\n * session model. The durable state is a root-context singleton (like the\n * shared session-settings page): it exists while any participant retains it\n * and is never owned by a business plugin. See `auxiliary-model.ts`. */\n\n/** Root context service key holding the shared auxiliary-model state. */\nexport const AUXILIARY_MODEL_SERVICE = 'dshAuxiliaryModel'\n\n/** Authenticated host-RPC channel for get/set of the shared default. */\nexport const AUXILIARY_MODEL_CHANNEL = '/dsh-auxiliary-model'\n\n/** Model-settings namespace under which the shared default is published. */\nexport const AUXILIARY_MODEL_NS = '@klarkxy/dsh-plugin-kit/auxiliary-model'\n\n/**\n * Typert identity of the shared change stream. Mounted on the root context\n * with ownerNs filtering, so frames only carry {@link AUXILIARY_MODEL_NS}.\n */\nexport const AUXILIARY_MODEL_CHANGES_IDENTITY = modelSettingsChangesIdentity('@klarkxy/dsh-plugin-kit')\n\n/** The value the shared default persists: `model: null` means follow the live session/host model. */\nexport interface AuxiliaryModelDefaults {\n readonly revision: number\n readonly model: ModelRoute | null\n}\n\n/** Shape of the root singleton; produced and owned by `auxiliary-model.ts`. */\nexport interface AuxiliaryModelShared {\n readonly ready: Promise<void>\n snapshot(): AuxiliaryModelDefaults\n}\n\nfunction sharedAuxiliaryModel(host: unknown): AuxiliaryModelShared | undefined {\n const root = (host as { root?: unknown } | undefined)?.root as { get?(name: string, strict?: boolean): unknown } | undefined\n try {\n const shared = root?.get?.(AUXILIARY_MODEL_SERVICE, false) as AuxiliaryModelShared | undefined\n return shared && typeof shared.snapshot === 'function' ? shared : undefined\n } catch { return undefined }\n}\n\n/**\n * Synchronously read the shared auxiliary default; `undefined` only when no\n * participant retains the singleton or the default is legitimately unset.\n * An initialization or snapshot failure propagates: silently falling back to\n * a different model after a storage error would spend the wrong budget.\n */\nexport function getAuxiliaryModel(host: unknown): ModelRoute | undefined {\n const shared = sharedAuxiliaryModel(host)\n if (!shared) return undefined\n return modelRouteOverride(shared.snapshot().model ?? undefined)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { createElement, useCallback, useEffect, useRef, useSyncExternalStore, type ReactNode } from 'react'\nimport { SESSION_SETTINGS_ITEM_SLOT, SESSION_SETTINGS_SECTION_ID, SETTINGS_SECTION_ICON_SLOT } from './contracts.ts'\n\n/** Fixed pause for failing background reads; manual work is never replayed. */\nexport function createPluginReadGate(now: () => number = Date.now) {\n let pausedUntil = 0\n let epoch = 0\n return {\n canRead: () => now() >= pausedUntil,\n reset: () => { epoch++; pausedUntil = 0 },\n async run<T>(read: () => Promise<T>): Promise<T> {\n const current = epoch\n try {\n const value = await read()\n if (current === epoch) pausedUntil = 0\n return value\n } catch (error) {\n // The native Connection error is an Error with this exact HTTP text.\n // Authentication, application failures, and cancellation stay distinct.\n const message = error instanceof Error ? error.message : ''\n if (current === epoch && (/(?:^|\\s)transport failure for .+: HTTP (?:404|405|503)\\b/.test(message)\n || (error instanceof TypeError && /^(?:Failed to fetch|fetch failed|NetworkError when attempting to fetch resource\\.?)$/i.test(message)))) {\n pausedUntil = now() + 30_000\n }\n throw error\n }\n },\n }\n}\n\nexport interface NativeSurfaceClient {\n sessions: {\n binding?(sessionId: string): { eventSource: { subscribe(listener: () => void): () => void } } | undefined\n }\n uiWorkspace: { current?: { getSnapshot(): { sessionId: string } | undefined; subscribe(listener: () => void): () => void } }\n uiSession: { adapter: { current: { getSnapshot(): { key?: string }; subscribe(listener: () => void): () => void } } }\n locale: { getSnapshot(): { active: string }; subscribe(listener: () => void): () => void }\n connection?: { generation?: { subscribe(listener: () => void): () => void } }\n}\n\n/** The Editor retains its manuscript session separately; native DSH exposes the main-view binding. */\nexport function selectedSessionId(client: Pick<NativeSurfaceClient, 'uiWorkspace' | 'uiSession'>): string {\n const workspace = client.uiWorkspace?.current\n return workspace\n ? workspace.getSnapshot()?.sessionId ?? ''\n : client.uiSession.adapter.current.getSnapshot().key ?? ''\n}\n\n/**\n * Owner props are data the host composed, never a Cordis context: reading an\n * undeclared property off one throws instead of returning undefined, which\n * would crash the slot entry and abdicate its cell for good. Tolerate a\n * throwing read so a mistaken prop degrades to \"not supplied\".\n */\nfunction read(source: unknown, key: string): unknown {\n if (source === null || typeof source !== 'object') return undefined\n try {\n return (source as Record<string, unknown>)[key]\n } catch {\n return undefined\n }\n}\n\nfunction readString(source: unknown, key: string): string | undefined {\n const value = read(source, key)\n return typeof value === 'string' ? value : undefined\n}\n\n/** Owner props win; native settings only supplies close, so resolve its selected session. */\nexport function useNativeSeat(client: NativeSurfaceClient, props?: unknown) {\n const current = useSyncExternalStore(\n useCallback((fn: () => void) => (client.uiWorkspace?.current ?? client.uiSession.adapter.current).subscribe(fn), [client]),\n useCallback(() => selectedSessionId(client), [client]),\n () => '',\n )\n const language = useSyncExternalStore(\n useCallback((fn: () => void) => client.locale.subscribe(fn), [client]),\n useCallback(() => client.locale.getSnapshot().active, [client]),\n () => 'en',\n )\n const sessionId = readString(props, 'sessionId') ?? readString(read(props, 'owner'), 'sessionId') ?? current\n const requestedLocale = read(props, 'locale') ?? read(read(props, 'owner'), 'locale') ?? language\n return { sessionId, locale: (String(requestedLocale).startsWith('zh') ? 'zh' : 'en') as 'zh' | 'en',\n hidden: read(props, 'hidden') === true || read(read(props, 'owner'), 'hidden') === true }\n}\n\n/** Refresh on native log boundaries/reconnect/focus. Read-only settling is bounded to an observed job. */\nexport function useFeatureRefresh(\n client: NativeSurfaceClient, sessionId: string, refresh: () => void,\n working = false, enabled = true,\n): void {\n const refreshRef = useRef(refresh)\n refreshRef.current = refresh\n useEffect(() => {\n if (!enabled) return\n let timer: ReturnType<typeof setTimeout> | undefined\n const queue = () => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return\n clearTimeout(timer)\n timer = setTimeout(() => refreshRef.current(), 150)\n }\n const source = sessionId ? client.sessions.binding?.(sessionId)?.eventSource : undefined\n const stopEvents = source?.subscribe(queue)\n const stopConnection = client.connection?.generation?.subscribe(queue)\n const visibility = () => { if (document.visibilityState === 'visible') queue() }\n window.addEventListener('focus', queue)\n document.addEventListener('visibilitychange', visibility)\n // Details are collapsed by default; opening an existing panel must get current state.\n document.addEventListener('toggle', queue, true)\n return () => {\n clearTimeout(timer)\n stopEvents?.(); stopConnection?.()\n window.removeEventListener('focus', queue)\n document.removeEventListener('visibilitychange', visibility)\n document.removeEventListener('toggle', queue, true)\n }\n }, [client, sessionId, enabled])\n useEffect(() => {\n if (!enabled || !working) return\n let delay = 250\n const until = Date.now() + 300_000\n let timer: ReturnType<typeof setTimeout>\n const tick = () => {\n if (Date.now() >= until) return\n if (document.visibilityState !== 'hidden') refreshRef.current()\n delay = Math.min(delay * 2, 2000)\n timer = setTimeout(tick, delay)\n }\n timer = setTimeout(tick, delay)\n return () => clearTimeout(timer)\n }, [client, sessionId, working, enabled])\n}\n\n/* Shared \"Session Management\" settings page. The page is root-owned shared\n * infrastructure, not a business plugin: any participant alone yields the same\n * section, and participants never import each other. Synchronization crosses\n * separately bundled copies of this helper through the Cordis root context —\n * `root.get`/`root.provide` is the only rendezvous, so no window global or\n * module singleton is needed and no participant depends on another being enabled.\n */\n\n/** A row contributed into the shared Session Management page. */\nexport interface SessionSettingsItemSpec {\n readonly id: string\n readonly order: number\n}\n\n/* Original line icons for settings-section navigation seats. The official\n * `dsh-client-ui-primitives` icon set covers generic glyphs only; these keep\n * the same conventions (16×16 viewBox, 1px stroke, round caps, currentColor)\n * so the plugin set stays visually consistent with the native nav. Colors\n * never appear here: `currentColor` lets the host style the active state, and\n * `aria-hidden` keeps the section label the single accessible name. */\n\n/** Owner props the host's `settings.section.icon` seat hands to its cell. */\nexport interface SettingsSectionIconProps {\n readonly size?: number\n /** Selection state; the nav styles active icons through color, not geometry. */\n readonly active?: boolean\n}\n\ntype IconChild = readonly [tag: string, attrs: Record<string, string | number>]\n\n/** One `<svg>` with the shared icon chrome; children are plain elements. */\nfunction lineIcon(children: IconChild[]) {\n return function SettingsSectionIcon(props: SettingsSectionIconProps): ReactNode {\n return createElement('svg', {\n 'aria-hidden': 'true',\n width: props.size ?? 16,\n height: props.size ?? 16,\n viewBox: '0 0 16 16',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 1,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n }, ...children.map(([tag, attrs], index) => createElement(tag, { key: index, ...attrs })))\n }\n}\n\n/** Chat bubble for the shared Session Management section. */\nexport const IconSessionSettings = lineIcon([\n ['path', { d: 'M8.5 13a5.5 5.5 0 0 0 5.5-5.5A5.5 5.5 0 0 0 8.5 2 5.5 5.5 0 0 0 3 7.5a5.48 5.48 0 0 0 .9 3L2.8 12.6a.5.5 0 0 0 .62.62l2.9-.98a5.48 5.48 0 0 0 2.18.76Z' }],\n])\n\n/** Serif-flavoured letter A for the Font section. */\nexport const IconFontSettings = lineIcon([\n ['path', { d: 'M3.3 12.6 7.9 3.1a.5.5 0 0 1 .9 0l4.6 9.5' }],\n ['path', { d: 'M5.2 9.4h6.3' }],\n ['path', { d: 'M2.4 12.6h2.4' }],\n ['path', { d: 'M11.9 12.6h2.4' }],\n])\n\n/** Keyboard for the Shortcuts section. */\nexport const IconKeyboardSettings = lineIcon([\n ['rect', { x: 1.75, y: 4.75, width: 12.5, height: 7.5, rx: 1.2 }],\n ['path', { d: 'M4.5 7.25h0' }],\n ['path', { d: 'M8 7.25h0' }],\n ['path', { d: 'M11.5 7.25h0' }],\n ['path', { d: 'M5.25 9.75h5.5' }],\n])\n\n/** Linked model nodes for the Model Management section. */\nexport const IconModelNetworkSettings = lineIcon([\n ['line', { x1: 10.6, y1: 5.3, x2: 8.8, y2: 7.1 }],\n ['line', { x1: 7.2, y1: 8.9, x2: 5.4, y2: 10.7 }],\n ['circle', { cx: 12, cy: 4, r: 1.9 }],\n ['circle', { cx: 4, cy: 12, r: 1.9 }],\n ['circle', { cx: 8, cy: 8, r: 1.5 }],\n])\n\n/**\n * Contribute the nav icon of a `settings.section` entry. The `settings\n * .section.icon` seat is declared by the host independently of the section\n * list, so the wait runs in parallel: the icon appears as soon as both seats\n * exist and unloading removes it again, restoring the host's default glyph.\n * The `id` must equal the section id; `order`/`priority` mirror `order` so the\n * icon cell sorts like its section and, for shared sections, several\n * contributors can register the same icon id under different priorities\n * without duplicating nav entries.\n */\nexport function registerSettingsSectionIcon(\n ctx: Context,\n sectionId: string,\n order: number,\n component: (props: SettingsSectionIconProps) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n return slots.inject(SETTINGS_SECTION_ICON_SLOT, () =>\n slots.register({ name: SETTINGS_SECTION_ICON_SLOT, id: sectionId, order, priority: order }, component))\n}\n\ninterface SessionSettingsSlots {\n inject(key: string, callback: () => Iterable<(() => void) | void> | (() => void) | void): () => void\n register(spec: Record<string, unknown>, render: unknown): () => void\n}\n\ninterface SessionSettingsRoot {\n get(name: string, strict?: boolean): unknown\n provide(name: string, value: unknown): () => void\n readonly slots?: SessionSettingsSlots\n}\n\n/** Private Cordis rendezvous; every bundled copy of this helper resolves the same root service. */\nconst SESSION_SETTINGS_PAGE_SERVICE = 'dshSessionSettingsPage'\n\ninterface SessionSettingsPage {\n retain(): void\n release(): void\n}\n\n/** The page component renders only its declared child list: items paint their own titles and styles. */\nfunction SessionSettingsPageView(props: { renderSlot: (key: string, owner: Record<string, never>) => ReactNode }): ReactNode {\n return props.renderSlot(SESSION_SETTINGS_ITEM_SLOT, {})\n}\n\n/**\n * Acquire the root-owned page service, creating and providing it on first use.\n * One counter covers participants, the section wait and the provider: the last\n * release removes the wait and then the provider synchronously (Cordis deletes\n * the impl before its async disposer awaits), so a later acquire sees a clean\n * get() miss and can re-establish the page.\n */\nfunction acquireSessionSettingsPage(root: SessionSettingsRoot): SessionSettingsPage {\n const existing = root.get(SESSION_SETTINGS_PAGE_SERVICE, false) as SessionSettingsPage | undefined\n if (existing) return existing\n const slots = root.slots as SessionSettingsSlots\n let users = 0\n let stopPage: (() => void) | undefined\n let unprovide: (() => void) | undefined\n const page: SessionSettingsPage = {\n retain() {\n // The reservation is counted before the throwing install, so a failure\n // lets the caller's release() undo it fully instead of leaking the service.\n users += 1\n if (!stopPage) {\n stopPage = slots.inject('settings.section', () => slots.register(\n {\n name: 'settings.section',\n id: SESSION_SETTINGS_SECTION_ID,\n order: 30,\n label: () => {\n const locale = root.get('locale', false) as { getSnapshot?(): { active?: unknown } } | undefined\n return String(locale?.getSnapshot?.().active ?? '').startsWith('zh') ? '会话管理' : 'Session Management'\n },\n children: { [SESSION_SETTINGS_ITEM_SLOT]: { kind: 'list', scope: 'root' } },\n },\n SessionSettingsPageView,\n ))\n }\n },\n release() {\n if (users <= 0) return\n users -= 1\n if (users > 0) return\n // The last contributor tears the section down; collapsing its children\n // declaration clears the item slot for every other bundle as well.\n stopPage?.()\n stopPage = undefined\n unprovide?.()\n },\n }\n unprovide = root.provide(SESSION_SETTINGS_PAGE_SERVICE, page)\n return page\n}\n\n/**\n * Contribute one row to the shared Session Management settings page.\n *\n * `ctx` is the plugin's own context: the row's slot wait unloads with the\n * plugin, while the page itself is retained on the shared root context for as\n * long as any contributor lives. There is no fallback seat — when every\n * contributor is gone the section disappears with the page. Returns a disposer.\n * Shared root-owned infrastructure (the auxiliary-model card) calls this on\n * `ctx.root` so its row, icon and page share are owned by the root lifetime\n * and released by the returned disposer, not by any plugin fiber.\n */\nexport function registerSessionSettingsItem(\n ctx: Context,\n item: SessionSettingsItemSpec,\n component: (props: never) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n const root = ctx.root as unknown as SessionSettingsRoot\n const page = acquireSessionSettingsPage(root)\n let stopItem: (() => void) | undefined\n let stopIcon: (() => void) | undefined\n try {\n page.retain()\n stopItem = slots.inject(SESSION_SETTINGS_ITEM_SLOT, () => slots.register({ name: SESSION_SETTINGS_ITEM_SLOT, ...item }, component))\n // Every contributor also waits on the nav-icon seat, registering the same\n // section icon id under its own priority (its row order). Same-id entries\n // coexist on the ledger while the host renders one icon, so no contributor\n // owns the icon and none depends on another for it; the wait lives with\n // this ctx, so it fires now on fresh loads and retro-fills on HMR.\n stopIcon = slots.inject(SETTINGS_SECTION_ICON_SLOT, () => slots.register(\n { name: SETTINGS_SECTION_ICON_SLOT, id: SESSION_SETTINGS_SECTION_ID, order: item.order, priority: item.order },\n IconSessionSettings,\n ))\n } catch (error) {\n // A synchronous failure (for example a duplicate row id or a failing page\n // install) must not pin the shared page for a contributor that never joined.\n stopIcon?.()\n stopItem?.()\n page.release()\n throw error\n }\n // The disposer may be invoked by both ctx.effect and an explicit caller;\n // releasing twice would unbalance the shared refcount.\n let disposed = false\n return () => {\n if (disposed) return\n disposed = true\n stopIcon?.()\n stopItem?.()\n page.release()\n }\n}\n","/**\n * Shared contract that keeps every plugin's browser-side UI on the official\n * DeepSeek Harness Web design language.\n *\n * Two rules produce that language, and both are load-bearing here:\n *\n * 1. Colour, radius, elevation and focus come from the host theme's real\n * `--dsw-*` tokens, written under their own names. Plugins never invent a\n * token, never alias the official ones behind a private palette (a private\n * alias is just a second, diverging theme), and never carries a literal\n * fallback — the host publishes light and dark, and a literal would pin one\n * of them. The only non-colour custom properties used are the host's own\n * content-font axis and frame clearance.\n *\n * 2. Anything the host already ships is used, not reimplemented. Controls come\n * from `@deepseek-ai/dsh-client-ui-primitives` (`Button`, `Input`,\n * `Checkbox`, `Switch`, `Tag`, `Pill`, `SegmentedControl`, `Menu`, `Modal`,\n * `Tooltip`, `Toast`, `DisclosureRow`, `StateDot`, `PathLabel`, the settings\n * form suite). This module only styles what primitives do not cover: page\n * scaffolding, field layout, banners, empty states and scroll regions.\n *\n * The metrics below are transcribed from the primitives' own CSS modules so a\n * feature panel lines up pixel-for-pixel with a native one: the 14/22 body and\n * 13/20 compact type tiers, the 0.5px hairline scale, and the elevation family\n * that draws a surface's edge in its shadow (`border: 0`) instead of a border.\n */\n\n/**\n * Every `--dsw-*` token this repo is allowed to reference, grouped by role.\n *\n * Plugins may only colour through this list. It is exported so the guard test\n * can fail a build when a stylesheet reaches for anything else — the failure\n * mode this prevents is silent: an unknown token resolves to nothing, so a\n * border disappears or a label inherits the wrong colour with no error anywhere.\n */\nexport const OFFICIAL_THEME_TOKENS = {\n /** Surfaces, from the page up to the topmost nested card. */\n surface: [\n '--dsw-alias-bg-base',\n '--dsw-alias-bg-layer-1',\n '--dsw-alias-bg-layer-2',\n '--dsw-alias-bg-layer-3',\n '--dsw-alias-bg-layer-4',\n '--dsw-alias-bg-module-platform',\n '--dsw-alias-bg-overlay',\n ],\n /** Hairlines. l1 is near-invisible on a menu surface, so menus use l2+. */\n border: ['--dsw-alias-border-l1', '--dsw-alias-border-l2', '--dsw-alias-border-l3', '--dsw-alias-border-l4'],\n /** Text. `caption` is menu shortcut text, `dimmed` is placeholder text. */\n label: [\n '--dsw-alias-label-primary',\n '--dsw-alias-label-secondary',\n '--dsw-alias-label-tertiary',\n '--dsw-alias-label-caption',\n '--dsw-alias-label-dimmed',\n '--dsw-alias-label-error',\n '--dsw-alias-label-primary-foreground',\n ],\n /** Interactive fills. The `-danger` hover belongs to destructive rows. */\n interactive: [\n '--dsw-alias-interactive-bg-hover',\n '--dsw-alias-interactive-bg-active',\n '--dsw-alias-interactive-bg-hover-danger',\n ],\n /** Accent and status. `business` is the focus ring's default colour. */\n accent: [\n '--dsw-alias-brand-primary',\n '--dsw-alias-button-primary-fill',\n '--dsw-alias-button-primary-hover',\n '--dsw-alias-button-tool-bar-fill',\n '--dsw-alias-button-tool-bar-hover',\n '--dsw-alias-button-ghost-active-fill',\n '--dsw-alias-button-ghost-active-border',\n ],\n state: [\n '--dsw-alias-state-business-primary',\n '--dsw-alias-state-success-primary',\n '--dsw-alias-state-warn-primary',\n '--dsw-alias-state-error-primary',\n '--dsw-alias-state-idle-primary',\n ],\n /** Corner scale: sm 8, md 12, lg the large card, panel the modal. */\n radius: ['--dsw-radius-sm', '--dsw-radius-md', '--dsw-radius-lg', '--dsw-radius-panel'],\n /** An elevated surface draws its edge in the shadow, so it keeps border: 0. */\n elevation: [\n '--dsw-elevation-soft',\n '--dsw-elevation-stroke',\n '--dsw-elevation-stroke-color',\n '--dsw-elevation-panel',\n '--dsw-elevation-prominent',\n ],\n /** Floats, masks and scrollbars. */\n overlay: [\n '--dsw-menu-surface-fill',\n '--dsw-menu-backdrop-filter',\n '--dsw-mask-blur',\n '--dsw-alias-bg-mask-1',\n '--dsw-alias-menu-icon',\n '--dsw-alias-scrollbar-bg-l2',\n '--dsw-alias-scrollbar-hover-l2',\n '--dsw-shadow-lv3',\n ],\n /** Motion, focus and type axis, published by the host rather than by a component. */\n system: [\n '--dsw-focus-ring-width',\n '--dsw-focus-ring-color',\n '--dsw-font-markdown-code-font-family',\n '--ds-transition-duration',\n '--ds-ease-in-out',\n '--ds-font-family-code',\n '--dsh-scrollbar-thumb',\n '--dsh-scrollbar-thumb-hover',\n '--dsh-content-font-size-secondary',\n '--dsh-content-font-delta',\n '--dsh-frame-top-clearance',\n // Published by the conversation.input.model seat for narrow composer rows.\n '--dsh-composer-model-icon-display',\n '--dsh-composer-model-text-display',\n ],\n} as const\n\n/** Every official token name, flat. Used by the token guard test. */\nexport const OFFICIAL_THEME_TOKEN_NAMES: readonly string[] = Object.values(OFFICIAL_THEME_TOKENS).flat()\n\n/** The elevation steps a surface can be raised by, softest first. */\nexport type OfficialElevation = 'soft' | 'stroke' | 'panel' | 'prominent'\n\n/**\n * The host's focus ring shorthand, verbatim. Writing this per control is how\n * rings drift apart; a stylesheet that draws its own focus style should use\n * {@link officialFocus} instead. The colour fallback is the host's own default.\n */\nexport const OFFICIAL_FOCUS_RING =\n 'var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))'\n\n/**\n * A complete `outline` declaration at the official geometry. `offset` defaults\n * to the 2px the native controls use; the host's inline field rules sit at 1px\n * and a segmented tab pulls the ring inside itself at -2px.\n */\nexport function officialFocus(offset = '2px'): string {\n return `outline: ${OFFICIAL_FOCUS_RING}; outline-offset: ${offset}`\n}\n\n/**\n * An elevated surface. The host draws a raised surface's edge inside its\n * shadow rather than as a border, so a card sets `border: 0` and takes the edge\n * from the elevation — which is also why its border stays off the alias-border\n * set that a flat, non-elevated rule would use.\n */\nexport function officialElevation(level: OfficialElevation): string {\n return `border: 0; box-shadow: var(--dsw-elevation-${level})`\n}\n\n/**\n * An elevated surface whose edge should read as a specific hairline. Rebinding\n * the stroke colour is how a menu card picks l1 while a panel picks l3, without\n * the two growing apart by hand.\n */\nexport function officialStrokedElevation(level: OfficialElevation, color: string): string {\n return `--dsw-elevation-stroke-color: ${color}; ${officialElevation(level)}`\n}\n\n/**\n * The shared stylesheet for a plugin UI, scoped under that plugin's root class.\n *\n * Scoping is what keeps this safe to always-bundle into every client: the rules\n * can only match inside the plugin's own subtree, so two plugins can both mount\n * `dsh-ui-card` without either styling the other's markup.\n *\n * Each recipe matches the root element *and* its descendants, because the\n * commonest arrangement is one element that is both — a surface that carries\n * the root class and `dsh-ui-card`, or a portaled dialog that is the root and\n * the `dsh-ui-surface`. A descendant-only scope would silently leave those\n * unstyled, with no error anywhere.\n *\n * A caveat worth knowing: `Modal` and `Menu` portal to `document.body`, so their\n * content leaves the plugin's subtree entirely. A portaled surface therefore\n * needs its own root class on an element inside the portal.\n *\n * Only patterns that primitives do not provide live here. If a control appears\n * below that `Button`/`Input`/`Switch`/`Tag`/`Menu` already covers, that is a\n * bug in this file: use the primitive and delete the recipe.\n */\nexport function officialUiCss(roots: string | readonly string[]): string {\n // One plugin often mounts several unrelated surfaces (a settings seat, a chat\n // card, a header menu), so the caller names every root. The rules below are\n // nested under a single selector list and use `&`, which the browser expands\n // per root — so one stylesheet covers all of them without duplicating itself.\n const scope = (typeof roots === 'string' ? [roots] : roots).map(root => `.${root}`).join(', ')\n const sheet = `\n/* Official DSH Web UI contract. Generated by @klarkxy/dsh-plugin-kit/official-ui.\n * Do not hand-edit the copy inside a plugin: change this module so every plugin\n * moves together. Scope: ${scope} */\n/* The scope rule below stays open for the whole sheet: every rule after it\n * nests with the parent selector, so one stylesheet can cover several unrelated\n * roots without leaking into a neighbouring plugin. Its closing brace is last. */\n${scope} {\n color: var(--dsw-alias-label-primary);\n font-family: inherit;\n font-size: 14px;\n line-height: 22px;\n min-width: 0;\n\n& *, & *::before, & *::after { box-sizing: border-box; }\n& h1, & h2, & h3, & h4, & p, & figure { margin: 0; }\n/* Keyboard focus only: pointer input keeps the native resting appearance. The\n * ring needs no radius of its own — the outline already follows the control's\n * own border-radius, and overriding it here would flatten every control. */\n& :focus-visible { ${officialFocus()}; }\n& [hidden] { display: none !important; }\n\n/* --- Type tiers. The same 14/22 and 13/20 steps the primitives use. --- */\n& .dsh-ui-title { font-size: 16px; line-height: 24px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-heading { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-compact { font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-meta { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-hint { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-error { font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-warn { color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-success { color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-muted { color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n& .dsh-ui-wrap { min-width: 0; overflow-wrap: anywhere; }\n\n/* --- Layout scaffolding. --- */\n& .dsh-ui-stack { display: flex; flex-direction: column; gap: 12px; }\n& .dsh-ui-stack-lg { display: flex; flex-direction: column; gap: 20px; }\n/* Plugin detail pages share one reading column. These are layout recipes;\n * controls keep their own primitive styles. Form spacing follows the host's\n * settings-form/fields.module.css and SettingsForm.module.css. */\n& .dsh-ui-page { display: flex; flex-direction: column; gap: 16px; width: 100%; max-width: 760px; min-width: 0; }\n& .dsh-ui-form { display: flex; flex-direction: column; gap: 0; min-width: 0; }\n&.dsh-ui-form > .dsh-ui-field, & .dsh-ui-form > .dsh-ui-field { padding: 12px 0; }\n& .dsh-ui-form-footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding-top: 16px; min-width: 0; }\n& .dsh-ui-fields-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 20px; min-width: 0; margin: 0; padding: 0; border: 0; }\n@media (max-width: 560px) {\n & .dsh-ui-fields-grid { grid-template-columns: minmax(0, 1fr); }\n}\n& .dsh-ui-row { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-row-wrap { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }\n& .dsh-ui-spacer { flex: 1; min-width: 0; }\n/* A 0.5px l2 rule is the host's section divider; reserve the same rhythm. */\n& .dsh-ui-divider { height: 0.5px; background: var(--dsw-alias-border-l2); }\n& .dsh-ui-section { display: flex; flex-direction: column; gap: 12px; padding-top: 16px; border-top: 0.5px solid var(--dsw-alias-border-l2); }\n\n/* --- Card: a raised surface whose edge lives in the shadow. --- */\n& .dsh-ui-card {\n ${officialElevation('stroke')}\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 16px;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-alias-bg-layer-1);\n color: var(--dsw-alias-label-primary);\n min-width: 0;\n}\n& .dsh-ui-card--flat { border: 0.5px solid var(--dsw-alias-border-l3); box-shadow: none; }\n& .dsh-ui-card--nested { background: var(--dsw-alias-bg-layer-2); }\n& .dsh-ui-card--plain { background: none; }\n\n/* --- Field: label, control, help, error. The control itself is an\n * official primitive, so this only owns the vertical rhythm. --- */\n& .dsh-ui-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }\n& .dsh-ui-field + .dsh-ui-field { border-top: 0.5px solid var(--dsw-alias-border-l2); padding-top: 12px; }\n/* Grid fields share a row, so the stacked-field divider must not win later in\n * the cascade. Reset it here, after the field recipe. */\n& .dsh-ui-fields-grid > .dsh-ui-field { padding: 0; border: 0; }\n& .dsh-ui-label { display: flex; align-items: center; gap: 6px; font-size: 13px; line-height: 20px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-label-row { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }\n& .dsh-ui-help { font-size: 12px; line-height: 1.6; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-help p { margin: 0; }\n& .dsh-ui-help p + p { margin-top: 8px; }\n& .dsh-ui-required { color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-control { width: 100%; min-width: 0; }\n/* An invalid control is marked on the control, not only in the message. */\n& .dsh-ui-control[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-readonly { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-readonly > dt { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-readonly > dd { margin: 0; font-size: 13px; line-height: 20px; overflow-wrap: anywhere; }\n\n/* --- Buttons row. A no-op container: it exists so actions line up on the\n * trailing edge the way every native panel does. --- */\n& .dsh-ui-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 4px; }\n& .dsh-ui-actions-end { justify-content: flex-end; }\n\n/* --- Banners. A banner is a left-rail notice, the shape used for warnings,\n * deprecations and blocking instructions. --- */\n& .dsh-ui-banner {\n display: flex;\n flex-direction: column;\n gap: 8px;\n padding: 10px 14px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-left: 3px solid var(--dsw-alias-state-warn-primary);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-banner-title { font-weight: 500; color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-banner--info { border-left-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-banner--danger { border-left-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-banner--success { border-left-color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-banner p { margin: 0; }\n\n/* --- Inline notice: a transient confirmation with no chrome of its own. --- */\n& .dsh-ui-notice { display: flex; align-items: center; gap: 6px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-notice--error { color: var(--dsw-alias-state-error-primary); }\n\n/* --- Empty and loading states. Both sit in a dashed well so an empty panel\n * reads as \"nothing here yet\" rather than as a broken layout. --- */\n& .dsh-ui-empty {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 6px;\n padding: 20px 16px;\n border: 0.5px dashed var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-loading { display: flex; align-items: center; gap: 8px; padding: 20px 0; font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-secondary); }\n\n/* --- Selectable list. A row is a button-sized target with a hover fill and\n * a selected fill; the name carries the weight, the description does not. --- */\n& .dsh-ui-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; min-width: 0; }\n& .dsh-ui-list-scroll { max-height: min(66vh, 760px); overflow-y: auto; overflow-x: hidden; }\n& .dsh-ui-list-row { border-radius: var(--dsw-radius-md); }\n& .dsh-ui-list-row:hover { background: var(--dsw-alias-interactive-bg-hover); }\n& .dsh-ui-list-row[aria-selected='true'], & .dsh-ui-list-row[data-selected] { background: var(--dsw-alias-interactive-bg-active); }\n& .dsh-ui-list-item {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 4px;\n width: 100%;\n min-width: 0;\n padding: 10px 12px;\n border: 0;\n border-radius: var(--dsw-radius-md);\n background: none;\n font: inherit;\n color: inherit;\n text-align: start;\n cursor: pointer;\n}\n& .dsh-ui-list-item:disabled { cursor: default; }\n& .dsh-ui-list-item:disabled:hover { background: none; }\n& .dsh-ui-list-name { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); overflow-wrap: anywhere; }\n& .dsh-ui-list-desc { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n\n/* --- Code and structured output. Wraps rather than scrolls, because a\n * feature panel is read rather than scanned. --- */\n& .dsh-ui-code {\n padding: 10px 12px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-family: var(--ds-font-family-code);\n font-size: 12px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n overflow-wrap: anywhere;\n white-space: pre-wrap;\n}\n& .dsh-ui-scroll { max-height: 60vh; overflow: auto; overscroll-behavior: contain; }\n\n/* --- A toggle row: label on the left, switch on the trailing edge. This is\n * layout only; the switch itself is the official primitive. --- */\n& .dsh-ui-toggle-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; padding: 12px 0; }\n& .dsh-ui-toggle-row + .dsh-ui-toggle-row { border-top: 0.5px solid var(--dsw-alias-border-l2); }\n& .dsh-ui-toggle-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-toggle-label { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Floating surface: a panel anchored to a trigger. This is the material\n * a menu card is made of — the translucent fill plus its backdrop blur, with\n * the edge riding inside the prominent elevation. A plugin that hand-rolls this\n * is how tokens like --dsw-specific-menu get invented; use this instead. --- */\n& .dsh-ui-surface {\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l1);\n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n position: relative;\n display: flex;\n flex-direction: column;\n border: 0;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-menu-surface-fill);\n backdrop-filter: var(--dsw-menu-backdrop-filter);\n box-shadow: var(--dsw-elevation-prominent);\n color: var(--dsw-alias-label-primary);\n font-size: 13px;\n line-height: 20px;\n min-width: 0;\n}\n& .dsh-ui-surface-body { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px 14px; overflow-y: auto; }\n& .dsh-ui-surface-head { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-surface-title { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Native select. The primitives ship no select, so a plugin that offers a\n * closed list of choices keeps the platform control and matches the official\n * settings field geometry exactly (34px, 0.5px l4, radius-md, layer-3). A\n * SegmentedControl is the primitive to reach for when the choices are few\n * enough to show at once. --- */\n& .dsh-ui-select {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n height: 34px;\n padding: 0 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n cursor: pointer;\n}\n& .dsh-ui-select:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-select:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-select[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* --- Native textarea. The primitives ship no textarea either, so a settings\n * prompt keeps the platform element and the same field shell as the select:\n * 0.5px l4, radius-md, layer-3, 13/1.5 type. It grows vertically instead of\n * locking to the select's 34px row. --- */\n& .dsh-ui-textarea {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n resize: vertical;\n padding: 8px 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n}\n& .dsh-ui-textarea:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-textarea:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-textarea::placeholder { color: var(--dsw-alias-label-dimmed); }\n& .dsh-ui-textarea[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* Long panels scroll inside themselves instead of growing the host page. */\n& .dsh-ui-panel { display: flex; flex-direction: column; gap: 16px; min-width: 0; }\n& .dsh-ui-panel-wide { max-width: 100%; }\n\n@media (prefers-reduced-motion: reduce) {\n & *, & *::before, & *::after { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; }\n}\n}\n`\n // Widen every recipe from \"a descendant of the root\" to \"the root, or one of\n // its descendants\". Written as a transform rather than by hand so no recipe\n // can be added later with only the descendant form. The pattern is narrow on\n // purpose: a leading `&` followed by one recipe class and no combinator, so\n // sibling and child rules such as `.dsh-ui-field + .dsh-ui-field` keep their\n // own meaning and are left alone.\n return sheet.replace(/^& (\\.dsh-ui-[a-z0-9-]+)(?=\\s*\\{)/gm, (_match, className: string) =>\n `&${className}, & ${className}`)\n}\n","import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'\nimport { modelSettingsChangesIdentity, type ModelSettingsChangesIdentity } from './contracts.ts'\n\nexport type ModelSettingsChangeFrame = { kind: 'ready' } | { kind: 'changed'; ns: string; revision: number }\n\n/** This stream carries invalidations only; ready is never a settings snapshot. */\nexport function parseModelSettingsChangeFrame(value: unknown): ModelSettingsChangeFrame {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid model settings change frame')\n const frame = value as Record<string, unknown>\n if (frame.kind === 'ready' && Object.keys(frame).length === 1) return { kind: 'ready' }\n if (frame.kind === 'changed' && Object.keys(frame).length === 3 && typeof frame.ns === 'string' && frame.ns.length > 0\n && typeof frame.revision === 'number' && Number.isSafeInteger(frame.revision) && frame.revision >= 0) {\n return { kind: 'changed', ns: frame.ns, revision: frame.revision }\n }\n throw new Error('Invalid model settings change frame')\n}\n\n/** One owner's contribution. Each package mounts only its own endpoint. */\nexport function modelSettingsChangesRemote(packageName: string, identity: ModelSettingsChangesIdentity = modelSettingsChangesIdentity(packageName)): TypertRemoteContribution {\n return {\n package: packageName,\n descriptors: [{\n id: `${identity.namespace}/watch`,\n service: identity.service,\n namespace: identity.namespace,\n method: 'watch',\n mode: 'stream' as const,\n invocation: { kind: 'direct' as const },\n parameters: [],\n cancellation: { parameter: 'signal' as const },\n result: { mode: 'strict' as const, typeSymbol: 'ModelSettings.ChangeFrame', create: () => ({ parse: parseModelSettingsChangeFrame }) },\n }],\n }\n}\n\ninterface RemoteMountScope {\n remote: { $mount(contribution: TypertRemoteContribution): Promise<() => Promise<void>> }\n effect(callback: () => () => void | Promise<void>): unknown\n}\ninterface RemoteMountContext {\n inject(dependencies: string[], callback: (scope: unknown) => void): unknown\n}\n\n/** Mount from a synchronous apply. Disposal waits for an in-flight mount and\n * then withdraws it, so the contribution cannot outlive the plugin. */\nexport function mountModelSettingsChanges(ctx: RemoteMountContext, packageName: string): void {\n const contribution = modelSettingsChangesRemote(packageName)\n ctx.inject(['remote'], injected => {\n const scope = injected as RemoteMountScope\n const mounting = scope.remote.$mount(contribution)\n void mounting.catch(() => {})\n scope.effect(() => async () => {\n const unmount = await mounting.catch(() => undefined)\n await unmount?.()\n })\n })\n}\n\ninterface StreamItem {\n generation: number\n value: unknown\n signal: AbortSignal\n accept(): void\n}\ninterface ChangeStream extends AsyncIterable<StreamItem> { dispose(): Promise<void> }\ntype OpenChangeStream = (options: {\n name: string\n open(signal: AbortSignal): AsyncIterable<unknown>\n ended(accepted: boolean): Error\n}) => ChangeStream\nexport interface ModelSettingsSubscriberScope {\n remote: { $stream: OpenChangeStream } & Record<string, { watch?(signal: AbortSignal): AsyncIterable<unknown> } | OpenChangeStream | undefined>\n effect(callback: () => () => void | Promise<void>): unknown\n}\nexport interface ModelSettingsSubscriberContext {\n inject(dependencies: string[], callback: (scope: unknown) => void): unknown\n}\nexport interface ModelSettingsSubscriber {\n subscribe(onChange: () => void, onError?: (message: string) => void): () => void\n}\n\n/** Native RemoteStream owns carrier reconnects; no timers or browser transport.\n * A factory shares one logical stream while at least one subscriber remains. */\nexport function createModelSettingsSubscriber(\n ctx: ModelSettingsSubscriberContext,\n packageName: string,\n identity: ModelSettingsChangesIdentity = modelSettingsChangesIdentity(packageName),\n accept: (ns: string) => boolean = ns => ns === packageName,\n): ModelSettingsSubscriber {\n const endpoint = identity\n const listeners = new Set<{ change: () => void; error?: (message: string) => void }>()\n let injection: { dispose(): void | Promise<void> } | undefined\n let current: { stream: ChangeStream; active: boolean } | undefined\n let lifecycle = 0\n let failureMessage: string | undefined\n const report = (message: string) => {\n failureMessage = message\n for (const listener of [...listeners]) {\n try { listener.error?.(message) } catch { /* Isolate page callbacks. */ }\n }\n }\n const invalidate = () => {\n for (const listener of [...listeners]) {\n if (!listeners.has(listener)) continue\n try { listener.change() } catch (error) {\n try { listener.error?.(error instanceof Error ? error.message : String(error)) } catch { /* Isolate callbacks. */ }\n }\n }\n }\n const start = () => {\n const life = ++lifecycle\n injection = ctx.inject(['remote', `remote.${endpoint.namespace}`], injected => {\n if (life !== lifecycle || !listeners.size) return\n const scope = injected as ModelSettingsSubscriberScope\n const service = scope.remote[endpoint.namespace]\n if (!service || !('watch' in service) || !service.watch) { report('Model settings sync service unavailable'); return }\n const watch = service.watch\n const stream = scope.remote.$stream({\n name: 'Model settings sync',\n open: signal => watch(signal),\n ended: accepted => new Error(`Model settings sync stream ended ${accepted ? 'after' : 'before'} ready; refresh or reopen the page`),\n })\n const session = { stream, active: true }\n current = session\n scope.effect(() => () => {\n session.active = false\n if (current === session) {\n current = undefined\n if (life === lifecycle && listeners.size) report('Model settings sync service unavailable')\n }\n return stream.dispose()\n })\n void (async () => {\n let generation: number | undefined\n let ready = false\n try {\n for await (const item of stream) {\n if (!session.active || life !== lifecycle || !listeners.size) break\n if (item.signal.aborted) continue\n if (generation !== item.generation) { generation = item.generation; ready = false }\n const frame = parseModelSettingsChangeFrame(item.value)\n if (frame.kind === 'ready') {\n ready = true\n failureMessage = undefined\n // Accept the validated invalidation baseline, not fetched data.\n // Every current listener queues its own latest settings read.\n item.accept()\n invalidate()\n } else {\n if (!ready) throw new Error('Model settings sync change arrived before ready')\n if (accept(frame.ns)) invalidate()\n }\n }\n } catch (error) {\n if (session.active && life === lifecycle) report(error instanceof Error ? error.message : String(error))\n } finally {\n if (current === session) current = undefined\n session.active = false\n await stream.dispose().catch(() => {})\n }\n })()\n }) as { dispose(): void | Promise<void> }\n queueMicrotask(() => {\n if (life === lifecycle && listeners.size && !current) report('Model settings sync service unavailable')\n })\n }\n return Object.freeze({ subscribe(onChange: () => void, onError?: (message: string) => void) {\n const listener = { change: onChange, error: onError }\n listeners.add(listener)\n if (!injection) start()\n else if (failureMessage) queueMicrotask(() => {\n if (listeners.has(listener) && failureMessage) {\n try { listener.error?.(failureMessage) } catch { /* Isolate callbacks. */ }\n }\n })\n return () => {\n if (!listeners.delete(listener) || listeners.size) return\n lifecycle++\n if (current) { current.active = false; void current.stream.dispose().catch(() => {}) }\n current = undefined\n failureMessage = undefined\n const previous = injection\n injection = undefined\n try { void Promise.resolve(previous?.dispose()).catch(() => {}) } catch { /* Already unloaded. */ }\n }\n } })\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { Button } from '@deepseek-ai/dsh-client-ui-primitives'\nimport {\n checkedModelCatalog, modelCatalogErrorMessage, modelCatalogFailures, parseModelMenuChoices,\n type ModelCatalogFailure, type ModelMenuChoice,\n} from './catalog.ts'\n\nexport interface UseModelCatalogOptions {\n /** Used only on mount; subsequent changes come from load(). */\n readonly initialCatalog?: unknown\n /** Disables initial, focus, subscription, and manual refreshes. */\n readonly enabled?: boolean\n readonly subscribe?: (onChange: () => void) => (() => void) | undefined\n}\n\nexport interface ModelCatalogState {\n readonly catalog: unknown\n readonly choices: ModelMenuChoice[]\n readonly loading: boolean\n readonly error: string\n readonly failures: readonly ModelCatalogFailure[]\n readonly refresh: () => Promise<void>\n}\n\ntype Snapshot = Pick<ModelCatalogState, 'catalog' | 'loading' | 'error'>\n\n/**\n * Latest refresh wins, including retries while a previous request is pending.\n * Keep load stable (for example with useCallback); changing it invalidates the\n * previous source and fetches again, so switching clients cannot publish stale data.\n */\nexport function useModelCatalog(load: () => Promise<unknown>, options: UseModelCatalogOptions = {}): ModelCatalogState {\n const enabled = options.enabled !== false\n const enabledRef = useRef(enabled)\n enabledRef.current = enabled\n const live = useRef(false)\n const source = useRef(load)\n const revision = useRef(0)\n const [state, setState] = useState<Snapshot>(() => {\n try {\n return { catalog: options.initialCatalog === undefined ? undefined : checkedModelCatalog(options.initialCatalog), loading: enabled, error: '' }\n } catch (error) {\n return { catalog: undefined, loading: enabled, error: modelCatalogErrorMessage(error) }\n }\n })\n const refresh = useCallback(async (): Promise<void> => {\n if (!live.current || !enabledRef.current) return\n const request = ++revision.current\n setState(previous => ({ ...previous, loading: true, error: '' }))\n try {\n const catalog = checkedModelCatalog(await load())\n if (live.current && request === revision.current) setState({ catalog, loading: false, error: '' })\n } catch (error) {\n if (live.current && request === revision.current) {\n setState(previous => ({ ...previous, loading: false, error: modelCatalogErrorMessage(error) }))\n }\n }\n }, [load, enabled])\n\n useEffect(() => {\n live.current = true\n if (source.current !== load) {\n source.current = load\n // Last-good retention belongs to one source; a new client must not\n // inherit another client's models if its initial request fails.\n setState({ catalog: undefined, loading: enabled, error: '' })\n }\n if (enabled) void refresh()\n else setState(previous => ({ ...previous, loading: false }))\n return () => { live.current = false; ++revision.current }\n }, [enabled, refresh])\n\n useEffect(() => {\n if (!enabled) return\n const reload = (): void => { void refresh() }\n // No polling: the host owns catalog production, and focus is a cheap\n // recovery path for missed ordinary notifications or changed credentials.\n if (typeof window !== 'undefined') window.addEventListener('focus', reload)\n let unsubscribe: (() => void) | undefined\n try { unsubscribe = options.subscribe?.(reload) } catch (error) {\n setState(previous => ({ ...previous, error: modelCatalogErrorMessage(error) }))\n }\n return () => {\n if (typeof window !== 'undefined') window.removeEventListener('focus', reload)\n unsubscribe?.()\n }\n }, [enabled, refresh, options.subscribe])\n\n const choices = useMemo(() => parseModelMenuChoices(state.catalog), [state.catalog])\n const failures = useMemo(() => state.catalog === undefined ? [] : modelCatalogFailures(state.catalog), [state.catalog])\n return { ...state, choices, failures, refresh }\n}\n\nexport interface ModelCatalogStatusProps {\n readonly state: Pick<ModelCatalogState, 'loading' | 'error' | 'failures' | 'refresh'>\n readonly locale?: string\n}\n\n/**\n * Also accepts a mapped state from a caller that owns broader async orchestration.\n *\n * The dsh-ui-* classes carry the styling and resolve through the consuming\n * plugin's own officialUiCss scope (every consumer mounts its root class, so\n * e.g. `.dsh-model-hub .dsh-ui-loading` paints this); dsh-model-catalog-status\n * stays as a structural hook for tests and layout, never a colour source.\n */\nexport function ModelCatalogStatus({ state, locale }: ModelCatalogStatusProps) {\n const zh = locale?.toLowerCase().startsWith('zh') === true\n const copy = zh\n ? { loading: '正在加载模型…', error: '模型列表加载失败', partial: '部分提供商的模型未能加载', retry: '重试' }\n : { loading: 'Loading models…', error: 'Unable to load models', partial: 'Some providers could not load their models', retry: 'Retry' }\n if (!state.loading && !state.error && state.failures.length === 0) return null\n return <div className=\"dsh-model-catalog-status dsh-ui-stack\" lang={zh ? 'zh' : 'en'}>\n {state.loading ? <p role=\"status\" className=\"dsh-ui-loading\">{copy.loading}</p> : null}\n {state.error ? <p role=\"alert\" className=\"dsh-ui-error dsh-ui-wrap\">{copy.error}: {state.error}</p> : null}\n {state.failures.length > 0 ? <div role=\"status\" className=\"dsh-ui-meta\">\n <p>{copy.partial}</p>\n <ul className=\"dsh-ui-list\">{state.failures.map((failure, index) => <li key={`${failure.id}:${index}`}>{failure.name || failure.id}: {failure.message}</li>)}</ul>\n </div> : null}\n {state.error || state.failures.length > 0\n ? <div className=\"dsh-ui-actions\"><Button type=\"button\" size=\"sm\" disabled={state.loading} onClick={() => { void state.refresh() }}>{copy.retry}</Button></div>\n : null}\n </div>\n}\n","/**\n * ModelMenu: the standard editor of one model-route field — the visible half\n * of the x-model-route contract. A feature plugin's settings page renders it\n * for its own marked field; the model hub renders one per detected field.\n *\n * It is a plugin-side copy of the host's composer model picker\n * (dsh-client-ui-model-selection's ModelSelect), rebuilt from the official\n * primitives and the published bundle's behavior: one card that opens on the\n * root pane (Model / Effort cells), drills into the provider-grouped,\n * searchable model list or the effort list, and Escapes back before closing.\n * Sticky group headings, subsequence ranking, highlight walking and focus\n * hand-back all match the host. SYNC POINT: when the host's ModelSelect or\n * ModelSelect.module.css changes, this copy must be re-transcribed; styles\n * below may only reference allowlisted theme tokens (the --dsw-* set plus the\n * host's --ds-* motion tokens), never literal colors.\n *\n * It statically imports the primitives, so only browser clients should load\n * this entry; host code and node tests use the core entry (`./index.ts`).\n */\nimport { cloneElement, isValidElement, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconCloseFillRegular, Input, MenuGroup, MenuSurface,\n observeStickyMenuGroups, rankByName,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nexport { useModelCatalog, ModelCatalogStatus } from './catalog-ui.tsx'\nexport type { UseModelCatalogOptions, ModelCatalogState, ModelCatalogStatusProps } from './catalog-ui.tsx'\nimport type { ModelMenuChoice } from './catalog.ts'\nimport { groupModelMenuChoices, modelMenuEffortLabel, modelMenuShortName } from './menu.ts'\n\n/** Extra rows rendered above the model groups (e.g. a plugin's \"follow\"/\"off\" modes). */\nexport interface ModelMenuLeadingItem {\n readonly id: string\n readonly label: ReactNode\n readonly selected?: boolean\n}\n\nexport interface ModelMenuProps {\n /** Active host locale, supplied by the owning plugin's live locale subscription. */\n readonly locale?: string\n readonly open: boolean\n readonly onOpenChange: (open: boolean) => void\n /** Trigger rendered in place; the menu anchors to it and returns focus to it. */\n readonly anchor: ReactNode\n readonly choices: readonly ModelMenuChoice[]\n readonly selected?: { readonly provider: string; readonly model: string }\n readonly onPick: (route: { provider: string; model: string }) => void\n readonly leading?: readonly ModelMenuLeadingItem[]\n readonly onPickLeading?: (id: string) => void\n /** Effort pane rows; the root Effort cell is hidden while this is empty. */\n readonly efforts?: ReadonlyArray<{ id: string; name: string }>\n readonly selectedEffort?: string\n readonly onPickEffort?: (effort: string | undefined) => void\n /** Root-cell labels and the values shown trailing them. */\n readonly modelLabel?: string\n readonly modelValue?: string\n readonly effortLabel?: string\n readonly effortValue?: string\n readonly defaultEffortLabel?: string\n readonly searchPlaceholder?: string\n readonly emptyLabel?: string\n readonly clearSearchLabel?: string\n /** Pane the menu opens on; default 'root'. 'model' opens the searchable model list directly. */\n readonly initialPane?: 'root' | 'model'\n /** Show the model search row even when the catalog has four or fewer choices. */\n readonly alwaysShowSearch?: boolean\n /**\n * Render the declared reasoning efforts as a discrete slider inside the model\n * pane. Additive: the effort list and the root Effort cell stay for the\n * default (false) mode, and only the caller-supplied effort rows are shown.\n */\n readonly reasoningSlider?: boolean\n /**\n * Optional banner rendered at the top of the menu card, above the search and\n * list — e.g. a directory status/error row. Pure library-local React content,\n * not a cross-factory data contract.\n */\n readonly menuHeader?: ReactNode\n /** Disable every action after opening; by default a true value also closes\n * the menu (closeOnDisable). */\n readonly disabled?: boolean\n /**\n * Submission in progress. Keeps the menu open (unlike `disabled`) and still\n * allows opening/closing and typing in search, but disables selection rows\n * and blocks repeated model/leading/effort/slider submissions.\n */\n readonly busy?: boolean\n /**\n * Close the card after a model pick. Default true (drill menus dismiss).\n * The composer picker sets false so a selection does not unmount the open\n * list — search and scroll belong to that card.\n */\n readonly closeOnPick?: boolean\n /**\n * Close the open card when `disabled` rises. Default true — a hard lock\n * dismisses. Keep-open callers (the composer picker) set false: an owner's\n * save-state \"disabled\" pulse gates actions without unmounting the open\n * list, and Escape/outside presses still dismiss while disabled.\n */\n readonly closeOnDisable?: boolean\n readonly className?: string\n /** Extra class on the portaled menu card, which renders under document.body. */\n readonly listClassName?: string\n}\n\ntype Pane = 'root' | 'model' | 'effort'\n\n/** Unplaced portal card: hidden but laid out at a fixed origin so measurements are real. */\nconst MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }\n\nexport function ModelMenu(props: ModelMenuProps) {\n const language = props.locale?.toLowerCase().startsWith('zh') ? 'zh' : 'en'\n const copy = language === 'zh'\n ? { model: '模型', effort: '思考强度', default: '默认', search: '搜索模型…', empty: '没有匹配的模型', clear: '清除搜索' }\n : { model: 'Model', effort: 'Reasoning', default: 'Default', search: 'Search models…', empty: 'No matching models', clear: 'Clear search' }\n const {\n open, onOpenChange, anchor, choices, selected, onPick,\n leading = [], onPickLeading, efforts = [], selectedEffort, onPickEffort,\n modelLabel = copy.model, modelValue = '—', effortLabel = copy.effort, effortValue, defaultEffortLabel = copy.default,\n searchPlaceholder = copy.search, emptyLabel = copy.empty, clearSearchLabel = copy.clear,\n initialPane = 'root', alwaysShowSearch = false, reasoningSlider = false,\n menuHeader, disabled = false, busy = false, closeOnPick = true, closeOnDisable = true,\n className, listClassName,\n } = props\n const rootRef = useRef<HTMLSpanElement | null>(null)\n const openRef = useRef(open)\n openRef.current = open\n const pendingOpenRef = useRef(false)\n const pendingRestoreFocus = useRef(false)\n const [requestedOpen, setRequestedOpen] = useState(false)\n const menuRef = useRef<HTMLDivElement | null>(null)\n const groupsRef = useRef<HTMLDivElement | null>(null)\n const searchRef = useRef<HTMLInputElement | null>(null)\n const itemRefs = useRef<Array<HTMLButtonElement | null>>([])\n const paneFocus = useRef<Pane | 'drill' | null>(null)\n const [pane, setPane] = useState<Pane>('root')\n const [query, setQuery] = useState('')\n const [highlightedIndex, setHighlightedIndex] = useState<number | null>(null)\n /* Keyboard arrows only. Mouse focus and a rebuilt choices array must not scroll. */\n const [keyNav, setKeyNav] = useState(0)\n const [menuPos, setMenuPos] = useState<CSSProperties | null>(null)\n const id = useId()\n const showSearch = alwaysShowSearch || choices.length > 4\n const effortRows = useMemo(() => [{ id: '', name: defaultEffortLabel }, ...efforts.map(effort => ({ ...effort, name: modelMenuEffortLabel(effort, language) }))], [defaultEffortLabel, efforts, language])\n /* The official ranks each provider group by a case-insensitive ordered\n * subsequence (prefix hits first, then alignment score, then catalog order);\n * groups left empty by the query drop out. */\n const filteredGroups = useMemo(() => groupModelMenuChoices(choices, '').map(group => ({\n ...group,\n items: rankByName(group.items.map(choice => ({\n choice,\n name: modelMenuShortName(choice),\n // The match surface deliberately carries the provider id, provider display\n // name, model id and the full \"Provider / Model\" label — never only the\n // possibly-truncated short model name — so provider and model-id searches\n // resolve while the rendered name stays short.\n label: [choice.provider, choice.providerLabel, choice.model, choice.label].filter(Boolean).join(' '),\n })), showSearch ? query.trim() : ''),\n })).filter(group => group.items.length > 0), [choices, query, showSearch])\n const visibleModels = useMemo(() => filteredGroups.flatMap(group => group.items.map(item => item.choice)), [filteredGroups])\n const currentVisibleIndex = visibleModels.findIndex(choice => choice.provider === selected?.provider && choice.model === selected.model)\n const activeModelIndex = Math.min(highlightedIndex ?? Math.max(0, currentVisibleIndex), visibleModels.length - 1)\n const changeOpen = (next: boolean): void => {\n if (openRef.current === next) return\n openRef.current = next\n onOpenChange(next)\n }\n const requestOpen = (): void => {\n if (open || pendingOpenRef.current) return\n pendingOpenRef.current = true\n pendingRestoreFocus.current = false\n setRequestedOpen(true)\n }\n const close = (restoreFocus = false): void => {\n const active = document.activeElement\n pendingRestoreFocus.current = restoreFocus && (active === document.body\n || rootRef.current?.contains(active) === true || menuRef.current?.contains(active) === true)\n changeOpen(false)\n }\n const drill = (next: Pane): void => {\n setQuery('')\n setHighlightedIndex(null)\n paneFocus.current = 'drill'\n setPane(next)\n }\n /** Leave a drilled pane for the entry pane, handing the keyboard back to it.\n * A root entry refocuses the cell that opened the pane; a search-first\n * (model) entry refocuses that pane's own intent. */\n const back = (from: Pane): void => {\n paneFocus.current = initialPane === 'root' ? from : 'drill'\n setPane(initialPane)\n }\n const moveFocus = (offset: number): void => {\n const items = itemRefs.current.filter((item): item is HTMLButtonElement => item !== null && !item.disabled)\n if (!items.length) return\n const active = items.findIndex(item => item === document.activeElement)\n items[active === -1 ? (offset > 0 ? 0 : items.length - 1) : (active + offset + items.length) % items.length]?.focus()\n }\n\n // A selection can synchronously disable its trigger while the owner writes.\n // Retry on the owner's next render, once the native button can take focus.\n useLayoutEffect(() => {\n if (open || !pendingRestoreFocus.current) return\n const active = document.activeElement\n if (active !== document.body && !rootRef.current?.contains(active)) {\n pendingRestoreFocus.current = false\n return\n }\n const trigger = rootRef.current?.querySelector('button')\n if (!trigger || trigger.disabled) return\n trigger.focus()\n if (document.activeElement === trigger) pendingRestoreFocus.current = false\n })\n useEffect(() => {\n if (open || !pendingRestoreFocus.current) return\n const cancelOutside = (event: Event): void => {\n if (event.target instanceof Node && !rootRef.current?.contains(event.target)) pendingRestoreFocus.current = false\n }\n document.addEventListener('focusin', cancelOutside)\n document.addEventListener('pointerdown', cancelOutside)\n return () => {\n document.removeEventListener('focusin', cancelOutside)\n document.removeEventListener('pointerdown', cancelOutside)\n }\n })\n\n useEffect(() => {\n if (!requestedOpen) return\n pendingOpenRef.current = false\n setRequestedOpen(false)\n // The caller's trigger handler may also update the controlled open prop.\n // Check the committed state before supplying the missing open callback.\n if (!open) changeOpen(true)\n }, [requestedOpen, open])\n\n useEffect(() => {\n if (!open) return\n // A consumer may open directly at the model pane (a search-first picker).\n // The root cells stay reachable with Escape; the default stays 'root' and\n // leaves the trigger's keyboard focus intent untouched.\n setPane(initialPane)\n if (initialPane === 'model') paneFocus.current = 'drill'\n setQuery('')\n setHighlightedIndex(null)\n }, [open, initialPane])\n // A consumer that becomes busy/locked after opening must not leave actions\n // available. With closeOnDisable a true value also closes the card (the\n // trigger owns the disabled look); without it the open card stays mounted\n // and only dismissal stays available.\n useEffect(() => {\n if (disabled && open && closeOnDisable) changeOpen(false)\n }, [disabled, open, closeOnDisable])\n useEffect(() => {\n if (!open) return\n const closeOutside = (event: MouseEvent): void => {\n const target = event.target as Node\n if (rootRef.current?.contains(target) || menuRef.current?.contains(target)) return\n changeOpen(false)\n }\n /* The span's React onKeyDown already sees Escape from inside the menu —\n * portal rows bubble through the React tree. What it cannot see is focus\n * that is no longer in the tree at all: a disabled rise ejects the\n * focused row's focus to document.body, and Escape there never reaches\n * the span. This listener keeps dismissal reachable for that focus; the\n * openRef check means it never double-acts after the in-tree handler. */\n const escapeOutside = (event: KeyboardEvent): void => {\n if (event.key !== 'Escape' || event.defaultPrevented || event.isComposing) return\n if (!openRef.current) return\n event.preventDefault()\n if (pane !== initialPane) back(pane)\n else close(true)\n }\n document.addEventListener('mousedown', closeOutside)\n document.addEventListener('keydown', escapeOutside)\n return () => {\n document.removeEventListener('mousedown', closeOutside)\n document.removeEventListener('keydown', escapeOutside)\n }\n }, [open, onOpenChange, pane, initialPane])\n /* Focus intent after a pane change: the model pane takes the search field when\n * it has one, every other drill takes the checked row, and going back takes\n * the cell that opened the pane. */\n useEffect(() => {\n const intent = paneFocus.current\n // MenuSurface forwards the measurement visibility:hidden style. Browsers\n // refuse focus there, so keep intent until placement has made it visible.\n if (!open || menuPos === null || intent === null) return\n // Reopening resets a previously drilled pane in a separate commit. Entry\n // and return intent belong to the root cells, never the outgoing rows.\n if (intent !== 'drill' && pane !== 'root') return\n paneFocus.current = null\n if (intent === 'drill') {\n if (pane === 'model' && showSearch) { searchRef.current?.focus(); return }\n (menuRef.current?.querySelector<HTMLButtonElement>('[role=\"menuitemradio\"][aria-checked=\"true\"]:not([disabled])')\n ?? itemRefs.current.find(item => item !== null && !item.disabled))?.focus()\n return\n }\n itemRefs.current[intent === 'effort' ? 1 : 0]?.focus()\n }, [open, pane, showSearch, menuPos])\n useEffect(() => {\n const viewport = groupsRef.current\n if (viewport === null) return\n return observeStickyMenuGroups(viewport)\n }, [open, pane, filteredGroups])\n /* Scroll when the model pane opens, or when a keyboard arrow moves the\n * highlight. `visibleModels` is a new array whenever a directory snapshot\n * replaces `current` and the caller rebuilds equivalent choices — depending\n * on that array jumped scrollTop. Search may replace the rows; a model\n * click must not. */\n const modelPaneOpen = open && pane === 'model'\n const scrollSignal = !modelPaneOpen ? 'closed' : keyNav === 0 ? 'open' : `key:${keyNav}`\n const scrollSignalRef = useRef<string | null>(null)\n useLayoutEffect(() => {\n if (!modelPaneOpen || activeModelIndex < 0) {\n if (!modelPaneOpen) scrollSignalRef.current = null\n return\n }\n if (scrollSignalRef.current === scrollSignal) return\n scrollSignalRef.current = scrollSignal\n itemRefs.current[leading.length + activeModelIndex]?.scrollIntoView({ block: 'nearest' })\n }, [modelPaneOpen, scrollSignal, activeModelIndex, leading.length])\n /* The card hangs above the trigger, right-aligned, inside 12px viewport\n * margins — the official placement formula, re-run on scroll and resize. */\n useLayoutEffect(() => {\n if (!open) { setMenuPos(null); return }\n const place = (): void => {\n const rect = rootRef.current?.getBoundingClientRect()\n if (!rect) return\n const margin = 12, lw = menuRef.current?.offsetWidth ?? 0, lh = menuRef.current?.offsetHeight ?? 0\n let x = rect.right - lw, y = rect.top - 8 - lh\n if (lw > 0) x = Math.min(Math.max(x, margin), window.innerWidth - lw - margin)\n if (lh > 0) y = Math.min(Math.max(y, margin), window.innerHeight - lh - margin)\n setMenuPos(prev => (prev && prev.left === x && prev.top === y ? prev : { left: x, top: y }))\n }\n place()\n window.addEventListener('scroll', place, true)\n window.addEventListener('resize', place)\n return () => {\n window.removeEventListener('scroll', place, true)\n window.removeEventListener('resize', place)\n }\n }, [open, pane, choices, query])\n\n function onKeyDown(event: React.KeyboardEvent): void {\n if (event.defaultPrevented || event.nativeEvent.isComposing) return\n // Escape dismisses even while actions are disabled — a save lock gates\n // selection, not closing. A drilled pane backs out to the entry pane\n // first; the entry pane closes outright.\n if (event.key === 'Escape' && open) {\n event.preventDefault()\n if (pane !== initialPane) back(pane)\n else close(true)\n return\n }\n if (disabled) return\n if (!open && ['Enter', ' ', 'ArrowDown', 'ArrowUp'].includes(event.key)) {\n const button = event.target instanceof Element ? event.target.closest('button') : null\n if (!(button instanceof HTMLButtonElement) || button.disabled || !rootRef.current?.contains(button)) return\n // Prevent the native Enter/Space click from opening a second time.\n event.preventDefault()\n paneFocus.current = 'model'\n requestOpen()\n return\n }\n if (!open) return\n if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {\n event.preventDefault()\n if (visibleModels.length > 0) {\n setHighlightedIndex((activeModelIndex + (event.key === 'ArrowDown' ? 1 : -1) + visibleModels.length) % visibleModels.length)\n setKeyNav(n => n + 1)\n searchRef.current?.focus()\n }\n return\n }\n if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) {\n if (event.key === 'Tab' && visibleModels.length === 0) return\n event.preventDefault()\n const highlighted = visibleModels[activeModelIndex]\n // A submission in progress must not be repeated by Enter/Tab.\n if (highlighted && !busy) { onPick({ provider: highlighted.provider, model: highlighted.model }); if (closeOnPick) close(true) }\n return\n }\n if (event.key === 'Tab') {\n if (event.shiftKey) {\n event.preventDefault()\n if (pane !== initialPane) back(pane)\n else close(true)\n return\n }\n const focused = document.activeElement\n const rows = itemRefs.current.filter((item): item is HTMLButtonElement => item !== null)\n if (focused instanceof HTMLButtonElement && rows.includes(focused)) {\n event.preventDefault()\n focused.click()\n return\n }\n if (pane === 'model' && showSearch) {\n event.preventDefault()\n setHighlightedIndex(null)\n searchRef.current?.focus()\n }\n return\n }\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n moveFocus(event.key === 'ArrowDown' ? 1 : -1)\n }\n }\n\n function onBlur(event: React.FocusEvent): void {\n const related = event.relatedTarget\n // A target already detached from the document (the menu re-rendering the\n // focused row) is inside for this purpose — never a dismissal.\n if (related instanceof Node\n && (rootRef.current?.contains(related) || menuRef.current?.contains(related)\n || !related.isConnected)) return\n // Keep-open mode never closes on a blur that has no connected next focus:\n // disabling the picked row, or a blur whose target raced a re-render, is\n // not the user dismissing the card. Outside presses, Escape, and focus\n // landing in a real outside node still close.\n if (!closeOnPick && !(related instanceof Node)) return\n // Disabling the focused row while a selection is in flight blurs it with\n // no next target. That is not a dismissal — closing here unmounts the card.\n if (busy && related == null) return\n if (open) changeOpen(false)\n }\n\n itemRefs.current = []\n let itemIndex = 0\n let modelIndex = 0\n const itemRef = () => {\n const at = itemIndex++\n return (node: HTMLButtonElement | null): void => { itemRefs.current[at] = node }\n }\n\n const menu = open && typeof document !== 'undefined'\n ? createPortal(\n <MenuSurface\n ref={menuRef}\n id={`${id}-menu`}\n className={`dsh-model-menu-menu${listClassName ? ` ${listClassName}` : ''}`}\n style={menuPos ?? MEASURE_STYLE}\n role={pane === 'model' ? 'group' : 'menu'}\n aria-label={modelLabel}\n lang={language}\n >\n {menuHeader ? <div className=\"dsh-model-menu-header\">{menuHeader}</div> : null}\n {pane === 'root' ? <>\n <button ref={itemRef()} type=\"button\" role=\"menuitem\" className=\"dsh-model-menu-cell\" disabled={disabled} onClick={() => drill('model')}>\n <span className=\"dsh-model-menu-cellLabel\">{modelLabel}</span>\n <span className=\"dsh-model-menu-cellValue\">{modelValue}</span>\n <IconChevronRightOutlineRegular className=\"dsh-model-menu-cellChevron\" />\n </button>\n {efforts.length > 0 && !reasoningSlider ? <button ref={itemRef()} type=\"button\" role=\"menuitem\" className=\"dsh-model-menu-cell\" disabled={disabled} onClick={() => drill('effort')}>\n <span className=\"dsh-model-menu-cellLabel\">{effortLabel}</span>\n <span className=\"dsh-model-menu-cellValue\">{effortValue ?? effortRows.find(row => row.id === (selectedEffort ?? ''))?.name ?? defaultEffortLabel}</span>\n <IconChevronRightOutlineRegular className=\"dsh-model-menu-cellChevron\" />\n </button> : null}\n </> : null}\n {pane === 'model' ? <>\n {showSearch ? <div className=\"dsh-model-menu-searchRow\">\n <Input\n ref={searchRef}\n disabled={disabled}\n className={`dsh-model-menu-search${query !== '' ? ' dsh-model-menu-searchWithQuery' : ''}`}\n type=\"text\"\n role=\"searchbox\"\n aria-label={searchPlaceholder}\n aria-controls={`${id}-models`}\n aria-activedescendant={activeModelIndex < 0 ? undefined : `${id}-model-${activeModelIndex}`}\n placeholder={searchPlaceholder}\n value={query}\n onChange={event => { setQuery(event.target.value); setHighlightedIndex(0) }}\n />\n {query !== '' ? <button type=\"button\" className=\"dsh-model-menu-searchClear\" aria-label={clearSearchLabel} disabled={disabled}\n onClick={() => { setQuery(''); setHighlightedIndex(null); searchRef.current?.focus() }}>\n <IconCloseFillRegular />\n </button> : null}\n </div> : null}\n <div ref={groupsRef} id={`${id}-models`} className=\"dsh-model-menu-groups scrollable\" role=\"menu\" aria-label={modelLabel}\n hidden={filteredGroups.length === 0}>\n {leading.length > 0 ? <div className=\"dsh-model-menu-leading\">\n {leading.map(item => (\n <button key={item.id} ref={itemRef()} type=\"button\" role=\"menuitemradio\" aria-checked={item.selected === true} disabled={disabled || busy}\n className={`dsh-model-menu-option${item.selected === true ? ' dsh-model-menu-selected' : ''}`}\n onClick={() => { if (disabled || busy) return; onPickLeading?.(item.id); if (closeOnPick) close(true) }}>\n <span className=\"dsh-model-menu-optionCopy\"><span className=\"dsh-model-menu-modelName\">{item.label}</span></span>\n <span className=\"dsh-model-menu-check\">{item.selected === true ? <IconCheckOutlineRegular /> : null}</span>\n </button>\n ))}\n </div> : null}\n {filteredGroups.map(group => (\n <MenuGroup key={group.provider} label={group.name}>\n {group.items.map(item => {\n const index = modelIndex++\n const choice = item.choice\n const checked = selected?.provider === choice.provider && selected.model === choice.model\n return <button\n key={`${choice.provider}/${choice.model}`}\n ref={itemRef()}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={checked}\n id={`${id}-model-${index}`}\n tabIndex={showSearch ? -1 : 0}\n disabled={disabled || busy}\n onFocus={() => setHighlightedIndex(index)}\n data-highlighted={index === activeModelIndex ? '' : undefined}\n className={`dsh-model-menu-option dsh-model-menu-modelOption${checked ? ' dsh-model-menu-selected' : ''}${index === activeModelIndex ? ' dsh-model-menu-optionActive' : ''}`}\n onMouseMove={index === activeModelIndex ? undefined : () => {\n if (showSearch) setHighlightedIndex(index)\n else itemRefs.current[leading.length + index]?.focus()\n }}\n title={choice.label}\n onClick={() => { if (disabled || busy) return; onPick({ provider: choice.provider, model: choice.model }); if (closeOnPick) close(true) }}\n >\n <span className=\"dsh-model-menu-optionCopy\"><span className=\"dsh-model-menu-modelName\">{modelMenuShortName(choice)}</span></span>\n <span className=\"dsh-model-menu-check\">{checked ? <IconCheckOutlineRegular /> : null}</span>\n </button>\n })}\n </MenuGroup>\n ))}\n </div>\n {reasoningSlider && efforts.length > 0 && filteredGroups.length > 0\n ? <EffortSlider label={effortLabel} rows={effortRows} selected={selectedEffort ?? ''} disabled={disabled} busy={busy}\n onPick={value => onPickEffort?.(value)} />\n : null}\n {filteredGroups.length === 0 ? <div className=\"dsh-model-menu-empty\" role=\"status\">{emptyLabel}</div> : null}\n </> : null}\n {pane === 'effort' ? <>\n {effortRows.map(row => {\n const checked = (selectedEffort ?? '') === row.id\n return <button key={row.id || '__default'} ref={itemRef()} type=\"button\" role=\"menuitemradio\" aria-checked={checked} disabled={disabled || busy}\n className={`dsh-model-menu-option${checked ? ' dsh-model-menu-selected' : ''}`}\n onClick={() => { if (disabled || busy) return; onPickEffort?.(row.id || undefined); if (closeOnPick) close(true) }}>\n <span className=\"dsh-model-menu-optionCopy\"><span className=\"dsh-model-menu-modelName\">{row.name}</span></span>\n <span className=\"dsh-model-menu-check\">{checked ? <IconCheckOutlineRegular /> : null}</span>\n </button>\n })}\n </> : null}\n </MenuSurface>,\n document.body,\n )\n : null\n const trigger = isValidElement<Record<string, unknown>>(anchor)\n ? cloneElement(anchor, { 'aria-haspopup': 'menu', 'aria-expanded': open, 'aria-controls': open ? `${id}-menu` : undefined, 'aria-disabled': disabled || undefined })\n : anchor\n return <span ref={rootRef} className={`dsh-model-menu-root${className ? ` ${className}` : ''}`} onKeyDown={onKeyDown} onBlur={onBlur}\n onClick={event => {\n if (disabled || event.defaultPrevented) return\n const button = event.target instanceof Element ? event.target.closest('button') : null\n if (!(button instanceof HTMLButtonElement) || button.disabled || !rootRef.current?.contains(button)) return\n requestOpen()\n }}\n onMouseDown={event => { if (event.target instanceof Element && menuRef.current?.contains(event.target) && event.target.closest('button') !== null) event.preventDefault() }}>\n {trigger}{menu}\n </span>\n}\n\n/**\n * Discrete reasoning-effort slider shown under the model list in enhanced mode.\n *\n * A native range input (`step=1`) over exactly the rows the caller supplies —\n * the default row plus each effort the selected model advertises — so it can\n * never invent a level. It previews locally while dragging or arrowing and\n * commits only when the gesture ends (pointer up, key up, or blur), so a drag\n * does not write on every step. The menu stays open, so adjusting the effort\n * never loses the model selection or the search query.\n *\n * The input itself stays the entire interaction and accessibility surface —\n * keyboard, ARIA, disabled and the native step snapping all come from it —\n * while the track, gradient fill and thumb below are decorative layers painted\n * from the `--_p` percentage the preview position sets on the rail. Value\n * changes only update that custom property, so the CSS transitions animate\n * between levels without remounting nodes or restarting an animation.\n */\nfunction EffortSlider(props: {\n readonly label: string\n readonly rows: ReadonlyArray<{ id: string; name: string }>\n readonly selected: string\n readonly disabled?: boolean\n readonly busy?: boolean\n readonly onPick: (effort: string | undefined) => void\n}) {\n const { label, rows, selected, disabled = false, busy = false, onPick } = props\n const active = Math.max(0, rows.findIndex(row => row.id === selected))\n const [position, setPosition] = useState(active)\n const positionRef = useRef(position)\n // A committed selection from the owner resets the preview.\n useEffect(() => { positionRef.current = active; setPosition(active) }, [active])\n const preview = (next: number): void => {\n positionRef.current = next\n setPosition(next)\n }\n // Commit once per gesture: pointer up, key up, or leaving the control. A\n // submission already in flight must not be repeated.\n const commit = (): void => {\n if (disabled || busy) return\n const row = rows[positionRef.current]\n if (row !== undefined) onPick(row.id === '' ? undefined : row.id)\n }\n const max = Math.max(0, rows.length - 1)\n const percent = max > 0 ? Math.round((position / max) * 100) : 0\n return <div className=\"dsh-model-menu-sliderGroup\" role=\"group\" aria-label={label}>\n <div className=\"dsh-model-menu-sliderHead\">\n <span className=\"dsh-model-menu-sliderTitle\">{label}</span>\n <span className=\"dsh-model-menu-sliderValue\">{rows[position]?.name}</span>\n </div>\n <div className=\"dsh-model-menu-sliderRail\" style={{ '--_p': percent } as CSSProperties}>\n <input\n type=\"range\"\n className=\"dsh-model-menu-sliderInput\"\n min={0}\n max={max}\n step={1}\n value={position}\n disabled={disabled}\n aria-label={label}\n aria-disabled={disabled || busy || undefined}\n aria-valuetext={rows[position]?.name}\n onChange={event => {\n // Read the event target, not currentTarget: a synthetic change event may\n // carry a detached `{ value }` target, while a real range event targets\n // the input itself. Both must preview the same position.\n const value = Number((event.target as HTMLInputElement).value)\n if (Number.isFinite(value)) preview(value)\n }}\n onPointerUp={commit}\n onKeyUp={commit}\n onBlur={commit}\n />\n <span className=\"dsh-model-menu-sliderTrack\" aria-hidden=\"true\">\n <span className=\"dsh-model-menu-sliderFill\"><span className=\"dsh-model-menu-sliderFillBar\" /></span>\n <span className=\"dsh-model-menu-sliderNodes\">\n {rows.map((row, index) => (\n <span key={row.id || '__default'} data-covered={index <= position ? '' : undefined}\n className=\"dsh-model-menu-sliderNode\" style={{ '--_n': max > 0 ? Math.round((index / max) * 100) : 0 } as CSSProperties} />\n ))}\n </span>\n </span>\n <span className=\"dsh-model-menu-sliderThumb\" aria-hidden=\"true\" />\n </div>\n </div>\n}\n\n/**\n * ModelMenu styles, transcribed from the official ModelSelect.module.css (the\n * published dsh-client-ui-model-selection bundle): card capped at\n * min(360px, 100vh - 96px), 34px option cells at 13/18 with 5px 7px padding,\n * 34px root cells at 13/20, a borderless 12px search row with a clear button,\n * sticky group headings (MenuGroup's own CSS), and the l1-stroke prominent\n * elevation at portal z-index 1100. The trigger mirrors the composer's 28px\n * model pill, chevron rotating open. MenuSurface paints fill and backdrop.\n * Only allowlisted --dsw- and --ds- theme tokens may appear here — a literal\n * color is a bug.\n */\nexport const modelMenuCss = `\n.dsh-model-menu-root { min-width: 0; position: relative; display: inline-flex; }\n.dsh-model-menu-trigger {\n border-radius: var(--dsw-radius-sm);\n min-width: 0;\n max-width: min(360px, 45cqw);\n height: 28px;\n color: var(--dsw-alias-label-secondary);\n cursor: pointer;\n background: none;\n border: none;\n outline: none;\n align-items: center;\n gap: 4px;\n padding: 0 4px 0 8px;\n font-size: 13px;\n font-weight: 400;\n line-height: 20px;\n display: flex;\n}\n.dsh-model-menu-trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-trigger:focus-visible:not([data-selection-focus]) { box-shadow: 0 0 0 var(--dsw-focus-ring-width) var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }\n.dsh-model-menu-trigger:disabled { color: var(--dsw-alias-label-dimmed); cursor: default; }\n.dsh-model-menu-triggerLabel { text-overflow: ellipsis; white-space: nowrap; min-width: 0; overflow: hidden; }\n.dsh-model-menu-triggerEffort { text-overflow: ellipsis; white-space: nowrap; min-width: 0; color: var(--dsw-alias-label-caption); flex-shrink: 1000; overflow: hidden; }\n.dsh-model-menu-chevron { color: var(--dsw-alias-label-caption); flex: none; transition: transform var(--ds-transition-duration) var(--ds-ease-in-out); }\n.dsh-model-menu-chevronOpen { transform: rotate(180deg); }\n/* Portal overlay: the host publishes no z-index token, so the card keeps the\n * native menu layer's 1100 verbatim. */\n.dsh-model-menu-menu {\n z-index: 1100;\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l1);\n width: max-content;\n min-width: min(240px, 100vw - 32px);\n max-width: min(420px, 100vw - 32px);\n max-height: min(360px, 100vh - 96px);\n box-shadow: var(--dsw-elevation-prominent);\n color: var(--dsw-alias-label-primary);\n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n border: 0;\n flex-direction: column;\n padding: 4px;\n display: flex;\n position: fixed;\n overflow: hidden;\n}\n.dsh-model-menu-status, .dsh-model-menu-empty { color: var(--dsw-alias-label-tertiary); padding: 8px; font-size: 12px; line-height: 18px; }\n.dsh-model-menu-header { flex: none; padding: 2px 2px 4px; }\n.dsh-model-menu-searchRow { flex-shrink: 0; margin: 2px 0 3px; position: relative; }\n.dsh-model-menu-searchRow .dsh-model-menu-search { border-radius: var(--dsw-radius-md); background: none; border: 0 solid transparent; height: auto; padding: 5px 7px; display: flex; }\n.dsh-model-menu-searchRow .dsh-model-menu-search:focus-within { border-color: transparent; }\n.dsh-model-menu-searchWithQuery { padding-right: 34px; }\n.dsh-model-menu-searchRow .dsh-model-menu-search input { padding: 0; font-size: 12px; line-height: normal; }\n.dsh-model-menu-searchRow .dsh-model-menu-search input::placeholder { color: var(--dsw-alias-label-caption); }\n/* The clear button is a circle by geometry (border-radius: 50%), a shape the\n * radius token scale does not describe. */\n.dsh-model-menu-searchClear {\n width: 24px;\n height: 24px;\n color: var(--dsw-alias-label-secondary);\n cursor: pointer;\n background: none;\n border: none;\n border-radius: 50%;\n justify-content: center;\n align-items: center;\n padding: 0;\n display: inline-flex;\n position: absolute;\n top: 50%;\n right: 4px;\n transform: translateY(-50%);\n}\n.dsh-model-menu-searchClear:hover, .dsh-model-menu-searchClear:focus-visible { background: var(--dsw-alias-interactive-bg-hover); outline: none; }\n.dsh-model-menu-groups { min-height: 0; overflow-y: auto; }\n.dsh-model-menu-leading { border-bottom: 0.5px solid var(--dsw-alias-border-l2); margin-bottom: 3px; padding-bottom: 3px; }\n.dsh-model-menu-option {\n box-sizing: border-box;\n border-radius: var(--dsw-radius-md);\n width: auto;\n min-width: 100%;\n min-height: 34px;\n color: inherit;\n text-align: left;\n cursor: pointer;\n background: none;\n border: none;\n outline: none;\n align-items: center;\n gap: 6px;\n padding: 5px 7px;\n display: flex;\n}\n.dsh-model-menu-option:not(.dsh-model-menu-modelOption):hover:not(:disabled),\n.dsh-model-menu-option:focus-visible,\n.dsh-model-menu-optionActive:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-modelOption:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-selected { background: none; }\n.dsh-model-menu-option:disabled { color: var(--dsw-alias-label-dimmed); cursor: default; }\n.dsh-model-menu-optionCopy { flex-direction: column; flex: 1; min-width: 0; display: flex; }\n.dsh-model-menu-modelName { color: inherit; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 400; line-height: 18px; overflow: hidden; }\n.dsh-model-menu-check { color: var(--dsw-alias-label-primary); flex: 0 0 14px; place-items: center; display: grid; }\n.dsh-model-menu-check svg { width: 14px; height: 14px; }\n.dsh-model-menu-cell {\n box-sizing: border-box;\n border-radius: var(--dsw-radius-md);\n width: auto;\n min-width: 100%;\n height: 34px;\n color: var(--dsw-alias-label-primary);\n cursor: pointer;\n text-align: left;\n background: none;\n border: none;\n outline: none;\n align-items: center;\n gap: 6px;\n padding: 0 8px;\n font-size: 13px;\n line-height: 20px;\n display: flex;\n}\n.dsh-model-menu-cell:hover, .dsh-model-menu-cell:focus-visible { background: var(--dsw-alias-interactive-bg-hover); }\n.dsh-model-menu-cellLabel { white-space: nowrap; flex: none; }\n.dsh-model-menu-cellValue { text-overflow: ellipsis; white-space: nowrap; text-align: right; min-width: 0; color: var(--dsw-alias-label-tertiary); flex: auto; overflow: hidden; }\n.dsh-model-menu-cellChevron { width: 12px; height: 12px; color: var(--dsw-alias-menu-icon); flex: none; }\n/* Discrete reasoning-effort slider under the model list (enhanced mode).\n * The painted control is layered over a fully functional native range input:\n * the input stays on top, transparent, and owns pointer/keyboard/ARIA, while\n * the decorative track, fill and thumb render beneath it at pointer-events:\n * none. Position lives in one custom property (--_p, 0–100) on the rail, so\n * the only animated work a level change triggers is a clip-path/left\n * transition — no keyframes, no element churn. */\n.dsh-model-menu-sliderGroup { border-top: 0.5px solid var(--dsw-alias-border-l2); flex: none; margin-top: 4px; padding: 6px 8px 8px; }\n.dsh-model-menu-sliderHead { align-items: baseline; justify-content: space-between; gap: 8px; margin: 0 2px 4px; display: flex; }\n.dsh-model-menu-sliderTitle { color: var(--dsw-alias-label-tertiary); font-size: 12px; line-height: 18px; }\n.dsh-model-menu-sliderValue { color: var(--dsw-alias-label-primary); font-size: 13px; font-weight: 600; line-height: 20px; transition: color var(--ds-transition-duration) var(--ds-ease-in-out); }\n.dsh-model-menu-sliderRail { position: relative; direction: ltr; height: 38px; margin-top: 2px; }\n.dsh-model-menu-sliderRail:has(:disabled) { opacity: 0.45; }\n.dsh-model-menu-sliderInput {\n appearance: none;\n -webkit-appearance: none;\n box-sizing: border-box;\n border: 0;\n cursor: pointer;\n direction: ltr;\n opacity: 0;\n margin: 0;\n padding: 0;\n width: 100%;\n height: 100%;\n position: absolute;\n inset: 0;\n z-index: 1;\n touch-action: pan-y;\n}\n.dsh-model-menu-sliderInput:disabled { cursor: default; }\n/* The transparent input must keep the painted thumb's geometry: an\n * appearance:none webkit thumb defaults to 16px, which would shift the\n * end-point positions 7px off the decorative 30px disc and misplace the\n * native drag hit target. Track gets the full rail height so the whole band\n * maps to values identically. */\n.dsh-model-menu-sliderInput::-webkit-slider-runnable-track { width: 100%; height: 100%; }\n.dsh-model-menu-sliderInput::-webkit-slider-thumb { appearance: none; -webkit-appearance: none; width: 30px; height: 30px; margin: 0; }\n.dsh-model-menu-sliderInput::-moz-range-track { width: 100%; height: 100%; }\n.dsh-model-menu-sliderInput::-moz-range-thumb { width: 30px; height: 30px; margin: 0; border: 0; }\n.dsh-model-menu-sliderTrack {\n pointer-events: none;\n border-radius: 999px;\n width: 100%;\n height: 26px;\n background: var(--dsw-alias-interactive-bg-hover);\n box-shadow: inset 0 0 0 0.5px var(--dsw-alias-border-l2);\n position: absolute;\n inset-inline: 0;\n top: 50%;\n transform: translateY(-50%);\n /* No overflow:hidden — it would clip the fill's drop-shadow glow; the bar's\n * own clip-path already supplies the rounded reveal shape. */\n}\n/* The accent ramp paints the full track width once and is revealed by an\n * animated clip-path, so raising the effort unwraps more of the spectrum\n * instead of squashing the same gradient into a narrower bar. The glow lives\n * on the un-clipped parent: a filter on the clipped element itself would be\n * clipped away with it. */\n.dsh-model-menu-sliderFill {\n display: block;\n height: 100%;\n filter: drop-shadow(0 0 5px var(--dsw-alias-state-business-primary));\n transition: filter var(--ds-transition-duration) var(--ds-ease-in-out);\n}\n.dsh-model-menu-sliderInput:hover:not(:disabled) ~ .dsh-model-menu-sliderTrack .dsh-model-menu-sliderFill,\n.dsh-model-menu-sliderInput:active:not(:disabled) ~ .dsh-model-menu-sliderTrack .dsh-model-menu-sliderFill {\n filter: drop-shadow(0 0 9px var(--dsw-alias-state-business-primary));\n}\n/* The fill stops at the thumb's center, not at the track edge — at a 30px\n * thumb the end stops sit 15px in from each side, matching the node dots. */\n.dsh-model-menu-sliderFillBar {\n display: block;\n height: 100%;\n background: linear-gradient(90deg,\n var(--dsw-alias-state-business-primary),\n var(--dsw-alias-state-success-primary),\n var(--dsw-alias-state-warn-primary),\n var(--dsw-alias-state-error-primary));\n clip-path: inset(0 calc(100% - 15px - (100% - 30px) * var(--_p, 0) / 100) 0 0 round 999px);\n transition: clip-path var(--ds-transition-duration) var(--ds-ease-in-out);\n}\n/* Stop dots: one per declared row (default + every advertised effort), evenly\n * spread across the band between the two thumb-center extremes (inset 15px,\n * i.e. half the 30px thumb). --_n is 0-100 along that band. A covered dot\n * reads as a pale pin through the gradient; an uncovered one stays a neutral\n * notch on the empty track. */\n.dsh-model-menu-sliderNodes {\n pointer-events: none;\n display: block;\n position: absolute;\n inset-inline: 15px;\n inset-block: 0;\n}\n.dsh-model-menu-sliderNode {\n pointer-events: none;\n box-sizing: border-box;\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: color-mix(in srgb, var(--dsw-alias-label-secondary) 35%, transparent);\n position: absolute;\n left: calc(var(--_n, 0) * 1%);\n top: 50%;\n transform: translate(-50%, -50%);\n transition: background-color var(--ds-transition-duration) var(--ds-ease-in-out),\n transform var(--ds-transition-duration) var(--ds-ease-in-out);\n}\n.dsh-model-menu-sliderNode[data-covered] { background: color-mix(in srgb, var(--dsw-alias-label-primary) 60%, transparent); }\n.dsh-model-menu-sliderThumb {\n pointer-events: none;\n box-sizing: border-box;\n border-radius: 50%;\n width: 30px;\n height: 30px;\n background: var(--dsw-alias-button-primary-fill);\n border: 0.5px solid var(--dsw-alias-border-l4);\n box-shadow: 0 0 0 3px var(--dsw-alias-interactive-bg-hover), var(--dsw-elevation-soft);\n position: absolute;\n left: calc((100% - 30px) * var(--_p, 0) / 100);\n top: 50%;\n transform: translateY(-50%) scale(0.92);\n transition: left var(--ds-transition-duration) var(--ds-ease-in-out),\n transform var(--ds-transition-duration) var(--ds-ease-in-out),\n box-shadow var(--ds-transition-duration) var(--ds-ease-in-out);\n}\n.dsh-model-menu-sliderInput:hover:not(:disabled) ~ .dsh-model-menu-sliderThumb { transform: translateY(-50%) scale(1); }\n.dsh-model-menu-sliderInput:active:not(:disabled) ~ .dsh-model-menu-sliderThumb {\n transform: translateY(-50%) scale(1.1);\n box-shadow: 0 0 0 4px var(--dsw-alias-interactive-bg-hover), 0 0 12px var(--dsw-alias-state-business-primary);\n}\n.dsh-model-menu-sliderInput:focus-visible ~ .dsh-model-menu-sliderThumb {\n box-shadow: 0 0 0 3px var(--dsw-alias-interactive-bg-hover),\n 0 0 0 calc(3px + var(--dsw-focus-ring-width)) var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));\n}\n@media (prefers-reduced-motion: reduce) {\n .dsh-model-menu-sliderFill, .dsh-model-menu-sliderFillBar, .dsh-model-menu-sliderThumb,\n .dsh-model-menu-sliderNode, .dsh-model-menu-sliderValue { transition: none; }\n}\n`\n","/**\n * Shared `klarkxy.model-picker` Factory contract.\n *\n * `@klarkxy/dsh-model-picker` registers one root-scoped Component Factory under\n * this name: a searchable model picker with a reasoning-effort slider, built on\n * the same ModelMenu recipe this package ships. Feature plugins opt in by\n * calling `renderFactorySlot('klarkxy.model-picker', props, options)` inside a\n * slot component; when no definition is registered the renderer resolves the\n * caller's `options.fallback`, so each consumer keeps its own native menu as\n * the fallback and gains the shared picker only while the plugin is installed.\n *\n * This entry is pure types and constants — no React, no host imports — so a\n * consumer can `import type` the declaration and the input/local props without\n * depending on the business plugin at runtime. The `SlotFactoryMap` merge is\n * what makes the `renderFactorySlot`/`registerFactory` calls type-check on\n * both sides; import it for the types only.\n */\nimport type { ModelMenuChoice, ModelCatalogFailure } from './catalog.ts'\nimport type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'\n\n/** Registered Factory name — the `renderFactorySlot`/`registerFactory` key. */\nexport const MODEL_PICKER_FACTORY = 'klarkxy.model-picker'\n/** The one caller-selectable local position: the trigger rendered in place. */\nexport const MODEL_PICKER_ANCHOR_SLOT = 'anchor'\n\n/** Extra row the picker renders above the model groups (pure data; no React). */\nexport interface ModelPickerLeadingItem {\n readonly id: string\n readonly label: string\n readonly selected?: boolean\n}\n\n/** Status banner data the picker renders inside the menu header, above the groups. */\nexport interface ModelPickerStatus {\n /** Whole-request failure text; renders with a retry action. */\n readonly error?: string | null\n /** Advisory row (e.g. the saved route left the catalog); rendered warn-toned, no retry. */\n readonly warning?: string\n /** Whether the owner is loading or selecting (dims the banner). */\n readonly busy?: boolean\n /** Provider-local failures; still usable groups stay selectable. */\n readonly failures?: readonly ModelCatalogFailure[]\n /** Reload action the banner's retry buttons call. */\n readonly retry?: () => void\n}\n\n/**\n * Occurrence input (`renderFactorySlot` `props`). Everything here is data or\n * callbacks — React content travels through the `anchor` local slot instead.\n */\nexport interface ModelPickerProps {\n /** Active UI language; `'zh*'` selects the built-in Chinese copy. */\n readonly locale?: string\n /** Flat catalog choices (grouped internally by provider). */\n readonly choices: readonly ModelMenuChoice[]\n /** Current selection highlight. */\n readonly selected?: { readonly provider: string; readonly model: string }\n /** Model pick; the picker closes after the callback runs. */\n readonly onPick: (route: { provider: string; model: string }) => void\n /** Extra rows above the model groups (e.g. a \"follow default\" row). */\n readonly leading?: readonly ModelPickerLeadingItem[]\n /** Leading-row pick; `undefined` keeps the menu open. */\n readonly onPickLeading?: (id: string) => void\n /** Declared reasoning-effort rows; the slider is hidden while empty. */\n readonly efforts?: ReadonlyArray<{ id: string; name: string }>\n /** Current effort id; `''`/undefined marks the provider-default row. */\n readonly selectedEffort?: string\n /** Effort pick; the menu stays open. `undefined` = provider default. */\n readonly onPickEffort?: (effort: string | undefined) => void\n /** Disables the trigger and every menu action. */\n readonly disabled?: boolean\n /** Trigger caption; the default anchor falls back to localized \"Select model\". */\n readonly triggerLabel?: string\n /** Current effort caption shown after the trigger label (\"model · high\"). */\n readonly triggerEffortLabel?: string\n /** Extra class on the default trigger button. */\n readonly triggerClassName?: string\n /** Show a spinner instead of the chevron while a selection settles. */\n readonly busy?: boolean\n /** Extra class on the portaled menu card. */\n readonly listClassName?: string\n /** Menu opens on the searchable model pane ('model') or the root cells. */\n readonly initialPane?: 'root' | 'model'\n /** Show the search row even for a small catalog. */\n readonly alwaysShowSearch?: boolean\n /** Show the reasoning-effort slider under the model list (default true here). */\n readonly reasoningSlider?: boolean\n /** Status banner rendered inside the menu header (load failures, retry). */\n readonly status?: ModelPickerStatus\n /** Menu open-state changes; the owner may react (e.g. refresh the catalog). */\n readonly onOpenChange?: (open: boolean) => void\n /** Copy overrides; every key is optional. */\n readonly modelLabel?: string\n readonly modelValue?: string\n readonly effortLabel?: string\n readonly defaultEffortLabel?: string\n readonly searchPlaceholder?: string\n readonly emptyLabel?: string\n readonly clearSearchLabel?: string\n readonly retryLabel?: string\n}\n\n/** Props one `anchor` local component receives (plus the framework kit). */\nexport interface ModelPickerAnchorProps {\n /** Mirror of `aria-expanded`; true while the menu is open. */\n readonly open: boolean\n /** Disabled state passed down by the owner. */\n readonly disabled: boolean\n /** Whether a selection is settling; the default anchor shows a spinner. */\n readonly busy: boolean\n /** Resolved trigger caption. */\n readonly label: string\n /** Resolved effort caption appended to the caption, if any. */\n readonly effortLabel?: string\n /** Extra class on the trigger element. */\n readonly className?: string\n /** Anchored-popup marker the picker stamps on the trigger (always 'menu'). */\n readonly 'aria-haspopup'?: 'menu'\n /** Mirror of `open`, for ARIA-compliant custom anchors. */\n readonly 'aria-expanded'?: boolean\n /** Menu element id while the menu is mounted. */\n readonly 'aria-controls'?: string\n /** Resolved accessible name for the trigger. */\n readonly 'aria-label'?: string\n /** Set when the picker is disabled; custom anchors may read it instead of `disabled`. */\n readonly 'aria-disabled'?: boolean\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface SlotFactoryMap {\n /**\n * Reusable model picker: one searchable provider-grouped model list plus an\n * optional reasoning-effort slider. Consumers call `renderFactorySlot` with\n * `ModelPickerProps`; `options.slots.anchor` may supply a custom trigger\n * component typed `ModelPickerAnchorProps`, and `options.fallback` is the\n * menu rendered while no `klarkxy.model-picker` definition is registered.\n */\n 'klarkxy.model-picker': {\n scope: 'root'\n props: ModelPickerProps\n /** Occurrence inject face: the active-locale observable bound as a hook. */\n inject: { hooks: { activeLocale: HostObservable<{ active: string }> } }\n slots: {\n anchor: {\n scope: 'root'\n props: ModelPickerAnchorProps\n }\n }\n locale: 'model-picker'\n }\n }\n interface LocaleNamespaceMap {\n /** Copy owned by @klarkxy/dsh-model-picker. */\n 'model-picker':\n | 'trigger.fallback' | 'trigger.aria' | 'trigger.ariaEffort'\n | 'menu.model' | 'menu.effort' | 'effort.providerDefault'\n | 'search.placeholder' | 'search.clear' | 'search.empty' | 'empty.models'\n | 'status.loading' | 'error.action' | 'action.retry' | 'warning.unroutable'\n }\n}\n","/**\n * Optional shared model picker (`klarkxy.model-picker` Factory).\n *\n * `@klarkxy/dsh-model-picker`, when installed, registers one root-scoped\n * Component Factory under `MODEL_PICKER_FACTORY`: an enhanced model menu with\n * a searchable provider-grouped list and a reasoning-effort slider, built on\n * the same ModelMenu recipe. Consumers keep their own ModelMenu as the\n * `fallback`; when no definition is registered the renderer resolves that\n * fallback verbatim, so the shared picker is strictly opt-in and every saved\n * value keeps its existing write path.\n *\n * `renderFactorySlot` is a framework-composed prop, never a context: the\n * component a plugin registers into any slot receives it automatically, but\n * the plugin must pass it down to whichever child renders the menu (or to the\n * render callback handed to registerSessionSettingsItem).\n *\n * The Factory manages its own open state; a consumer's `open`/`onOpenChange`\n * pair belongs to the fallback menu only and must not be fed to both.\n */\nimport { useEffect, useMemo, useRef, type ReactNode } from 'react'\nimport { IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { RenderFactorySlot } from '@deepseek-ai/dsh-client-ui-slots'\nimport {\n MODEL_PICKER_FACTORY, MODEL_PICKER_ANCHOR_SLOT,\n type ModelPickerAnchorProps, type ModelPickerProps,\n} from '@klarkxy/dsh-model-route/model-picker'\n\nexport {\n MODEL_PICKER_ANCHOR_SLOT,\n MODEL_PICKER_FACTORY,\n type ModelPickerAnchorProps,\n type ModelPickerLeadingItem,\n type ModelPickerProps,\n type ModelPickerStatus,\n} from '@klarkxy/dsh-model-route/model-picker'\nexport type { RenderFactorySlot } from '@deepseek-ai/dsh-client-ui-slots'\n\n/**\n * The trigger every consumer used to hand its own ModelMenu, rebuilt as the\n * factory's `anchor` local component: identical classes and chevron, the menu\n * state coming from the occurrence's props instead of local open state.\n *\n * `ariaLabel` and `title` are the whole accessible name and tooltip (the\n * caller formats \"field: current route\" itself because the factory's resolved\n * caption may intentionally be a short name). The component identity stays\n * put across label changes — a new function would unmount the trigger, and\n * its cleanup would close a menu that `closeOnPick={false}` is keeping open.\n * The latest label, title, and `onClose` are read from refs.\n */\nexport function useModelMenuAnchor(ariaLabel: string, title?: string, onClose?: () => void): (props: ModelPickerAnchorProps) => ReactNode {\n const closeRef = useRef(onClose)\n const labelRef = useRef(ariaLabel)\n const titleRef = useRef(title)\n closeRef.current = onClose\n labelRef.current = ariaLabel\n titleRef.current = title\n return useMemo(() => {\n const ModelPickerTrigger = (props: ModelPickerAnchorProps): ReactNode => {\n /* A real unmount means the factory occurrence left (definition unloaded\n * or the row closed). `onOpenChange` only tracks user-driven opens, so\n * without this the fallback's shared open state could stay true. */\n useEffect(() => () => closeRef.current?.(), [])\n /* The factory injects its own aria set (aria-controls among them) plus\n * the caller's triggerClassName into the local component's props.\n * Forward exactly those attributes — a blanket {...props} spread would\n * leak framework props (including renderFactorySlot) onto the DOM. The\n * caller's label/title win over any injected aria-label; popup semantics\n * default to the mirror of the fallback trigger and yield to injected\n * values when present. */\n const record = props as unknown as Record<string, unknown>\n const injected: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(record)) {\n if (key.startsWith('aria-')) injected[key] = value\n }\n const extraClass = typeof record.className === 'string' ? ` ${record.className}` : ''\n return (\n <button\n type=\"button\"\n className={`dsh-model-menu-trigger${extraClass}`}\n disabled={props.disabled}\n aria-haspopup=\"menu\"\n aria-expanded={props.open}\n {...injected}\n aria-label={labelRef.current}\n title={titleRef.current}\n >\n <span className=\"dsh-model-menu-triggerLabel\">{props.label}</span>\n {props.effortLabel ? <span className=\"dsh-model-menu-triggerEffort\">{props.effortLabel}</span> : null}\n <IconChevronDownOutlineRegular className={`dsh-model-menu-chevron${props.open ? ' dsh-model-menu-chevronOpen' : ''}`} />\n </button>\n )\n }\n return ModelPickerTrigger\n }, [])\n}\n\n/**\n * Render the shared model picker while it is registered; `options.fallback`\n * whenever it is not (plugin absent, disabled, or unloaded).\n *\n * `options.anchor` is optional: the factory ships a default trigger, so only\n * consumers that need their own chrome (custom aria-label, tooltip, class)\n * pass one built with {@link useModelMenuAnchor}. The returned node is never\n * assumed to be the factory's own output — a defensive `?? fallback` covers a\n * renderer that yields null for an unregistered definition.\n */\nexport function renderModelPicker(\n renderFactorySlot: RenderFactorySlot | undefined,\n props: ModelPickerProps,\n options: {\n readonly anchor?: (props: ModelPickerAnchorProps) => ReactNode\n readonly fallback: ReactNode\n },\n): ReactNode {\n if (typeof renderFactorySlot !== 'function') return options.fallback\n const rendered = renderFactorySlot(MODEL_PICKER_FACTORY, props, {\n ...(options.anchor ? { slots: { [MODEL_PICKER_ANCHOR_SLOT]: options.anchor } } : {}),\n fallback: options.fallback,\n })\n return rendered ?? options.fallback\n}\n","/**\n * Shared \"default auxiliary model\" settings card.\n *\n * Any number of feature plugins call `registerAuxiliaryModelSettings(ctx)`\n * from their client half; a single card appears as the `auxiliary-model` row\n * of the shared Session Management settings column for as long as at least\n * one participant lives. The card is root-owned shared infrastructure, not a\n * business plugin: every bundled copy of this helper rendezvouses on the same\n * Cordis root service, so no participant depends on another being enabled, the\n * card is mounted once (duplicate row ids would throw), and the last\n * `release()` removes it. The card also retains the shared page itself, so a\n * lone auxiliary plugin still yields the column — participants never depend\n * on another business plugin providing their settings page.\n *\n * The storage side lives in the shared host service behind the plugin-kit RPC\n * channel: `defaults.get` returns `{revision, model}` and `defaults.set`\n * carries `{model, expectedRevision}` with an empty provider/model clearing\n * the override. Cross-window invalidation rides the existing model-settings\n * change stream — no polling is added anywhere in this file.\n */\nimport type { Context } from '@deepseek-ai/cordis'\nimport { Button, IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'\nimport {\n readModelCatalog, modelMenuEffortLabel, modelMenuEffortOptions, parseModelMenuChoices, type ModelRoute,\n} from '@klarkxy/dsh-model-route'\nimport { ModelCatalogStatus, ModelMenu, modelMenuCss, useModelCatalog } from '@klarkxy/dsh-model-route/ui'\nimport { officialUiCss } from './official-ui.ts'\nimport { renderModelPicker, useModelMenuAnchor, type RenderFactorySlot } from './model-picker.tsx'\nimport {\n createModelSettingsSubscriber, modelSettingsChangesRemote, type ModelSettingsSubscriber,\n} from './model-settings-client.ts'\nimport { registerSessionSettingsItem } from './client-utils.ts'\nimport {\n AUXILIARY_MODEL_CHANNEL, AUXILIARY_MODEL_CHANGES_IDENTITY, AUXILIARY_MODEL_NS,\n type AuxiliaryModelDefaults, type RpcResult,\n} from './contracts.ts'\n\nconst AUXILIARY_MODEL_PACKAGE = '@klarkxy/dsh-plugin-kit'\n\n/** The stored row; re-exported so card consumers share the contract shape. */\nexport type AuxiliaryModelSnapshot = AuxiliaryModelDefaults\n\n/* The card is one row of the shared Session Management column: the item slot\n * is a root-scope list declared by the shared page, and row ids must be\n * unique. The row sorts ahead of every business participant. */\nexport const AUXILIARY_MODEL_SEAT_ID = 'auxiliary-model'\nexport const AUXILIARY_MODEL_SEAT_ORDER = 55\n\n/** Private Cordis rendezvous; every bundled copy resolves the same root service. */\nconst AUXILIARY_MODEL_CARD_SERVICE = 'dshAuxiliaryModelSettingsCard'\n\n/** Theme-token-only stylesheet: officialUiCss scope plus the shared ModelMenu recipe. */\nexport const auxiliaryModelCss = `${officialUiCss('ams-root')}${modelMenuCss}\n.ams-root .ams-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }\n`\n\nconst auxiliaryCopy = {\n zh: {\n title: '默认辅助模型',\n help: '各辅助功能(如标题生成、摘要)没有单独指定模型时使用的模型;仅影响声明使用它的功能。',\n model: '辅助模型',\n modelDefault: '跟随会话或宿主默认',\n modelHint: '不选择模型时,各功能按自己的规则决定对话模型。',\n effortDefault: '跟随模型默认',\n loading: '正在读取设置…',\n failed: '无法读取模型设置。',\n stale: '设置已被其他窗口更新,请刷新后重试。',\n saveFailed: '保存失败,原设置未更改。请重试。',\n saved: '已保存。',\n retry: '重试',\n refresh: '刷新设置',\n syncUnavailable: '自动刷新不可用,请手动刷新设置。',\n },\n en: {\n title: 'Default Auxiliary Model',\n help: 'The model used by auxiliary features (such as title generation or summarizing) that do not name their own model; only features that opted in are affected.',\n model: 'Auxiliary model',\n modelDefault: 'Follow session or host default',\n modelHint: 'With no model selected, each feature follows its own rules for the conversation model.',\n effortDefault: 'Follow model default',\n loading: 'Loading settings…',\n failed: 'Could not load model settings.',\n stale: 'Settings were changed elsewhere; refresh and retry.',\n saveFailed: 'Save failed; the previous setting was not changed. Try again.',\n saved: 'Saved.',\n retry: 'Retry',\n refresh: 'Refresh settings',\n syncUnavailable: 'Automatic refresh unavailable; refresh settings manually.',\n },\n} as const\ntype AuxiliaryCopy = (typeof auxiliaryCopy)['zh'] | (typeof auxiliaryCopy)['en']\n\n/** A failed RPC keeps its code so the card can translate known rejections. */\nclass AuxiliaryRpcError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = 'AuxiliaryRpcError' }\n}\n\n/** The client services this card reads; the shared service passes ctx.root. */\nexport interface AuxiliaryModelClient {\n connection: {\n rpc: { call(channel: string, endpoint: string, payload: unknown): Promise<unknown> }\n generation?: { subscribe(listener: () => void): () => void }\n }\n remote?: { session?: { modelCatalog?: () => Promise<unknown> } }\n locale?: { getSnapshot(): { active: string }; subscribe(listener: () => void): () => void }\n}\n\n/** Host UI language, following live switches with the host's English fallback. */\nfunction useAuxiliaryLocale(client: AuxiliaryModelClient): 'zh' | 'en' {\n const subscribe = useCallback((listener: () => void) => client.locale?.subscribe(listener) ?? (() => {}), [client])\n const snapshot = useCallback(() => client.locale?.getSnapshot().active ?? 'en', [client])\n return String(useSyncExternalStore(subscribe, snapshot, snapshot)).startsWith('zh') ? 'zh' : 'en'\n}\n\nfunction isAbort(error: unknown): boolean {\n return error instanceof Error && (error.name === 'AbortError' || /abort|cancel/i.test(error.message))\n}\n\n/* A revision mismatch is a lost race, not a broken save: the stored row moved\n * past the one the user edited. The host reports it as auxiliary-model/conflict;\n * the message fallback covers older hosts that surfaced it as internal. */\nfunction isStaleRejection(error: unknown): boolean {\n if (!(error instanceof AuxiliaryRpcError)) return false\n return error.code === 'stale' || error.code === 'auxiliary-model/conflict'\n || /changed|revision|reload|stale|conflict/i.test(error.message)\n}\n\nasync function callAuxiliaryRpc<T>(\n client: AuxiliaryModelClient, endpoint: string, payload: unknown = {},\n): Promise<T> {\n const result = await client.connection.rpc.call(AUXILIARY_MODEL_CHANNEL, endpoint, payload) as RpcResult<T> | undefined\n if (!result || result.ok !== true) {\n const error = result && 'error' in result ? result.error : undefined\n throw new AuxiliaryRpcError(error?.code ?? 'unknown', error?.message ?? `RPC ${endpoint} failed`)\n }\n return result.value\n}\n\n/**\n * The shared card. All state comes from the shared host service over the\n * plugin-kit RPC channel; the card only renders the stored row.\n */\nexport function AuxiliaryModelCard({ client, subscribe, renderFactorySlot }: {\n client: AuxiliaryModelClient\n /** Settings-change invalidation; injected for tests without a live stream. */\n subscribe?: (change: () => void, error?: (message: string) => void) => () => void\n /** Framework-composed factory renderer; absent under direct test renders. */\n renderFactorySlot?: RenderFactorySlot\n}): ReactNode {\n const language = useAuxiliaryLocale(client)\n const text: AuxiliaryCopy = auxiliaryCopy[language]\n const [settings, setSettings] = useState<AuxiliaryModelSnapshot>()\n const loadCatalog = useCallback(() => readModelCatalog(client), [client])\n const subscribeCatalog = useCallback(\n (change: () => void) => client.connection.generation?.subscribe(change), [client])\n const catalogState = useModelCatalog(loadCatalog, { subscribe: subscribeCatalog })\n const { refresh: refreshCatalog } = catalogState\n const choices = parseModelMenuChoices(catalogState.catalog, settings?.model ?? undefined)\n const [menuOpen, setMenuOpen] = useState(false)\n const [error, setError] = useState<'' | 'failed' | 'stale' | 'saveFailed'>('')\n const [note, setNote] = useState(false)\n const [busy, setBusy] = useState(false)\n const [syncError, setSyncError] = useState('')\n const operation = useRef({ epoch: 0, active: false, reading: false, writing: false, pending: false })\n const refreshRef = useRef<() => void>(() => {})\n\n const refresh = () => {\n const state = operation.current\n if (!state.active) return\n if (state.reading || state.writing) { state.pending = true; return }\n state.pending = false; state.reading = true; setBusy(true)\n const epoch = state.epoch\n void callAuxiliaryRpc<AuxiliaryModelSnapshot>(client, 'defaults.get').then(next => {\n if (state.active && state.epoch === epoch && !state.pending) {\n setSettings(next); setError('')\n }\n }).catch(reason => {\n if (state.active && state.epoch === epoch && !state.pending && !isAbort(reason)) setError('failed')\n }).finally(() => {\n if (!state.active || state.epoch !== epoch) return\n state.reading = false; setBusy(false)\n if (state.pending) refreshRef.current()\n })\n }\n refreshRef.current = refresh\n useEffect(() => {\n const state = operation.current\n state.epoch++; state.active = true; state.reading = false; state.writing = false; state.pending = false\n setBusy(false); setSettings(undefined); setError(''); setNote(false)\n refreshRef.current()\n return () => { state.active = false; state.epoch++ }\n }, [client])\n // Cross-window invalidation rides the shared model-settings change stream.\n useEffect(() => {\n setSyncError('')\n let live = true\n let stop: (() => void) | undefined\n try {\n stop = subscribe?.(() => {\n if (live) { setSyncError(''); refreshCatalog(); refreshRef.current() }\n }, message => { if (live) setSyncError(message) })\n } catch {\n // A subscriber that cannot even attach degrades to manual refresh.\n if (live) setSyncError('Model settings sync service unavailable')\n }\n return () => { live = false; try { stop?.() } catch { /* detach is best-effort */ } }\n }, [subscribe, refreshCatalog])\n\n const save = useCallback((model: ModelRoute | null) => {\n const state = operation.current\n if (!settings || !state.active || state.writing || state.reading) return\n state.writing = true\n const epoch = state.epoch\n setBusy(true); setNote(false); setError('')\n void callAuxiliaryRpc<AuxiliaryModelSnapshot>(client, 'defaults.set', {\n model: model ?? { provider: '', model: '' },\n expectedRevision: settings.revision,\n }).then(next => {\n if (state.active && state.epoch === epoch) { setSettings(next); setNote(true); refreshCatalog() }\n }).catch(reason => {\n if (state.active && state.epoch === epoch) {\n setError(isStaleRejection(reason) ? 'stale' : 'saveFailed')\n }\n }).finally(() => {\n if (!state.active || state.epoch !== epoch) return\n state.writing = false; setBusy(false)\n if (state.pending) refreshRef.current()\n })\n }, [client, settings, refreshCatalog])\n\n const locked = busy\n const current = settings?.model ?? { provider: '', model: '' }\n const follow = !current.provider || !current.model\n const selected = follow ? undefined : choices.find(item => item.provider === current.provider && item.model === current.model)\n const efforts = follow ? [] : modelMenuEffortOptions(selected, current.reasoningEffort)\n const currentLabel = follow ? text.modelDefault : selected?.label ?? `${current.provider} / ${current.model}`\n const selectedEffort = efforts.find(item => item.id === (current.reasoningEffort || ''))\n const effortName = selectedEffort ? modelMenuEffortLabel(selectedEffort, language) : undefined\n // The shared picker's anchor mirrors the trigger the fallback menu renders.\n const anchor = useModelMenuAnchor(`${text.model}: ${settings ? currentLabel : ''}`, undefined,\n () => setMenuOpen(false))\n if (!settings) {\n return <section className=\"ams-root dsh-ui-card\" data-testid=\"auxiliary-model-settings\">\n <span className=\"dsh-ui-heading\">{text.title}</span>\n <p className=\"dsh-ui-help\">{text.help}</p>\n {error\n ? <p role=\"alert\" className=\"dsh-ui-error\">{text[error]}</p>\n : <p role=\"status\" className=\"dsh-ui-hint\">{text.loading}</p>}\n {syncError && <p role=\"status\" className=\"dsh-ui-hint\">{text.syncUnavailable}</p>}\n <div className=\"dsh-ui-actions\">\n <Button variant=\"ghost\" size=\"sm\" disabled={locked} onClick={() => refreshRef.current()}>{text.retry}</Button>\n </div>\n </section>\n }\n\n\n return <section className=\"ams-root dsh-ui-card\" data-testid=\"auxiliary-model-settings\">\n <span className=\"dsh-ui-heading\">{text.title}</span>\n <p className=\"dsh-ui-help\">{text.help}</p>\n <div className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.model}</span>\n <ModelCatalogStatus state={catalogState} locale={language} />\n {renderModelPicker(renderFactorySlot, {\n locale: language,\n disabled: locked,\n busy: locked,\n onOpenChange: next => setMenuOpen(next && !locked),\n listClassName: 'ams-root ams-menu-portal',\n choices,\n selected: follow ? undefined : { provider: current.provider, model: current.model },\n onPick: picked => save({ provider: picked.provider, model: picked.model }),\n leading: [{ id: 'default', label: text.modelDefault, selected: follow }],\n onPickLeading: () => save(null),\n efforts,\n selectedEffort: current.reasoningEffort || '',\n onPickEffort: effort => save(follow\n ? null\n : { provider: current.provider, model: current.model, ...(effort ? { reasoningEffort: effort } : {}) }),\n triggerLabel: currentLabel,\n triggerEffortLabel: !follow && efforts.length ? (effortName ?? text.effortDefault) : undefined,\n modelLabel: text.model,\n modelValue: currentLabel,\n defaultEffortLabel: text.effortDefault,\n }, {\n anchor,\n fallback: <ModelMenu\n locale={language}\n open={menuOpen && !locked}\n onOpenChange={next => setMenuOpen(next && !locked)}\n listClassName=\"ams-root ams-menu-portal\"\n anchor={<button type=\"button\" className=\"dsh-model-menu-trigger\" disabled={locked}\n aria-label={`${text.model}: ${currentLabel}`}>\n <span className=\"dsh-model-menu-triggerLabel\">{currentLabel}</span>\n {!follow && efforts.length ? <span className=\"dsh-model-menu-triggerEffort\">{effortName ?? text.effortDefault}</span> : null}\n <IconChevronDownOutlineRegular className={`dsh-model-menu-chevron${menuOpen && !locked ? ' dsh-model-menu-chevronOpen' : ''}`} />\n </button>}\n choices={choices}\n selected={follow ? undefined : { provider: current.provider, model: current.model }}\n onPick={picked => save({ provider: picked.provider, model: picked.model })}\n leading={[{ id: 'default', label: text.modelDefault, selected: follow }]}\n onPickLeading={() => save(null)}\n efforts={efforts}\n selectedEffort={current.reasoningEffort || ''}\n onPickEffort={effort => save(follow\n ? null\n : { provider: current.provider, model: current.model, ...(effort ? { reasoningEffort: effort } : {}) })}\n modelLabel={text.model}\n modelValue={currentLabel}\n defaultEffortLabel={text.effortDefault}\n />,\n })}\n <span className=\"dsh-ui-hint\">{text.modelHint}</span>\n </div>\n <div className=\"ams-row\">\n {syncError && <p role=\"status\" className=\"dsh-ui-hint\">{text.syncUnavailable}</p>}\n {error && <p role=\"alert\" className=\"dsh-ui-error\">{text[error]}</p>}\n {note && <p role=\"status\" className=\"dsh-ui-notice\">{text.saved}</p>}\n {error || syncError ? (\n <Button variant=\"ghost\" size=\"sm\" disabled={locked} onClick={() => refreshRef.current()}>{text.refresh}</Button>\n ) : null}\n </div>\n </section>\n}\n\ninterface AuxiliaryRoot {\n get(name: string, strict?: boolean): unknown\n provide(name: string, value: unknown): () => void\n inject(deps: string[], callback: (scope: unknown) => void): AuxiliaryFiber\n}\ninterface AuxiliaryFiber {\n dispose(): void | Promise<void>\n}\ninterface AuxiliaryRemoteMountScope {\n remote: { $mount(contribution: unknown): Promise<unknown> }\n effect(cb: () => () => void | Promise<void>): unknown\n}\n\n/* The client-side stream descriptor mount, serialized through one root\n * coordinator. Its tail carries mounts and unmounts in strict order: a new\n * mount cannot start while a previous fiber's unmount is in flight, and a\n * lease that closes before its continuation runs never mounts at all. The\n * coordinator leaves the store only when the queue is drained and no lease\n * is active — a fast teardown→re-acquire chains onto the same tail instead\n * of hitting \"already registered\" or overlapping a second mount. */\ninterface AuxiliaryWatchLease {\n fiber: AuxiliaryFiber | undefined\n closed: boolean\n done(): void\n}\ninterface AuxiliaryWatchCoordinator {\n tail: Promise<void>\n active: number\n mount(): AuxiliaryWatchLease\n}\nconst AUXILIARY_MODEL_WATCH_COORDINATOR = 'dshAuxiliaryModelWatchCoordinator'\n\nfunction acquireWatchCoordinator(root: AuxiliaryRoot): AuxiliaryWatchCoordinator {\n const existing = root.get(AUXILIARY_MODEL_WATCH_COORDINATOR, false) as AuxiliaryWatchCoordinator | undefined\n if (existing) return existing\n let unprovide: (() => void) | undefined\n const coordinator: AuxiliaryWatchCoordinator = {\n tail: Promise.resolve(),\n active: 0,\n mount() {\n coordinator.active += 1\n const previousTail = coordinator.tail\n const lease: AuxiliaryWatchLease = {\n closed: false,\n done() {\n if (lease.closed) return\n lease.closed = true\n coordinator.active -= 1\n const owned = lease.fiber\n lease.fiber = undefined\n // The unmount joins the tail every later mount waits on.\n coordinator.tail = coordinator.tail\n .then(() => Promise.resolve(owned?.dispose()).catch(() => {}))\n // Unprovide only once the queue is really drained: a newer lease\n // already queued on this coordinator must keep it alive.\n void coordinator.tail.then(() => {\n if (coordinator.active > 0) return\n try {\n if (root.get(AUXILIARY_MODEL_WATCH_COORDINATOR, false) === coordinator) {\n void Promise.resolve(unprovide?.()).catch(() => {})\n }\n } catch { /* Root already unloading. */ }\n })\n },\n fiber: undefined,\n }\n void previousTail.then(() => {\n // A release that beat the mount ends here: nothing mounted, nothing\n // to unmount, and the tail already moved on.\n if (lease.closed) return\n // mountModelSettingsChanges performs this exact inject/$mount pair;\n // it is repeated here only because that helper returns void and the\n // fiber must be captured for symmetric teardown.\n try {\n lease.fiber = root.inject(['remote'], injected => {\n const scope = injected as AuxiliaryRemoteMountScope\n const mounting = scope.remote.$mount(\n modelSettingsChangesRemote(AUXILIARY_MODEL_PACKAGE, AUXILIARY_MODEL_CHANGES_IDENTITY),\n ) as Promise<(() => Promise<void>) | undefined>\n void mounting.catch(() => {})\n scope.effect(() => async () => {\n const unmount = await mounting.catch(() => undefined)\n await unmount?.()\n })\n })\n } catch { /* remote unavailable: the card degrades to manual refresh */ }\n })\n return lease\n },\n }\n unprovide = root.provide(AUXILIARY_MODEL_WATCH_COORDINATOR, coordinator)\n return coordinator\n}\n\ninterface AuxiliaryCardService {\n retain(): void\n release(): void\n}\n\n/**\n * Acquire the root-owned card service, creating it on first use. One counter\n * covers participants, the seat wait and the change-stream mount: the last\n * release removes the wait, then the watch contribution, then the provider\n * itself synchronously (Cordis deletes the impl before its async disposer\n * awaits), so a later acquire sees a clean get() miss and can re-establish.\n */\nfunction acquireAuxiliaryModelCard(root: AuxiliaryRoot, ctx: Context): AuxiliaryCardService {\n const existing = root.get(AUXILIARY_MODEL_CARD_SERVICE, false) as AuxiliaryCardService | undefined\n if (existing) return existing\n let users = 0\n let styleElement: HTMLStyleElement | undefined\n let stopItem: (() => void) | undefined\n let unprovide: (() => void) | undefined\n // The client-side stream descriptor hangs off the shared root context —\n // never a plugin fiber — so the first participant's unload cannot take the\n // card's change stream down. The coordinator still unmounts it, in tail\n // order, on the last release.\n const watchLease = acquireWatchCoordinator(root).mount()\n const subscriber: ModelSettingsSubscriber = createModelSettingsSubscriber(\n ctx.root as unknown as Parameters<typeof createModelSettingsSubscriber>[0],\n AUXILIARY_MODEL_PACKAGE,\n AUXILIARY_MODEL_CHANGES_IDENTITY,\n ns => ns === AUXILIARY_MODEL_NS,\n )\n const render = (props: { renderFactorySlot?: RenderFactorySlot }) => <AuxiliaryModelCard\n client={root as unknown as AuxiliaryModelClient}\n subscribe={subscriber.subscribe}\n renderFactorySlot={props.renderFactorySlot} />\n const service: AuxiliaryCardService = {\n retain() {\n // The reservation is counted before the throwing installs, so a failure\n // lets the caller's release() undo it fully instead of leaking the service.\n users += 1\n if (styleElement === undefined && typeof document !== 'undefined') {\n styleElement = document.createElement('style')\n styleElement.setAttribute('data-plugin', 'dsh-auxiliary-model-shared')\n styleElement.textContent = auxiliaryModelCss\n document.head.appendChild(styleElement)\n }\n /* The card is a participant of the shared column too: the root-owned\n * call contributes its row AND retains the page and nav icon, which is\n * what guarantees a lone auxiliary plugin still creates the Session\n * Management section — no business plugin has to provide it. The waits\n * sit on the root context, so they live exactly as long as the card. */\n if (!stopItem) {\n stopItem = registerSessionSettingsItem(ctx.root, {\n id: AUXILIARY_MODEL_SEAT_ID,\n order: AUXILIARY_MODEL_SEAT_ORDER,\n }, render)\n }\n },\n release() {\n if (users <= 0) return\n users -= 1\n if (users > 0) return\n stopItem?.()\n stopItem = undefined\n styleElement?.remove()\n styleElement = undefined\n watchLease.done()\n // The store entry leaves synchronously, like the shared page service:\n // the next acquire must not see a stale \"already registered\" marker.\n try { void Promise.resolve(unprovide?.()).catch(() => {}) } catch { /* Root already unloading. */ }\n unprovide = undefined\n },\n }\n unprovide = root.provide(AUXILIARY_MODEL_CARD_SERVICE, service)\n return service\n}\n\n/**\n * Show the shared \"default auxiliary model\" card while the calling plugin is\n * enabled.\n *\n * `ctx` is the plugin's own client context: the card itself is retained on the\n * shared root context for as long as any participant lives, so an arbitrary\n * subset of enabled plugins yields the same single card. The mount's slot wait\n * and the change-stream contribution are owned by the root service — the first\n * participant's unload cannot take the card down. Returns a disposer; it may\n * be invoked by both ctx.effect and an explicit caller and releases at most\n * once, so a double call cannot unbalance the shared refcount.\n */\nexport function registerAuxiliaryModelSettings(ctx: Context): () => void {\n const root = ctx.root as unknown as AuxiliaryRoot\n const service = acquireAuxiliaryModelCard(root, ctx)\n try {\n service.retain()\n } catch (error) {\n // A synchronous failure (for example a duplicate row id) must not pin the\n // shared card for a participant that never joined.\n service.release()\n throw error\n }\n let disposed = false\n return () => {\n if (disposed) return\n disposed = true\n service.release()\n }\n}\n","import { defaultModelRoute, normalizeModelRoute, type ModelRoute } from '@klarkxy/dsh-model-route'\nexport { defaultModelRoute, normalizeModelRoute }\n\n/** Browser-safe contracts. Shared RPC/result types stay on @klarkxy/dsh-plugin-kit. */\nexport type { RpcResult } from '@klarkxy/dsh-plugin-kit/contracts'\n\nexport const PLUGIN_NAME = '@klarkxy/dsh-current-title'\nexport const FEATURE_ID = 'current-title'\nexport const PROVIDER_ID = '@klarkxy/dsh-current-title'\nexport const PURPOSE_ID = 'current-title.generate'\nexport const RPC_CHANNEL = '/dsh-current-title'\nexport const TITLE_CLIENT_SERVICE = 'dshCurrentTitleClient'\nexport const PROMPT_VERSION = 'current-title.v2'\n/** Feature id stamped on the auxiliary-context envelope for this call. */\nexport const TITLE_CALL_FEATURE = 'session-title'\nexport const SCHEMA_VERSION = 'title-json.v1'\nexport const CONTRACT_VERSION = 1\nexport const SETTINGS_KEY = 'current'\nexport const MAX_PROMPT_CHARS = 4000\n\nexport const DEFAULT_MAX_RECENT_MESSAGES = 8\nexport const DEFAULT_TARGET_WORDS = 5\nexport const DEFAULT_TARGET_CJK = 10\nexport const DEFAULT_MAX_INPUT_BYTES = 4096\nexport const DEFAULT_MAX_OUTPUT_TOKENS = 256\nexport const DEFAULT_TIMEOUT_MS = 60_000\nexport const DEFAULT_MAX_TITLE_BYTES = 80\n\nexport type TitleLocaleMode = 'auto' | 'zh' | 'en'\nexport type TitleSourceKind = 'fallback' | 'provider' | 'user'\n/** Automatic generation cadence: every eligible message, or only the first. */\nexport type TitleCadence = 'all-prompts' | 'first-prompt'\n\nexport interface TitleMessage {\n readonly seq: number\n readonly text: string\n}\n\nexport interface TitleSnapshot {\n readonly title: string\n readonly messageSeqs: readonly number[]\n readonly source: { readonly kind: TitleSourceKind; readonly provider?: string }\n readonly eventSeq: number\n readonly updatedAt: number\n}\n\n/**\n * Empty provider and model means the shared weak role. Both must be set together.\n * No title-only fields: the stored value is the shared ModelRoute (250/80 caps\n * live in @klarkxy/dsh-model-route). The alias keeps the title-specific name.\n */\nexport type TitleModelRoute = ModelRoute\n\nexport interface TitleSettings {\n revision: number\n locale: TitleLocaleMode\n /** Empty keeps the built-in title instruction. */\n prompt: string\n model: TitleModelRoute\n cadence: TitleCadence\n}\n\nexport interface TitleSupport {\n nativeOwner: string | null\n weOwn: boolean\n limitation?: string\n}\n\nexport interface TitleStatus {\n settings: TitleSettings\n support: TitleSupport\n session?: {\n sessionId: string\n title?: string\n sourceKind?: TitleSourceKind\n generating: boolean\n pinned: boolean\n }\n}\n\nexport interface TitleClientMarker {\n active: boolean\n}\n\nexport interface GenerateConfig {\n readonly maxRecentMessages: number\n readonly locale: TitleLocaleMode\n readonly targetWords: number\n readonly targetCjkCharacters: number\n readonly maxInputBytes: number\n readonly maxOutputTokens: number\n readonly timeoutMs: number\n readonly maxTitleBytes: number\n}\n\nexport function defaultSettings(locale: TitleLocaleMode = 'auto'): TitleSettings {\n return { revision: 0, locale, prompt: '', model: defaultModelRoute(), cadence: 'all-prompts' }\n}\n\nexport function normalizeCadence(value: unknown): TitleCadence {\n return value === 'first-prompt' ? 'first-prompt' : 'all-prompts'\n}\n\nexport function normalizePrompt(value: unknown): string {\n if (typeof value !== 'string') return ''\n return value.replace(/\\u0000/gu, '').trim().slice(0, MAX_PROMPT_CHARS)\n}\n\nexport function defaultGenerateConfig(locale: TitleLocaleMode = 'auto'): GenerateConfig {\n return {\n maxRecentMessages: DEFAULT_MAX_RECENT_MESSAGES,\n locale,\n targetWords: DEFAULT_TARGET_WORDS,\n targetCjkCharacters: DEFAULT_TARGET_CJK,\n maxInputBytes: DEFAULT_MAX_INPUT_BYTES,\n maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n maxTitleBytes: DEFAULT_MAX_TITLE_BYTES,\n }\n}\n\nexport function isTitleLocaleMode(value: unknown): value is TitleLocaleMode {\n return value === 'auto' || value === 'zh' || value === 'en'\n}\n","import type { RpcResult, TitleCadence, TitleModelRoute, TitleStatus } from './contracts.ts'\n\nexport const titleCopy = {\n zh: {\n label: '自动标题',\n groupHint: '标题模型、提示词与更新节奏',\n session: '当前会话',\n noSession: '没有打开的会话。打开一个会话后,可以在这里查看并重新生成标题。',\n pinned: '已手动命名',\n generating: '正在生成标题…',\n regenerate: '重新生成',\n locale: '类型标签语言',\n auto: '自动',\n prompt: '标题提示词',\n promptHint: '留空用内置说明,仍返回类型和摘要;离开输入框即保存。',\n loading: '正在读取标题设置…',\n model: '标题模型',\n modelDefault: '默认辅助模型',\n modelHint: '使用全局默认辅助模型;未设置时跟随当前会话模型,再回落到宿主默认对话模型。',\n cadence: '更新节奏',\n cadenceAll: '跟随当前任务(每条消息)',\n cadenceFirst: '仅首条消息',\n saved: '已保存。',\n failed: '无法读取标题设置。',\n inactive: '标题服务未接管,新消息暂时不会自动更新。',\n retry: '重试',\n externalChange: '设置已在别处修改。提示词草稿已保留,请重新加载后确认。',\n syncUnavailable: '自动刷新不可用,请手动重新加载设置。',\n reload: '重新加载(丢弃草稿)',\n defaults: '默认设置',\n },\n en: {\n label: 'Auto Title',\n groupHint: 'Title model, prompt and update cadence',\n session: 'Current session',\n noSession: 'No session is open. Open one to see its title and regenerate it here.',\n pinned: 'Renamed manually',\n generating: 'Generating title…',\n regenerate: 'Regenerate',\n locale: 'Type-label language',\n auto: 'Auto',\n prompt: 'Title prompt',\n promptHint: 'Empty uses the built-in instruction; a type and summary are still returned. Saves on blur.',\n loading: 'Loading title settings…',\n model: 'Title model',\n modelDefault: 'Default auxiliary model',\n modelHint: 'Uses the global default auxiliary model; when none is set, the current conversation model, then the host default chat model.',\n cadence: 'Update cadence',\n cadenceAll: 'Track the current task (every message)',\n cadenceFirst: 'First message only',\n saved: 'Saved.',\n failed: 'Could not read title settings.',\n inactive: 'Title generation is not active, so new messages will not rename this session.',\n retry: 'Retry',\n externalChange: 'Settings changed elsewhere. Prompt draft preserved; reload and review.',\n syncUnavailable: 'Automatic refresh unavailable; reload settings manually.',\n reload: 'Reload (discard draft)',\n defaults: 'Default settings',\n },\n} as const\n\n/** Only plugin-owned defaults are translated; model output and remote diagnostics stay intact. */\nconst titleMessages = [\n ['标题设置无效。', 'Invalid title settings.'],\n ['设置已更新,请刷新后重试。', 'Settings changed. Refresh and try again.'],\n ['无法保存标题设置。', 'Could not save title settings.'],\n ['缺少会话。', 'A session is required.'],\n ['找不到该会话。', 'Session not found.'],\n ['标题服务未就绪。', 'Title service is not ready.'],\n ['已取消。', 'Cancelled.'],\n ['标题生成失败。', 'Title generation failed.'],\n ['未知操作。', 'Unknown operation.'],\n ['缺少所需的宿主服务。', 'required host services are missing'],\n ['原生标题服务位置已被占用。', 'native title provider slot is occupied'],\n ['其他标题服务已接管;先前的服务未恢复。', 'another title provider owns the slot; previous owner was not restored'],\n [titleCopy.zh.saved, titleCopy.en.saved],\n [titleCopy.zh.failed, titleCopy.en.failed],\n] as const\n\nexport function titleMessage(message: string, locale: 'zh' | 'en'): string {\n const pair = titleMessages.find(pair => (pair as readonly string[]).includes(message))\n return pair?.[locale === 'zh' ? 0 : 1] ?? message\n}\n\n/** `undefined` draft = not edited; an empty string is a real edit (use built-in instruction). */\nexport function promptFieldValue(draft: string | undefined, saved: string): string {\n return draft ?? saved\n}\n\n/** The prompt to persist on blur, or `undefined` when nothing changed. */\nexport function promptToSave(draft: string | undefined, saved: string): string | undefined {\n if (draft === undefined) return undefined\n const next = draft.trim()\n return next === saved ? undefined : next\n}\n\nexport function shouldSkipTitleRefresh(input: { busy: boolean }): boolean {\n return input.busy\n}\n\nexport function createTitleClientWork() {\n let generation = 0\n let request = 0\n let disposed = false\n return {\n get disposed() { return disposed },\n beginLoad() {\n generation += 1\n request += 1\n return generation\n },\n captureLoad() {\n return generation\n },\n beginRequest() {\n request += 1\n return { generation, request }\n },\n isLoad(generationToken: number) {\n return !disposed && generation === generationToken\n },\n isRequest(token: { generation: number; request: number }) {\n return !disposed && generation === token.generation && request === token.request\n },\n dispose() {\n disposed = true\n generation += 1\n request += 1\n },\n }\n}\n\nexport type TitleClientWork = ReturnType<typeof createTitleClientWork>\nexport type TitleClientCall = (endpoint: string, payload?: unknown) => Promise<unknown>\n\nfunction unwrap<T>(result: RpcResult<T>): T {\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n}\n\nasync function invoke<T>(call: TitleClientCall, endpoint: string, payload?: unknown): Promise<T> {\n return unwrap(await call(endpoint, payload) as RpcResult<T>)\n}\n\nexport async function runTitleStatusLoad(input: {\n call: TitleClientCall\n sessionId?: string\n isCurrent: () => boolean\n failedMessage: string\n onStatus: (status: TitleStatus) => void\n onError: (message: string) => void\n onMarker: (status: TitleStatus | undefined) => void\n}): Promise<void> {\n try {\n const status = await invoke<TitleStatus>(\n input.call,\n 'status',\n input.sessionId ? { sessionId: input.sessionId } : {},\n )\n if (!input.isCurrent()) return\n input.onStatus(status)\n input.onMarker(status)\n } catch {\n if (!input.isCurrent()) return\n input.onMarker(undefined)\n input.onError(input.failedMessage)\n }\n}\n\nexport async function runTitleRegenerateFlow(input: {\n call: TitleClientCall\n sessionId: string\n isCurrent: () => boolean\n failedMessage: string\n onBusy: (busy: boolean) => void\n onStatus: (status: TitleStatus) => void\n onError: (message: string) => void\n onMarker: (status: TitleStatus | undefined) => void\n}): Promise<void> {\n if (!input.sessionId || !input.isCurrent()) return\n input.onBusy(true)\n try {\n await invoke(input.call, 'regenerate', { sessionId: input.sessionId })\n if (!input.isCurrent()) return\n const status = await invoke<TitleStatus>(input.call, 'status', { sessionId: input.sessionId })\n if (!input.isCurrent()) return\n input.onStatus(status)\n input.onMarker(status)\n } catch (cause) {\n if (!input.isCurrent()) return\n input.onError(cause instanceof Error ? cause.message : input.failedMessage)\n } finally {\n if (!input.isCurrent()) return\n input.onBusy(false)\n }\n}\n\nexport async function runTitleSettingsSave(input: {\n call: TitleClientCall\n prompt?: string\n model?: TitleModelRoute\n cadence?: TitleCadence\n expectedRevision: number\n isCurrent: () => boolean\n savedMessage: string\n failedMessage: string\n onBusy: (busy: boolean) => void\n onSettings: (settings: TitleStatus['settings']) => void\n onNote: (note: string) => void\n onError: (message: string) => void\n}): Promise<void> {\n input.onBusy(true)\n try {\n const settings = await invoke<TitleStatus['settings']>(input.call, 'settings', {\n ...(input.prompt !== undefined ? { prompt: input.prompt } : {}),\n ...(input.model !== undefined ? { model: input.model } : {}),\n ...(input.cadence !== undefined ? { cadence: input.cadence } : {}),\n expectedRevision: input.expectedRevision,\n })\n if (!input.isCurrent()) return\n input.onSettings(settings)\n input.onNote(input.savedMessage)\n } catch (cause) {\n if (!input.isCurrent()) return\n input.onError(cause instanceof Error ? cause.message : input.failedMessage)\n } finally {\n if (!input.isCurrent()) return\n input.onBusy(false)\n }\n}\n","import type { TitleClientMarker, TitleStatus } from './contracts.ts'\n\nexport function createTitleClientMarker(): TitleClientMarker {\n return { active: false }\n}\n\nexport function applyMarkerFromStatus(marker: TitleClientMarker, status: Pick<TitleStatus, 'support'> | undefined, live: boolean): void {\n if (!live) return\n marker.active = status?.support.weOwn === true\n}\n\nexport function disposeTitleClientMarker(marker: TitleClientMarker): void {\n marker.active = false\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type { NativeSurfaceClient } from '@klarkxy/dsh-plugin-kit/client-utils'\nimport { createPluginReadGate, registerSessionSettingsItem, useFeatureRefresh, useNativeSeat } from '@klarkxy/dsh-plugin-kit/client-utils'\nimport { Button, IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { officialUiCss } from '@klarkxy/dsh-plugin-kit/official-ui'\nimport { modelSettingsChangesIdentity } from '@klarkxy/dsh-plugin-kit/contracts'\nimport { createModelSettingsSubscriber, mountModelSettingsChanges } from '@klarkxy/dsh-plugin-kit/model-settings-client'\nimport { registerAuxiliaryModelSettings } from '@klarkxy/dsh-plugin-kit/auxiliary-model-client'\nimport {\n MODEL_CATALOG_INJECT, readModelCatalog, modelMenuEffortLabel, modelMenuEffortOptions, parseModelMenuChoices,\n} from '@klarkxy/dsh-model-route'\nimport { ModelCatalogStatus, ModelMenu, modelMenuCss, useModelCatalog } from '@klarkxy/dsh-model-route/ui'\nimport { renderModelPicker, useModelMenuAnchor, type RenderFactorySlot } from '@klarkxy/dsh-plugin-kit/model-picker'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { RPC_CHANNEL, TITLE_CLIENT_SERVICE, type RpcResult, type TitleCadence, type TitleModelRoute, type TitleStatus } from './contracts.ts'\nimport {\n createTitleClientWork, promptFieldValue, promptToSave, runTitleRegenerateFlow, runTitleSettingsSave, runTitleStatusLoad,\n shouldSkipTitleRefresh, titleCopy, titleMessage, type TitleClientCall, type TitleClientWork,\n} from './client-work.ts'\nimport { applyMarkerFromStatus, createTitleClientMarker, disposeTitleClientMarker } from './marker.ts'\n\nexport const name = 'dsh-current-title-client'\nexport const inject = ['slots', 'connection', ...MODEL_CATALOG_INJECT, 'sessions', 'locale', 'uiWorkspace', 'uiSession'] as const\nexport { createTitleClientMarker, disposeTitleClientMarker, applyMarkerFromStatus }\n\ntype Client = NativeSurfaceClient & {\n connection: NonNullable<NativeSurfaceClient['connection']> & {\n rpc: { call(channel: string, endpoint: string, payload: unknown): Promise<unknown> }\n }\n remote?: { session?: { modelCatalog?: () => Promise<unknown> } }\n}\n\nexport function TitleSettings(props: {\n client: Client\n marker: { active: boolean }\n subscribeSettings?: (change: () => void, error?: (message: string) => void) => () => void\n /** Framework-composed factory renderer; absent under direct test renders. */\n renderFactorySlot?: RenderFactorySlot\n}) {\n const seat = useNativeSeat(props.client)\n const sessionId = seat.sessionId\n const text = titleCopy[seat.locale]\n // Async work stores canonical defaults; translation belongs to the current render.\n const messages = titleCopy.en\n const [status, setStatus] = useState<TitleStatus>()\n const [busy, setBusy] = useState(false)\n const [note, setNote] = useState('')\n const [error, setError] = useState('')\n // undefined = not edited; '' is a deliberate clear (built-in instruction).\n const [prompt, setPrompt] = useState<string | undefined>(undefined)\n const loadCatalog = useCallback(() => readModelCatalog(props.client), [props.client])\n const subscribeCatalog = useCallback((change: () => void) => props.client.connection.generation?.subscribe(change), [props.client])\n const catalogState = useModelCatalog(loadCatalog, { subscribe: subscribeCatalog })\n const { refresh: refreshCatalog } = catalogState\n const choices = parseModelMenuChoices(catalogState.catalog, status?.settings?.model)\n const [menuOpen, setMenuOpen] = useState(false)\n const [externalChange, setExternalChange] = useState(false)\n const [syncError, setSyncError] = useState('')\n const [loadingSettings, setLoadingSettings] = useState(true)\n const dirty = useRef(false)\n const external = useRef(false)\n const reading = useRef(false)\n const pending = useRef(false)\n const syncRef = useRef<() => void>(() => {})\n const workRef = useRef<TitleClientWork>(undefined)\n if (!workRef.current) workRef.current = createTitleClientWork()\n const work = workRef.current\n const readGateRef = useRef<ReturnType<typeof createPluginReadGate>>(undefined)\n if (!readGateRef.current) readGateRef.current = createPluginReadGate()\n const readGate = readGateRef.current\n const busyRef = useRef(busy)\n busyRef.current = busy\n const changeBusy = (value: boolean) => {\n busyRef.current = value; setBusy(value)\n if (!value && pending.current) syncRef.current()\n }\n\n const call: TitleClientCall = (endpoint, payload = {}) => (\n props.client.connection.rpc.call(RPC_CHANNEL, endpoint, payload)\n )\n const readCall: TitleClientCall = (endpoint, payload) => readGate.run(() => call(endpoint, payload))\n\n function commitMarker(next: TitleStatus | undefined) {\n applyMarkerFromStatus(props.marker, next, true)\n }\n\n useEffect(() => () => { readGate.reset(); work.dispose() }, [work, readGate])\n useEffect(() => props.client.connection.generation?.subscribe(() => {\n readGate.reset()\n work.beginLoad()\n reading.current = false\n setLoadingSettings(false)\n busyRef.current = false\n setBusy(false)\n }), [props.client, work, readGate])\n\n useEffect(() => {\n const generation = work.beginLoad()\n reading.current = true; pending.current = false\n setLoadingSettings(true)\n readGate.reset()\n const isCurrent = () => work.isLoad(generation)\n setBusy(false)\n setError('')\n setNote('')\n void runTitleStatusLoad({\n call: readCall,\n sessionId: sessionId || undefined,\n isCurrent,\n failedMessage: messages.failed,\n onStatus: next => { if (!pending.current) setStatus(current => current && external.current ? { ...next, settings: current.settings } : next) },\n onError: message => { if (!pending.current) setError(message) },\n onMarker: commitMarker,\n }).finally(() => {\n if (!work.isLoad(generation)) return\n reading.current = false\n setLoadingSettings(false)\n if (pending.current) syncRef.current()\n })\n return () => { if (work.isLoad(generation)) work.beginLoad() }\n }, [props.client, props.marker, sessionId, work])\n\n const refreshStatus = useCallback(() => {\n if (!readGate.canRead() || shouldSkipTitleRefresh({ busy: busyRef.current }) || work.disposed) return\n if (reading.current) return\n reading.current = true\n setLoadingSettings(true)\n readGate.reset()\n const token = work.beginRequest()\n void runTitleStatusLoad({\n call: readCall,\n sessionId: sessionId || undefined,\n isCurrent: () => work.isRequest(token) && !shouldSkipTitleRefresh({ busy: busyRef.current }),\n failedMessage: messages.failed,\n onStatus: next => {\n if (pending.current || shouldSkipTitleRefresh({ busy: busyRef.current })) return\n setStatus(current => current && external.current ? { ...next, settings: current.settings } : next)\n setError('')\n },\n onError: message => { if (!pending.current) setError(message) },\n onMarker: next => {\n if (!next || shouldSkipTitleRefresh({ busy: busyRef.current })) return\n commitMarker(next)\n },\n }).finally(() => {\n if (!work.isRequest(token)) return\n reading.current = false\n setLoadingSettings(false)\n if (pending.current) syncRef.current()\n })\n }, [props.client, props.marker, sessionId, work])\n\n useFeatureRefresh(\n props.client,\n sessionId,\n refreshStatus,\n status?.session?.generating === true && !busy,\n Boolean(sessionId),\n )\n syncRef.current = () => {\n if (work.disposed) return\n if (reading.current || busyRef.current) { pending.current = true; return }\n pending.current = false\n if (dirty.current) { external.current = true; setExternalChange(true); return }\n readGate.reset(); refreshStatus()\n }\n useEffect(() => {\n setSyncError('')\n let live = true\n const stop = props.subscribeSettings?.(() => {\n if (!live) return\n setSyncError('')\n refreshCatalog()\n if (dirty.current && !busyRef.current) { external.current = true; setExternalChange(true) }\n syncRef.current()\n }, message => { if (live) setSyncError(message) })\n return () => { live = false; stop?.() }\n }, [props.subscribeSettings, props.client, refreshCatalog])\n\n const savedPrompt = status?.settings?.prompt ?? ''\n const savedModel = status?.settings?.model ?? { provider: '', model: '' }\n const follow = !savedModel.provider || !savedModel.model\n const selectedModel = follow ? undefined : choices.find(choice => choice.provider === savedModel.provider && choice.model === savedModel.model)\n const efforts = follow ? [] : modelMenuEffortOptions(selectedModel, savedModel.reasoningEffort)\n const currentLabel = follow ? text.modelDefault : selectedModel?.label ?? `${savedModel.provider} / ${savedModel.model}`\n const selectedEffort = efforts.find(item => item.id === (savedModel.reasoningEffort || ''))\n const effortName = selectedEffort ? modelMenuEffortLabel(selectedEffort, seat.locale) : undefined\n const anchor = useModelMenuAnchor(`${text.model}: ${currentLabel}`, undefined, () => setMenuOpen(false))\n const title = status?.session?.title\n const pinned = status?.session?.pinned === true\n const weOwn = status?.support?.weOwn === true\n const canRegenerate = Boolean(sessionId) && weOwn && !busy && !loadingSettings\n\n function saveSettings(patch: { model?: TitleModelRoute; cadence?: TitleCadence }) {\n if (!status || busyRef.current || reading.current || external.current) return\n readGate.reset()\n const token = work.beginRequest()\n setError('')\n setNote('')\n void runTitleSettingsSave({\n call,\n ...patch,\n expectedRevision: status.settings.revision,\n isCurrent: () => work.isRequest(token),\n savedMessage: messages.saved,\n failedMessage: messages.failed,\n onBusy: changeBusy,\n onSettings: settings => setStatus(current => current ? { ...current, settings } : current),\n onNote: setNote,\n onError: setError,\n })\n }\n\n return <section className=\"current-title-settings ct-root\" lang={seat.locale} data-testid=\"current-title-settings\">\n {!status && !error ? <p role=\"status\" className=\"dsh-ui-hint\">{text.loading}</p> : null}\n <article className=\"dsh-ui-card\" data-testid=\"current-title-session\">\n <h3 className=\"dsh-ui-heading\">{text.session}</h3>\n {title\n ? <p translate=\"no\" className=\"dsh-ui-title dsh-ui-wrap\">{title}</p>\n : <p className=\"dsh-ui-hint\">{text.noSession}</p>}\n {pinned ? <p className=\"dsh-ui-meta\">{text.pinned}</p> : null}\n {status?.session?.generating ? <p role=\"status\" className=\"dsh-ui-hint\">{text.generating}</p> : null}\n {status && !weOwn ? <p role=\"status\" className=\"dsh-ui-hint\">{text.inactive}{status.support?.limitation ? ` ${titleMessage(status.support.limitation, seat.locale)}` : ''}</p> : null}\n {error ? <>\n <p role=\"alert\" className=\"dsh-ui-error dsh-ui-wrap\">{titleMessage(error, seat.locale)}</p>\n <Button variant=\"outline\" size=\"sm\" disabled={busy} onClick={() => { readGate.reset(); refreshStatus() }}>\n {text.retry}\n </Button>\n </> : null}\n {note ? <p role=\"status\" className=\"dsh-ui-notice\">{titleMessage(note, seat.locale)}</p> : null}\n {externalChange ? <p role=\"alert\" className=\"dsh-ui-error\">{text.externalChange}</p> : null}\n {syncError ? <p role=\"status\" className=\"dsh-ui-hint\">{text.syncUnavailable}</p> : null}\n <div className=\"dsh-ui-actions\">\n <Button variant=\"ghost\" size=\"sm\" disabled={busy || loadingSettings} onClick={() => {\n setPrompt(undefined); dirty.current = false; external.current = false; setExternalChange(false)\n readGate.reset(); syncRef.current()\n }}>{text.reload}</Button>\n {sessionId ? <Button variant=\"outline\" size=\"md\" disabled={!canRegenerate}\n onClick={() => {\n if (!sessionId) return\n readGate.reset()\n const token = work.beginRequest()\n setError('')\n setNote('')\n void runTitleRegenerateFlow({\n call,\n sessionId,\n isCurrent: () => work.isRequest(token),\n failedMessage: messages.failed,\n onBusy: changeBusy,\n onStatus: setStatus,\n onError: setError,\n onMarker: commitMarker,\n })\n }}>{text.regenerate}</Button> : null}\n </div>\n </article>\n <section className=\"dsh-ui-section\" data-testid=\"current-title-defaults\">\n <h3 className=\"dsh-ui-heading\">{text.defaults}</h3>\n <label className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.prompt}</span>\n <textarea\n className=\"dsh-ui-textarea ct-prompt\"\n value={status ? promptFieldValue(prompt, savedPrompt) : ''}\n maxLength={4000}\n rows={5}\n disabled={busy || loadingSettings || !status}\n onChange={event => { dirty.current = true; setPrompt(event.target.value); setNote('') }}\n onBlur={() => {\n if (!status || busyRef.current || reading.current || external.current) return\n const next = promptToSave(prompt, savedPrompt)\n if (next === undefined) { dirty.current = false; setPrompt(undefined); return }\n readGate.reset()\n const token = work.beginRequest()\n setError('')\n void runTitleSettingsSave({\n call,\n prompt: next,\n expectedRevision: status.settings.revision,\n isCurrent: () => work.isRequest(token),\n savedMessage: messages.saved,\n failedMessage: messages.failed,\n onBusy: changeBusy,\n onSettings: settings => { setStatus(current => current ? { ...current, settings } : current); dirty.current = false; setPrompt(undefined) },\n onNote: setNote,\n onError: setError,\n })\n }}\n />\n <span className=\"dsh-ui-help\">{text.promptHint}</span>\n </label>\n <div className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.model}</span>\n <ModelCatalogStatus state={catalogState} locale={seat.locale} />\n {renderModelPicker(props.renderFactorySlot, {\n locale: seat.locale,\n disabled: busy || loadingSettings || !status,\n busy: busy || loadingSettings,\n onOpenChange: next => setMenuOpen(next && Boolean(status) && !busy && !loadingSettings),\n listClassName: 'ct-root',\n choices,\n selected: follow ? undefined : { provider: savedModel.provider, model: savedModel.model },\n onPick: picked => saveSettings({ model: { provider: picked.provider, model: picked.model } }),\n leading: [{ id: 'default', label: text.modelDefault, selected: follow }],\n onPickLeading: () => saveSettings({ model: { provider: '', model: '' } }),\n efforts,\n selectedEffort: savedModel.reasoningEffort || '',\n onPickEffort: effort => saveSettings({ model: follow\n ? { provider: '', model: '' }\n : { provider: savedModel.provider, model: savedModel.model, ...(effort ? { reasoningEffort: effort } : {}) } }),\n triggerLabel: currentLabel,\n triggerEffortLabel: !follow && efforts.length ? (effortName ?? text.modelDefault) : undefined,\n modelLabel: text.model,\n modelValue: currentLabel,\n defaultEffortLabel: text.modelDefault,\n }, {\n anchor,\n fallback: <ModelMenu\n locale={seat.locale}\n open={menuOpen && Boolean(status) && !busy && !loadingSettings}\n onOpenChange={next => setMenuOpen(next && Boolean(status) && !busy && !loadingSettings)}\n listClassName=\"ct-root\"\n anchor={<button type=\"button\" className=\"dsh-model-menu-trigger\" disabled={busy || loadingSettings || !status} aria-label={`${text.model}: ${currentLabel}`}>\n <span className=\"dsh-model-menu-triggerLabel\">{currentLabel}</span>\n {!follow && efforts.length ? <span className=\"dsh-model-menu-triggerEffort\">{effortName ?? text.modelDefault}</span> : null}\n <IconChevronDownOutlineRegular className={`dsh-model-menu-chevron${menuOpen ? ' dsh-model-menu-chevronOpen' : ''}`} />\n </button>}\n choices={choices}\n selected={follow ? undefined : { provider: savedModel.provider, model: savedModel.model }}\n onPick={picked => saveSettings({ model: { provider: picked.provider, model: picked.model } })}\n leading={[{ id: 'default', label: text.modelDefault, selected: follow }]}\n onPickLeading={() => saveSettings({ model: { provider: '', model: '' } })}\n efforts={efforts}\n selectedEffort={savedModel.reasoningEffort || ''}\n onPickEffort={effort => saveSettings({ model: follow\n ? { provider: '', model: '' }\n : { provider: savedModel.provider, model: savedModel.model, ...(effort ? { reasoningEffort: effort } : {}) } })}\n modelLabel={text.model}\n modelValue={currentLabel}\n defaultEffortLabel={text.modelDefault}\n />,\n })}\n <p className=\"dsh-ui-meta\">{text.modelHint}</p>\n </div>\n <label className=\"dsh-ui-field\">\n <span className=\"dsh-ui-label\">{text.cadence}</span>\n <select\n className=\"dsh-ui-select\"\n value={status?.settings?.cadence ?? 'all-prompts'}\n disabled={busy || loadingSettings || !status}\n onChange={event => {\n saveSettings({ cadence: event.target.value === 'first-prompt' ? 'first-prompt' : 'all-prompts' })\n }}\n >\n <option value=\"all-prompts\">{text.cadenceAll}</option>\n <option value=\"first-prompt\">{text.cadenceFirst}</option>\n </select>\n </label>\n </section>\n </section>\n}\n\n/**\n * The settings row: a named native details group. The content mounts\n * on the first expand only — the shared page must not fire every plugin's\n * model/status requests — and stays mounted afterwards so a collapsed group\n * never drops an unsaved prompt draft or an in-flight write.\n */\nexport function TitleSettingsItem(props: {\n client: Client\n marker: { active: boolean }\n subscribeSettings?: (change: () => void, error?: (message: string) => void) => () => void\n /** Framework-composed factory renderer; absent under direct test renders. */\n renderFactorySlot?: RenderFactorySlot\n}) {\n const seat = useNativeSeat(props.client)\n const text = titleCopy[seat.locale]\n const [visited, setVisited] = useState(false)\n return (\n <details\n className=\"ct-root ct-item\"\n lang={seat.locale}\n data-testid=\"current-title-settings-item\"\n onToggle={event => { if ((event.currentTarget as HTMLDetailsElement).open) setVisited(true) }}\n >\n <summary className=\"ct-item-summary\">\n <span>\n <span className=\"ct-item-title\">{text.label}</span>\n <span className=\"ct-item-desc\">{text.groupHint}</span>\n </span>\n <IconChevronDownOutlineRegular className=\"ct-item-chevron\" aria-hidden=\"true\" />\n </summary>\n {visited ? (\n <div className=\"ct-item-body\">\n <TitleSettings client={props.client} marker={props.marker} subscribeSettings={props.subscribeSettings}\n renderFactorySlot={props.renderFactorySlot} />\n </div>\n ) : null}\n </details>\n )\n}\n\n/* The contract owns every type tier, the field rhythm, the focus ring, the\n * select shell and the textarea shell. The only geometry left here is this\n * panel's own: its reading width, a taller prompt box, and the settings\n * group's row geometry (mirroring the native item rows: 16px padding, a 0.5px\n * l2 rule the shell drops on the last item, 24px label-control gutter). */\nexport const currentTitleOwnCss = `\n.ct-root .ct-prompt { min-height: 96px; }\n.ct-root.ct-item { padding: 0; border-bottom: 0.5px solid var(--dsw-alias-border-l2); }\n.ct-root .ct-item-summary { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 16px 0; list-style: none; cursor: pointer; }\n.ct-root .ct-item-summary::-webkit-details-marker { display: none; }\n.ct-root .ct-item-summary > span:first-child { min-width: 0; }\n.ct-root .ct-item-title { display: block; font-size: 14px; line-height: 20px; color: var(--dsw-alias-label-primary); }\n.ct-root .ct-item-desc { display: block; margin-top: 4px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }\n.ct-root .ct-item-chevron { width: 14px; height: 14px; color: var(--dsw-alias-label-secondary); transition: transform 0.15s ease; }\n.ct-root.ct-item[open] > .ct-item-summary .ct-item-chevron { transform: rotate(180deg); }\n.ct-root .ct-item-body { padding: 0 0 16px; }\n`\nexport const currentTitleStyles = `${officialUiCss('ct-root')}${modelMenuCss}${currentTitleOwnCss}`\nconst styles = currentTitleStyles\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context { dshCurrentTitleClient: { active: boolean } }\n}\n\nexport function apply(ctx: Context): void {\n const client = ctx as unknown as Client\n const packageName = '@klarkxy/dsh-current-title'\n mountModelSettingsChanges(ctx, packageName)\n const settingsSubscriber = createModelSettingsSubscriber(ctx, packageName, modelSettingsChangesIdentity(packageName))\n const subscribeSettings = (change: () => void, error?: (message: string) => void) => settingsSubscriber.subscribe(change, error)\n const marker = createTitleClientMarker()\n ctx.provide(TITLE_CLIENT_SERVICE, marker)\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const style = document.createElement('style')\n style.setAttribute('data-plugin', name)\n style.textContent = styles\n document.head.appendChild(style)\n return () => style.remove()\n }, 'current-title.styles')\n // The settings group is one row on the shared Session Management page; the\n // page is root-owned shared infrastructure, so this plugin contributes only\n // its row and never depends on another plugin.\n ctx.effect(() => registerSessionSettingsItem(\n ctx,\n { id: 'current-title', order: 70 },\n // A slot component never receives `ctx`: the host composes its own props, and a\n // Cordis context throws on any undeclared property read (so feeding one back\n // through `useNativeSeat` crashed the entry and abdicated its keyed cell).\n // The client and marker stay in the apply closure instead.\n slotProps => <TitleSettingsItem client={client} marker={marker} subscribeSettings={subscribeSettings}\n renderFactorySlot={(slotProps as { renderFactorySlot?: RenderFactorySlot } | undefined)?.renderFactorySlot} />,\n ), 'current-title.settings')\n // The shared \"default auxiliary model\" card is root-owned infrastructure:\n // this plugin retains one share while enabled and the card unloads with the\n // last participant, never depending on another plugin.\n ctx.effect(() => registerAuxiliaryModelSettings(ctx), 'current-title.auxiliary-model')\n ctx.effect(() => {\n let live = true\n void client.connection.rpc.call(RPC_CHANNEL, 'status', {}).then(result => {\n const row = result as RpcResult<TitleStatus>\n if (!live) return\n applyMarkerFromStatus(marker, row?.ok ? row.value : undefined, live)\n }).catch(() => { if (live) applyMarkerFromStatus(marker, undefined, live) })\n return () => { live = false; disposeTitleClientMarker(marker) }\n }, 'current-title.marker')\n}\n"],"mappings":";;;;;;;AAsBA,MAAa,uBAAuB,CAAC,UAAU,gBAAgB;AAe/D,SAAS,SAAS,OAAqD;CACrE,OAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAI,QAAmC,KAAA;AAC1G;AAEA,SAAS,OAAO,OAAoC;CAClD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,IAAI,MAAM,KAAK,IAAI,KAAA;AACpE;;AAGA,SAAgB,yBAAyB,OAAwB;CAC/D,IAAI,iBAAiB,SAAS,MAAM,SAAS,OAAO,MAAM;CAE1D,OAAO,OADK,SAAS,KACL,CAAC,EAAE,OAAO,KAAK,OAAO,KAAK,KAAK;AAClD;;;;;;AAOA,SAAgB,oBAAoB,OAAyB;CAC3D,MAAM,WAAW,SAAS,KAAK;CAC/B,IAAI,UAAU,OAAO,OAAO,MAAM,IAAI,MAAM,yBAAyB,SAAS,SAAS,QAAQ,CAAC;CAChG,MAAM,OAAO,UAAU,OAAO,OAAO,SAAS,SAAS,KAAK,IAAI;CAChE,MAAM,aAAa,UAAyB;EAAE,MAAM,IAAI,MAAM,0BAA0B,MAAM,EAAE;CAAE;CAClG,IAAI,CAAC,QAAQ,CAAC,MAAM,QAAQ,KAAK,MAAM,GAAG,OAAO,UAAU,yBAAyB;CACpF,KAAK,MAAM,SAAS,KAAK,QAAQ;EAC/B,MAAM,QAAQ,SAAS,KAAK;EAC5B,IAAI,CAAC,SAAS,CAAC,OAAO,MAAM,EAAE,KAAK,CAAC,MAAM,QAAQ,MAAM,MAAM,GAAG,OAAO,U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