dsh-vision-router 3.2.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,53 +11,71 @@ export const REMOTE_SETTINGS_CHANNEL = '/vision-router-settings'
11
11
  export const REMOTE_SETTINGS_PERMISSION = 'allowRemoteSettings'
12
12
  export const REMOTE_SETTINGS_AUTHORIZE_ENDPOINT = 'authorize'
13
13
 
14
- // Remote DSH pages are deliberately less privileged than the loopback settings UI.
15
- // This is a capability allow-list, not a blacklist: a future Config field is local-only
16
- // until it is reviewed and explicitly added here.
17
- export const REMOTE_SETTINGS_READABLE_FIELDS = Object.freeze([
18
- 'providers',
19
- 'routing',
20
- 'reverseRouting',
21
- 'routingMode',
22
- 'routingPreference',
23
- 'backgroundBenchmarking',
24
- 'textProvider',
25
- 'tool',
26
- 'structuredVisionBootstrap',
27
- 'visionDepth',
28
- 'visionDepthMaxCalls',
29
- 'guidanceOverrides',
30
- 'progressiveTools',
31
- 'autoActivateOnImage',
32
- 'extraVisionModels',
33
- 'rewriteImages',
34
- 'downscale',
35
- 'downscaleMaxPixels',
36
- 'cache',
37
- 'cacheTtlSeconds',
38
- 'cacheMaxEntries',
39
- 'timeoutMs',
40
- 'visionTaskTimeoutMs',
41
- 'visionTurnBudgetMs',
42
- 'ocrTimeoutMs',
43
- 'ocrEngine',
44
- 'localOnlyVision',
45
- 'freeFallback',
46
- 'freeCloudFirst',
47
- 'autoWrapProviders',
48
- 'wrappedProviders',
49
- 'onboardingSeen',
50
- ])
14
+ // Remote settings are an opt-in view of the *same* Host-owned DVR namespace.
15
+ // No second field allow-list: after the once-per-profile risk acknowledgement,
16
+ // DSH-authenticated clients can edit any ordinary field admitted by the Host
17
+ // schema. The permission flag itself is managed through the explicit
18
+ // risk-confirmation/revocation flow, not as an ordinary settings mutation.
19
+ const REDACTED = '[REDACTED]'
20
+ const SECRET_KEY = /(?:password|passwd|private.?key|(?:api|access|refresh).?token|token|secret|credential|api.?key|authorization)/i
51
21
 
