dsh-thinking-slider 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MuFeng262
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,135 @@
1
+ # dsh-thinking-slider
2
+
3
+ 把 DeepSeek Harness(DSH)composer 里的**模型选择器**换成「模型 + 推理强度」:
4
+ 平时显示 `模型名 · 等级`,点开是一张卡片 —— 上面是模型列表入口,下面是带**渐变与粒子**的强度滑块。
5
+
6
+ *An opinionated model + reasoning-effort picker for the DSH composer, with a gradient particle rail.*
7
+
8
+ ![四档对比](docs/preview.png)
9
+
10
+ ## 它做什么
11
+
12
+ - **关闭态**:正常的一行文字 `deepseek-flash · Max`,不占地方
13
+ - **点开**:卡片里大字显示当前等级,`模型名 ›` 可切模型,下面一条厚滑块
14
+ - **拖滑块**:即时切换推理强度;轨道渐变、光晕、粒子密度随等级上升
15
+ - **键盘**:`←/→`、`Home/End` 切换,`Esc` 关闭
16
+ - **降级**:模型没有推理等级时只显示模型名,不出现滑块(不会给你一个假的控件)
17
+
18
+ 等级**不写死在插件里** —— 它读 DSH 上报的 `model.reasoning.efforts`,
19
+ 所以任何在配置里声明了 `reasoningEfforts` 的供应商路由都会自动出现在滑块上。
20
+
21
+ ## 要求
22
+
23
+ - DSH Desktop 或 `dsh web`,内核 **0.2.x**(开发时验证于 `0.2.0-rc.1` / `0.2.0-rc.2`)
24
+ - 无第三方依赖:只用 DSH 自带的 `react` / `react/jsx-runtime` / `react-dom`
25
+
26
+ 插件**没有声明 `peerDependencies`**,所以不会被 DSH 的版本门禁整包跳过;
27
+ 代价是版本兼容由你自己判断,升级 DSH 后如果 UI 槽位变了可能失效。
28
+
29
+ ## 安装
30
+
31
+ ```bash
32
+ dsh plugin --profile desktop add github:MuFeng262/dsh-thinking-slider
33
+ ```
34
+
35
+ 装完**完全退出 DSH Desktop 再打开**(客户端插件在启动时组合加载)。
36
+
37
+ > 如果你的 profile 名不是 `desktop`,把 `--profile desktop` 换成实际名字。
38
+ > 插件管理器里添加同一条 `github:MuFeng262/dsh-thinking-slider` 也可以。
39
+
40
+ <details>
41
+ <summary>手动安装(命令不可用时)</summary>
42
+
43
+ 1. 克隆到插件源码目录:
44
+
45
+ ```bash
46
+ git clone https://github.com/MuFeng262/dsh-thinking-slider %USERPROFILE%\.dsh\plugins-src\dsh-thinking-slider
47
+ ```
48
+
49
+ 2. 把 `node_modules\dsh-thinking-slider` 做成指向它的**目录联结(junction)**:
50
+
51
+ ```powershell
52
+ New-Item -ItemType Junction `
53
+ -Path "$env:USERPROFILE\.dsh\profiles\desktop\node_modules\dsh-thinking-slider" `
54
+ -Target "$env:USERPROFILE\.dsh\plugins-src\dsh-thinking-slider"
55
+ ```
56
+
57
+ 3. 在 `%USERPROFILE%\.dsh\profiles\desktop\package.json` 里加两处:
58
+
59
+ ```jsonc
60
+ {
61
+ "dependencies": {
62
+ "dsh-thinking-slider": "file:../../plugins-src/dsh-thinking-slider"
63
+ },
64
+ "dsh": {
65
+ "profile": {
66
+ "bundles": [
67
+ "dsh-thinking-slider" // ← 加进这个数组
68
+ ]
69
+ }
70
+ }
71
+ }
72
+ ```
73
+
74
+ 4. 重启 DSH Desktop。
75
+ </details>
76
+
77
+ ## 让自定义模型也有推理等级
78
+
79
+ **档位不在插件里。** 插件是通用的,但 `Off / Low / High / Max` 来自你自己的 profile 配置。
80
+ DSH 的 Models 设置页**刻意不提供**这个字段,只能手写进 profile 的 `cordis.patch.yml`:
81
+
82
+ ```yaml
83
+ - id: llm-pi-ai
84
+ name: "@deepseek-ai/dsh-llm-pi-ai"
85
+ config:
86
+ providers:
87
+ your-gateway:
88
+ displayName: 你的中转商
89
+ apiKeyEnv: YOUR_API_KEY
90
+ api: openai-completions
91
+ baseURL: https://your-gateway.example/v1
92
+ models:
93
+ - id: some-model
94
+ name: some-model
95
+ reasoningEfforts: # ← 关键:每个模型单独写
96
+ off: none
97
+ low: low
98
+ high: high
99
+ max: max
100
+ ```
101
+
102
+ 几点注意:
103
+
104
+ - 右边那些值是**原样发到网关的拼写**,不是 DSH 的枚举。不同中转商认的词不一样,
105
+ 填错可能 400 —— 建议先只给一个模型加上试。
106
+ - 键名(`off` / `minimal` / `low` / `medium` / `high` / `xhigh` / `max`)决定了滑块上有几档。
107
+ - 省略 `reasoningEfforts` 时,DSH 只会按**模型 id** 去查内置目录;
108
+ 自定义模型名查不到 → 该模型就没有等级。
109
+ - `reasoningEfforts: false` 可以显式声明为「非推理模型」。
110
+
111
+ ## 卸载
112
+
113
+ ```bash
114
+ dsh plugin --profile desktop remove dsh-thinking-slider
115
+ ```
116
+
117
+ 手动装的,要删三处:`node_modules\dsh-thinking-slider`、
118
+ `package.json` 的 `dependencies` 条目、以及 `dsh.profile.bundles` 里的同名项。
119
+ **只删 dependencies 不够** —— bundles 里的条目不清掉,插件开机仍会被加载。
120
+
121
+ ## 开发
122
+
123
+ ```bash
124
+ git clone https://github.com/MuFeng262/dsh-thinking-slider
125
+ cd dsh-thinking-slider
126
+ node test/smoke.mjs # 66 项行为测试,零依赖,不需要 DSH
127
+ ```
128
+
129
+ `test/smoke.mjs` 自带一个迷你 React 运行时(hooks 槽位、类组件与错误边界、
130
+ 跨渲染的 DOM 节点身份、真实执行的 effect 与 cleanup),所以
131
+ 「节点重挂后动画有没有重新绑定」这类问题是可以断言的,不需要开浏览器。
132
+
133
+ ## 许可
134
+
135
+ MIT
@@ -0,0 +1,8 @@
1
+ # dsh-thinking-slider
2
+ #
3
+ # Host half is intentionally empty: this plugin is pure browser UI. The `insert`
4
+ # row below is what makes the composition load `./client` (declared through
5
+ # package.json's `dsh.client`) into the web app.
6
+ - insert:
7
+ - id: thinking-slider
8
+ name: 'dsh-thinking-slider'
package/lib/client.js ADDED
@@ -0,0 +1,1077 @@
1
+ /**
2
+ * dsh-thinking-slider - browser half.
3
+ *
4
+ * Composer seat replacement for `conversation.input.model`:
5
+ *
6
+ * - the trigger reads like the shipped one: `model · level`
7
+ * - clicking it opens a card in the Codex idiom: the level as the headline,
8
+ * the model as a link that swaps the card to the model list, and a wide
9
+ * gradient track with a heavy thumb
10
+ * - the track's gradient, glow and particle field all climb with the level;
11
+ * "off" is a cold, motionless rail rather than a lying control
12
+ *
13
+ * Levels are never hard-coded: the seat reads the catalog the Host advertises,
14
+ * so any provider route declaring `reasoningEfforts` becomes draggable.
15
+ *
16
+ * Stability contract: the seat is wrapped in its own error boundary. The slot
17
+ * renderer retires an entry whose render throws, so an unguarded crash would
18
+ * silently hand the seat back to the shipped selector ("the slider vanished").
19
+ * Everything below therefore degrades to a visible fallback instead of throwing.
20
+ */
21
+ window.__ModuleLoader__.load({
22
+ id: 'dsh-thinking-slider',
23
+ factory: (require) => {
24
+ var module = { exports: {} }
25
+ var exports = module.exports
26
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
27
+
28
+ const react = require('react')
29
+ const { jsx, jsxs } = require('react/jsx-runtime')
30
+ const { createPortal } = require('react-dom')
31
+
32
+ const LOG = '[dsh-thinking-slider]'
33
+
34
+ // ---------------------------------------------------------------------
35
+ // Styles. Only confirmed theme tokens are used, each with a literal
36
+ // fallback so a token rename degrades rather than breaks.
37
+ // ---------------------------------------------------------------------
38
+ const CSS = `
39
+ .tsl-root{display:flex;align-items:center;min-width:0}
40
+ .tsl-trigger{display:flex;align-items:center;gap:4px;height:28px;max-width:min(360px,45cqw);min-width:0;padding:0 6px 0 8px;border:0;border-radius:var(--dsw-radius-sm,6px);background:0 0;color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;font-weight:400;line-height:20px;cursor:pointer;outline:none}
41
+ .tsl-trigger:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}
42
+ .tsl-trigger:focus-visible{box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary,#4d6bfe))}
43
+ .tsl-trigger:disabled{color:var(--dsw-alias-label-dimmed);cursor:default}
44
+ .tsl-triggerModel{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
45
+ .tsl-triggerDot{flex:none;color:var(--dsw-alias-label-caption);opacity:.7}
46
+ .tsl-triggerLevel{flex:none;max-width:112px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-caption)}
47
+ .tsl-triggerChevron{flex:none;color:var(--dsw-alias-label-caption);transition:transform .12s ease}
48
+ .tsl-triggerChevronOpen{transform:rotate(180deg)}
49
+ .tsl-card{position:fixed;z-index:1100;--tsl-knob:26px;width:320px;padding:18px 18px 16px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18));border-radius:16px;background:var(--dsw-alias-bg-overlay,var(--dsw-alias-bg-layer-1,#fff));color:var(--dsw-alias-label-primary);box-shadow:var(--dsw-elevation-prominent,0 12px 40px rgba(0,0,0,.28));animation:tsl-in .14s ease-out}
50
+ @keyframes tsl-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
51
+ @media (prefers-reduced-motion: reduce){.tsl-card{animation:none}}
52
+ .tsl-head{display:flex;align-items:center;justify-content:center;position:relative;min-height:26px;margin-bottom:2px}
53
+ .tsl-level{font-size:17px;line-height:26px;font-weight:500;letter-spacing:.02em;transition:color .18s ease}
54
+ .tsl-reset{position:absolute;right:-2px;top:0;display:flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:0;border-radius:999px;background:0 0;color:var(--dsw-alias-label-caption);cursor:pointer;opacity:.85}
55
+ .tsl-reset:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));color:var(--dsw-alias-label-primary)}
56
+ .tsl-modelRow{display:flex;align-items:center;justify-content:center;gap:2px;width:100%;margin:0 0 14px;padding:2px 6px;border:0;border-radius:8px;background:0 0;color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;line-height:20px;cursor:pointer}
57
+ .tsl-modelRow:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}
58
+ .tsl-modelRow:disabled{cursor:default;color:var(--dsw-alias-label-dimmed)}
59
+ .tsl-modelName{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:230px}
60
+ .tsl-trackWrap{position:relative;height:30px;display:flex;align-items:center;outline:none;cursor:pointer;touch-action:none}
61
+ .tsl-trackWrap[data-inert=true]{cursor:default;opacity:.55}
62
+ .tsl-trackWrap:focus-visible .tsl-track{box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary,#4d6bfe))}
63
+ .tsl-track{position:relative;width:100%;height:var(--tsl-knob);border-radius:999px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.16));overflow:hidden;transition:box-shadow .2s ease}
64
+ .tsl-fill{position:absolute;left:0;top:0;bottom:0;border-radius:999px;transition:width .18s ease}
65
+ .tsl-canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
66
+ .tsl-ticks{position:absolute;inset:0;pointer-events:none}
67
+ .tsl-tick{position:absolute;top:50%;width:4px;height:4px;margin:-2px 0 0 -2px;border-radius:999px;background:currentColor;opacity:.55}
68
+ .tsl-thumb{position:absolute;top:50%;width:var(--tsl-knob);height:var(--tsl-knob);margin:calc(var(--tsl-knob) / -2) 0 0 calc(var(--tsl-knob) / -2);border-radius:999px;background:#fff;pointer-events:none;transition:left .18s ease,box-shadow .2s ease;box-shadow:0 1px 4px rgba(0,0,0,.32)}
69
+ .tsl-scale{position:relative;height:16px;margin-top:6px;font-size:11px;line-height:16px;color:var(--dsw-alias-label-caption)}
70
+ .tsl-scaleItem{position:absolute;top:0;white-space:nowrap;transform:translateX(-50%);transition:color .18s ease}
71
+ .tsl-scaleItem[data-active=true]{font-weight:500}
72
+ .tsl-empty{margin-top:10px;font-size:12px;line-height:18px;text-align:center;color:var(--dsw-alias-label-caption)}
73
+ .tsl-list{max-height:min(320px,50vh);overflow:auto;margin:0 -6px;padding:0 6px;--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2);--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2)}
74
+ .tsl-group{margin:2px 0 6px;font-size:11px;line-height:16px;letter-spacing:.04em;text-transform:uppercase;color:var(--dsw-alias-label-caption)}
75
+ .tsl-item{display:flex;align-items:center;gap:8px;width:100%;padding:7px 8px;border:0;border-radius:8px;background:0 0;color:inherit;font:inherit;font-size:13px;text-align:left;cursor:pointer}
76
+ .tsl-item:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}
77
+ .tsl-item[data-active=true]{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}
78
+ .tsl-itemText{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
79
+ .tsl-itemMeta{flex:none;display:inline-flex;align-items:center;font-size:11px;color:var(--dsw-alias-label-caption)}
80
+ .tsl-ramp{display:inline-flex;align-items:center;gap:3px}
81
+ .tsl-rampDot{display:block;width:5px;height:5px;border-radius:999px}
82
+ .tsl-rampNone{color:var(--dsw-alias-label-dimmed)}
83
+ .tsl-check{flex:none;width:14px;height:14px}
84
+ .tsl-failure{margin:4px 0;padding:6px 8px;border-radius:8px;font-size:12px;line-height:18px;background:var(--dsw-alias-interactive-bg-hover-danger,rgba(220,60,60,.12));color:var(--dsw-alias-state-error-primary,#d64545)}
85
+ .tsl-fallback{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:var(--dsw-radius-sm,6px);background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));font-size:13px;color:var(--dsw-alias-label-secondary)}
86
+ .tsl-fallbackBadge{font-size:11px;color:var(--dsw-alias-state-warn-primary,#b7791f)}
87
+ .tsl-fallbackRetry{border:0;padding:0;background:0 0;color:inherit;font:inherit;font-size:11px;text-decoration:underline;cursor:pointer;opacity:.85}
88
+ .tsl-fallbackRetry:hover{opacity:1}
89
+ `
90
+ const TAG_ID = 'dsh-thinking-slider/styles.css'
91
+ const installStyles = () => {
92
+ if (typeof document === 'undefined') return
93
+ if (document.querySelector(`style[data-plugin-css=${JSON.stringify(TAG_ID)}]`) !== null) return
94
+ const tag = document.createElement('style')
95
+ tag.dataset.plugin = 'dsh-thinking-slider'
96
+ tag.dataset.pluginCss = TAG_ID
97
+ tag.textContent = CSS
98
+ document.head.appendChild(tag)
99
+ }
100
+ installStyles()
101
+
102
+ // ---------------------------------------------------------------------
103
+ // Level palette: one gradient stop set per level, interpolated across a
104
+ // continuous position so a drag previews the exact level it would pick.
105
+ // ---------------------------------------------------------------------
106
+ /** `off` is deliberately cold and still, so it never reads as a live level. */
107
+ const OFF_LOOK = {
108
+ gradient: 'linear-gradient(90deg, rgb(100, 116, 139) 0%, rgb(148, 163, 184) 100%)',
109
+ accent: 'rgb(148, 163, 184)',
110
+ glow: 'rgba(148, 163, 184, 0.18)',
111
+ energy: 0,
112
+ }
113
+ /**
114
+ * Thinking-level stops, coldest to hottest. A model's non-off levels map
115
+ * across these two extremes, so a three-level model spans blue -> magenta
116
+ * exactly and a seven-level one interpolates smoothly through the same
117
+ * range instead of pinning several levels to one colour.
118
+ */
119
+ const STOPS = [
120
+ { from: [59, 130, 246], to: [99, 102, 241], glow: 'rgba(99,102,241,', energy: 0.34 }, // low - blue
121
+ { from: [124, 58, 237], to: [168, 85, 247], glow: 'rgba(168,85,247,', energy: 0.68 }, // mid - violet
122
+ { from: [217, 70, 239], to: [249, 115, 22], glow: 'rgba(236,72,153,', energy: 1.0 }, // top - magenta -> amber
123
+ ]
124
+
125
+ const clamp01 = (value) => (value < 0 ? 0 : value > 1 ? 1 : value)
126
+ const mix = (a, b, t) => a.map((channel, index) => Math.round(channel + (b[index] - channel) * t))
127
+ const rgb = (channels) => `rgb(${channels[0]}, ${channels[1]}, ${channels[2]})`
128
+
129
+ /**
130
+ * One model row's level ramp: a dot per offered level, coloured along the
131
+ * same palette the rail uses, so the list speaks the slider's visual
132
+ * language. `off` takes the cold accent; the rest climb blue -> magenta.
133
+ * @param efforts - the model's advertised levels.
134
+ * @returns one colour per level, in order.
135
+ */
136
+ function rampOf(efforts) {
137
+ const positive = efforts.filter((level) => level?.id !== 'off')
138
+ return efforts.map((level) => {
139
+ if (level?.id === 'off') return OFF_LOOK.accent
140
+ const at = positive.findIndex((candidate) => candidate?.id === level?.id)
141
+ const rank = positive.length <= 1 ? 1 : Math.max(0, at) / (positive.length - 1)
142
+ return lookOf(rank).accent
143
+ })
144
+ }
145
+
146
+ /**
147
+ * Visual state for a thinking level at fractional depth `t` in `[0, 1]`.
148
+ * @param t - 0 is the coldest thinking level, 1 the hottest.
149
+ * @returns gradient stops, accent, glow, and particle energy.
150
+ */
151
+ function lookOf(t) {
152
+ const p = clamp01(t)
153
+ const span = STOPS.length - 1
154
+ const scaled = p * span
155
+ const index = Math.min(span - 1, Math.floor(scaled))
156
+ const local = scaled - index
157
+ const low = STOPS[index]
158
+ const high = STOPS[index + 1]
159
+ const energy = low.energy + (high.energy - low.energy) * local
160
+ return {
161
+ gradient: `linear-gradient(90deg, ${rgb(mix(low.from, high.from, local))} 0%, ${rgb(mix(low.to, high.to, local))} 100%)`,
162
+ accent: rgb(mix(low.to, high.to, local)),
163
+ glow: `${local < 0.5 ? low.glow : high.glow}${(0.18 + energy * 0.42).toFixed(2)})`,
164
+ energy,
165
+ }
166
+ }
167
+
168
+ // ---------------------------------------------------------------------
169
+ // Particle field. Density, speed, sparkle and trails all follow energy;
170
+ // nothing is drawn at all on the "off" rail.
171
+ // ---------------------------------------------------------------------
172
+ /**
173
+ * Pixel x where the particle field must stop: the knob's centre.
174
+ * @param width - measured rail width.
175
+ * @param height - measured rail height, which equals the knob diameter.
176
+ * @param fraction - stop fraction in `[0, 1]`.
177
+ * @returns the limit in CSS pixels.
178
+ */
179
+ function limitOf(width, height, fraction) {
180
+ const knob = Math.min(height, width)
181
+ return knob / 2 + (width - knob) * clamp01(fraction ?? 1)
182
+ }
183
+ /**
184
+ * Animation loop bound to one canvas ELEMENT, not to a ref object.
185
+ *
186
+ * The canvas only exists while the effort pane is mounted, and switching to
187
+ * the model pane unmounts it — returning mounts a brand-new node. Keying the
188
+ * effect on a ref object would leave the dependency list unchanged across
189
+ * that swap, so the loop would keep painting the orphaned canvas and the new
190
+ * one would stay blank until the card was closed and reopened.
191
+ *
192
+ * @param canvas - the mounted canvas node, or null while unmounted.
193
+ * @param lookRef - current visual state, published per render.
194
+ * @param repaintRef - receives a nudge function the seat calls on change.
195
+ * @param enabled - whether the rail should animate at all.
196
+ */
197
+ function useParticles(canvas, lookRef, repaintRef, enabled) {
198
+ react.useEffect(() => {
199
+ if (!enabled || canvas === null || canvas === undefined) return undefined
200
+ let context = null
201
+ try {
202
+ context = canvas.getContext('2d')
203
+ } catch (error) {
204
+ console.warn(LOG, 'canvas 2d unavailable; falling back to a static rail', error)
205
+ }
206
+ if (context === null) return undefined
207
+
208
+ const reduceMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
209
+ let frame = 0
210
+ let width = 0
211
+ let height = 0
212
+ let last = 0
213
+ const particles = []
214
+
215
+ const measure = () => {
216
+ const rect = canvas.getBoundingClientRect()
217
+ const dpr = Math.min(2, window.devicePixelRatio || 1)
218
+ width = Math.max(1, Math.round(rect.width))
219
+ height = Math.max(1, Math.round(rect.height))
220
+ canvas.width = Math.round(width * dpr)
221
+ canvas.height = Math.round(height * dpr)
222
+ context.setTransform(dpr, 0, 0, dpr, 0, 0)
223
+ }
224
+ measure()
225
+
226
+ let observer = null
227
+ if (typeof ResizeObserver === 'function') {
228
+ observer = new ResizeObserver(measure)
229
+ observer.observe(canvas)
230
+ }
231
+
232
+ const MAX_PARTICLES = 120
233
+ const seed = (particle, atStart) => {
234
+ const energy = lookRef.current.energy
235
+ // The field lives inside the filled part of the rail, so energy reads
236
+ // as belonging to the selected level rather than the whole track.
237
+ const limit = limitOf(width, height, lookRef.current.fillFraction)
238
+ particle.x = atStart === true ? Math.random() * limit : -4
239
+ particle.y = height * (0.28 + Math.random() * 0.44)
240
+ particle.vx = (0.22 + Math.random() * 0.55) * (0.35 + energy)
241
+ particle.vy = (Math.random() - 0.5) * 0.3
242
+ particle.radius = 0.7 + Math.random() * 1.35
243
+ particle.age = 0
244
+ particle.span = 28 + Math.random() * 36
245
+ return particle
246
+ }
247
+
248
+ const draw = (now) => {
249
+ const delta = last === 0 ? 16.7 : Math.min(48, now - last)
250
+ last = now
251
+ const look = lookRef.current
252
+ const energy = look.energy
253
+ const limit = limitOf(width, height, look.fillFraction)
254
+ const wanted = Math.round(energy <= 0.02 ? 0 : 10 + energy * (MAX_PARTICLES - 10))
255
+
256
+ while (particles.length < wanted) particles.push(seed({}, true))
257
+ if (particles.length > wanted) particles.length = wanted
258
+
259
+ context.clearRect(0, 0, width, height)
260
+ if (particles.length > 0) {
261
+ const speed = 1 + energy * 2.5
262
+ for (const particle of particles) {
263
+ particle.x += particle.vx * speed * (delta / 16.7)
264
+ particle.y += particle.vy * (delta / 16.7)
265
+ particle.age += delta / 16.7
266
+ if (particle.age > particle.span || particle.x > limit + 6) seed(particle, false)
267
+ const fade = Math.sin(Math.PI * clamp01(particle.age / particle.span))
268
+ const alpha = fade * (0.24 + energy * 0.5)
269
+ const radius = particle.radius * (0.8 + energy * 0.85)
270
+ context.beginPath()
271
+ context.arc(particle.x, particle.y, radius, 0, Math.PI * 2)
272
+ context.fillStyle = `rgba(255,255,255,${alpha.toFixed(3)})`
273
+ context.fill()
274
+ if (energy > 0.55) {
275
+ context.beginPath()
276
+ context.moveTo(particle.x, particle.y)
277
+ context.lineTo(particle.x - particle.vx * 8 * energy, particle.y - particle.vy * 8)
278
+ context.strokeStyle = `rgba(255,255,255,${(alpha * 0.3).toFixed(3)})`
279
+ context.lineWidth = Math.max(0.5, radius * 0.5)
280
+ context.stroke()
281
+ }
282
+ }
283
+ }
284
+ frame = requestAnimationFrame(draw)
285
+ }
286
+
287
+ const start = () => {
288
+ if (frame !== 0 || reduceMotion) return
289
+ last = 0
290
+ frame = requestAnimationFrame(draw)
291
+ }
292
+ repaintRef.current = start
293
+ start()
294
+
295
+ return () => {
296
+ if (frame !== 0) cancelAnimationFrame(frame)
297
+ frame = 0
298
+ repaintRef.current = null
299
+ observer?.disconnect()
300
+ context.clearRect(0, 0, width, height)
301
+ }
302
+ }, [canvas, lookRef, repaintRef, enabled])
303
+ }
304
+
305
+ // ---------------------------------------------------------------------
306
+ // Error boundary: the seat must never throw, or the slot renderer retires
307
+ // it and the shipped selector silently takes the seat back.
308
+ //
309
+ // It must also never be STICKY. A transient render failure — a catalog
310
+ // reloading, a session whose directory is momentarily unresolvable — would
311
+ // otherwise park this fallback in the composer forever, which reads to the
312
+ // user as "the slider worked, then it disappeared".
313
+ // ---------------------------------------------------------------------
314
+ /** Retry backoff, capped; the seat keeps trying for as long as it is mounted. */
315
+ const RETRY_BASE_MS = 1200
316
+ const RETRY_CAP_MS = 10000
317
+
318
+ class SeatBoundary extends react.Component {
319
+ constructor(props) {
320
+ super(props)
321
+ this.state = { error: null, attempt: 0 }
322
+ this.timer = null
323
+ this.clearTimer = () => {
324
+ if (this.timer !== null) {
325
+ clearTimeout(this.timer)
326
+ this.timer = null
327
+ }
328
+ }
329
+ this.retry = () => {
330
+ this.clearTimer()
331
+ this.setState((state) => ({ error: null, attempt: state.attempt + 1 }))
332
+ }
333
+ }
334
+
335
+ static getDerivedStateFromError(error) {
336
+ return { error }
337
+ }
338
+
339
+ componentDidCatch(error, info) {
340
+ // Feed the shared diagnostic channel: this is what raises the visible
341
+ // notice and fills window.__dshThinkingSlider for a DevTools read.
342
+ record('seat-render', error)
343
+ console.error(`${LOG} seat render failed; showing the fallback and retrying`, error, info)
344
+ this.clearTimer()
345
+ const delay = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * (this.state.attempt + 1))
346
+ this.timer = setTimeout(this.retry, delay)
347
+ }
348
+
349
+ componentDidUpdate() {
350
+ // A successful render clears the backoff so a later failure starts fresh.
351
+ if (this.state.error === null && this.state.attempt > 0) this.setState({ attempt: 0 })
352
+ }
353
+
354
+ componentWillUnmount() {
355
+ this.clearTimer()
356
+ }
357
+
358
+ render() {
359
+ if (this.state.error === null) {
360
+ // Remount the seat on every retry so a stale subtree cannot survive.
361
+ return jsx(Seat, { ...this.props.face, key: `attempt-${this.state.attempt}` })
362
+ }
363
+ return jsxs('div', {
364
+ className: 'tsl-fallback',
365
+ title: String(this.state.error?.message ?? this.state.error),
366
+ children: [
367
+ jsx('span', { children: '模型' }),
368
+ jsx('span', { className: 'tsl-fallbackBadge', children: '推理等级不可用' }),
369
+ jsx('button', {
370
+ type: 'button',
371
+ className: 'tsl-fallbackRetry',
372
+ onClick: () => this.retry(),
373
+ children: '重试',
374
+ }),
375
+ ],
376
+ })
377
+ }
378
+ }
379
+
380
+ // ---------------------------------------------------------------------
381
+ // The seat
382
+ // ---------------------------------------------------------------------
383
+ const CHECK_PATH = 'M2.5 8.2 6 11.5 13.5 4'
384
+
385
+ /**
386
+ * The one geometry both the fill and the knob use.
387
+ *
388
+ * The knob is a full-height circle, so a stop's position is its CENTRE,
389
+ * inset by half a knob at each end: the first stop sits flush against the
390
+ * left cap and the last flush against the right cap. The fill is given this
391
+ * same expression as its `width`, which is what keeps the coloured rail
392
+ * ending exactly under the knob — two different formulas (a percentage
393
+ * inset versus a pixel inset) drift apart and leave a bare notch of track
394
+ * showing beside the knob.
395
+ *
396
+ * `--tsl-knob` is the single source of the size: the stylesheet sizes the
397
+ * knob and the rail from it, this function places everything by it, and the
398
+ * particle field derives its own limit from the measured canvas height.
399
+ *
400
+ * @param index - stop index.
401
+ * @param count - number of stops.
402
+ * @returns a CSS length usable as `left`, `width`, or a scale-label anchor.
403
+ */
404
+ function centerOf(index, count) {
405
+ const fraction = count <= 1 ? 1 : index / (count - 1)
406
+ return `calc(var(--tsl-knob) / 2 + (100% - var(--tsl-knob)) * ${fraction})`
407
+ }
408
+
409
+ /** The same fraction `centerOf` uses, for consumers that need a number. */
410
+ function fractionOf(index, count) {
411
+ return count <= 1 ? 1 : index / (count - 1)
412
+ }
413
+
414
+ function Seat(props) {
415
+ const { locked, available, directory, load, select } = props
416
+
417
+ const state = react.useSyncExternalStore(
418
+ (subscribe) => directory.subscribe(subscribe),
419
+ () => directory.getSnapshot(),
420
+ )
421
+
422
+ const [open, setOpen] = react.useState(false)
423
+ const [pane, setPane] = react.useState('effort')
424
+ const [preview, setPreview] = react.useState(null)
425
+ const [notice, setNotice] = react.useState(null)
426
+ const [placement, setPlacement] = react.useState(null)
427
+
428
+ const rootRef = react.useRef(null)
429
+ const cardRef = react.useRef(null)
430
+ const trackRef = react.useRef(null)
431
+ // A callback ref in state, not a ref object: the particle loop must
432
+ // re-bind whenever a canvas is remounted (pane switches).
433
+ const [canvasNode, setCanvasNode] = react.useState(null)
434
+ const lookRef = react.useRef(OFF_LOOK)
435
+ const repaintRef = react.useRef(null)
436
+
437
+ react.useEffect(() => {
438
+ if (available === true) load()
439
+ }, [available, load])
440
+
441
+ const groups = Array.isArray(state?.groups) ? state.groups : []
442
+ const failures = Array.isArray(state?.failures) ? state.failures : []
443
+ const current = state?.current ?? null
444
+
445
+ const currentModel = react.useMemo(() => {
446
+ if (current === null) return undefined
447
+ for (const group of groups) {
448
+ if (group?.id !== current.provider) continue
449
+ const models = Array.isArray(group.models) ? group.models : []
450
+ const hit = models.find((model) => model?.id === current.model)
451
+ if (hit !== undefined) return hit
452
+ }
453
+ return undefined
454
+ }, [groups, current])
455
+
456
+ const efforts = Array.isArray(currentModel?.reasoning?.efforts) ? currentModel.reasoning.efforts : []
457
+ const supported = efforts.length > 0
458
+ const activeEffort = current?.reasoningEffort ?? currentModel?.reasoning?.defaultEffort ?? null
459
+ const shownEffort = preview ?? activeEffort
460
+ const busy = state?.pending !== null && state?.pending !== undefined
461
+ const inert = locked === true || available !== true || current === null || !supported
462
+
463
+ const index = supported ? Math.max(0, efforts.findIndex((level) => level?.id === shownEffort)) : -1
464
+ /** Thinking levels only: `off` is styled apart from the escalation ramp. */
465
+ const positive = react.useMemo(
466
+ () => efforts.filter((level) => level?.id !== 'off'),
467
+ [efforts],
468
+ )
469
+ const isOff = shownEffort === null || shownEffort === undefined || String(shownEffort).toLowerCase() === 'off'
470
+ const positiveIndex = positive.findIndex((level) => level?.id === shownEffort)
471
+ const thinking = !isOff && positive.length > 0 && positiveIndex >= 0
472
+ const rank = positive.length <= 1 ? 1 : Math.max(0, positiveIndex) / (positive.length - 1)
473
+ const look = react.useMemo(() => (thinking ? lookOf(rank) : OFF_LOOK), [thinking, rank])
474
+ const fillFraction = fractionOf(Math.max(0, index), Math.max(1, efforts.length))
475
+
476
+ // Publish the look for the animation loop, then nudge a repaint so a
477
+ // change lands even while the browser is throttling frames.
478
+ react.useEffect(() => {
479
+ lookRef.current = { ...look, fillFraction }
480
+ repaintRef.current?.()
481
+ }, [look, fillFraction, lookRef, repaintRef])
482
+
483
+ useParticles(canvasNode, lookRef, repaintRef, open && supported)
484
+
485
+ const activeLabel = !supported
486
+ ? state?.retainedEffort ?? '推理等级'
487
+ : isOff
488
+ ? efforts[0]?.name ?? 'Off'
489
+ : efforts[index]?.name ?? String(shownEffort)
490
+ const modelLabel = currentModel?.name ?? (current === null ? '模型' : `${current.provider}/${current.model}`)
491
+
492
+ const commit = react.useCallback(
493
+ async (effort) => {
494
+ if (current === null || effort === activeEffort) return
495
+ try {
496
+ const result = await select({
497
+ provider: current.provider,
498
+ model: current.model,
499
+ ...(effort === null || effort === undefined ? {} : { reasoningEffort: effort }),
500
+ })
501
+ if (result !== undefined && result !== null && result.ok === false) {
502
+ setNotice(`${result.error?.code ?? 'error'}: ${result.error?.message ?? '选择失败'}`)
503
+ } else {
504
+ setNotice(null)
505
+ }
506
+ } catch (error) {
507
+ console.error(LOG, 'selection failed', error)
508
+ setNotice(String(error?.message ?? error))
509
+ }
510
+ },
511
+ [activeEffort, current, select],
512
+ )
513
+
514
+ const effortAt = react.useCallback(
515
+ (clientX) => {
516
+ const node = trackRef.current
517
+ if (node === null || node === undefined || efforts.length === 0) return undefined
518
+ const rect = node.getBoundingClientRect()
519
+ if (rect.width <= 0) return undefined
520
+ const ratio = clamp01((clientX - rect.left) / rect.width)
521
+ const scaled = (ratio - 0.06) / 0.88
522
+ const index = Math.round(clamp01(scaled) * (efforts.length - 1))
523
+ return efforts[index]?.id
524
+ },
525
+ [efforts],
526
+ )
527
+
528
+ const endDrag = react.useCallback(
529
+ (event) => {
530
+ const next = effortAt(event.clientX)
531
+ setPreview(null)
532
+ if (next !== undefined) void commit(next)
533
+ },
534
+ [commit, effortAt],
535
+ )
536
+
537
+ const onKeyDown = (event) => {
538
+ if (inert) return
539
+ const move = (delta) => {
540
+ const from = index < 0 ? 0 : index
541
+ const next = efforts[Math.min(efforts.length - 1, Math.max(0, from + delta))]
542
+ if (next !== undefined) void commit(next.id)
543
+ }
544
+ if (event.key === 'ArrowRight' || event.key === 'ArrowUp') { event.preventDefault(); move(1) }
545
+ else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') { event.preventDefault(); move(-1) }
546
+ else if (event.key === 'Home') { event.preventDefault(); if (efforts[0]) void commit(efforts[0].id) }
547
+ else if (event.key === 'End') { event.preventDefault(); const last = efforts[efforts.length - 1]; if (last) void commit(last.id) }
548
+ else if (event.key === 'Escape') { event.preventDefault(); setOpen(false) }
549
+ }
550
+
551
+ // Anchor the card just above the trigger, clamped into the viewport.
552
+ react.useLayoutEffect(() => {
553
+ if (!open) { setPlacement(null); return undefined }
554
+ const place = () => {
555
+ const trigger = rootRef.current?.getBoundingClientRect()
556
+ const card = cardRef.current?.getBoundingClientRect()
557
+ if (trigger === undefined || card === undefined) return
558
+ const margin = 12
559
+ const gap = 10
560
+ const width = card.width || 320
561
+ const left = Math.min(
562
+ Math.max(margin, trigger.right - width),
563
+ Math.max(margin, window.innerWidth - width - margin),
564
+ )
565
+ const bottom = Math.min(
566
+ Math.max(margin, window.innerHeight - trigger.top + gap),
567
+ Math.max(margin, window.innerHeight - card.height - margin),
568
+ )
569
+ setPlacement({ left: Math.round(left), bottom: Math.round(bottom) })
570
+ }
571
+ place()
572
+ window.addEventListener('resize', place)
573
+ return () => window.removeEventListener('resize', place)
574
+ }, [open, pane])
575
+
576
+ // Dismiss on outside pointer down / Escape.
577
+ react.useEffect(() => {
578
+ if (!open) return undefined
579
+ const onPointerDown = (event) => {
580
+ const target = event.target
581
+ if (rootRef.current?.contains(target) === true) return
582
+ if (cardRef.current?.contains(target) === true) return
583
+ setOpen(false)
584
+ }
585
+ document.addEventListener('pointerdown', onPointerDown, true)
586
+ return () => document.removeEventListener('pointerdown', onPointerDown, true)
587
+ }, [open])
588
+
589
+ const chooseModel = (group, model) => {
590
+ setNotice(null)
591
+ const effort = model?.reasoning?.defaultEffort
592
+ const same = current !== null && current.provider === group.id && current.model === model.id
593
+ if (!same) {
594
+ void select({
595
+ provider: group.id,
596
+ model: model.id,
597
+ ...(effort === undefined ? {} : { reasoningEffort: effort }),
598
+ }).then((result) => {
599
+ if (result !== undefined && result !== null && result.ok === false) {
600
+ setNotice(`${result.error?.code ?? 'error'}: ${result.error?.message ?? '选择失败'}`)
601
+ } else {
602
+ setPane('effort')
603
+ }
604
+ }).catch((error) => {
605
+ console.error(LOG, 'model selection failed', error)
606
+ setNotice(String(error?.message ?? error))
607
+ })
608
+ } else {
609
+ setPane('effort')
610
+ }
611
+ }
612
+
613
+ const triggerChevron = jsx('svg', {
614
+ className: `tsl-triggerChevron${open ? ' tsl-triggerChevronOpen' : ''}`,
615
+ width: 12,
616
+ height: 12,
617
+ viewBox: '0 0 16 16',
618
+ fill: 'none',
619
+ 'aria-hidden': true,
620
+ children: jsx('path', {
621
+ d: 'M4 6.5 8 10.5 12 6.5',
622
+ stroke: 'currentColor',
623
+ strokeWidth: 1.5,
624
+ strokeLinecap: 'round',
625
+ strokeLinejoin: 'round',
626
+ }),
627
+ })
628
+
629
+ const trigger = jsxs('button', {
630
+ ref: rootRef,
631
+ type: 'button',
632
+ className: 'tsl-trigger',
633
+ disabled: locked === true || available !== true || current === null,
634
+ 'aria-haspopup': 'dialog',
635
+ 'aria-expanded': open,
636
+ title: supported ? `${modelLabel} · ${activeLabel}` : modelLabel,
637
+ onClick: () => {
638
+ setNotice(null)
639
+ setPane('effort')
640
+ setOpen((value) => !value)
641
+ },
642
+ children: [
643
+ jsx('span', { className: 'tsl-triggerModel', children: modelLabel }),
644
+ supported
645
+ ? jsx('span', { className: 'tsl-triggerDot', children: '·' })
646
+ : null,
647
+ supported
648
+ ? jsx('span', {
649
+ className: 'tsl-triggerLevel',
650
+ style: { color: isOff ? undefined : look.accent },
651
+ children: busy ? '…' : activeLabel,
652
+ })
653
+ : null,
654
+ triggerChevron,
655
+ ],
656
+ })
657
+
658
+ if (!open) return jsx('div', { className: 'tsl-root', children: trigger })
659
+
660
+ const scale = jsx('div', {
661
+ className: 'tsl-scale',
662
+ children: efforts.map((level, at) => jsx('span', {
663
+ className: 'tsl-scaleItem',
664
+ 'data-active': at === index,
665
+ style: {
666
+ left: centerOf(at, efforts.length),
667
+ ...(at === index && !isOff ? { color: look.accent } : {}),
668
+ },
669
+ children: level?.name ?? level?.id,
670
+ }, level?.id ?? at)),
671
+ })
672
+
673
+ const track = jsxs('div', {
674
+ ref: trackRef,
675
+ className: 'tsl-trackWrap',
676
+ role: 'slider',
677
+ tabIndex: inert ? -1 : 0,
678
+ 'aria-label': '推理强度',
679
+ 'aria-valuemin': 0,
680
+ 'aria-valuemax': Math.max(0, efforts.length - 1),
681
+ 'aria-valuenow': Math.max(0, index),
682
+ 'aria-valuetext': activeLabel,
683
+ 'aria-disabled': inert,
684
+ 'data-inert': inert,
685
+ onPointerDown: (event) => {
686
+ if (inert) return
687
+ event.preventDefault()
688
+ try { event.currentTarget.setPointerCapture(event.pointerId) } catch {}
689
+ const next = effortAt(event.clientX)
690
+ setPreview(next ?? null)
691
+ },
692
+ onPointerMove: (event) => {
693
+ if (inert || event.buttons !== 1) return
694
+ const next = effortAt(event.clientX)
695
+ setPreview(next ?? null)
696
+ },
697
+ onPointerUp: (event) => {
698
+ if (inert) return
699
+ endDrag(event)
700
+ },
701
+ onPointerCancel: () => setPreview(null),
702
+ onKeyDown,
703
+ children: [
704
+ jsxs('div', {
705
+ className: 'tsl-track',
706
+ style: { boxShadow: look.energy > 0.02 ? `0 0 14px ${look.glow}` : undefined },
707
+ children: [
708
+ jsx('div', {
709
+ className: 'tsl-fill',
710
+ style: {
711
+ width: centerOf(Math.max(0, index), Math.max(1, efforts.length)),
712
+ background: look.gradient,
713
+ opacity: isOff ? 0.45 : 1,
714
+ },
715
+ }),
716
+ jsx('canvas', { ref: setCanvasNode, className: 'tsl-canvas' }),
717
+ jsx('div', {
718
+ className: 'tsl-ticks',
719
+ style: { color: isOff ? 'var(--dsw-alias-label-caption)' : '#fff' },
720
+ children: efforts.map((level, at) => jsx('span', {
721
+ className: 'tsl-tick',
722
+ style: { left: centerOf(at, efforts.length) },
723
+ }, `tick-${level?.id ?? at}`)),
724
+ }),
725
+ jsx('div', {
726
+ className: 'tsl-thumb',
727
+ style: {
728
+ left: centerOf(Math.max(0, index), Math.max(1, efforts.length)),
729
+ boxShadow: `0 1px 4px rgba(0,0,0,.32)${look.energy > 0.02 ? `, 0 0 12px ${look.glow}` : ''}`,
730
+ },
731
+ }),
732
+ ],
733
+ }),
734
+ ],
735
+ })
736
+
737
+ const effortPane = jsxs('div', {
738
+ children: [
739
+ jsxs('div', {
740
+ className: 'tsl-head',
741
+ children: [
742
+ jsx('span', {
743
+ className: 'tsl-level',
744
+ style: { color: isOff ? undefined : look.accent },
745
+ children: busy ? '…' : activeLabel,
746
+ }),
747
+ activeEffort !== null && activeEffort !== undefined
748
+ ? jsx('button', {
749
+ type: 'button',
750
+ className: 'tsl-reset',
751
+ title: '回到 Default',
752
+ 'aria-label': '回到 Default',
753
+ onClick: () => {
754
+ if (current === null) return
755
+ void select({ provider: current.provider, model: current.model })
756
+ },
757
+ children: jsx('svg', {
758
+ width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true,
759
+ children: jsx('path', {
760
+ d: 'M13 8a5 5 0 1 1-1.6-3.7M13 2.5V5.5H10',
761
+ stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round',
762
+ }),
763
+ }),
764
+ })
765
+ : null,
766
+ ],
767
+ }),
768
+ jsxs('button', {
769
+ type: 'button',
770
+ className: 'tsl-modelRow',
771
+ disabled: current === null,
772
+ onClick: () => setPane('model'),
773
+ children: [
774
+ jsx('span', { className: 'tsl-modelName', children: modelLabel }),
775
+ jsx('svg', {
776
+ width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true,
777
+ children: jsx('path', {
778
+ d: 'M6 3.5 10.5 8 6 12.5',
779
+ stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round',
780
+ }),
781
+ }),
782
+ ],
783
+ }),
784
+ supported ? track : jsx('div', { className: 'tsl-empty', children: '这个模型没有提供推理等级' }),
785
+ supported ? scale : null,
786
+ notice !== null ? jsx('div', { className: 'tsl-failure', children: notice }) : null,
787
+ ],
788
+ })
789
+
790
+ const modelPane = jsxs('div', {
791
+ children: [
792
+ jsxs('div', {
793
+ className: 'tsl-head',
794
+ children: [
795
+ jsx('button', {
796
+ type: 'button',
797
+ className: 'tsl-reset',
798
+ style: { left: -2, right: 'auto' },
799
+ title: '返回推理强度',
800
+ 'aria-label': '返回推理强度',
801
+ onClick: () => setPane('effort'),
802
+ children: jsx('svg', {
803
+ width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true,
804
+ children: jsx('path', {
805
+ d: 'M10 3.5 5.5 8 10 12.5',
806
+ stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round',
807
+ }),
808
+ }),
809
+ }),
810
+ jsx('span', { className: 'tsl-level', style: { fontSize: 15 }, children: '选择模型' }),
811
+ ],
812
+ }),
813
+ jsx('div', { style: { height: 10 } }),
814
+ jsxs('div', {
815
+ className: 'tsl-list',
816
+ role: 'listbox',
817
+ children: [
818
+ groups.length === 0 ? jsx('div', { className: 'tsl-empty', children: '正在加载模型目录…' }) : null,
819
+ ...groups.map((group) => {
820
+ const models = Array.isArray(group?.models) ? group.models : []
821
+ return jsxs('div', {
822
+ children: [
823
+ jsx('div', { className: 'tsl-group', children: group?.name ?? group?.id }),
824
+ ...models.map((model) => {
825
+ const selected = current !== null && current.provider === group.id && current.model === model?.id
826
+ const levels = Array.isArray(model?.reasoning?.efforts) ? model.reasoning.efforts : []
827
+ const ramp = rampOf(levels)
828
+ const names = levels.map((level) => level?.name ?? level?.id).join(' · ')
829
+ return jsxs('button', {
830
+ type: 'button',
831
+ role: 'option',
832
+ 'aria-selected': selected,
833
+ className: 'tsl-item',
834
+ 'data-active': selected,
835
+ title: levels.length > 0 ? `推理等级:${names}` : '这个模型没有推理等级',
836
+ onClick: () => chooseModel(group, model),
837
+ children: [
838
+ jsx('span', { className: 'tsl-itemText', children: model?.name ?? model?.id }),
839
+ jsx('span', {
840
+ className: 'tsl-itemMeta',
841
+ 'aria-hidden': true,
842
+ children: levels.length > 0
843
+ ? jsx('span', {
844
+ className: 'tsl-ramp',
845
+ children: levels.map((level, at) => jsx('i', {
846
+ className: 'tsl-rampDot',
847
+ style: { background: ramp[at] },
848
+ }, `dot-${level?.id ?? at}`)),
849
+ })
850
+ : jsx('span', { className: 'tsl-rampNone', children: '—' }),
851
+ }),
852
+ selected
853
+ ? jsx('svg', {
854
+ className: 'tsl-check', viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true,
855
+ children: jsx('path', {
856
+ d: CHECK_PATH, stroke: 'currentColor', strokeWidth: 1.8,
857
+ strokeLinecap: 'round', strokeLinejoin: 'round',
858
+ }),
859
+ })
860
+ : null,
861
+ ],
862
+ }, `${group.id}/${model?.id}`)
863
+ }),
864
+ ],
865
+ }, group?.id)
866
+ }),
867
+ ...failures.map((failure) => jsx('div', {
868
+ className: 'tsl-failure',
869
+ children: `${failure?.name ?? failure?.id}: ${failure?.message ?? '加载失败'}`,
870
+ }, `failure/${failure?.id}`)),
871
+ notice !== null ? jsx('div', { className: 'tsl-failure', children: notice }) : null,
872
+ ],
873
+ }),
874
+ ],
875
+ })
876
+
877
+ const card = jsx('div', {
878
+ ref: cardRef,
879
+ className: 'tsl-card',
880
+ role: 'dialog',
881
+ 'aria-label': '模型与推理强度',
882
+ style: placement === null ? { left: 0, bottom: 0, visibility: 'hidden' } : placement,
883
+ children: pane === 'model' ? modelPane : effortPane,
884
+ })
885
+
886
+ const portal = typeof document === 'undefined'
887
+ ? card
888
+ : createPortal(card, document.body)
889
+
890
+ return jsxs('div', { className: 'tsl-root', children: [trigger, portal] })
891
+ }
892
+
893
+ // ---------------------------------------------------------------------
894
+ // Plugin body
895
+ // ---------------------------------------------------------------------
896
+ /**
897
+ * Services this plugin needs.
898
+ *
899
+ * `remote` and `remote.session` are not used directly — they are required
900
+ * because `ctx.modelDirectories` hands back a cordis *traceable* proxy whose
901
+ * `.ctx` is rebound to the ACCESSING context. `directoryFor()` then reads
902
+ * `this.ctx.remote.session` against this plugin's context, so the dependency
903
+ * must be declared here or cordis throws
904
+ * `cannot get property "remote.session" without inject`. The shipped
905
+ * ui-model-selection plugin declares the same pair for the same reason.
906
+ */
907
+ const inject = ['slots', 'sessions', 'remote', 'remote.session']
908
+
909
+ /** The composer seat this plugin shadows. */
910
+ const SLOT = 'conversation.input.model'
911
+ /** Register just below the shipped selector: the lowest priority renders. */
912
+ const BASE_PRIORITY = -1
913
+ /**
914
+ * Priority slots this plugin will retreat through before giving up.
915
+ *
916
+ * The Host hot-reloads a client bundle whenever its file changes, and a
917
+ * `single` slot REFUSES a second registration at an occupied priority. A
918
+ * generation whose predecessor was not disposed therefore cannot register
919
+ * at all, `apply()` fails, and the seat silently reverts to the shipped
920
+ * selector until a full page reload — the "it loaded, then it vanished"
921
+ * failure. Retreating to a lower priority always still shadows the shipped
922
+ * seat (lowest renders), so a leaked generation is inert instead of fatal.
923
+ */
924
+ const MAX_GENERATIONS = 24
925
+ /** Abdication recoveries allowed per plugin load, so a hard crash cannot spin. */
926
+ const MAX_RECOVERIES = 3
927
+ /** Diagnostics retained for DevTools inspection. */
928
+ const diagnostics = []
929
+ const record = (phase, error) => {
930
+ const entry = {
931
+ at: new Date().toISOString(),
932
+ phase,
933
+ message: String(error?.message ?? error),
934
+ stack: typeof error?.stack === 'string' ? error.stack.split('\n').slice(0, 6).join('\n') : undefined,
935
+ }
936
+ diagnostics.push(entry)
937
+ if (diagnostics.length > 20) diagnostics.shift()
938
+ console.error(`${LOG} ${phase} failed`, error)
939
+ publishDiagnostics()
940
+ showNotice(entry)
941
+ return entry
942
+ }
943
+ /** Expose the log where a DevTools one-liner can read it. */
944
+ const publishDiagnostics = () => {
945
+ try {
946
+ globalThis.__dshThinkingSlider = { diagnostics, plugin: 'dsh-thinking-slider' }
947
+ } catch {}
948
+ }
949
+ /** One visible, dismissible notice per page load: an invisible failure is unfixable. */
950
+ let noticeShown = false
951
+ const showNotice = (entry) => {
952
+ if (noticeShown || typeof document === 'undefined' || document.body === null) return
953
+ noticeShown = true
954
+ try {
955
+ const box = document.createElement('div')
956
+ box.setAttribute('data-plugin', 'dsh-thinking-slider')
957
+ box.style.cssText = [
958
+ 'position:fixed', 'right:16px', 'bottom:16px', 'z-index:2147483000',
959
+ 'max-width:420px', 'padding:10px 12px', 'border-radius:10px',
960
+ 'background:#3a1d1d', 'color:#ffd7d7', 'font:12px/18px ui-monospace,monospace',
961
+ 'box-shadow:0 10px 30px rgba(0,0,0,.45)', 'white-space:pre-wrap',
962
+ ].join(';')
963
+ box.textContent = `dsh-thinking-slider ${entry.phase} 失败:\n${entry.message}\n\n(截图给我即可定位;点此关闭)`
964
+ box.addEventListener('click', () => box.remove())
965
+ document.body.appendChild(box)
966
+ } catch {}
967
+ }
968
+
969
+ function apply(ctx) {
970
+ try {
971
+ ctx.inject(['slots', 'modelDirectories'], (scope) => {
972
+ const slots = scope.slots
973
+ const sessions = scope.sessions
974
+ const models = scope.modelDirectories
975
+
976
+ let generation = 0
977
+ let recoveries = 0
978
+ let handle = null
979
+ let stopped = false
980
+
981
+ /**
982
+ * The per-session face handed to the seat.
983
+ *
984
+ * This runs OUTSIDE the seat's React error boundary, so a throw here
985
+ * retires the slot entry outright — the seat would disappear with no
986
+ * fallback at all. The directory genuinely throws for a session whose
987
+ * scope or binding is not resolvable yet, so degrade instead.
988
+ */
989
+ const face = (sessionId) => {
990
+ try {
991
+ const directory = models.directoryFor(sessionId)
992
+ const available = sessions.subagentAddress(sessionId) === undefined
993
+ return {
994
+ available,
995
+ directory: directory.store,
996
+ load: () => {
997
+ if (available) directory.load().catch(() => {})
998
+ },
999
+ select: (selection) => (available ? directory.select(selection) : Promise.resolve(undefined)),
1000
+ }
1001
+ } catch (error) {
1002
+ record('inject', error)
1003
+ return {
1004
+ available: false,
1005
+ directory: undefined,
1006
+ load: () => {},
1007
+ select: () => Promise.resolve(undefined),
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ /** Register at the lowest free priority this plugin may claim. */
1013
+ const register = () => {
1014
+ while (generation < MAX_GENERATIONS) {
1015
+ const priority = BASE_PRIORITY - generation
1016
+ generation += 1
1017
+ try {
1018
+ handle = slots.register(
1019
+ { name: SLOT, priority, inject: face },
1020
+ (props) => jsx(SeatBoundary, { face: props }),
1021
+ )
1022
+ return handle
1023
+ } catch (error) {
1024
+ if (!/already has a registration/.test(String(error?.message ?? ''))) {
1025
+ record('register', error)
1026
+ throw error
1027
+ }
1028
+ // A predecessor leaked its registration; step down and retry.
1029
+ }
1030
+ }
1031
+ record('register', new Error(`no free priority after ${MAX_GENERATIONS} generations`))
1032
+ return null
1033
+ }
1034
+
1035
+ /** Put the seat back after the renderer retired it for a crash. */
1036
+ const recover = (error) => {
1037
+ record('entry-error', error)
1038
+ if (stopped || recoveries >= MAX_RECOVERIES) return
1039
+ recoveries += 1
1040
+ try {
1041
+ handle?.()
1042
+ } catch {}
1043
+ handle = null
1044
+ register()
1045
+ }
1046
+
1047
+ const stopErrors = typeof slots.onEntryError === 'function'
1048
+ ? slots.onEntryError((key, _entry, error, info) => {
1049
+ if (key !== SLOT || info?.abdicated !== true) return
1050
+ recover(error)
1051
+ })
1052
+ : undefined
1053
+
1054
+ const stopInject = slots.inject(SLOT, () => register())
1055
+
1056
+ // Owned by THIS plugin's fiber, so a hot reload disposes the seat
1057
+ // instead of leaving a registration that blocks the next generation.
1058
+ return () => {
1059
+ stopped = true
1060
+ try { stopInject?.() } catch {}
1061
+ try { stopErrors?.() } catch {}
1062
+ try { handle?.() } catch {}
1063
+ handle = null
1064
+ }
1065
+ })
1066
+ } catch (error) {
1067
+ // apply() must never throw: a throwing plugin body takes the seat away
1068
+ // with no fallback and no diagnostic.
1069
+ record('apply', error)
1070
+ }
1071
+ }
1072
+
1073
+ exports.apply = apply
1074
+ exports.inject = inject
1075
+ return module.exports
1076
+ },
1077
+ })
package/lib/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * dsh-thinking-slider - host half.
3
+ *
4
+ * This plugin is entirely browser-side: it replaces the composer model seat
5
+ * with a Codex-style reasoning-effort slider. The Host only needs the row to
6
+ * exist so the composition loads `./client` (declared in package.json under
7
+ * `dsh.client`); no Host Service, Event, or Config is contributed.
8
+ */
9
+ export const name = 'dsh-thinking-slider'
10
+
11
+ /** No Host capabilities are required. */
12
+ export const inject = []
13
+
14
+ /** Host half is a no-op. */
15
+ export function apply() {}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "dsh-thinking-slider",
3
+ "version": "0.1.0",
4
+ "description": "Codex-style reasoning-effort slider for the DeepSeek Harness composer: pick a model, then drag its thinking level on a gradient particle rail.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "MuFeng262",
8
+ "keywords": [
9
+ "deepseek-harness",
10
+ "dsh",
11
+ "dsh-plugin",
12
+ "cordis",
13
+ "reasoning-effort",
14
+ "thinking-level",
15
+ "ui"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/MuFeng262/dsh-thinking-slider.git"
20
+ },
21
+ "homepage": "https://github.com/MuFeng262/dsh-thinking-slider#readme",
22
+ "bugs": {
23
+ "url": "https://github.com/MuFeng262/dsh-thinking-slider/issues"
24
+ },
25
+ "main": "lib/index.js",
26
+ "exports": {
27
+ ".": "./lib/index.js",
28
+ "./client": "./lib/client.js",
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "lib",
33
+ "cordis.patch.yml",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "test": "node test/smoke.mjs"
39
+ },
40
+ "dsh": {
41
+ "bundle": {
42
+ "patch": "./cordis.patch.yml"
43
+ },
44
+ "client": {
45
+ "platform": "web"
46
+ }
47
+ }
48
+ }