/** * Session-scoped model and reasoning-effort control for the DSH composer model seat. * * The control deliberately follows DSH's own session model-selection contract: * `sessions.models()` supplies the exact current route and its adapter-owned * effort metadata; `sessions.selectModel()` submits the complete selection for * the next assembled turn. The slider adapts to whatever effort levels the * current model exposes — their count and order are the adapter's, never * assumed here. * * @module dsh-model-selector/client */ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent } from 'react' import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import type { SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type { ModelSelection, SessionId } from '@deepseek-ai/dsh-api-remotes/client' import type { ModelDirectory, ModelDirectoryResolver, ModelDirectoryState, } from '@deepseek-ai/dsh-client-ui-model-selection/client' import { CSS } from './styles' /** One selectable effort exactly as the owning adapter advertised it. */ interface EffortLevel { readonly id: string readonly name: string } interface ModelSeatProps { readonly locked: boolean readonly available: boolean readonly controller: ModelDirectory readonly directory: SnapshotStore readonly load: () => void readonly select: (selection: ModelSelection) => Promise readonly connection?: StatsConnection readonly useSession?: (selector: (snapshot: { nodes?: readonly GlmLimitNode[] }) => T) => T } /** Minimal wire faces for the token-stats reader (sessions + host + settings domain). */ interface StatsConnection { readonly api: { readonly sessions: { list(req: { cursor?: string }): Promise> history(req: { sessionId: string; beforeSeq?: number; maxMessages?: number }): Promise> } readonly host: { describe(req: {}): Promise> openPath(req: { path: string }): Promise> } readonly settings: { describe(req: {}): Promise | null; revision: number }> }>> update(req: { ns: string; patch: object }): Promise> openDocument(req: {}): Promise> } } } interface StatsRpc { readonly result: { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: { readonly code: string; readonly message: string } } } interface StatsSession { readonly sessionId: string readonly updatedAt: number } interface StatsHistoryEntry { readonly event: { readonly type: string; readonly seq: number; readonly time: number; readonly data: unknown } } const SLOT = 'conversation.input.model' const SETTINGS_SLOT = 'settings.general.item' const ENABLED_STORAGE_KEY = 'dsh-model-selector.enabled' export const inject = ['slots', 'modelDirectories'] function readEnabledPreference(): boolean { try { const stored = window.localStorage.getItem(ENABLED_STORAGE_KEY) return stored !== 'false' } catch { return true } } let enabledPreference = readEnabledPreference() const enabledListeners = new Set<() => void>() const enabledStore = { getSnapshot: () => enabledPreference, subscribe: (listener: () => void) => { enabledListeners.add(listener) return () => enabledListeners.delete(listener) }, set: (enabled: boolean, persist = true) => { if (enabledPreference === enabled) return enabledPreference = enabled if (persist) { try { window.localStorage.setItem(ENABLED_STORAGE_KEY, String(enabled)) } catch { // The current page still follows the choice when storage is unavailable. } } enabledListeners.forEach((listener) => listener()) }, } // --------------------------------------------------------------------------- // 插件总开关(新语义):控制整个插件的功能 UI(模型浮窗 / 定时发送 / // 待发队列 / Token 统计)。与旧的 enabledStore(原"推理强度滑块"开关) // 解耦:旧值迁移为滑块开关,总开关默认开启;设置 → 插件 的插件卡永远 // 保留,因此总开关关闭也不会失去配置入口。 // --------------------------------------------------------------------------- const PLUGIN_ENABLED_STORAGE_KEY = 'dsh-model-selector.plugin-enabled' function readPluginEnabled(): boolean { try { return window.localStorage.getItem(PLUGIN_ENABLED_STORAGE_KEY) !== 'false' } catch { return true } } let pluginEnabled = readPluginEnabled() const pluginEnabledListeners = new Set<() => void>() const pluginStore = { getSnapshot: () => pluginEnabled, subscribe: (listener: () => void) => { pluginEnabledListeners.add(listener) return () => pluginEnabledListeners.delete(listener) }, set: (enabled: boolean, persist = true) => { if (pluginEnabled === enabled) return pluginEnabled = enabled if (persist) { try { window.localStorage.setItem(PLUGIN_ENABLED_STORAGE_KEY, String(enabled)) } catch { // The current page still follows the choice when storage is unavailable. } } pluginEnabledListeners.forEach((listener) => listener()) }, } // --------------------------------------------------------------------------- // 推理强度滑块开关(由旧 enabledStore 语义迁移而来):只控制模型浮窗内 // 滑块的显隐。默认值继承旧 key(dsh-model-selector.enabled 系列)。 // --------------------------------------------------------------------------- const SLIDER_ENABLED_STORAGE_KEY = 'dsh-model-selector.slider-enabled' function readSliderEnabled(): boolean { try { const current = window.localStorage.getItem(SLIDER_ENABLED_STORAGE_KEY) if (current !== null) return current !== 'false' const legacy = window.localStorage.getItem(ENABLED_STORAGE_KEY) return legacy === null ? true : legacy !== 'false' } catch { return true } } let sliderEnabled = readSliderEnabled() const sliderEnabledListeners = new Set<() => void>() const sliderStore = { getSnapshot: () => sliderEnabled, subscribe: (listener: () => void) => { sliderEnabledListeners.add(listener) return () => sliderEnabledListeners.delete(listener) }, set: (enabled: boolean, persist = true) => { if (sliderEnabled === enabled) return sliderEnabled = enabled if (persist) { try { window.localStorage.setItem(SLIDER_ENABLED_STORAGE_KEY, String(enabled)) } catch { // The current page still follows the choice when storage is unavailable. } } sliderEnabledListeners.forEach((listener) => listener()) }, } // --------------------------------------------------------------------------- // GLM Coding Plan 高峰/空闲提醒开关(默认关闭): // 非高峰时段模型调用按基础积分消耗的 50% 抵扣; // 高峰时段 = 每周一至周五 14:00–18:00(UTC+8)。 // --------------------------------------------------------------------------- const GLM_REMINDER_STORAGE_KEY = 'dsh-model-selector.glm-reminder' function readGlmReminder(): boolean { try { return window.localStorage.getItem(GLM_REMINDER_STORAGE_KEY) === 'true' } catch { return false } } let glmReminderEnabled = readGlmReminder() const glmReminderListeners = new Set<() => void>() const glmReminderStore = { getSnapshot: () => glmReminderEnabled, subscribe: (listener: () => void) => { glmReminderListeners.add(listener) return () => glmReminderListeners.delete(listener) }, set: (enabled: boolean, persist = true) => { if (glmReminderEnabled === enabled) return glmReminderEnabled = enabled if (persist) { try { window.localStorage.setItem(GLM_REMINDER_STORAGE_KEY, String(enabled)) } catch { // The current page still follows the choice when storage is unavailable. } } glmReminderListeners.forEach((listener) => listener()) }, } // --------------------------------------------------------------------------- // GLM Coding Plan 限额提醒开关(默认开启):自动识别 429/1308 类 // "已达到 5 小时的使用上限"错误并在输入框上方展示重置时间。 // --------------------------------------------------------------------------- const GLM_LIMIT_ALERT_KEY = 'dsh-model-selector.glm-limit-alert' function readGlmLimitAlert(): boolean { try { return window.localStorage.getItem(GLM_LIMIT_ALERT_KEY) !== 'false' } catch { return true } } let glmLimitAlertEnabled = readGlmLimitAlert() const glmLimitAlertListeners = new Set<() => void>() const glmLimitStore = { getSnapshot: () => glmLimitAlertEnabled, subscribe: (listener: () => void) => { glmLimitAlertListeners.add(listener) return () => glmLimitAlertListeners.delete(listener) }, set: (enabled: boolean, persist = true) => { if (glmLimitAlertEnabled === enabled) return glmLimitAlertEnabled = enabled if (persist) { try { window.localStorage.setItem(GLM_LIMIT_ALERT_KEY, String(enabled)) } catch { // The current page still follows the choice when storage is unavailable. } } glmLimitAlertListeners.forEach((listener) => listener()) }, } /** 已手动关闭过(或已提示过)的 turn-error seq,避免历史错误重复提醒。 */ const GLM_LIMIT_SEEN_KEY = 'dsh-model-selector.glm-limit-seen' function readGlmLimitSeen(): number { try { return Number(window.localStorage.getItem(GLM_LIMIT_SEEN_KEY) ?? 0) || 0 } catch { return 0 } } function writeGlmLimitSeen(seq: number): void { try { window.localStorage.setItem(GLM_LIMIT_SEEN_KEY, String(seq)) } catch { // Optional persistence only. } } // --------------------------------------------------------------------------- // Model alias (short name) store. // --------------------------------------------------------------------------- const ALIAS_STORAGE_KEY = 'dsh-model-selector.model-aliases' type AliasMap = Record function readAliases(): AliasMap { try { const raw = window.localStorage.getItem(ALIAS_STORAGE_KEY) if (raw === null) return {} const parsed: unknown = JSON.parse(raw) if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { return parsed as AliasMap } return {} } catch { return {} } } let aliases: AliasMap = readAliases() const aliasListeners = new Set<() => void>() function aliasKeyOf(provider: string, model: string): string { return `${provider}/${model}` } const aliasStore = { getSnapshot: () => aliases, subscribe: (listener: () => void) => { aliasListeners.add(listener) return () => aliasListeners.delete(listener) }, set: (provider: string, model: string, alias: string) => { const key = aliasKeyOf(provider, model) const trimmed = alias.trim() const next: AliasMap = { ...aliases } if (trimmed === '') { delete next[key] } else { next[key] = trimmed } aliases = next try { window.localStorage.setItem(ALIAS_STORAGE_KEY, JSON.stringify(aliases)) } catch { // The current page still follows the choice when storage is unavailable. } aliasListeners.forEach((listener) => listener()) }, } function currentModel(state: ModelDirectoryState) { if (state.current === null) return undefined const group = state.groups.find((candidate) => candidate.id === state.current?.provider) return group?.models.find((candidate) => candidate.id === state.current?.model) } /** * Effort levels the current model advertises, in adapter order. A model needs * at least two before a slider says anything a plain label would not, so * fewer-than-two collapses to none. */ function sliderLevels(state: ModelDirectoryState): readonly EffortLevel[] { const efforts = currentModel(state)?.reasoning?.efforts return efforts !== undefined && efforts.length >= 2 ? efforts : [] } function effortIndex(levels: readonly EffortLevel[], id: string | undefined): number { return levels.findIndex((level) => level.id === id) } function clampIndex(value: number, count: number): number { return Math.max(0, Math.min(count - 1, Math.round(value))) } /** * Level index the slider should rest at: the session's current effort when the * model still offers it, else the adapter default, else the middle level. */ function effectiveEffortIndex(levels: readonly EffortLevel[], state: ModelDirectoryState): number { const reasoning = currentModel(state)?.reasoning const current = effortIndex(levels, state.current?.reasoningEffort) if (current >= 0) return current const fallback = effortIndex(levels, reasoning?.defaultEffort) if (fallback >= 0) return fallback return Math.floor((levels.length - 1) / 2) } interface RadiationState { progress: number dragging: boolean } function drawRadiation( context: CanvasRenderingContext2D, width: number, height: number, time: number, state: RadiationState, ): void { const origin = state.progress * width const isDark = document.body.hasAttribute('data-ds-dark-theme') const cell = 4 const speed = state.dragging ? 2.8 : 1 context.clearRect(0, 0, width, height) if (origin <= 0) return context.save() context.beginPath() context.rect(0, 0, origin, height) context.clip() for (let x = 0; x < origin; x += cell) { const delta = x + cell * 0.5 - origin const distance = Math.abs(delta) const phaseA = distance / 10 - time * 0.0074 * speed const phaseB = distance / 23 - time * 0.0041 * speed + 1.7 const phaseC = distance / 40 - time * 0.0022 * speed + 3.4 const sinA = Math.max(0, Math.sin(phaseA)) const sinB = Math.max(0, Math.sin(phaseB)) const sinC = Math.max(0, Math.sin(phaseC)) const waveA = Math.pow(sinA, 2.6) const waveB = Math.pow(sinB, 3.2) const waveC = Math.pow(sinC, 4) const crest = Math.pow(sinA, 15) + Math.pow(sinB, 18) * 0.78 const wave = Math.min(1, waveA * 0.76 + waveB * 0.58 + waveC * 0.32) const trail = 0.38 + 0.62 * Math.exp(-distance / Math.max(55, width * 0.72)) const pillar = Math.pow(Math.max(0, Math.sin(x / 20 + time * 0.0016)), 3) * 0.27 const columnEnergy = trail * (wave * 1.04 + pillar + crest * 0.32) if (columnEnergy > 0.012) { const nearness = Math.max(0, 1 - distance / Math.max(1, width * 0.78)) const red = isDark ? Math.round(42 + 124 * nearness + 75 * wave) : Math.round(28 + 58 * nearness + 15 * wave) const green = isDark ? Math.round(56 + 58 * nearness + 44 * crest) : Math.round(88 + 72 * nearness + 30 * crest) const blue = isDark ? Math.round(175 + 72 * nearness + 8 * wave) : Math.round(182 + 62 * nearness) const alpha = isDark ? Math.min(0.88, columnEnergy * 0.72) : Math.min(0.62, columnEnergy * 0.54) context.fillStyle = `rgba(${red}, ${green}, ${blue}, ${alpha})` context.fillRect(x, 0, cell - 1, height) } for (let y = 0; y < height; y += cell) { const deltaY = y + cell * 0.5 - height * 0.5 const radial = Math.hypot(delta / 38, deltaY / 11) const halo = Math.exp(-radial * 0.96) * 1.08 const verticalShape = 0.58 + 0.42 * Math.cos((deltaY / height) * Math.PI) const grain = 0.72 + 0.28 * Math.sin(x * 0.73 + y * 1.31 + time * 0.006) const alpha = Math.min(0.96, (columnEnergy * 0.88 + halo + crest * 0.19) * verticalShape * grain) if (alpha < 0.035) continue const hot = Math.max(0, 1 - radial / 2.4) const red = isDark ? Math.round(54 + 148 * hot + 42 * wave + 35 * crest) : Math.round(25 + 72 * hot + 12 * wave) const green = isDark ? Math.round(68 + 78 * hot + 46 * crest) : Math.round(98 + 72 * hot + 24 * crest) const blue = isDark ? Math.round(186 + 64 * hot) : Math.round(194 + 56 * hot) context.fillStyle = `rgba(${red}, ${green}, ${blue}, ${isDark ? alpha : alpha * 0.72})` context.fillRect(x, y, cell - 1, cell - 1) } } for (let i = 0; i < 14; i += 1) { const travel = (time * (state.dragging ? 0.16 : 0.065) * (0.78 + (i % 5) * 0.09) + i * 23) % Math.max(30, origin + 64) const particleX = origin - travel if (particleX < -24 || particleX > width + 16) continue const particleY = 3 + ((i * 13 + Math.sin(time * 0.003 + i) * 5) % Math.max(7, height - 6)) const length = 4 + (i % 4) * 4 + (state.dragging ? 6 : 0) const alpha = 0.28 + (i % 5) * 0.1 const streak = context.createLinearGradient(particleX, 0, particleX + length, 0) streak.addColorStop(0, isDark ? 'rgba(72,118,255,0)' : 'rgba(24,94,184,0)') streak.addColorStop(0.68, isDark ? `rgba(112,135,255,${alpha})` : `rgba(36,108,202,${alpha * 0.72})`) streak.addColorStop(1, isDark ? `rgba(236,222,255,${Math.min(1, alpha + 0.26)})` : `rgba(103,175,248,${Math.min(0.82, alpha + 0.18)})`) context.fillStyle = streak context.fillRect(particleX, particleY, length, i % 3 === 0 ? 2 : 1) } const glow = context.createRadialGradient(origin, height / 2, 0, origin, height / 2, 24) glow.addColorStop(0, isDark ? 'rgba(255,255,255,.82)' : 'rgba(255,255,255,.86)') glow.addColorStop(0.14, isDark ? 'rgba(183,190,255,.54)' : 'rgba(162,210,255,.48)') glow.addColorStop(0.44, isDark ? 'rgba(103,74,255,.28)' : 'rgba(37,112,207,.22)') glow.addColorStop(1, isDark ? 'rgba(86,31,210,0)' : 'rgba(25,91,181,0)') context.fillStyle = glow context.fillRect(origin - 26, 0, 52, height) context.restore() } function EffortSlider({ directory }: { directory: ModelDirectory }) { const directoryState = useSyncExternalStore( (notify) => directory.store.subscribe(notify), () => directory.store.getSnapshot(), ) const levels = sliderLevels(directoryState) const [effort, setEffort] = useState('') const [preview, setPreview] = useState(0) const [committing, setCommitting] = useState(false) const [dragging, setDragging] = useState(false) const [localError, setLocalError] = useState(null) const canvasRef = useRef(null) const inputRef = useRef(null) const committedRef = useRef('') const committingRef = useRef(false) const previewRef = useRef(0) const draggingRef = useRef(false) const pointerActiveRef = useRef(false) const activePointerIdRef = useRef(null) const globalPointerMoveRef = useRef<((event: PointerEvent) => void) | null>(null) const globalPointerEndRef = useRef<((event: PointerEvent) => void) | null>(null) const globalPointerCancelRef = useRef<((event: PointerEvent) => void) | null>(null) const radiationRef = useRef({ progress: 0.5, dragging: false }) const redrawRef = useRef<(() => void) | null>(null) // 梁系列档位标签(小难梁~梁神)只在 DeepSeek 系列模型上显示。 const isDeepSeekModel = (() => { const current = directoryState.current if (current === null) return false return current.provider.toLowerCase().includes('deepseek') || current.model.toLowerCase().includes('deepseek') })() const available = directoryState.current !== null && levels.length >= 2 const busy = committing || directoryState.status === 'selecting' const error = localError ?? directoryState.error useEffect(() => { if (!available || committingRef.current || draggingRef.current) return const index = effectiveEffortIndex(levels, directoryState) const next = levels[index]?.id ?? '' committedRef.current = next previewRef.current = index setEffort(next) setPreview(index) setLocalError(null) }, [available, levels, directoryState]) useEffect(() => { directory.load().catch(() => undefined) }, [directory]) useEffect(() => { previewRef.current = preview radiationRef.current.progress = levels.length >= 2 ? preview / (levels.length - 1) : 0.5 redrawRef.current?.() }, [preview, levels.length]) useEffect(() => { radiationRef.current.dragging = dragging redrawRef.current?.() }, [dragging]) useEffect(() => { const canvas = canvasRef.current if (canvas === null) return const context = canvas.getContext('2d') if (context === null) return const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)') let width = 1 let height = 1 let frame = 0 const resize = () => { const bounds = canvas.getBoundingClientRect() const ratio = Math.min(window.devicePixelRatio || 1, 2) width = Math.max(1, bounds.width) height = Math.max(1, bounds.height) canvas.width = Math.max(1, Math.round(width * ratio)) canvas.height = Math.max(1, Math.round(height * ratio)) context.setTransform(ratio, 0, 0, ratio, 0, 0) } const draw = (time = performance.now()) => { drawRadiation(context, width, height, time, radiationRef.current) } const loop = (time: number) => { draw(time) frame = window.requestAnimationFrame(loop) } const redraw = () => { if (reducedMotion.matches) draw() } const resizeObserver = new ResizeObserver(() => { resize() draw() }) const themeObserver = new MutationObserver(() => draw()) resizeObserver.observe(canvas) themeObserver.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme'] }) redrawRef.current = redraw resize() draw() if (!reducedMotion.matches) frame = window.requestAnimationFrame(loop) return () => { window.cancelAnimationFrame(frame) resizeObserver.disconnect() themeObserver.disconnect() redrawRef.current = null } }, []) const rollback = useCallback(() => { const previous = committedRef.current previewRef.current = Math.max(0, effortIndex(levels, previous)) pointerActiveRef.current = false activePointerIdRef.current = null draggingRef.current = false setEffort(previous) setPreview(Math.max(0, effortIndex(levels, previous))) setDragging(false) }, [levels]) const commit = useCallback(async (raw: number) => { if (committingRef.current) return committingRef.current = true const previous = committedRef.current setDragging(false) setCommitting(true) setLocalError(null) // Optimistic snap from the rendered levels keeps the thumb responsive // while the directory round-trip revalidates against fresh data below. const optimisticIndex = clampIndex(raw, levels.length) const optimistic = levels[optimisticIndex]?.id if (optimistic !== undefined) { previewRef.current = optimisticIndex setPreview(optimisticIndex) setEffort(optimistic) } try { const models = await directory.load() const fresh: ModelDirectoryState = { current: models.current, routable: models.routable, groups: models.groups, failures: models.failures, status: 'ready', error: null, } const freshLevels = sliderLevels(fresh) const index = clampIndex(raw, freshLevels.length) const next = freshLevels[index]?.id if (next === undefined) throw new Error('当前模型未提供推理强度档位') previewRef.current = index setPreview(index) setEffort(next) await directory.select({ provider: models.current.provider, model: models.current.model, reasoningEffort: next, }) const snapshot = directory.store.getSnapshot() const accepted = effortIndex(freshLevels, snapshot.current?.reasoningEffort) const settled = accepted >= 0 ? accepted : index const settledId = freshLevels[settled]?.id ?? next committedRef.current = settledId previewRef.current = settled setEffort(settledId) setPreview(settled) } catch (cause) { const restore = Math.max(0, effortIndex(levels, previous)) committedRef.current = previous previewRef.current = restore setEffort(previous) setPreview(restore) setLocalError(cause instanceof Error ? cause.message : String(cause)) } finally { committingRef.current = false setCommitting(false) } }, [directory, levels]) const rawFromPointer = (input: HTMLInputElement, clientX: number) => { const bounds = input.getBoundingClientRect() if (bounds.width <= 0 || levels.length < 2) return previewRef.current // The input spans `slots` positions (real levels + the reserved 梁神 slot). // The thumb stops at the last real level so 梁神 can never be selected. return Math.max( 0, Math.min(levels.length - 1, (clientX - bounds.left) / bounds.width * (slots - 1)), ) } const showPointerPreview = (raw: number) => { // The input spans `slots` positions; keep the preview inside the real // selectable levels so the reserved 梁神 slot never becomes active. const limited = Math.max(0, Math.min(levels.length - 1, raw)) previewRef.current = limited setPreview(limited) setEffort(levels[clampIndex(limited, levels.length)]?.id ?? '') } const beginDragging = (input: HTMLInputElement, pointerId: number, clientX: number) => { pointerActiveRef.current = true activePointerIdRef.current = pointerId draggingRef.current = true setDragging(true) showPointerPreview(rawFromPointer(input, clientX)) try { if (!input.hasPointerCapture(pointerId)) input.setPointerCapture(pointerId) } catch { // The window-level pointer listeners below remain the reliable fallback. } } const moveDragging = (input: HTMLInputElement, pointerId: number, clientX: number) => { if (!pointerActiveRef.current || activePointerIdRef.current !== pointerId) return showPointerPreview(rawFromPointer(input, clientX)) } const stopDragging = (input: HTMLInputElement, pointerId?: number, clientX?: number) => { if (!pointerActiveRef.current) return if (pointerId !== undefined && activePointerIdRef.current !== pointerId) return const raw = clientX === undefined ? previewRef.current : rawFromPointer(input, clientX) pointerActiveRef.current = false activePointerIdRef.current = null draggingRef.current = false if (pointerId !== undefined && input.hasPointerCapture(pointerId)) { input.releasePointerCapture(pointerId) } showPointerPreview(raw) void commit(raw) } globalPointerMoveRef.current = (event) => { const input = inputRef.current if (input !== null) moveDragging(input, event.pointerId, event.clientX) } globalPointerEndRef.current = (event) => { const input = inputRef.current if (input !== null) stopDragging(input, event.pointerId, event.clientX) } globalPointerCancelRef.current = (event) => { if (activePointerIdRef.current !== event.pointerId) return rollback() } useEffect(() => { const move = (event: PointerEvent) => globalPointerMoveRef.current?.(event) const end = (event: PointerEvent) => globalPointerEndRef.current?.(event) const cancel = (event: PointerEvent) => globalPointerCancelRef.current?.(event) window.addEventListener('pointermove', move, true) window.addEventListener('pointerup', end, true) window.addEventListener('pointercancel', cancel, true) return () => { window.removeEventListener('pointermove', move, true) window.removeEventListener('pointerup', end, true) window.removeEventListener('pointercancel', cancel, true) } }, []) const onKeyDown = (event: ReactKeyboardEvent) => { const current = clampIndex(Number(event.currentTarget.value), levels.length) let target: number | undefined if (event.key === 'ArrowLeft' || event.key === 'ArrowDown' || event.key === 'PageDown') { target = Math.max(0, current - 1) } else if (event.key === 'ArrowRight' || event.key === 'ArrowUp' || event.key === 'PageUp') { target = Math.min(levels.length - 1, current + 1) } else if (event.key === 'Home') { target = 0 } else if (event.key === 'End') { target = levels.length - 1 } if (target === undefined) return event.preventDefault() void commit(target) } if (!available) return null const count = levels.length // DeepSeek 模型多一个"梁神"占位槽位;其他模型槽位数 = 实际档位数。 const slots = isDeepSeekModel ? count + 1 : count const effortName = levels[effortIndex(levels, effort)]?.name ?? effort const isTop = effortIndex(levels, effort) === count - 1 const progress = preview / (slots - 1) * 100 const style = { '--re-progress': `${progress}%` } as CSSProperties const title = error === null ? `推理强度 · ${effortName}` : `推理强度设置失败:${error}` const LIANG_LEVELS = [ { name: '小难梁', sub: 'Off', effort: 0 }, { name: '梁子', sub: 'Low', effort: 1 }, { name: '梁文锋', sub: 'High', effort: 2 }, { name: '梁圣', sub: 'Max', effort: 3 }, { name: '梁神', sub: '无法选中', effort: null }, ] as const return (
{/* 标签行:DeepSeek 用梁系列档位;其他模型用配置里实际暴露的档位字 */} {isDeepSeekModel ? ( ) : ( )}
{error === null ? null : {error}}
) } function AdvancedModelSelect({ locked, available, controller, directory, load, select, connection, useSession, }: ModelSeatProps) { const state = useSyncExternalStore( (notify) => directory.subscribe(notify), () => directory.getSnapshot(), ) const [open, setOpen] = useState(false) const [paneMode, setPaneMode] = useState<'main' | 'settings'>('main') const [now, setNow] = useState(Date.now()) const [editing, setEditing] = useState(null) const [aliasDraft, setAliasDraft] = useState('') const rootRef = useRef(null) const triggerRef = useRef(null) const aliasMap = useSyncExternalStore(aliasStore.subscribe, aliasStore.getSnapshot) const sliderEnabled = useSyncExternalStore(sliderStore.subscribe, sliderStore.getSnapshot) const glmLimitOn = useSyncExternalStore(glmLimitStore.subscribe, glmLimitStore.getSnapshot) // GLM Coding Plan 限额用尽提示:显示在 zai-coding-plan 组标题右侧(含倒计时)。 const limitError = findLastLimitError(useSession?.((snapshot) => snapshot.nodes) ?? undefined) const limitResetAt = limitError === undefined ? null : parseResetTime(limitError.message) const limitCountdownMs = limitResetAt === null ? Infinity : limitResetAt - now const showLimitBadge = glmLimitOn && limitError !== undefined && limitCountdownMs > 0 const choice = currentModel(state) const levels = sliderLevels(state) const effortName = levels[effectiveEffortIndex(levels, state)]?.name ?? '默认' const currentKey = state.current === null ? '' : aliasKeyOf(state.current.provider, state.current.model) const modelLabel = (currentKey !== '' && aliasMap[currentKey]) || choice?.name || state.current?.model || '选择模型' const busy = state.status === 'loading' || state.status === 'selecting' const peak = phase(now) const peakStateName = peak.peak ? '梁文锋' : '梁文谷' const peakStateDesc = peak.peak ? '梁文锋(高峰时段)· 全价' : '梁文谷(空闲时段)· 半价' // 规则:高峰=黄色,空闲=绿色 const peakAccent = peak.peak ? '#f6b93b' : '#3ddc84' const peakTargetName = peak.peak ? '梁文谷' : '梁文锋' const peakTargetDesc = peak.peak ? '空闲时段' : '高峰时段' // 规则:倒计时颜色 = 目标状态的颜色(高峰→空闲 绿色;空闲→高峰 黄色) const peakTargetAccent = peak.peak ? '#3ddc84' : '#f6b93b' useEffect(() => { const id = window.setInterval(() => setNow(Date.now()), 1000) return () => window.clearInterval(id) }, []) useEffect(() => { if (!available) return load() }, [available, load]) useEffect(() => { if (!open) return const closeOutside = (event: MouseEvent) => { if (!rootRef.current?.contains(event.target as Node)) { setOpen(false) } } document.addEventListener('mousedown', closeOutside) return () => document.removeEventListener('mousedown', closeOutside) }, [open]) if (!available) return null const close = (restoreFocus = false) => { setOpen(false) setEditing(null) setPaneMode('main') if (restoreFocus) queueMicrotask(() => triggerRef.current?.focus()) } const onKeyDown = (event: ReactKeyboardEvent) => { if (event.key !== 'Escape' || !open) return event.preventDefault() if (editing !== null) { setEditing(null) return } close(true) } const chooseModel = async (provider: string, model: string, defaultEffort?: string) => { if (state.current?.provider === provider && state.current.model === model) return await select({ provider, model, ...(defaultEffort === undefined ? {} : { reasoningEffort: defaultEffort }), }) } const startEdit = (provider: string, model: string) => { const key = aliasKeyOf(provider, model) setAliasDraft(aliasMap[key] ?? '') setEditing(key) } const commitAlias = () => { if (editing === null) return const [provider, model] = editing.split('/') aliasStore.set(provider, model, aliasDraft) setEditing(null) } return (
{open ? (
{paneMode === 'settings' ? ( setPaneMode('main')} connection={connection} groups={state.groups} /> ) : ( <>
距 {peakTargetName}({peakTargetDesc})还有: {formatDur(peak.secondsToTarget)}
{state.status === 'loading' && state.groups.length === 0 ? (
正在加载模型…
) : null} {state.groups.map((group) => (
{group.name}
{showLimitBadge && group.id.toLowerCase().includes('zai-coding') ? ( ⚠ GLM 限额已用尽 · {fmtCountdown(limitCountdownMs)} 后重置 ) : null}
{group.models.map((model) => { const selected = state.current?.provider === group.id && state.current.model === model.id const key = aliasKeyOf(group.id, model.id) const displayName = aliasMap[key] || model.name const isEditing = editing === key return (
{isEditing ? (
全称:{model.name}
setAliasDraft(event.currentTarget.value)} onKeyDown={(event) => { event.stopPropagation() if (event.key === 'Enter') commitAlias() if (event.key === 'Escape') setEditing(null) }} />
) : null} {selected && levels.length >= 2 && sliderEnabled ? (
) : null}
) })}
))} {state.status === 'ready' && state.groups.every((group) => group.models.length === 0) ? (
没有可用模型
) : null} {state.error === null ? null :
{state.error}
} )}
) : null}
) } function ReasoningEffortSetting() { const enabled = useSyncExternalStore(enabledStore.subscribe, enabledStore.getSnapshot) return (
推理强度滑块
在模型菜单中显示推理强度滑块和动态辐射特效,档位随当前模型自动适配
{enabled ? '启用' : '停用'}
) } // --------------------------------------------------------------------------- // Keep-awake switch. The host half owns the Windows execution state; this // browser half writes one boolean into the `dsh-model-selector` settings // namespace through the settingsScope service, whose mirror folds host-side // changes and reloads back in. // --------------------------------------------------------------------------- interface KeepAwakeSettingsScope { bind(spec: { namespace: string; decode?: (value: unknown) => unknown }): KeepAwakeSettingsHandle } interface KeepAwakeSettingsHandle { getSnapshot(): { status?: string; value?: Record } subscribe(listener: () => void): () => void set(field: string, value: boolean): Promise } let keepAwakeScope: KeepAwakeSettingsHandle | null = null const EMPTY_SETTINGS_SNAPSHOT = { value: undefined } function KeepAwakeSetting() { const snap = useSyncExternalStore( (notify) => keepAwakeScope?.subscribe(notify) ?? (() => undefined), () => keepAwakeScope?.getSnapshot() ?? EMPTY_SETTINGS_SNAPSHOT, ) const enabled = snap.value?.keepAwake === true return (
保持唤醒
DSH 运行期间阻止计算机睡眠/休眠,用于低谷时段定时任务
{enabled ? '启用' : '停用'}
) } // --------------------------------------------------------------------------- // Popover settings pane: opened via the gear at the top right of the model // popover. Configures the plugin's own toggles (token stats visibility and // keep-awake) without touching the shipped settings page. // --------------------------------------------------------------------------- // 模型配置文件路径记忆(⚙ 设置页"模型配置"块):默认从 host.describe 的 // home 拼 `$HOME/.dsh/settings.yaml`,DSH 装在自定义目录时可手动改路径。 const SETTINGS_PATH_KEY = 'dsh-model-selector.settings-file-path' function readSettingsPath(): string { try { return window.localStorage.getItem(SETTINGS_PATH_KEY) ?? '' } catch { return '' } } function writeSettingsPath(path: string): void { try { window.localStorage.setItem(SETTINGS_PATH_KEY, path) } catch { // Optional persistence only. } } // --------------------------------------------------------------------------- // 凭据文件(.credentials.yaml)打开:客户端拿不到 DSH_HOME 环境变量, // 因此使用「记住的路径 → 候选路径自动尝试(home/.dsh、home、cwd)→ // 全失败时让用户填写完整路径(成功后记住)」的策略。 // --------------------------------------------------------------------------- const CREDENTIALS_PATH_KEY = 'dsh-model-selector.credentials-file-path' function readCredentialsPath(): string { try { return window.localStorage.getItem(CREDENTIALS_PATH_KEY) ?? '' } catch { return '' } } function writeCredentialsPath(path: string): void { try { window.localStorage.setItem(CREDENTIALS_PATH_KEY, path) } catch { // Optional persistence only. } } async function tryOpenHostPath(connection: StatsConnection, path: string): Promise { try { const response = await connection.api.host.openPath({ path }) const result = response?.result return result !== undefined && result.ok } catch { return false } } /** 尝试打开凭据文件:记忆路径优先,其次候选路径,失败返回 false。 */ async function openCredentialsFile(connection: StatsConnection): Promise<{ opened: boolean; path?: string }> { const remembered = readCredentialsPath() if (remembered !== '') { if (await tryOpenHostPath(connection, remembered)) return { opened: true, path: remembered } } const response = await connection.api.host.describe({}) const result = response?.result if (result === undefined || !result.ok) return { opened: false } const home = result.value.home const cwd = result.value.cwd ?? '' const sep = home.includes('\\') ? '\\' : '/' const candidates = [ `${home}${sep}.dsh${sep}.credentials.yaml`, `${home}${sep}.credentials.yaml`, cwd === '' ? '' : `${cwd}${sep}.dsh${sep}.credentials.yaml`, cwd === '' ? '' : `${cwd}${sep}.credentials.yaml`, ].filter((path) => path !== '') for (const path of candidates) { if (await tryOpenHostPath(connection, path)) { writeCredentialsPath(path) return { opened: true, path } } } return { opened: false } } // --------------------------------------------------------------------------- // 默认模型与默认思考强度:读写 Host 的 agent-default-model 设置命名空间 // (打开新对话时使用)。UI 预设默认值 = DeepSeek flash vision exp / max。 // --------------------------------------------------------------------------- const DEFAULT_MODEL_KEY = 'dsh-model-selector.default-model' interface DefaultModelState { provider: string model: string reasoningEffort: string } const DEFAULT_MODEL_PRESET: DefaultModelState = { provider: 'deepseek-official', model: 'deepseek-v4-flash-vision-exp', reasoningEffort: 'max', } function readDefaultModel(): DefaultModelState { try { const raw = window.localStorage.getItem(DEFAULT_MODEL_KEY) if (raw !== null) { const parsed: unknown = JSON.parse(raw) if (parsed !== null && typeof parsed === 'object') { const value = parsed as Record if (typeof value.provider === 'string' && typeof value.model === 'string') { return { provider: value.provider, model: value.model, reasoningEffort: typeof value.reasoningEffort === 'string' ? value.reasoningEffort : '', } } } } } catch { // Fall through to the preset below. } return { ...DEFAULT_MODEL_PRESET } } function writeDefaultModel(state: DefaultModelState): void { try { window.localStorage.setItem(DEFAULT_MODEL_KEY, JSON.stringify(state)) } catch { // Optional persistence only. } } function SettingsPane({ onBack, connection, groups }: { onBack: () => void connection?: StatsConnection groups?: ReadonlyArray<{ id: string; models: ReadonlyArray<{ id: string; name: string; reasoning?: { efforts?: ReadonlyArray<{ id: string; name: string }> } }> }> }) { const statsEnabled = useSyncExternalStore(tokenStatsStore.subscribe, tokenStatsStore.getSnapshot) const sliderEnabled = useSyncExternalStore(sliderStore.subscribe, sliderStore.getSnapshot) const glmEnabled = useSyncExternalStore(glmReminderStore.subscribe, glmReminderStore.getSnapshot) const glmLimitEnabled = useSyncExternalStore(glmLimitStore.subscribe, glmLimitStore.getSnapshot) const keepSnap = useSyncExternalStore( (notify) => keepAwakeScope?.subscribe(notify) ?? (() => undefined), () => keepAwakeScope?.getSnapshot() ?? EMPTY_SETTINGS_SNAPSHOT, ) const keepEnabled = keepSnap.value?.keepAwake === true const [settingsPath, setSettingsPath] = useState(() => readSettingsPath()) const [pathState, setPathState] = useState<'idle' | 'opening' | 'ok' | 'fail'>('idle') const [pathError, setPathError] = useState(null) const [defaultModel, setDefaultModel] = useState(() => readDefaultModel()) const [defaultState, setDefaultState] = useState<'idle' | 'saving' | 'ok' | 'fail'>('idle') const [defaultMsg, setDefaultMsg] = useState('') useEffect(() => { // 本地镜像为空时,从 Host 的 agent-default-model 命名空间加载当前默认值。 if (connection === undefined) return let disposed = false void connection.api.settings.describe({}).then((response) => { if (disposed) return const result = response?.result if (result === undefined || !result.ok) return const modelNs = result.value.namespaces.find((entry) => entry.ns === 'agent-default-model') const modelValue = modelNs?.value if (modelValue === null || modelValue === undefined || typeof modelValue !== 'object') return const patch: DefaultModelState = { ...readDefaultModel() } if (typeof modelValue.provider === 'string' && modelValue.provider !== '') patch.provider = modelValue.provider if (typeof modelValue.model === 'string' && modelValue.model !== '') patch.model = modelValue.model if (typeof modelValue.reasoningEffort === 'string') patch.reasoningEffort = modelValue.reasoningEffort setDefaultModel(patch) writeDefaultModel(patch) }, () => undefined) return () => { disposed = true } }, [connection]) useEffect(() => { if (settingsPath !== '' || connection === undefined) return let disposed = false void connection.api.host.describe({}).then((response) => { if (disposed) return const result = response?.result if (result !== undefined && result.ok) { const sep = result.value.home.includes('\\') ? '\\' : '/' setSettingsPath(`${result.value.home}${sep}.dsh${sep}settings.yaml`) } }, () => undefined) return () => { disposed = true } }, [connection, settingsPath]) const openSettingsFile = async () => { const path = settingsPath.trim() if (connection === undefined || path === '') return setPathState('opening') setPathError(null) try { const response = await connection.api.host.openPath({ path }) const result = response?.result if (result !== undefined && result.ok) { setPathState('ok') writeSettingsPath(path) } else { setPathState('fail') setPathError(`${result?.error.code ?? 'unknown'}: ${result?.error.message ?? '打开失败'}`) } } catch (cause) { setPathState('fail') setPathError(cause instanceof Error ? cause.message : String(cause)) } } const saveDefaultModel = async () => { if (connection === undefined) return setDefaultState('saving') setDefaultMsg('') const patch: Record = { provider: defaultModel.provider, model: defaultModel.model, } if (defaultModel.reasoningEffort.trim() !== '') { patch.reasoningEffort = defaultModel.reasoningEffort.trim() } try { const response = await connection.api.settings.update({ ns: 'agent-default-model', patch }) const result = response?.result if (result !== undefined && result.ok) { writeDefaultModel(defaultModel) setDefaultState('ok') setDefaultMsg('已保存,新对话将使用此配置') } else { setDefaultState('fail') setDefaultMsg(`${result?.error.code ?? 'unknown'}: ${result?.error.message ?? '保存失败'}`) } } catch (cause) { setDefaultState('fail') setDefaultMsg(cause instanceof Error ? cause.message : String(cause)) } } const openConfigDocument = async () => { if (connection === undefined) return setPathState('opening') setPathError(null) try { const response = await connection.api.settings.openDocument({}) const result = response?.result if (result !== undefined && result.ok) setPathState('ok') else { setPathState('fail') setPathError(`${result?.error.code ?? 'unknown'}: ${result?.error.message ?? '打开失败'}`) } } catch (cause) { setPathState('fail') setPathError(cause instanceof Error ? cause.message : String(cause)) } } return (
插件设置
显示 Token 统计
在浮窗中显示今日 Token 用量统计
推理强度滑块
在模型菜单中显示推理强度滑块和动态辐射特效,档位随当前模型自动适配
保持唤醒
DSH 运行期间阻止计算机睡眠/休眠,用于低谷时段定时任务
GLM 提醒
在浮窗显示 GLM Coding Plan 高峰/空闲提醒(周一至五 14:00–18:00 高峰,空闲 50% 积分抵扣)
GLM 限额提醒
自动识别「已达到 5 小时的使用上限…限额将在 …重置」类报错(429/1308)并在输入框上方显示重置时间(智谱 GLM 文档:docs.bigmodel.cn/cn/guide/capabilities/thinking)
默认模型与思考强度
打开新对话时将使用此配置;预留默认:DeepSeek flash vision exp / max。其他模型(如 GLM)的思考档位可在配置文件中手动填写(详见下方模型配置)
{(() => { const effortOptions = (() => { const group = (groups ?? []).find((candidate) => candidate.id === defaultModel.provider) const model = group?.models.find((candidate) => candidate.id === defaultModel.model) const efforts = model?.reasoning?.efforts ?? [] return efforts.length > 0 ? efforts : [{ id: 'off', name: 'off' }, { id: 'low', name: 'low' }, { id: 'high', name: 'high' }, { id: 'max', name: 'max' }] })() const hasCurrent = effortOptions.some((option) => option.id === defaultModel.reasoningEffort) return ( ) })()}
{defaultState === 'ok' ? {defaultMsg} : null} {defaultState === 'fail' ? {defaultMsg} : null}
模型配置
原始 JSON 编辑器(空间更大)位于 设置 → 插件 → 模型选择器增强;此处可快捷打开配置文档(settings.yaml)与凭据文件(.credentials.yaml)
{pathState === 'ok' ? 已请求系统打开配置文档 : null} {pathError !== null ? {pathError} : null}
) } // --------------------------------------------------------------------------- // 模型配置块(完整版,供"设置 → 插件"大窗口使用):打开配置文档 + // llm-* 命名空间原始 JSON 编辑器(与设置页显示的值一致)+ 保存。 // 小浮窗 ⚙ 只保留快捷打开按钮(见 SettingsPane 精简版)。 // --------------------------------------------------------------------------- function ModelConfigBlock({ connection }: { connection?: StatsConnection }) { const [rawNs, setRawNs] = useState('') const [rawText, setRawText] = useState('') const [rawState, setRawState] = useState<'idle' | 'saving' | 'ok' | 'fail'>('idle') const [rawMsg, setRawMsg] = useState('') const [pathState, setPathState] = useState<'idle' | 'opening' | 'ok' | 'fail'>('idle') const [pathError, setPathError] = useState(null) const loadRawNamespace = (ns: string, namespaces: ReadonlyArray<{ ns: string; value?: Record | null; revision: number }> | undefined) => { const entry = namespaces?.find((item) => item.ns === ns) const value = entry?.value if (value === null || value === undefined) { setRawText('') return } setRawText(JSON.stringify(value, null, 2)) setRawState('idle') setRawMsg('') } useEffect(() => { if (connection === undefined) return let disposed = false void connection.api.settings.describe({}).then((response) => { if (disposed) return const result = response?.result if (result === undefined || !result.ok) return const namespaces = result.value.namespaces const llmNamespaces = namespaces.filter((entry) => entry.ns.startsWith('llm-')) if (rawNs === '' && llmNamespaces.length > 0) setRawNs(llmNamespaces[0].ns) if (rawNs !== '') loadRawNamespace(rawNs, namespaces) }, () => undefined) return () => { disposed = true } }, [connection, rawNs]) const openConfigDocument = async () => { if (connection === undefined) return setPathState('opening') setPathError(null) try { const response = await connection.api.settings.openDocument({}) const result = response?.result if (result !== undefined && result.ok) setPathState('ok') else { setPathState('fail') setPathError(`${result?.error.code ?? 'unknown'}: ${result?.error.message ?? '打开失败'}`) } } catch (cause) { setPathState('fail') setPathError(cause instanceof Error ? cause.message : String(cause)) } } const saveRawConfig = async () => { if (connection === undefined || rawNs === '') return setRawState('saving') setRawMsg('') let patch: unknown try { patch = JSON.parse(rawText) } catch (cause) { setRawState('fail') setRawMsg(cause instanceof Error ? `JSON 解析失败:${cause.message}` : 'JSON 解析失败') return } if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { setRawState('fail') setRawMsg('配置内容必须是对象') return } try { const response = await connection.api.settings.update({ ns: rawNs, patch }) const result = response?.result if (result !== undefined && result.ok) { setRawState('ok') setRawMsg(`已保存 ${rawNs}`) } else { setRawState('fail') setRawMsg(`${result?.error.code ?? 'unknown'}: ${result?.error.message ?? '保存失败'}`) } } catch (cause) { setRawState('fail') setRawMsg(cause instanceof Error ? cause.message : String(cause)) } } return (
模型配置
配置文档(settings.yaml)由 DSH 管理;下方可编辑 llm-* 命名空间的原始配置(与设置页显示的值一致),其他模型(GLM 等)的思考档位在此填写 reasoningEfforts
{pathState === 'ok' ? 已请求系统打开配置文档 : null} {pathError !== null ? {pathError} : null}