52
- // Privacy-critical local-only policy is visible remotely for truthful status,
53
- // but only a loopback/local Settings page may disable it. This prevents an
54
- // already-authorized remote Settings session from re-enabling visual egress.
55
- export const REMOTE_SETTINGS_MUTABLE_FIELDS = Object.freeze(
56
- REMOTE_SETTINGS_READABLE_FIELDS.filter((field) => field !== 'localOnlyVision'),
57
- )
22
+ function redactUrl(value) {
23
+ if (typeof value !== 'string' || !/^[a-z][a-z\d+.-]*:\/\//i.test(value)) return value
24
+ try {
25
+ const url = new URL(value)
26
+ let changed = false
27
+ if (url.username || url.password) {
28
+ url.username = REDACTED
29
+ url.password = REDACTED
30
+ changed = true
31
+ }
32
+ for (const key of url.searchParams.keys()) {
33
+ if (SECRET_KEY.test(key)) { url.searchParams.set(key, REDACTED); changed = true }
34
+ }
35
+ return changed ? url.toString() : value
36
+ } catch { return value }
37
+ }
58
38
 
59
- const readable = new Set(REMOTE_SETTINGS_READABLE_FIELDS)
60
- const mutable = new Set(REMOTE_SETTINGS_MUTABLE_FIELDS)
39
+ function containsRedactedCredential(value, field = '') {
40
+ // A remote descriptor may contain a redacted proxy or endpoint URL. If a
41
+ // user edits that form field and re-saves it, a masked placeholder is NOT a
42
+ // credential and must never overwrite the original value in Host settings.
43
+ if (field !== 'apiKeyEnv' && field !== 'credentialRef' &&
44
+ SECRET_KEY.test(field) && value === REDACTED) return true
45
+ if (typeof value === 'string' && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
46
+ try {
47
+ const url = new URL(value)
48
+ if ([url.username, url.password].some((part) => {
49
+ try { return decodeURIComponent(part) === REDACTED } catch { return true }
50
+ })) return true
51
+ for (const [key, part] of url.searchParams) {
52
+ if (SECRET_KEY.test(key) && part === REDACTED) return true
53
+ }
54
+ } catch { /* Leave malformed URLs to the Host schema. */ }
55
+ }
56
+ if (Array.isArray(value)) return value.some((part) => containsRedactedCredential(part))
57
+ if (value && typeof value === 'object') {
58
+ return Object.entries(value).some(([key, part]) => containsRedactedCredential(part, key))
59
+ }
60
+ return false
61
+ }
62
+
63
+ function safeSettingsValue(value, field = '') {
64
+ // The DSH descriptor is already Host-redacted. These additional guards
65
+ // cover plain-text proxy URL userinfo and future nested secret-shaped fields
66
+ // without reintroducing a field-level *capability* allow-list.
67
+ if (field !== 'apiKeyEnv' && field !== 'credentialRef' && SECRET_KEY.test(field)) return REDACTED
68
+ if (Array.isArray(value)) return value.map((item) => safeSettingsValue(item))
69
+ if (value && typeof value === 'object') {
70
+ const out = {}
71
+ for (const [key, item] of Object.entries(value)) {
72
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue
73
+ out[key] = safeSettingsValue(item, key)
74
+ }
75
+ return out
76
+ }
77
+ return redactUrl(value)
78
+ }
61
79
 
62
80
  function badRequest(message) {
63
81
  return { ok: false, error: { code: 'bad-request', message, details: { issues: [] } } }
@@ -67,12 +85,12 @@ function settingsRejected(message) {
67
85
  return { ok: false, error: { code: 'settings-rejected', message, details: { ns: SETTINGS_NS } } }
68
86
  }
69
87
 
70
- function project(value, fields = readable) {
88
+ function project(value) {
71
89
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
72
- const out = Object.create(null)
73
- for (const field of fields) {
74
- if (Object.prototype.hasOwnProperty.call(value, field)) out[field] = structuredClone(value[field])
75
- }
90
+ const out = safeSettingsValue(value)
91
+ // Permission is not a normal remote-editable field. The authenticated
92
+ // describe envelope already exposes enabled/disabled state explicitly.
93
+ delete out[REMOTE_SETTINGS_PERMISSION]
76
94
  return out
77
95
  }
78
96
 
@@ -112,12 +130,15 @@ function validateMutation(payload, descriptor) {
112
130
  if (!Array.isArray(op.path) || op.path.length !== 1 || typeof op.path[0] !== 'string' || op.path[0] === '') return { error: 'remote settings may edit one top-level field at a time' }
113
131
  const field = op.path[0]
114
132
  if (field === '__proto__' || field === 'prototype' || field === 'constructor') return { error: 'unsafe settings field name' }
115
- if (!mutable.has(field)) return { error: 'Vision Router setting ' + JSON.stringify(field) + ' is local-only' }
133
+ if (field === REMOTE_SETTINGS_PERMISSION) return { error: 'Remote permission is managed by risk confirmation and local revocation' }
116
134
  const value = descriptor && descriptor.value
117
135
  if (typeof value !== 'object' || value === null || Array.isArray(value) || !Object.prototype.hasOwnProperty.call(value, field)) return { error: 'unknown Vision Router settings field ' + JSON.stringify(field) }
118
136
  if (op.op === 'set') {
119
137
  const budgetError = remoteConfigFieldAdmissionError(field, op.value)
120
138
  if (budgetError) return { error: budgetError }
139
+ if (containsRedactedCredential(op.value, field)) {
140
+ return { error: 'masked credentials cannot be saved; re-enter the credential value before editing this field' }
141
+ }
121
142
  }
122
143
  return { ops: [op], expectedRevision }
123
144
  }
@@ -144,10 +165,10 @@ function conflictResult(error) {
144
165
  * `acceptedRisk === true` is an acknowledgement bit for the UX flow, not an
145
166
  * authentication/authorization credential, proof of local presence, challenge
146
167
  * response, one-time secret, or administrator approval. Do not strengthen this
147
- * endpoint into a second security gate unless the product policy is explicitly
148
- * changed. The real capability boundary is the narrow remote mutable-field
149
- * allow-list plus the fields that remain local-only. The historical RPC/function
150
- * name uses "authorize"; do not infer security-auth semantics from that name.
168
+ * endpoint into a second authentication mechanism. Security is enforced by
169
+ * the DSH-authenticated Connection carrier, the persisted opt-in, the Host
170
+ * schema and resource bounds. Sensitive stored values are redacted on reads.
171
+ * The historical RPC name "authorize" does not mean user authentication.
151
172
  */
152
173
  export async function authorizeRemoteSettingsAfterRiskConfirmation(settings, payload, logger) {
153
174
  if (!payload || typeof payload !== 'object' || Array.isArray(payload) || payload.acceptedRisk !== true) {
@@ -248,8 +269,23 @@ export function createVisionRouterRemoteSettingsHandler(settings, logger) {
248
269
  logger?.warn?.('vision-router: remote settings mutation rejected: %s', error?.message ?? String(error))
249
270
  return settingsRejected(error?.message ?? 'Vision Router settings write was rejected')
250
271
  }
251
- try { return { ok: true, value: accessSnapshot(settings) } }
252
- catch { return settingsRejected('Vision Router settings changed but the refreshed view could not be read') }
272
+ try {
273
+ const after = namespaceDescriptor(settings)
274
+ const result = accessSnapshot(settings)
275
+ if (validated.ops[0].op === 'set' && result.enabled && after) {
276
+ const field = validated.ops[0].path[0]
277
+ const requested = validated.ops[0].value
278
+ const persisted = after.value?.[field]
279
+ // The Host may normalize values. Only echo what this caller already
280
+ // provided if the authoritative persisted value matches exactly.
281
+ if (JSON.stringify(persisted) === JSON.stringify(requested)
282
+ && JSON.stringify(result.view.value[field]) !== JSON.stringify(requested)) {
283
+ result.view.value[field] = structuredClone(requested)
284
+ if (Object.hasOwn(after.user ?? {}, field)) result.view.user[field] = structuredClone(requested)
285
+ }
286
+ }
287
+ return { ok: true, value: result }
288
+ } catch { return settingsRejected('Vision Router settings changed but the refreshed view could not be read') }
253
289
  }
254
290
  }
255
291
 
@@ -39,8 +39,8 @@ export function createRemoteSettingsRiskClientBoundary(rawOptions) {
39
39
 
40
40
  function riskMessage() {
41
41
  return chineseLocale()
42
- ? '启用远程设置?\n\n当前页面通过远程地址访问 DSH。启用后,能够访问此 trusted host 的客户端可以修改 Vision Router 已开放的设置。\n\nDSH trustedHosts 不是身份认证,请仅在你信任当前网络和访问者时继续。API Key、HTTP Provider 凭据、本地 Ollama / LM Studio、产物路径等未列入远程白名单的敏感配置仍不会开放。\n\n确定要允许远程修改设置吗?'
43
- : 'Enable remote settings?\n\nThis page is accessing DSH through a remote address. After enabling this, clients that can reach this trusted host can change the Vision Router settings exposed by the remote allow-list.\n\nDSH trustedHosts is not authentication. Continue only if you trust the current network and its users. Sensitive settings outside the remote allow-list, including API keys, HTTP-provider credentials, local Ollama / LM Studio, and artifact paths, remain unavailable remotely.\n\nAllow remote settings?'
42
+ ? '启用完整远程设置?\n\n当前页面通过远程地址访问 DSH。确认后,通过 DSH 登录认证且能访问该 Host 的客户端可修改完整的 Vision Router 普通配置,包括代理/网络出口、HTTP Provider、本地 Ollama / LM Studio、产物路径、仅本地视觉策略和桌面截图开关。这些修改会影响运行 DSH 的设备和图片数据流向。\n\n已保存的密钥和 URL 凭据不会以明文回显,但远程用户可以替换相应配置。远程修改桌面截图开关不会自动授予操作系统录屏权限;打开仅本地视觉之前,云端识图仍可能上传图片。\n\nDSH trustedHosts 本身不是身份认证,风险确认也不是身份认证。请只在信任 DSH 登录用户及网络访问环境时继续。\n\n确定允许远程修改完整配置吗?'
43
+ : 'Enable full remote settings?\n\nThis page is accessing DSH through a remote address. After confirmation, clients authenticated to DSH that can reach this Host can edit the full ordinary Vision Router configuration, including proxy/network egress, HTTP providers, local Ollama / LM Studio, artifact paths, the Local-only vision policy and the desktop-capture toggle. Changes affect the machine running DSH and where image data may be sent.\n\nSaved keys and URL credentials are not echoed in plaintext, but remote users can replace their configuration. Editing the capture toggle does not grant OS screen-recording permission. Cloud vision may still upload images until Local-only vision is enabled.\n\nDSH trustedHosts is not authentication, and this risk confirmation is not authentication. Continue only if you trust the authenticated DSH users and network access.\n\nAllow full remote configuration edits?'
44
44
  }
45
45
 
46
46
  function isLoopbackLocation(locationLike) {
@@ -214,9 +214,11 @@ export const SETTINGS_017_CLIENT_PRELUDE = String.raw`(function(){
214
214
  if (typeof getter !== 'function') return getter;
215
215
  return function(name) {
216
216
  if (name === 'settingsScope') {
217
+ // Match ctx.settingsScope: an empty legacy Host binder must
218
+ // never bypass the DVR namespace's generation-safe local bridge.
217
219
  var original = safeGet(target, 'settingsScope');
218
- if (original && typeof original.bind === 'function') return original;
219
- return syntheticBinder(ctx, configFormsBinder(target));
220
+ return syntheticBinder(ctx,
221
+ original && typeof original.bind === 'function' ? original : configFormsBinder(target));
220
222
  }
221
223
  var value = getter.call(target, name);
222
224
  return name === 'connection' ? normalizeConnection(value) : value;
@@ -145,7 +145,26 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
145
145
  function reportFailures(failures){if(!localPage()||typeof fetch!=='function'||!Array.isArray(failures)||!failures.length)return;try{void fetch('/_dsh/vision-router/settings-save-diagnostics',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({failures:failures.slice(0,24)})}).catch(function(){});}catch(_){}}
146
146
 
147
147
  if(!snapshot||snapshot.status!=='ready'){
148
- var loading=!snapshot||snapshot.status==='loading';var disabled=snapshot&&snapshot.remoteDisabled===true;var reason=snapshot&&snapshot.remoteReason;var titleText=loading?tx('正在加载 Vision Router 设置…','Loading Vision Router settings…'):disabled?tx('远程设置未启用','Remote settings are not enabled'):reason==='namespace-unavailable'?tx('Vision Router 设置正在初始化','Vision Router settings are initializing'):tx('远程设置通道不可用','Remote settings channel unavailable');var bodyText=loading?tx('正在读取 Host 设置。','Reading Host settings.'):disabled?tx('你刚才没有授权远程修改。请在可信网络中重新进入此页面并确认风险提示,或从运行 DSH 的机器通过回环地址开启远程设置。','Remote editing was not authorized. Reopen this page and accept the risk prompt on a trusted network, or enable it from the DSH machine over loopback.'):snapshot&&snapshot.remoteErrorCode==='not-found'?tx('远程设置路由返回 404;若使用 Nginx/Caddy,请同时转发 /vision-router-settings/*。','The remote settings route returned 404; if using Nginx/Caddy, proxy /vision-router-settings/* as well.'):tx('无法读取 Vision Router 的远程设置。请检查 trusted host、反向代理和插件版本。','Vision Router remote settings could not be read. Check the trusted host, reverse proxy, and plugin version.');return h('div',{className:'vr-settings-ia-root','data-vr-settings-ia':'1'},h('div',{className:'vr-card vr-card-open vr-ia-card'},h('div',{className:'vr-body',style:{borderTop:0}},h('h3',{className:'vr-ia-title'},titleText),h('p',{className:'vr-hint'},bodyText),scope&&typeof scope.load==='function'&&!loading?h('button',{type:'button',className:'vr-btn',onClick:function(){void scope.load();}},tx('重试','Retry')):null)));
148
+ var loading=!snapshot||snapshot.status==='loading';
149
+ var localFailure=snapshot&&snapshot.mode==='host';
150
+ var disabled=snapshot&&snapshot.remoteDisabled===true;
151
+ var reason=snapshot&&snapshot.remoteReason;
152
+ var titleText=loading?tx('正在加载 Vision Router 设置…','Loading Vision Router settings…')
153
+ :localFailure?tx('本地设置不可用','Local settings unavailable')
154
+ :disabled?tx('远程设置未启用','Remote settings are not enabled')
155
+ :reason==='namespace-unavailable'?tx('Vision Router 设置正在初始化','Vision Router settings are initializing')
156
+ :tx('远程设置通道不可用','Remote settings channel unavailable');
157
+ var bodyText=loading?tx('正在读取 Host 设置。','Reading Host settings.')
158
+ :localFailure?tx('本地设置桥接未能读取配置,请检查 /_dsh/vision-router/local-settings 和插件加载状态。','The local settings bridge could not read configuration. Check /_dsh/vision-router/local-settings and the plugin lifecycle.')
159
+ :disabled?tx('你尚未授权远程修改。请在可信网络中重新进入此页面并确认风险提示,或从运行 DSH 的机器通过回环地址开启远程设置。','Remote editing was not authorized. Reopen this page and accept the risk prompt on a trusted network, or enable it over loopback.')
160
+ :snapshot&&snapshot.remoteErrorCode==='remote-route-missing'?tx('远程设置路由返回 404;若使用 Nginx/Caddy,请同时转发 /vision-router-settings/*。','The remote settings route returned 404; if using Nginx/Caddy, proxy /vision-router-settings/* as well.')
161
+ :tx('无法读取 Vision Router 的远程设置。请检查 DSH 登录状态、trusted host、反向代理和插件版本。','Vision Router remote settings could not be read. Check DSH authentication, trusted host, reverse proxy, and plugin version.');
162
+ return h('div',{className:'vr-settings-ia-root','data-vr-settings-ia':'1'},
163
+ h('div',{className:'vr-card vr-card-open vr-ia-card'},
164
+ h('div',{className:'vr-body',style:{borderTop:0}},
165
+ h('h3',{className:'vr-ia-title'},titleText),
166
+ h('p',{className:'vr-hint'},bodyText),
167
+ scope&&typeof scope.load==='function'&&!loading?h('button',{type:'button',className:'vr-btn',onClick:function(){void scope.load();}},tx('重试','Retry')):null)));
149
168
  }
150
169
 
151
170
  var saved=obj(snapshot.value),user=obj(snapshot.user),writable=snapshot.writable===true,saving=saveState.status==='saving',local=localPage();
@@ -204,13 +223,10 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
204
223
  function modelOptions(provider,current,allowAll){var group=groupById.get(provider),models=arr(group&&group.models),listed=new Set(models.map(function(model){return model&&model.id;}).filter(Boolean)),nodes=[h('option',{value:'',key:'__empty'},allowAll?tx('全部模型','All models'):(provider?tx('选择模型…','Choose model…'):tx('先选供应商','Choose provider first')))];if(current&&!listed.has(current))nodes.push(h('option',{value:current,key:'__stale-'+current},current+' '+tx('(已保存)','(saved)')));models.forEach(function(model){if(model&&typeof model.id==='string'&&model.id)nodes.push(h('option',{value:model.id,key:model.id},modelName(group,model.id)));});return nodes;}
205
224
  function modelRow(row,index,rows,setRows,allowAll){var ready=groups.length>0;function update(next){var copy=rows.map(function(item){return Object.assign({},item);});copy[index]=next;setRows(copy);setSaveState({status:'idle'});}function providerChanged(provider){var next=Object.assign({},row,{provider:provider,model:''});if(!allowAll)next.fallbacks=[];update(next);}function remove(){var copy=rows.filter(function(_,i){return i!==index;});setRows(copy.length?copy:[{provider:'',model:'',fallbacks:[]}]);setSaveState({status:'idle'});}return h('div',{className:'vr-chain-row',key:index},ready?h('select',{className:'vr-input vr-select',value:row.provider||'',disabled:!writable||saving,onChange:function(event){providerChanged(event.target.value);}},providerOptions(row.provider||'')):h('input',{className:'vr-input',placeholder:'provider',value:row.provider||'',disabled:!writable||saving,onChange:function(event){providerChanged(event.target.value);}}),ready?h('select',{className:'vr-input vr-select',value:row.model||'',disabled:!writable||saving||!row.provider,onChange:function(event){update(Object.assign({},row,{model:event.target.value}));}},modelOptions(row.provider||'',row.model||'',allowAll)):h('input',{className:'vr-input',placeholder:allowAll?tx('model(留空=全部)','model (empty = all)'):'model',value:row.model||'',disabled:!writable||saving,onChange:function(event){update(Object.assign({},row,{model:event.target.value}));}}),h('button',{type:'button',className:'vr-reset',disabled:!writable||saving,onClick:remove},tx('移除','Remove')));}
206
225
 
207
- function egressInstructions(local){
208
- if(local)return tx(
226
+ function egressInstructions(){
227
+ return tx(
209
228
  '数据流向:云端识图(含免费兜底)会上传图片、裁剪和提示词。免费或免 Key 不等于离线。要停止上传,请在本页开启「仅本地视觉」,然后点击「保存」。云端聊天模型仍可能收到识图结果文字;要完全不出网,还需在聊天页选择本地聊天模型。',
210
229
  'Data flow: Cloud vision, including the free fallback, uploads images, crops and prompts. Free or keyless is not offline. To stop uploads, enable Local-only vision here and select Save. A cloud chat model may still receive result text; choose a local chat model in the composer to keep the whole workflow local.');
211
- return tx(
212
- '云端识图可能上传图片。要停止上传,请在运行 DSH 的电脑上打开「设置 → Vision Router → 常规」,开启「仅本地视觉」并保存。云端聊天模型仍可能收到识图结果文字;要完全不出网,还需在聊天页选择本地聊天模型。',
213
- 'Cloud vision may upload images. To stop uploads, open Settings → Vision Router → General on the DSH computer, enable Local-only vision and save. A cloud chat model may still receive result text; choose a local chat model in the composer to keep the whole workflow local.');
214
230
  }
215
231
  function egressNotice(localOnly,local){
216
232
  if(localOnly)return h('p',{className:'vr-hint',key:'egress'},tx(
@@ -262,7 +278,7 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
262
278
  '旧版 DSH:llm-pi-ai 使用 input: [text, image];llm-deepseek 使用 inputModalities: [text, image]。只有模型本身支持图片时才这样配置。经验证的 HTTP Chat Completions 通道也可能直接桥接;单独添加视觉能力标记不能开启图片传输。',
263
279
  'Older DSH: llm-pi-ai uses input: [text, image]; llm-deepseek uses inputModalities: [text, image]. Only declare image input if the model supports it. Verified HTTP Chat Completions may bridge; a capability label alone cannot enable image delivery.')));
264
280
  }
265
- return h(React.Fragment,null,title(tx('常规','General'),tx('这里只设置“谁负责看图”。聊天模型仍在聊天页选择。','This page only decides who reads images; the chat model is still chosen in chat.')),card([toggle('localOnlyVision',tx('仅本地视觉','Local-only vision'),tx('只使用本机识图模型;云端识图和免费兜底暂停,原配置保留。识图结果文字仍可能发给云端聊天模型。只能在本机修改。','Use only local vision models; cloud vision and the free fallback are paused without deleting settings. Result text may still go to a cloud chat model. Change this only on the local DSH machine.'),!local),h('div',{className:'vr-ia-status',key:'status'},h('strong',null,(activeLocalOnly?'🔒 ':localOnlyPending?'⚠ ':configured.length||fallback?'● ':'⚠ ')+status),h('p',{className:'vr-hint'},tx('需要看图时,在聊天框旁点击「👁 识图」。','Use “👁 Vision” beside the chat box when an image needs inspection.')),egressNotice(activeLocalOnly,local),localOnlyPending?h('p',{className:localOnly?'vr-failed':'vr-hint',key:'local-only-pending'},localOnly?tx('尚未生效:请点击页面底部「保存」。保存前图片仍可能上传。','Not active yet: select Save at the bottom. Images may still be uploaded until saved.'):tx('还没有保存:当前仍在仅本地视觉模式,保存后才会允许云端识图。','Not saved yet: Local-only vision remains active until you save.')):null,ordered.length?h('p',{className:'vr-ia-chain-summary'},ordered.join(' → ')):null,stale.length?h('p',{className:'vr-failed'},tx('有已保存的识图模型当前不在可调用目录中;请到“诊断”重新检测。','A saved vision model is not currently in the callable catalog; re-detect it in Diagnostics.')):null)]),card([h('div',{className:'vr-field',id:'vr-vision-backend-chain','data-vr-guide-target':'vision-backend',key:'chain'},fieldHead('providers',tx('识图模型','Vision models')),h('p',{className:'vr-hint'},tx('从上到下依次尝试;前一个失败时自动切换到下一个。','Models are tried from top to bottom and fall through automatically on failure.')),rows.map(function(row,index){return modelRow(row,index,rows,setChainDraft,false);}),
281
+ return h(React.Fragment,null,title(tx('常规','General'),tx('这里只设置“谁负责看图”。聊天模型仍在聊天页选择。','This page only decides who reads images; the chat model is still chosen in chat.')),card([toggle('localOnlyVision',tx('仅本地视觉','Local-only vision'),tx('只使用本机识图模型;云端识图和免费兜底暂停,原配置保留。识图结果文字仍可能发给云端聊天模型。远程修改也会改变 Host 的图像数据流向。','Use only local vision models; cloud vision and the free fallback are paused without deleting settings. Result text may still go to a cloud chat model. Remote changes also affect the Host image-data flow.'),false),h('div',{className:'vr-ia-status',key:'status'},h('strong',null,(activeLocalOnly?'🔒 ':localOnlyPending?'⚠ ':configured.length||fallback?'● ':'⚠ ')+status),h('p',{className:'vr-hint'},tx('需要看图时,在聊天框旁点击「👁 识图」。','Use “👁 Vision” beside the chat box when an image needs inspection.')),egressNotice(activeLocalOnly,local),localOnlyPending?h('p',{className:localOnly?'vr-failed':'vr-hint',key:'local-only-pending'},localOnly?tx('尚未生效:请点击页面底部「保存」。保存前图片仍可能上传。','Not active yet: select Save at the bottom. Images may still be uploaded until saved.'):tx('还没有保存:当前仍在仅本地视觉模式,保存后才会允许云端识图。','Not saved yet: Local-only vision remains active until you save.')):null,ordered.length?h('p',{className:'vr-ia-chain-summary'},ordered.join(' → ')):null,stale.length?h('p',{className:'vr-failed'},tx('有已保存的识图模型当前不在可调用目录中;请到“诊断”重新检测。','A saved vision model is not currently in the callable catalog; re-detect it in Diagnostics.')):null)]),card([h('div',{className:'vr-field',id:'vr-vision-backend-chain','data-vr-guide-target':'vision-backend',key:'chain'},fieldHead('providers',tx('识图模型','Vision models')),h('p',{className:'vr-hint'},tx('从上到下依次尝试;前一个失败时自动切换到下一个。','Models are tried from top to bottom and fall through automatically on failure.')),rows.map(function(row,index){return modelRow(row,index,rows,setChainDraft,false);}),
266
282
  readiness.filter(function(entry){return !localOnly&&(caps.status==='ready'||caps.status==='error')&&entry.state!=='evidence';}).map(function(entry,index){return h('div',{
267
283
  className:'vr-field',key:'readiness-'+index,'data-vr-model-readiness':entry.state
268
284
  },h('p',{className:entry.state==='text-only'||entry.state==='blocked'?'vr-failed':'vr-hint'},
@@ -344,13 +360,13 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
344
360
  );
345
361
  }
346
362
  function localProviderCard(key,label,defaults,which){var current=Object.assign({},defaults,obj(value(key,{}))),opened=which==='ollama'?open.ollama:open.lmstudio;function update(patch){setValue(key,Object.assign({},current,patch));}function sample(name,min,max){return h('div',{className:'vr-field'},h('span',{className:'vr-label'},name),h('input',{className:'vr-input',type:'number',step:'0.1',min:min,max:max,value:current[name]===undefined?'':current[name],disabled:!writable||saving,onChange:function(event){var patch={};patch[name]=event.target.value===''?undefined:Number(event.target.value);update(patch);}}));}return card([h('div',{className:'vr-ia-backend-head',key:'head'},h('div',null,h('div',{className:'vr-ia-field-head'},h('strong',null,label),override(key)),h('p',{className:'vr-hint'},current.enabled?tx('已启用','Enabled'):tx('未启用','Disabled'))),h('input',{type:'checkbox',checked:current.enabled===true,disabled:!writable||saving,onChange:function(event){update({enabled:event.target.checked});}})),h('div',{className:'vr-field',key:'model'},h('span',{className:'vr-label'},tx('模型','Model')),h('input',{className:'vr-input',value:String(current.model||''),disabled:!writable||saving,onChange:function(event){update({model:event.target.value});}}),key==='localLmStudio'&&invalidKeys.includes(key)?h('p',{className:'vr-failed'},tx('启用 LM Studio 时必须填写真实模型标识。','A real model id is required when LM Studio is enabled.')):null),h('div',{className:'vr-field',key:'url'},h('span',{className:'vr-label'},tx('服务地址','Service URL')),h('input',{className:'vr-input',value:String(current.baseURL||''),disabled:!writable||saving,onChange:function(event){update({baseURL:event.target.value});}})),h('button',{type:'button',className:'vr-btn',onClick:function(){setOpen(Object.assign({},open,which==='ollama'?{ollama:!opened}:{lmstudio:!opened}));}},opened?tx('收起高级连接设置','Hide advanced connection settings'):tx('高级连接设置','Advanced connection settings')),opened?h('div',{className:'vr-ia-subgrid',key:'advanced'},h('div',{className:'vr-field'},h('span',{className:'vr-label'},tx('请求协议','Request protocol')),h('select',{className:'vr-input',value:current.format==='anthropic'?'anthropic':current.format==='lmstudio'?'lmstudio':'openai',disabled:!writable||saving,onChange:function(event){update({format:event.target.value});}},h('option',{value:'openai'},'OpenAI'),h('option',{value:'anthropic'},'Anthropic'),which==='lmstudio'?h('option',{value:'lmstudio'},tx('LM Studio 原生','LM Studio native')):null)),h('div',{className:'vr-field'},h('span',{className:'vr-label'},tx('最大输出 token','Max output tokens')),h('input',{className:'vr-input',type:'number',step:'256',min:'256',max:'32768',value:String(current.maxTokens||4096),disabled:!writable||saving,onChange:function(event){update({maxTokens:Number(event.target.value)});}})),h('div',{className:'vr-field'},h('span',{className:'vr-label'},tx('推理强度','Reasoning effort')),h('select',{className:'vr-input',value:String(current.reasoningEffort||defaults.reasoningEffort||'provider_default'),disabled:!writable||saving||(which==='lmstudio'?current.format!=='lmstudio':current.format==='anthropic'),onChange:function(event){update({reasoningEffort:event.target.value});}},h('option',{value:'provider_default'},tx('服务端默认','Provider default')),h('option',{value:'none'},tx('关闭推理','Disable reasoning')),h('option',{value:'low'},'low'),h('option',{value:'medium'},'medium'),h('option',{value:'high'},'high'),h('option',{value:'max'},'max'))),sample('temperature',0,2),sample('top_p',0,1)):null]);}
347
- function localPageContent(){if(!local)return h(React.Fragment,null,title(tx('本地与设备','Local & device')),card([h('p',{className:'vr-hint',key:'remote'},tx('本地视觉后端和桌面截图只能在运行 DSH 的机器上配置。','Local vision backends and desktop capture can only be configured on the DSH machine.'))]));return h(React.Fragment,null,title(tx('本地与设备','Local & device'),tx('本地视觉可让图像像素留在本机;但若云端识图行或免费兜底仍开启,失败时仍可能出网,识图结果也会交给当前聊天模型。','Local vision can keep image pixels on this machine. Cloud vision rows or the free fallback may still send them off-device after a failure, and vision result text is still passed to the current chat model.')),localProviderCard('localOllama','Ollama',{enabled:false,baseURL:'http://127.0.0.1:11434/v1',model:'qwen2.5vl',format:'openai',maxTokens:4096,reasoningEffort:'none'},'ollama'),localProviderCard('localLmStudio','LM Studio',{enabled:false,baseURL:'http://localhost:1234/v1',model:'',format:'openai',maxTokens:4096,reasoningEffort:'none'},'lmstudio'),card([toggle('desktopScreenshot',tx('允许 Agent 读取桌面截图','Allow the agent to capture the desktop'),tx('这是独立的隐私权限;macOS 上保存为开启后会立即触发屏幕录制权限检查。','This is a separate privacy permission; on macOS saving it enabled immediately triggers the screen-recording permission check.'))]));}
363
+ function localPageContent(){return h(React.Fragment,null,title(tx('本地与设备','Local & device'),tx('本地视觉可让图像像素留在本机;但若云端识图行或免费兜底仍开启,失败时仍可能出网,识图结果也会交给当前聊天模型。','Local vision can keep image pixels on this machine. Cloud vision rows or the free fallback may still send them off-device after a failure, and vision result text is still passed to the current chat model.')),localProviderCard('localOllama','Ollama',{enabled:false,baseURL:'http://127.0.0.1:11434/v1',model:'qwen2.5vl',format:'openai',maxTokens:4096,reasoningEffort:'none'},'ollama'),localProviderCard('localLmStudio','LM Studio',{enabled:false,baseURL:'http://localhost:1234/v1',model:'',format:'openai',maxTokens:4096,reasoningEffort:'none'},'lmstudio'),card([toggle('desktopScreenshot',tx('允许 Agent 读取桌面截图','Allow the agent to capture the desktop'),tx('这是独立的隐私权限;macOS 上保存为开启后会立即触发屏幕录制权限检查。','This is a separate privacy permission; on macOS saving it enabled immediately triggers the screen-recording permission check.'))]));}
348
364
  function wrappersEditor(){var rows=wrapperRows();return h('div',{className:'vr-field'},fieldHead('wrappedProviders',tx('哪些聊天模型可以开启识图','Which chat models can use Vision mode')),h('p',{className:'vr-hint'},tx('通常无需修改;模型留空表示整个 Provider。','Usually leave this alone; an empty model means the whole provider.')),rows.map(function(row,index){return modelRow(row,index,rows,setWrapperDraft,true);}),h('button',{type:'button',className:'vr-btn',disabled:!writable||saving,onClick:function(){setWrapperDraft(rows.concat([{provider:'',model:''}]))}},tx('+ 添加范围','+ Add scope')));}
349
365
  function textProviderEditor(){var current=Object.assign({provider:'',model:''},obj(value('textProvider',{}))),ready=groups.length>0;return h('div',{className:'vr-field'},fieldHead('textProvider',tx('文字回退模型','Text fallback model')),h('div',{className:'vr-chain-row'},ready?h('select',{className:'vr-input',value:current.provider||'',disabled:!writable||saving,onChange:function(event){setValue('textProvider',{provider:event.target.value,model:''});}},providerOptions(current.provider||'')):h('input',{className:'vr-input',value:current.provider||'',disabled:!writable||saving,onChange:function(event){setValue('textProvider',{provider:event.target.value,model:current.model||''});}}),ready?h('select',{className:'vr-input',value:current.model||'',disabled:!writable||saving||!current.provider,onChange:function(event){setValue('textProvider',{provider:current.provider||'',model:event.target.value});}},modelOptions(current.provider||'',current.model||'',false)):h('input',{className:'vr-input',value:current.model||'',disabled:!writable||saving,onChange:function(event){setValue('textProvider',{provider:current.provider||'',model:event.target.value});}})),invalidKeys.includes('textProvider')?h('p',{className:'vr-failed'},tx('Provider 和 model 必须同时填写,或同时留空恢复默认。','Provider and model must both be filled, or both left empty to restore the default.')):null);}
350
- function advancedPage(){var routing=toggleValue('routing',false),turnBudget=Number(value('visionTurnBudgetMs',0))||0,customBudget=turnBudget>0;return h(React.Fragment,null,title(tx('高级','Advanced'),tx('这些默认值对大多数用户已经合适。','Defaults are suitable for most users.')),card([h('h4',{className:'vr-ia-subtitle',key:'p'},tx('性能与稳定性','Performance & stability')),toggle('downscale',tx('自动缩放','Auto downscale')),numberField('downscaleMaxPixels',tx('图片像素上限','Image pixel limit'),null,1000,100000000),toggle('cache',tx('识图缓存','Vision answer cache')),numberField('cacheTtlSeconds',tx('缓存有效期(秒)','Cache TTL (seconds)'),null,0,31536000),numberField('cacheMaxEntries',tx('最大缓存数量','Maximum cached answers'),null,1,100000),h('h4',{className:'vr-ia-subtitle',key:'t'},tx('超时','Timeouts')),numberField('timeoutMs',tx('单次模型请求','Single model request'),tx('毫秒。','Milliseconds.'),1000,600000),numberField('visionTaskTimeoutMs',tx('单个视觉任务','Single visual task'),tx('包含该任务内部的重试和备用模型;不是每个后端各自一份。','Includes retries and fallbacks inside the task; it is not a fresh budget per backend.'),1000,180000),numberField('ocrTimeoutMs',tx('OCR 任务','OCR task'),null,1000,120000),h('div',{className:'vr-field',key:'ocr-engine'},fieldHead('ocrEngine',tx('OCR 默认引擎','Default OCR engine')),h('select',{className:'vr-input',value:String(value('ocrEngine','auto')||'auto'),disabled:!writable||saving,onChange:function(event){setValue('ocrEngine',event.target.value);}},h('option',{value:'auto'},tx('自动(Tesseract → 视觉模型)','Auto (Tesseract → vision)')),h('option',{value:'tesseract'},tx('仅 Tesseract','Tesseract only')),h('option',{value:'vision'},tx('仅视觉模型','Vision model only'))),h('p',{className:'vr-hint'},tx('vision_ocr 未显式指定 engine 时使用;单次调用的 engine=tesseract/vision 始终优先。','Used when vision_ocr does not explicitly choose an engine; per-call engine=tesseract/vision always wins.'))),h('div',{className:'vr-field',key:'budget'},fieldHead('visionTurnBudgetMs',tx('整轮视觉工具上限','Whole-turn vision-tool limit')),h('select',{className:'vr-input',value:customBudget?'custom':'unlimited',disabled:!writable||saving,onChange:function(event){setValue('visionTurnBudgetMs',event.target.value==='unlimited'?0:(turnBudget>0?turnBudget:180000));}},h('option',{value:'unlimited'},tx('不限制(推荐)','Unlimited (recommended)')),h('option',{value:'custom'},tx('自定义','Custom'))),customBudget?numberField('visionTurnBudgetMs',tx('上限(毫秒)','Limit (ms)'),null,10000,600000):null)]),card([h('h4',{className:'vr-ia-subtitle',key:'cost'},tx('模型顺序与成本','Model order & cost')),toggle('freeCloudFirst',tx('免费云模型优先','Try free cloud models first'))]),card([h('h4',{className:'vr-ia-subtitle',key:'scope'},tx('识图模式范围','Vision mode scope')),toggle('autoWrapProviders',tx('自动允许已启用模型使用识图','Automatically allow enabled models to use Vision mode')),wrappersEditor()]),local?card([h('h4',{className:'vr-ia-subtitle',key:'network'},tx('网络与远程','Network & remote')),h('p',{className:'vr-hint',key:'network-authority'},tx('默认沿用 DSH/Host 的网络出口;只有需要让视觉请求走不同出口时才填写下方覆盖。','By default Vision Router follows the DSH/Host network path. Use the override below only when vision requests need a different egress route.')),toggle('allowRemoteSettings',tx('允许可信 Host 远程修改设置','Allow trusted-host remote settings'),tx('默认关闭;trustedHosts 不是身份认证。','Off by default; trustedHosts is not authentication.')),textField('proxy',tx('视觉专用代理覆盖','Vision-only proxy override'),tx('留空即沿用 DSH/Host;支持 http(s)://、socks5://,并兼容旧 socks5h://。','Leave empty to follow DSH/Host; supports http(s):// and socks5://, with legacy socks5h:// compatibility.')),textareaArray('proxyHosts',tx('视觉代理覆盖域名','Vision proxy override hosts'),tx('仅在上方覆盖非空时生效;每行一个,其余请求继续沿用 DSH/Host。','Used only when the override above is non-empty; one host per line. All other requests keep the DSH/Host path.'))]):null,card([h('h4',{className:'vr-ia-subtitle',key:'compat'},tx('兼容模式','Compatibility')),toggle('rewriteImages',tx('保护纯文本模型','Protect text-only models')),toggle('routing',tx('整轮视觉路由(旧工作流)','Whole-turn vision routing (legacy workflow)')),routing?toggle('reverseRouting',tx('纯文字消息继续使用聊天模型','Keep text-only messages on the chat model')):null,routing?textProviderEditor():null]),card([h('button',{type:'button',className:'vr-btn',key:'dev',onClick:function(){setOpen(Object.assign({},open,{developer:!open.developer}));}},open.developer?tx('隐藏开发者设置','Hide developer settings'):tx('显示开发者设置','Show developer settings')),open.developer?h('div',{className:'vr-ia-dev',key:'body'},toggle('progressiveTools',tx('渐进式工具暴露','Progressive tool exposure')),h('p',{className:'vr-hint',key:'progressive-restart'},tx('保存后需重启 DSH 才生效。','Restart DSH after saving for this change to take effect.')),local?toggle('stealth','Stealth'):null,local?textField('wrapperRoute',tx('包装路由名','Wrapper route name')):null,local?textField('chainRoute',tx('视觉链路由名','Vision chain route name')):null,textareaArray('extraVisionModels',tx('额外视觉能力标记','Extra vision capability labels'),tx('只有诊断发现模型未声明图片能力时才需要。','Needed only when diagnostics show missing image-capability metadata.'))):null]));}
366
+ function advancedPage(){var routing=toggleValue('routing',false),turnBudget=Number(value('visionTurnBudgetMs',0))||0,customBudget=turnBudget>0;return h(React.Fragment,null,title(tx('高级','Advanced'),tx('这些默认值对大多数用户已经合适。','Defaults are suitable for most users.')),card([h('h4',{className:'vr-ia-subtitle',key:'p'},tx('性能与稳定性','Performance & stability')),toggle('downscale',tx('自动缩放','Auto downscale')),numberField('downscaleMaxPixels',tx('图片像素上限','Image pixel limit'),null,1000,100000000),toggle('cache',tx('识图缓存','Vision answer cache')),numberField('cacheTtlSeconds',tx('缓存有效期(秒)','Cache TTL (seconds)'),null,0,31536000),numberField('cacheMaxEntries',tx('最大缓存数量','Maximum cached answers'),null,1,100000),h('h4',{className:'vr-ia-subtitle',key:'t'},tx('超时','Timeouts')),numberField('timeoutMs',tx('单次模型请求','Single model request'),tx('毫秒。','Milliseconds.'),1000,600000),numberField('visionTaskTimeoutMs',tx('单个视觉任务','Single visual task'),tx('包含该任务内部的重试和备用模型;不是每个后端各自一份。','Includes retries and fallbacks inside the task; it is not a fresh budget per backend.'),1000,180000),numberField('ocrTimeoutMs',tx('OCR 任务','OCR task'),null,1000,120000),h('div',{className:'vr-field',key:'ocr-engine'},fieldHead('ocrEngine',tx('OCR 默认引擎','Default OCR engine')),h('select',{className:'vr-input',value:String(value('ocrEngine','auto')||'auto'),disabled:!writable||saving,onChange:function(event){setValue('ocrEngine',event.target.value);}},h('option',{value:'auto'},tx('自动(Tesseract → 视觉模型)','Auto (Tesseract → vision)')),h('option',{value:'tesseract'},tx('仅 Tesseract','Tesseract only')),h('option',{value:'vision'},tx('仅视觉模型','Vision model only'))),h('p',{className:'vr-hint'},tx('vision_ocr 未显式指定 engine 时使用;单次调用的 engine=tesseract/vision 始终优先。','Used when vision_ocr does not explicitly choose an engine; per-call engine=tesseract/vision always wins.'))),h('div',{className:'vr-field',key:'budget'},fieldHead('visionTurnBudgetMs',tx('整轮视觉工具上限','Whole-turn vision-tool limit')),h('select',{className:'vr-input',value:customBudget?'custom':'unlimited',disabled:!writable||saving,onChange:function(event){setValue('visionTurnBudgetMs',event.target.value==='unlimited'?0:(turnBudget>0?turnBudget:180000));}},h('option',{value:'unlimited'},tx('不限制(推荐)','Unlimited (recommended)')),h('option',{value:'custom'},tx('自定义','Custom'))),customBudget?numberField('visionTurnBudgetMs',tx('上限(毫秒)','Limit (ms)'),null,10000,600000):null)]),card([h('h4',{className:'vr-ia-subtitle',key:'cost'},tx('模型顺序与成本','Model order & cost')),toggle('freeCloudFirst',tx('免费云模型优先','Try free cloud models first'))]),card([h('h4',{className:'vr-ia-subtitle',key:'scope'},tx('识图模式范围','Vision mode scope')),toggle('autoWrapProviders',tx('自动允许已启用模型使用识图','Automatically allow enabled models to use Vision mode')),wrappersEditor()]),card([h('h4',{className:'vr-ia-subtitle',key:'network'},tx('网络与远程','Network & remote')),h('p',{className:'vr-hint',key:'network-authority'},tx('默认沿用 DSH/Host 的网络出口;只有需要让视觉请求走不同出口时才填写下方覆盖。','By default Vision Router follows the DSH/Host network path. Use the override below only when vision requests need a different egress route.')),local?toggle('allowRemoteSettings',tx('允许可信 Host 远程修改设置','Allow trusted-host remote settings'),tx('默认关闭;trustedHosts 不是身份认证。','Off by default; trustedHosts is not authentication.')):null,textField('proxy',tx('视觉专用代理覆盖','Vision-only proxy override'),tx('留空即沿用 DSH/Host;支持 http(s)://、socks5://,并兼容旧 socks5h://。','Leave empty to follow DSH/Host; supports http(s):// and socks5://, with legacy socks5h:// compatibility.')),textareaArray('proxyHosts',tx('视觉代理覆盖域名','Vision proxy override hosts'),tx('仅在上方覆盖非空时生效;每行一个,其余请求继续沿用 DSH/Host。','Used only when the override above is non-empty; one host per line. All other requests keep the DSH/Host path.'))]),card([h('h4',{className:'vr-ia-subtitle',key:'compat'},tx('兼容模式','Compatibility')),toggle('rewriteImages',tx('保护纯文本模型','Protect text-only models')),toggle('routing',tx('整轮视觉路由(旧工作流)','Whole-turn vision routing (legacy workflow)')),routing?toggle('reverseRouting',tx('纯文字消息继续使用聊天模型','Keep text-only messages on the chat model')):null,routing?textProviderEditor():null]),card([h('button',{type:'button',className:'vr-btn',key:'dev',onClick:function(){setOpen(Object.assign({},open,{developer:!open.developer}));}},open.developer?tx('隐藏开发者设置','Hide developer settings'):tx('显示开发者设置','Show developer settings')),open.developer?h('div',{className:'vr-ia-dev',key:'body'},toggle('progressiveTools',tx('渐进式工具暴露','Progressive tool exposure')),h('p',{className:'vr-hint',key:'progressive-restart'},tx('保存后需重启 DSH 才生效。','Restart DSH after saving for this change to take effect.')),toggle('stealth','Stealth'),textField('wrapperRoute',tx('包装路由名','Wrapper route name')),textField('chainRoute',tx('视觉链路由名','Vision chain route name')),textareaArray('extraVisionModels',tx('额外视觉能力标记','Extra vision capability labels'),tx('只有诊断发现模型未声明图片能力时才需要。','Needed only when diagnostics show missing image-capability metadata.'))):null]));}
351
367
  function diagnosticValue(label,valueText){return h('div',{className:'vr-ia-diag-row',key:label},h('span',null,label),h('strong',null,valueText));}
352
368
  function updatePanel(){if(!local)return null;var result=updateState.result,auto=result&&result.autoUpdate,current=result&&result.currentVersion?result.currentVersion:tx('检测中','Checking'),latest=result&&result.latestVersion?result.latestVersion:'—',available=result&&result.ok===true&&result.updateAvailable===true,profile=auto&&auto.profile?auto.profile:'web',manualVersion=result&&result.latestVersion?result.latestVersion:'<version>',spec='dsh-vision-router@'+manualVersion,pnpm='pnpm dsh plugin --profile '+profile+' add '+spec,npx='npx @deepseek-ai/dsh plugin --profile '+profile+' add '+spec;return card([h('h4',{className:'vr-ia-subtitle',key:'title'},tx('版本更新','Updates')),h('p',{className:'vr-hint',key:'status'},updateState.status==='running'?tx('正在检查更新…','Checking for updates…'):result&&result.ok===false?tx('更新检查失败:','Update check failed: ')+String(result.error||'unknown'):available?tx('发现新版本:v','Update available: v')+latest+tx('(当前 v',' (current v')+current+')':result&&result.ok===true?tx('已是最新版本 v','Up to date: v')+current:tx('尚未检查','Not checked yet')),h('div',{className:'vr-ia-actions',key:'actions'},h('button',{type:'button',className:'vr-btn',disabled:updateState.status==='running',onClick:function(){void runUpdateCheck(true);}},tx('检查更新','Check for updates')),available&&auto&&auto.supported===true&&auto.token?h('button',{type:'button',className:'vr-btn vr-btn-save',disabled:selfUpdateState.status==='running',onClick:function(){void runSelfUpdate();}},selfUpdateState.status==='running'?tx('更新中…','Updating…'):tx('一键更新','Update now')):null),selfUpdateState.status==='done'&&selfUpdateState.result?h('p',{className:'vr-hint',key:'updated'},tx('更新完成,请重启 DSH。','Update complete. Restart DSH.')):selfUpdateState.error?h('p',{className:'vr-failed',key:'uerr'},String(selfUpdateState.error)):null,available&&(!auto||auto.supported!==true)?h('div',{className:'vr-ia-manual',key:'manual'},h('p',{className:'vr-hint'},tx('当前安装方式不支持安全的一键更新,请使用与你当前 DSH 安装方式一致的命令:','This install method cannot be safely auto-updated. Use the command matching your DSH installation:')),h('code',{className:'vr-ia-code'},pnpm),h('code',{className:'vr-ia-code'},npx)):null]);}
353
- function diagnosticsPage(){var providerCount=groups.length,modelCount=groups.reduce(function(total,group){return total+arr(group&&group.models).length;},0),configured=chainRows().filter(function(row){return row&&row.provider&&row.model;}).length,ollama=obj(value('localOllama',{})),lm=obj(value('localLmStudio',{})),testText=!local?tx('仅本机可见','Local only'):testState.status==='running'?tx('检测中','Checking'):testState.status==='done'&&testState.result&&testState.result.ok===true?tx('连接正常','Connected'):testState.status==='done'?tx('连接失败','Failed'):tx('未检测','Not checked'),capsText=caps.status==='ready'?tx('正常','Ready'):caps.status==='loading'?tx('检测中','Checking'):caps.status==='error'?tx('不可用','Unavailable'):tx('未检测','Not checked');var rows=[[tx('设置协议','Settings contract'),String(value('settingsContractRevision','—'))],[tx('模型目录','Model catalog'),catalog.status==='ready'?tx('正常','Ready'):catalog.status==='loading'?tx('检测中','Checking'):tx('不可用','Unavailable')],[tx('图片能力元数据','Image capability metadata'),capsText],[tx('可选 Provider','Selectable providers'),String(providerCount)],[tx('可选模型','Selectable models'),String(modelCount)],[tx('已配置识图模型','Configured vision models'),String(configured)],[tx('内置免费兜底','Built-in free fallback'),toggleValue('freeFallback',true)?(caps.builtinFallback.length?tx('已启用,','Enabled, ')+caps.builtinFallback.length+tx(' 个模型',' models'):tx('已启用','Enabled')):tx('已关闭','Disabled')],[tx('后端连接','Backend connection'),testText],[tx('Ollama','Ollama'),local?(ollama.enabled===true?tx('已启用','Enabled'):tx('未启用','Disabled')):tx('仅本机可见','Local only')],[tx('LM Studio','LM Studio'),local?(lm.enabled===true?tx('已启用','Enabled'):tx('未启用','Disabled')):tx('仅本机可见','Local only')],[tx('桌面截图','Desktop capture'),local?(toggleValue('desktopScreenshot',false)?tx('已启用','Enabled'):tx('未启用','Disabled')):tx('仅本机可见','Local only')],[tx('网络出口','Network egress'),local?(String(value('proxy','')).trim()?tx('视觉专用覆盖','Vision-only override'):tx('DSH/Host(默认)','DSH/Host (default)')):tx('仅本机可见','Local only')],[tx('识图结果去向','Vision result destination'),tx('当前聊天模型(可能为云端)','Current chat model (may be remote)')],[tx('远程设置','Remote settings'),local?(toggleValue('allowRemoteSettings',false)?tx('已启用','Enabled'):tx('未启用','Disabled')):tx('当前为远程安全视图','Remote safe view')]];function reportText(){return ['Vision Router diagnostics'].concat(rows.map(function(row){return row[0]+': '+row[1];}),['doctor: dsh-vision-router doctor']).join('\n');}async function copyReport(){try{if(typeof navigator!=='undefined'&&navigator.clipboard&&typeof navigator.clipboard.writeText==='function')await navigator.clipboard.writeText(reportText());setActionState({status:'copied'});}catch(error){setActionState({status:'error',error:error&&error.message?error.message:String(error)});}}return h(React.Fragment,null,title(tx('诊断','Diagnostics'),tx('状态页不会修改你的模型/路由设置;连接测试和更新操作会明确由按钮触发。','The status page does not change model or routing settings; connection tests and updates are explicit actions.')),card(rows.map(function(row){return diagnosticValue(row[0],row[1]);})),card([h('div',{className:'vr-ia-actions',key:'actions'},local?h('button',{type:'button',className:'vr-btn',disabled:testState.status==='running',onClick:function(){void runTestConnection();}},tx('测试连接','Test connection')):null,h('button',{type:'button',className:'vr-btn',onClick:function(){invalidateCatalog();}},tx('重新检测模型','Re-detect models')),local?h('button',{type:'button',className:'vr-btn',onClick:function(){void openLogs();}},tx('打开日志文件夹','Open logs folder')):null,h('button',{type:'button',className:'vr-btn',onClick:function(){void copyReport();}},tx('复制诊断信息','Copy diagnostics'))),h('p',{className:'vr-hint',key:'doctor'},tx('需要完整 DSH 版本、安装、Profile、运行时路由和会话诊断时执行:dsh-vision-router doctor','For the full DSH version, installation, profile, runtime-route, and session report, run: dsh-vision-router doctor')),testState.status==='done'&&testState.result&&testState.result.ok!==true?h('p',{className:'vr-failed',key:'testerr'},String(testState.result.error||tx('连接测试失败','Connection test failed'))):null,actionState.status==='error'?h('p',{className:'vr-failed',key:'aerr'},String(actionState.error||'unknown')):null]),updatePanel());}
369
+ function diagnosticsPage(){var providerCount=groups.length,modelCount=groups.reduce(function(total,group){return total+arr(group&&group.models).length;},0),configured=chainRows().filter(function(row){return row&&row.provider&&row.model;}).length,ollama=obj(value('localOllama',{})),lm=obj(value('localLmStudio',{})),testText=!local?tx('仅本机可见','Local only'):testState.status==='running'?tx('检测中','Checking'):testState.status==='done'&&testState.result&&testState.result.ok===true?tx('连接正常','Connected'):testState.status==='done'?tx('连接失败','Failed'):tx('未检测','Not checked'),capsText=caps.status==='ready'?tx('正常','Ready'):caps.status==='loading'?tx('检测中','Checking'):caps.status==='error'?tx('不可用','Unavailable'):tx('未检测','Not checked');var rows=[[tx('设置协议','Settings contract'),String(value('settingsContractRevision','—'))],[tx('模型目录','Model catalog'),catalog.status==='ready'?tx('正常','Ready'):catalog.status==='loading'?tx('检测中','Checking'):tx('不可用','Unavailable')],[tx('图片能力元数据','Image capability metadata'),capsText],[tx('可选 Provider','Selectable providers'),String(providerCount)],[tx('可选模型','Selectable models'),String(modelCount)],[tx('已配置识图模型','Configured vision models'),String(configured)],[tx('内置免费兜底','Built-in free fallback'),toggleValue('freeFallback',true)?(caps.builtinFallback.length?tx('已启用,','Enabled, ')+caps.builtinFallback.length+tx(' 个模型',' models'):tx('已启用','Enabled')):tx('已关闭','Disabled')],[tx('后端连接','Backend connection'),testText],[tx('Ollama','Ollama'),(ollama.enabled===true?tx('已启用','Enabled'):tx('未启用','Disabled'))],[tx('LM Studio','LM Studio'),(lm.enabled===true?tx('已启用','Enabled'):tx('未启用','Disabled'))],[tx('桌面截图','Desktop capture'),(toggleValue('desktopScreenshot',false)?tx('已启用','Enabled'):tx('未启用','Disabled'))],[tx('网络出口','Network egress'),(String(value('proxy','')).trim()?tx('视觉专用覆盖','Vision-only override'):tx('DSH/Host(默认)','DSH/Host (default)'))],[tx('识图结果去向','Vision result destination'),tx('当前聊天模型(可能为云端)','Current chat model (may be remote)')],[tx('远程设置','Remote settings'),local?(toggleValue('allowRemoteSettings',false)?tx('已启用','Enabled'):tx('未启用','Disabled')):tx('已通过风险确认','Risk acknowledged')]];function reportText(){return ['Vision Router diagnostics'].concat(rows.map(function(row){return row[0]+': '+row[1];}),['doctor: dsh-vision-router doctor']).join('\n');}async function copyReport(){try{if(typeof navigator!=='undefined'&&navigator.clipboard&&typeof navigator.clipboard.writeText==='function')await navigator.clipboard.writeText(reportText());setActionState({status:'copied'});}catch(error){setActionState({status:'error',error:error&&error.message?error.message:String(error)});}}return h(React.Fragment,null,title(tx('诊断','Diagnostics'),tx('状态页不会修改你的模型/路由设置;连接测试和更新操作会明确由按钮触发。','The status page does not change model or routing settings; connection tests and updates are explicit actions.')),card(rows.map(function(row){return diagnosticValue(row[0],row[1]);})),card([h('div',{className:'vr-ia-actions',key:'actions'},local?h('button',{type:'button',className:'vr-btn',disabled:testState.status==='running',onClick:function(){void runTestConnection();}},tx('测试连接','Test connection')):null,h('button',{type:'button',className:'vr-btn',onClick:function(){invalidateCatalog();}},tx('重新检测模型','Re-detect models')),local?h('button',{type:'button',className:'vr-btn',onClick:function(){void openLogs();}},tx('打开日志文件夹','Open logs folder')):null,h('button',{type:'button',className:'vr-btn',onClick:function(){void copyReport();}},tx('复制诊断信息','Copy diagnostics'))),h('p',{className:'vr-hint',key:'doctor'},tx('需要完整 DSH 版本、安装、Profile、运行时路由和会话诊断时执行:dsh-vision-router doctor','For the full DSH version, installation, profile, runtime-route, and session report, run: dsh-vision-router doctor')),testState.status==='done'&&testState.result&&testState.result.ok!==true?h('p',{className:'vr-failed',key:'testerr'},String(testState.result.error||tx('连接测试失败','Connection test failed'))):null,actionState.status==='error'?h('p',{className:'vr-failed',key:'aerr'},String(actionState.error||'unknown')):null]),updatePanel());}
354
370
 
355
371
  var pages=[['general',tx('常规','General')],['strategy',tx('识图策略','Vision strategy')],['local',tx('本地与设备','Local & device')],['advanced',tx('高级','Advanced')],['diagnostics',tx('诊断','Diagnostics')]];
356
372
  var content=page==='strategy'?strategyPage():page==='local'?localPageContent():page==='advanced'?advancedPage():page==='diagnostics'?diagnosticsPage():generalPage();
@@ -0,0 +1,163 @@
1
+ import { parentPort, workerData } from 'node:worker_threads'
2
+ import { createRequire } from 'node:module'
3
+
4
+ const require = createRequire(import.meta.url)
5
+ const vtracer = require('@visioncortex/vtracer')
6
+ const MAX_TRACE_PIXELS = 1_000_000
7
+
8
+ function assertDimensions(width, height, byteLength) {
9
+ if (
10
+ !Number.isSafeInteger(width) || !Number.isSafeInteger(height) ||
11
+ width < 1 || height < 1 || width * height > MAX_TRACE_PIXELS ||
12
+ byteLength !== width * height * 4
13
+ ) throw new RangeError('invalid trace RGBA dimensions')
14
+ }
15
+
16
+ function grayPalette(gray, channels, width, height, steps) {
17
+ const histogram = new Float64Array(256)
18
+ const pixels = width * height
19
+ for (let i = 0; i < pixels; i++) histogram[gray[i * channels]]++
20
+ const count = Math.min(17, Math.max(2, steps + 1))
21
+ const quantile = (fraction) => {
22
+ let seen = 0
23
+ for (let i = 0; i < 256; i++) {
24
+ seen += histogram[i]
25
+ if (seen >= fraction * pixels) return i
26
+ }
27
+ return 255
28
+ }
29
+ let centers = Array.from({ length: count }, (_, i) => quantile((i + 0.5) / count))
30
+ for (let pass = 0; pass < 15; pass++) {
31
+ const sums = new Float64Array(count)
32
+ const sizes = new Float64Array(count)
33
+ for (let value = 0; value < 256; value++) {
34
+ const frequency = histogram[value]
35
+ if (!frequency) continue
36
+ let closest = 0
37
+ let distance = Infinity
38
+ for (let j = 0; j < count; j++) {
39
+ const delta = Math.abs(value - centers[j])
40
+ if (delta < distance) { closest = j; distance = delta }
41
+ }
42
+ sums[closest] += value * frequency
43
+ sizes[closest] += frequency
44
+ }
45
+ centers = centers.map((v, j) => sizes[j] ? sums[j] / sizes[j] : v)
46
+ }
47
+ const values = [...new Set(centers.map((v) => Math.max(0, Math.min(255, Math.round(v)))))]
48
+ if (values.length === 1) values.push(values[0] < 128 ? 255 : 0)
49
+ return values.sort((a, b) => a - b).map((v) => '#' + v.toString(16).padStart(2, '0').repeat(3))
50
+ }
51
+
52
+ function colorPalette(palette) {
53
+ if (!Array.isArray(palette) || palette.length > 16 ||
54
+ palette.some((p) => !p || typeof p.hex !== 'string' || !/^#[0-9a-f]{6}$/i.test(p.hex))) {
55
+ throw new RangeError('invalid trace color palette')
56
+ }
57
+ // Exact-palette callers own their color choices. Never silently append
58
+ // white (which could exceed the 16-color contract); alpha is still composited
59
+ // against white before tracing.
60
+ return [...new Set(palette.map((p) => p.hex.toLowerCase()))]
61
+ }
62
+
63
+ async function grayscaleTrace(bytes, steps) {
64
+ if (!Number.isInteger(steps) || steps < 1 || steps > 16) {
65
+ throw new RangeError('trace steps must be an integer between 1 and 16')
66
+ }
67
+ const sharpModule = await import(workerData.sharpUrl)
68
+ const sharp = sharpModule.default ?? sharpModule
69
+ const image = sharp(bytes, { failOn: 'error', limitInputPixels: MAX_TRACE_PIXELS })
70
+ const { data, info } = await image.flatten({ background: '#ffffff' }).greyscale()
71
+ .raw().toBuffer({ resolveWithObject: true })
72
+ const { width, height, channels } = info
73
+ if (width * height > MAX_TRACE_PIXELS || !channels) throw new RangeError('trace image exceeds pixel budget')
74
+ const rgba = Buffer.alloc(width * height * 4)
75
+ for (let i = 0; i < width * height; i++) {
76
+ const gray = data[i * channels]
77
+ const offset = i * 4
78
+ rgba[offset] = gray
79
+ rgba[offset + 1] = gray
80
+ rgba[offset + 2] = gray
81
+ rgba[offset + 3] = 255
82
+ }
83
+ const palette = grayPalette(data, channels, width, height, steps)
84
+ // VTracer's palette option constrains color *selection* but does not force
85
+ // grayscale pixel clustering. Without quantizing the raster itself,
86
+ // smooth black-to-white gradients can collapse to a single solid path.
87
+ // Explicitly posterize each input pixel to the nearest adaptive level.
88
+ const paletteValues = palette.map((hex) => Number.parseInt(hex.slice(1, 3), 16))
89
+ const lookup = new Uint8Array(256)
90
+ for (let gray = 0; gray < 256; gray++) {
91
+ let closest = paletteValues[0]
92
+ let distance = Infinity
93
+ for (const candidate of paletteValues) {
94
+ const delta = Math.abs(candidate - gray)
95
+ if (delta < distance) { distance = delta; closest = candidate }
96
+ }
97
+ lookup[gray] = closest
98
+ }
99
+ for (let i = 0; i < rgba.length; i += 4) {
100
+ const q = lookup[rgba[i]]
101
+ rgba[i] = q
102
+ rgba[i + 1] = q
103
+ rgba[i + 2] = q
104
+ }
105
+ return vtracer.convertPixels(rgba, width, height, {
106
+ preset: 'poster', mode: 'spline', hierarchical: 'cutout',
107
+ palette, maxColors: palette.length, simplify: 0.5, optimize: 1,
108
+ })
109
+ }
110
+
111
+ function colorTrace(data, width, height, palette, colorLimit) {
112
+ assertDimensions(width, height, data.length)
113
+ const explicit = Array.isArray(palette)
114
+ const colors = explicit ? colorPalette(palette) : undefined
115
+ const maxColors = explicit ? Math.max(1, colors.length) : colorLimit
116
+ if (!Number.isInteger(maxColors) || maxColors < 1 || maxColors > 16) {
117
+ throw new RangeError('invalid trace color limit')
118
+ }
119
+ const raw = Buffer.from(data)
120
+ for (let i = 0; i < raw.length; i += 4) {
121
+ const alpha = raw[i + 3]
122
+ // Preserve existing DVR's opaque-white SVG artifact background.
123
+ if (alpha === 0) {
124
+ raw[i] = 255; raw[i + 1] = 255; raw[i + 2] = 255
125
+ } else if (alpha < 255) {
126
+ const a = alpha / 255
127
+ raw[i] = Math.round(raw[i] * a + 255 * (1 - a))
128
+ raw[i + 1] = Math.round(raw[i + 1] * a + 255 * (1 - a))
129
+ raw[i + 2] = Math.round(raw[i + 2] * a + 255 * (1 - a))
130
+ }
131
+ raw[i + 3] = 255
132
+ }
133
+ if (explicit && colors.length === 0) {
134
+ return '<svg xmlns="http://www.w3.org/2000/svg" width="' + width +
135
+ '" height="' + height + '" viewBox="0 0 ' + width + ' ' + height +
136
+ '"><rect width="' + width + '" height="' + height + '" fill="#ffffff"/></svg>'
137
+ }
138
+ return vtracer.convertPixels(raw, width, height, {
139
+ preset: 'poster', mode: 'spline', hierarchical: 'cutout',
140
+ ...(explicit ? { palette: colors } : {}),
141
+ maxColors, simplify: 0.5, optimize: 1,
142
+ })
143
+ }
144
+
145
+ async function main() {
146
+ const { mode } = workerData
147
+ let svg
148
+ if (mode === 'grayscale') {
149
+ svg = await grayscaleTrace(Buffer.from(workerData.bytes), workerData.steps)
150
+ } else if (mode === 'color') {
151
+ svg = colorTrace(workerData.data, workerData.width, workerData.height,
152
+ workerData.palette, workerData.colors)
153
+ } else {
154
+ throw new RangeError('unsupported trace mode')
155
+ }
156
+ if (typeof svg !== 'string' || !/<svg[\s>]/.test(svg) || svg.length > 16 * 1024 * 1024) {
157
+ throw new Error('vectorizer returned an invalid or oversized SVG')
158
+ }
159
+ // VTracer writes uppercase RGB hex codes; preserve DVR's lowercase palette contract.
160
+ parentPort.postMessage({ ok: true, svg: svg.replace(/#[a-fA-F0-9]{6}\b/g, (hex) => hex.toLowerCase()) })
161
+ }
162
+
163
+ main().catch((error) => parentPort.postMessage({ error: String(error?.message ?? error) }))