dsh-vision-router 3.2.1 → 3.4.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.
Files changed (43) hide show
  1. package/README.md +5 -4
  2. package/README.zh.md +20 -3
  3. package/THIRD_PARTY_NOTICES.md +60 -0
  4. package/assets/licenses/llvm-mingw-LICENSE.txt +279 -0
  5. package/assets/licenses/mingw-w64-runtime-COPYING.txt +265 -0
  6. package/assets/licenses/ncnn-LICENSE.txt +86 -0
  7. package/docs/architecture/dsh-support-window.md +25 -6
  8. package/docs/compatibility/dsh-0.2.2-rc3-audit.md +131 -0
  9. package/docs/releases/v3.2.2.md +25 -0
  10. package/docs/releases/v3.3.0.md +34 -0
  11. package/docs/releases/v3.4.0.md +41 -0
  12. package/index.js +313 -169
  13. package/lib/client.js +4 -4
  14. package/lib/core-primitives.js +115 -56
  15. package/lib/dsh-support-window.js +6 -3
  16. package/lib/maintenance-routes.js +2 -0
  17. package/lib/managed-tesseract-child.js +33 -0
  18. package/lib/native-ocr-annotation-risk.js +33 -0
  19. package/lib/native-ocr-canary.js +156 -0
  20. package/lib/native-ocr-chemistry-review.js +37 -0
  21. package/lib/native-ocr-document.js +243 -0
  22. package/lib/native-ocr-installation.js +17 -0
  23. package/lib/native-ocr-integrity.js +93 -0
  24. package/lib/native-ocr-question-labels.js +167 -0
  25. package/lib/native-ocr-supervisor.js +268 -0
  26. package/lib/optional-ocr-engines.js +330 -0
  27. package/lib/optional-ocr-routes.js +87 -0
  28. package/lib/runtime-reliability.js +7 -0
  29. package/lib/session-query-readers.js +8 -2
  30. package/lib/session-vision-attachment-index.js +61 -14
  31. package/lib/settings-ia-client-prelude.js +56 -2
  32. package/lib/tesseract-image-preprocess.js +35 -0
  33. package/lib/trace-vtracer-process-runtime.js +133 -0
  34. package/lib/trace-vtracer-process.js +43 -0
  35. package/lib/vision-attachment-handle-runtime.js +11 -2
  36. package/lib/vision-backend-runtime-policy.js +5 -3
  37. package/lib/vision-image-input-reader.js +67 -0
  38. package/lib/vision-image-input-verdict.js +24 -3
  39. package/lib/vision-tool-runtime-boundary.js +7 -10
  40. package/lib/vision-tool-stage.js +58 -0
  41. package/lib/web-capability-boundary.js +4 -0
  42. package/package.json +5 -4
  43. package/scripts/install-native-ocr.mjs +144 -0
@@ -0,0 +1,87 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { isLocalUiRequest } from './web-capability-boundary.js'
3
+ import { mutateOptionalOcr, optionalOcrStatus } from './optional-ocr-engines.js'
4
+
5
+ export const OPTIONAL_OCR_ROUTE = '/_dsh/vision-router/local-ocr'
6
+ const MAX_BUNDLE_BYTES = 64 * 1024 * 1024
7
+ function respond(res, status, data) {
8
+ res.writeHead(status, {
9
+ 'content-type': 'application/json; charset=utf-8',
10
+ 'cache-control': 'no-store',
11
+ 'x-content-type-options': 'nosniff',
12
+ })
13
+ res.end(JSON.stringify(data))
14
+ }
15
+ async function archiveFromRequest(req) {
16
+ const len = req.headers?.['content-length']
17
+ if (len !== undefined && (!/^\d+$/.test(String(len)) || Number(len) > MAX_BUNDLE_BYTES))
18
+ throw Error('bundle too large')
19
+ if (String(req.headers?.['content-type'] ?? '').split(';')[0].trim() !== 'application/octet-stream')
20
+ throw Error('expected a single binary OCR archive')
21
+ const blocks = []
22
+ let length = 0
23
+ for await (const part of req) {
24
+ length += part.length
25
+ if (length > MAX_BUNDLE_BYTES) throw Error('bundle too large')
26
+ blocks.push(part)
27
+ }
28
+ if (length < 128) throw Error('missing OCR bundle')
29
+ return Buffer.concat(blocks, length)
30
+ }
31
+ export function installOptionalOcrRoutes(ctx, {
32
+ statusReader = optionalOcrStatus,
33
+ mutate = mutateOptionalOcr,
34
+ tokenFactory = () => randomBytes(24).toString('base64url'),
35
+ } = {}) {
36
+ if (!ctx || typeof ctx.inject !== 'function') return
37
+ let token = tokenFactory()
38
+ let inFlight = false
39
+ ctx.inject(['webServer'], (webCtx) => {
40
+ webCtx.effect(() => webCtx.webServer.register({
41
+ kind: 'exact',
42
+ path: OPTIONAL_OCR_ROUTE,
43
+ handler: async (req, res) => {
44
+ if (!isLocalUiRequest(req)) return respond(res, 403, { ok: false, error: 'local DSH UI required' })
45
+ if (req.method === 'GET') {
46
+ try {
47
+ const state = await statusReader()
48
+ return respond(res, 200, { ...state, token })
49
+ } catch {
50
+ return respond(res, 500, { ok: false, error: 'local OCR status unavailable' })
51
+ }
52
+ }
53
+ if (req.method !== 'POST') {
54
+ res.setHeader('Allow', 'GET, POST')
55
+ return respond(res, 405, { ok: false, error: 'method not allowed' })
56
+ }
57
+ const fetchSite = String(req.headers?.['sec-fetch-site'] ?? '')
58
+ if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'none')
59
+ return respond(res, 403, { ok: false, error: 'cross-origin OCR operation rejected' })
60
+ if (String(req.headers?.['x-dsh-vision-router-ocr-token'] ?? '') !== token || !token)
61
+ return respond(res, 403, { ok: false, error: 'invalid OCR operation token' })
62
+ let url
63
+ try { url = new URL(req.url, 'http://localhost') }
64
+ catch { return respond(res, 400, { ok: false, error: 'invalid request' }) }
65
+ const engine = url.searchParams.get('engine')
66
+ const action = url.searchParams.get('action')
67
+ if (!['tesseract', 'ppocrv6'].includes(engine) || !['install', 'uninstall'].includes(action))
68
+ return respond(res, 400, { ok: false, error: 'unsupported OCR operation' })
69
+ if (inFlight) return respond(res, 409, { ok: false, error: 'OCR installation already running' })
70
+ inFlight = true
71
+ try {
72
+ const archive = engine === 'ppocrv6' && action === 'install'
73
+ ? await archiveFromRequest(req) : undefined
74
+ const result = await mutate({ engine, action, archive })
75
+ token = tokenFactory()
76
+ return respond(res, 200, result)
77
+ } catch (error) {
78
+ const message = String(error?.message ?? '')
79
+ const expected = /(?:missing|not installed|already exists|unavailable|busy|invalid|integrity|unsupported|untrusted|not approved|too large|OCR bundle|unowned|refusing|timed out|failed|mismatch)/i.test(message)
80
+ return respond(res, expected ? 409 : 500, {
81
+ ok: false, error: expected ? message.slice(0, 240) : 'local OCR management failed',
82
+ })
83
+ } finally { inFlight = false }
84
+ },
85
+ }), 'vision-router: optional local OCR manager')
86
+ })
87
+ }
@@ -165,6 +165,13 @@ export async function describeCacheKey(ctx, args = {}, exec, revision = 0) {
165
165
  hash.update(`revision:${revision}\n`)
166
166
  const paths = Array.isArray(args.paths) ? args.paths : []
167
167
  const attachments = Array.isArray(args.attachmentIds) ? args.attachmentIds : []
168
+ // Cache hits bypass the actual tool executor, including its Session-owned
169
+ // attachment authorization. Until authorization can be proved at this outer
170
+ // boundary, never cache any upload-identity input (including the paths alias).
171
+ // Ordinary paths remain cacheable only after fs.resolve/readBytes succeeds.
172
+ if (attachments.length > 0 || paths.some((input) => /^sha256:/i.test(String(input).trim()))) {
173
+ return undefined
174
+ }
168
175
  const fs = ctx?.get?.('fs')
169
176
  const cwd = exec?.agent?.session?.header?.cwd
170
177
  const signal = exec?.signal
@@ -214,7 +214,8 @@ export function createSessionEventTailReader(ctx) {
214
214
  * the released readSession() path.
215
215
  */
216
216
  export function createSessionLogReader(ctx) {
217
- return async function readSessionLog(session) {
217
+ return async function readSessionLog(session, signal) {
218
+ signal?.throwIfAborted();
218
219
  const sessionId = sessionIdOf(session);
219
220
  if (sessionId === undefined || sessionId === null)
220
221
  return { supported: false };
@@ -225,7 +226,8 @@ export function createSessionLogReader(ctx) {
225
226
  if (typeof observeSession === 'function') {
226
227
  let observation;
227
228
  try {
228
- observation = await observeSession.call(query, sessionId, { projectionMode: 'none' });
229
+ observation = await observeSession.call(query, sessionId, signal === undefined ? { projectionMode: 'none' } : { projectionMode: 'none', signal });
230
+ signal?.throwIfAborted();
229
231
  const observationBag = propertyBag(observation);
230
232
  const events = observationBag?.events;
231
233
  if (!Array.isArray(events)) {
@@ -249,6 +251,10 @@ export function createSessionLogReader(ctx) {
249
251
  if (typeof readSession !== 'function')
250
252
  return { supported: false };
251
253
  const snapshot = await readSession.call(query, sessionId);
254
+ // Older Hosts expose readSession without a signal parameter. They cannot
255
+ // interrupt the underlying read, but aborted reads must never publish
256
+ // recovered attachment authority after the result eventually arrives.
257
+ signal?.throwIfAborted();
252
258
  const snapshotBag = propertyBag(snapshot);
253
259
  const events = snapshotBag?.events;
254
260
  if (!Array.isArray(events)) {
@@ -1,4 +1,5 @@
1
1
  import { legacySessionEvents } from './session-event-history-compat.js';
2
+ import { sessionImageAttachmentRefs } from './vision-attachment-handle-runtime.js';
2
3
  function propertyBag(value) {
3
4
  return value !== null && (typeof value === 'object' || typeof value === 'function')
4
5
  ? value
@@ -23,10 +24,21 @@ function iterableValues(value) {
23
24
  }
24
25
  return value;
25
26
  }
26
- function boundedMessage(error) {
27
- const record = propertyBag(error);
28
- const text = record?.message ?? error;
29
- return String(text ?? '').slice(0, 400);
27
+ // Host error messages may contain file paths, image ids or provider credentials.
28
+ // Only log a controlled diagnostic category, never arbitrary exception text.
29
+ function recoveryFailureKind(error) {
30
+ const code = propertyBag(error)?.code;
31
+ if (code === 'ENOENT')
32
+ return 'not-found';
33
+ if (code === 'EACCES' || code === 'EPERM')
34
+ return 'permission';
35
+ if (code === 'EBUSY')
36
+ return 'busy';
37
+ if (code === 'ETIMEDOUT')
38
+ return 'timeout';
39
+ if (code === 'SESSION_QUERY_CORRUPT_SESSION')
40
+ return 'corrupt-session';
41
+ return 'session-query-error';
30
42
  }
31
43
  /**
32
44
  * Attachment access boundary for one SessionVisionStateStore.
@@ -76,16 +88,18 @@ export function createSessionVisionAttachmentIndex({ stateStore, collectEventAtt
76
88
  return found;
77
89
  };
78
90
  const warnAttachmentRecoveryFailure = (session, attachmentId, error) => {
79
- const message = boundedMessage(error);
80
- const warningKey = `${String(attachmentId)}:${message}`;
91
+ const kind = recoveryFailureKind(error);
92
+ // The full attachment id is used only for in-memory de-duplication.
93
+ const warningKey = `${String(attachmentId)}:${kind}`;
81
94
  const key = weakKey(session);
82
95
  if (key !== undefined && attachmentRecoveryWarnings.get(key) === warningKey)
83
96
  return;
84
97
  if (key !== undefined)
85
98
  attachmentRecoveryWarnings.set(key, warningKey);
86
- logger?.warn?.('vision-router: session attachment recovery failed id=%s error=%s', String(attachmentId), message);
99
+ logger?.warn?.('vision-router: session attachment recovery failed kind=%s', kind);
87
100
  };
88
- const resolveAttachments = async (session, attachmentIds) => {
101
+ const resolveAttachments = async (session, attachmentIds, signal) => {
102
+ signal?.throwIfAborted();
89
103
  const requested = [
90
104
  ...new Set((Array.isArray(attachmentIds) ? attachmentIds : []).map((id) => String(id))),
91
105
  ];
@@ -100,14 +114,45 @@ export function createSessionVisionAttachmentIndex({ stateStore, collectEventAtt
100
114
  }
101
115
  if (missing.length === 0 || session === undefined)
102
116
  return resolved;
117
+ // Modern Session.deriveMessages() gives Session-owned image references
118
+ // without acquiring the Host SessionQuery observation lease. This is the
119
+ // same authorized source already used for projected short image handles.
120
+ // Especially on a cold resumed Session, avoid waiting on full-log I/O
121
+ // when all requested images are already present in derived messages.
122
+ const wanted = new Set(missing);
123
+ const fromSession = [];
124
+ for (const value of sessionImageAttachmentRefs(session)) {
125
+ const ref = attachmentRef(value);
126
+ if (ref === undefined)
127
+ continue;
128
+ const id = attachmentIdOf(ref);
129
+ if (!wanted.has(id))
130
+ continue;
131
+ wanted.delete(id);
132
+ resolved.set(id, ref);
133
+ fromSession.push(ref);
134
+ if (wanted.size === 0)
135
+ break;
136
+ }
137
+ signal?.throwIfAborted();
138
+ if (fromSession.length > 0)
139
+ stateStore.recordAttachments(session, fromSession);
140
+ if (wanted.size === 0)
141
+ return resolved;
142
+ const remaining = missing.filter((id) => wanted.has(id));
103
143
  let events;
104
144
  if (typeof readSessionLog === 'function') {
105
145
  let result;
106
146
  try {
107
- result = await readSessionLog(session);
147
+ result = await readSessionLog(session, signal);
148
+ signal?.throwIfAborted();
108
149
  }
109
150
  catch (error) {
110
- warnAttachmentRecoveryFailure(session, missing[0], error);
151
+ // Cancellation is not a corrupted or missing Session. Never convert
152
+ // it to a successful partial lookup or log an attachment identifier.
153
+ if (signal?.aborted)
154
+ throw signal.reason ?? error;
155
+ warnAttachmentRecoveryFailure(session, remaining[0], error);
111
156
  return resolved;
112
157
  }
113
158
  const resultRecord = propertyBag(result);
@@ -118,21 +163,23 @@ export function createSessionVisionAttachmentIndex({ stateStore, collectEventAtt
118
163
  events = resultRecord.events;
119
164
  }
120
165
  else if (resultRecord?.supported !== false) {
121
- warnAttachmentRecoveryFailure(session, missing[0], new Error('Session log reader returned an invalid capability result'));
166
+ warnAttachmentRecoveryFailure(session, remaining[0], new Error('Session log reader returned an invalid capability result'));
122
167
  return resolved;
123
168
  }
124
169
  }
125
170
  // Explicitly unsupported SessionQuery keeps the released Session-local
126
171
  // compatibility fallback. Advertised reader failures above never fall back.
172
+ signal?.throwIfAborted();
127
173
  if (events === undefined)
128
174
  events = legacySessionEvents(session);
129
- const recovered = recoverAttachmentsFromEvents(session, missing, events);
175
+ signal?.throwIfAborted();
176
+ const recovered = recoverAttachmentsFromEvents(session, remaining, events);
130
177
  for (const [id, ref] of recovered)
131
178
  resolved.set(id, ref);
132
179
  return resolved;
133
180
  };
134
- const resolveAttachment = async (session, attachmentId) => {
135
- return (await resolveAttachments(session, [attachmentId])).get(String(attachmentId));
181
+ const resolveAttachment = async (session, attachmentId, signal) => {
182
+ return (await resolveAttachments(session, [attachmentId], signal)).get(String(attachmentId));
136
183
  };
137
184
  return Object.freeze({
138
185
  recordAttachments,
@@ -108,6 +108,8 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
108
108
  var updatePair=React.useState({status:'idle'}),updateState=updatePair[0],setUpdateState=updatePair[1];
109
109
  var selfUpdatePair=React.useState({status:'idle'}),selfUpdateState=selfUpdatePair[0],setSelfUpdateState=selfUpdatePair[1];
110
110
  var actionPair=React.useState({status:'idle'}),actionState=actionPair[0],setActionState=actionPair[1];
111
+ var ocrPair=React.useState({status:'idle'}),ocrState=ocrPair[0],setOcrState=ocrPair[1];
112
+ var ocrFilePair=React.useState(undefined),ocrFile=ocrFilePair[0],setOcrFile=ocrFilePair[1];
111
113
  var egressStatePair=React.useState(readEgressNoticeDismissed()),egressDismissed=egressStatePair[0],setEgressDismissed=egressStatePair[1];
112
114
  var catalogGen=React.useRef?React.useRef(0):{current:0};
113
115
  var capsGen=React.useRef?React.useRef(0):{current:0};
@@ -137,6 +139,58 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
137
139
  function invalidateCatalog(){catalogGen.current+=1;capsGen.current+=1;setCatalog({status:'idle',groups:[],failures:[]});setCaps({status:'idle',capabilities:{},builtinFallback:[],anonymousRpmPerModel:2});void loadCatalog();void loadCapabilities(false);}
138
140
  React.useEffect(function(){var disposed=false,stops=[];function refresh(){if(!disposed)invalidateCatalog();}void loadCatalog();void loadCapabilities(false);try{if(typeof helpers.subscribeCatalogInvalidations==='function')stops.push(helpers.subscribeCatalogInvalidations(props&&props.remote,refresh));else if(props&&props.remote&&typeof props.remote.$on==='function'){stops.push(props.remote.$on('llm/adapters-updated',refresh));stops.push(props.remote.$on('settings/document-updated',refresh));stops.push(props.remote.$on('credentials/updated',refresh));}}catch(_){}try{if(props&&typeof props.subscribeConnectionReset==='function')stops.push(props.subscribeConnectionReset(refresh));}catch(_){}return function(){disposed=true;catalogGen.current+=1;capsGen.current+=1;stops.forEach(function(stop){try{if(typeof stop==='function')stop();}catch(_){}});};},[props&&props.getConnection,props&&props.remote,props&&props.subscribeConnectionReset]);
139
141
 
142
+ function refreshOptionalOcr(){
143
+ if(!localPage()||typeof fetch!=='function')return Promise.resolve();
144
+ setOcrState(function(previous){return {status:'loading',value:previous.value};});
145
+ return fetch('/_dsh/vision-router/local-ocr',{cache:'no-store'}).then(function(response){
146
+ return response.json().then(function(body){if(!response.ok||!body||body.ok!==true)throw Error(body&&body.error?body.error:'HTTP '+response.status);return body;});
147
+ }).then(function(value){setOcrState({status:'ready',value:value});},function(error){setOcrState({status:'error',error:error&&error.message?error.message:String(error)});});
148
+ }
149
+ React.useEffect(function(){if(localPage())void refreshOptionalOcr();},[]);
150
+ function runOptionalOcr(engine,action){
151
+ var value=ocrState.value;
152
+ if(!localPage()||!value||!value.token||ocrState.status!=='ready'||typeof fetch!=='function')return Promise.resolve();
153
+ if(engine==='ppocrv6'&&action==='install'&&!ocrFile)return Promise.resolve();
154
+ if(action==='uninstall'){
155
+ try{if(typeof window.confirm==='function'&&!window.confirm(tx('卸载此插件管理的 '+(engine==='ppocrv6'?'PP-OCRv6':'Tesseract')+' 文件?不会卸载系统其他软件。','Remove plugin-managed '+(engine==='ppocrv6'?'PP-OCRv6':'Tesseract')+' files? System-wide packages will be untouched.')))return Promise.resolve();}catch(_){}
156
+ }
157
+ setOcrState({status:'running',value:value});
158
+ var headers={'x-dsh-vision-router-ocr-token':value.token};
159
+ var file=engine==='ppocrv6'&&action==='install'?ocrFile:undefined;
160
+ if(file)headers['content-type']='application/octet-stream';
161
+ return fetch('/_dsh/vision-router/local-ocr?engine='+encodeURIComponent(engine)+'&action='+encodeURIComponent(action),{
162
+ method:'POST',cache:'no-store',headers:headers,body:file
163
+ }).then(function(response){return response.json().then(function(body){if(!response.ok||!body||body.ok!==true)throw Error(body&&body.error?body.error:'HTTP '+response.status);return body;});})
164
+ .then(function(){if(action==='install')setOcrFile(undefined);return refreshOptionalOcr();},function(error){setOcrState({status:'error',value:value,error:error&&error.message?error.message:String(error)});});
165
+ }
166
+ function optionalOcrPanel(){
167
+ var value=ocrState.value||{},tess=value.tesseract||{},pp=value.ppocrv6||{},busy=ocrState.status==='running'||value.busy===true;
168
+ if(!localPage())return h('p',{className:'vr-hint'},tx('本地 OCR 管理仅可在运行 DSH 的本机打开。','Local OCR management is only available in the local DSH UI.'));
169
+ return card([
170
+ h('h4',{className:'vr-ia-subtitle',key:'heading'},tx('可选本地 OCR','Optional local OCR')),
171
+ h('p',{className:'vr-hint',key:'hint'},tx('两套引擎都不强制安装。没安装时仍可按照既有隐私设置使用视觉模型回退;云端回退可能上传图片。','Both engines are optional. Without a local OCR engine, the configured vision model may handle OCR; a cloud model may receive the image.')),
172
+ h('div',{className:'vr-ia-actions',key:'refresh'},h('button',{type:'button',className:'vr-btn',disabled:busy,onClick:function(){void refreshOptionalOcr();}},tx('刷新安装状态','Refresh installation status'))),
173
+ h('div',{className:'vr-field',key:'tesseract'},
174
+ h('strong',null,'Tesseract (WASM)'),
175
+ h('p',{className:'vr-hint'},ocrState.status==='loading'?tx('检测中…','Checking…'):tess.managedInstalled?tx('插件私有安装已就绪(简体中文+英文,离线识别)。','Plugin-managed installation ready (Chinese + English, offline).'):tess.systemInstalled?tx('系统 Tesseract(简体中文+英文)已可使用,无需额外安装。','System Tesseract with Chinese and English is ready; no additional installation needed.'):tx('未安装。仅点击安装时才下载 WASM 与语言数据;卸载不会修改系统软件。','Not installed. WASM and languages are downloaded only on request. Uninstall never changes system packages.')),
176
+ h('div',{className:'vr-ia-actions'},
177
+ h('button',{type:'button',className:'vr-btn vr-btn-save',disabled:busy||ocrState.status!=='ready'||tess.managedInstalled||tess.canInstall!==true,onClick:function(){void runOptionalOcr('tesseract','install');}},tx('安装 Tesseract','Install Tesseract')),
178
+ h('button',{type:'button',className:'vr-btn',disabled:busy||ocrState.status!=='ready'||tess.canUninstall!==true,onClick:function(){void runOptionalOcr('tesseract','uninstall');}},tx('卸载插件版','Remove plugin copy'))
179
+ )
180
+ ),
181
+ h('div',{className:'vr-field',key:'ppocrv6'},
182
+ h('strong',null,'PP-OCRv6 small / ncnn'),
183
+ h('p',{className:'vr-hint'},!pp.supported?tx('此平台暂无审核通过的本地原生引擎。','Native engine not qualified for this platform.'):pp.installed?tx('已经安装且完整性校验通过。','Installed and integrity-verified.'):pp.damaged?tx('检测到插件管理的安装文件损坏;可点击卸载后重新导入可信离线包。','Managed installation is damaged; you may remove it and import a trusted bundle again.'):tx('尚未安装。原生包公开分发审核未完成;当前只能选择你已合法获得的可信本地安装包。','Not installed. Public native-bundle redistribution is not cleared; only an owner-provided trusted local archive can be imported.')),
184
+ pp.supported?h('input',{className:'vr-input',type:'file',accept:'.tar.gz,.tgz,application/gzip','aria-label':tx('选择 PP-OCRv6 离线包','Choose PP-OCRv6 offline bundle'),disabled:busy||ocrState.status!=='ready',onChange:function(event){setOcrFile(event.target.files&&event.target.files[0]||undefined);}}):null,
185
+ h('div',{className:'vr-ia-actions'},
186
+ h('button',{type:'button',className:'vr-btn vr-btn-save',disabled:busy||ocrState.status!=='ready'||!pp.supported||!ocrFile||ocrFile.size>64*1024*1024,onClick:function(){void runOptionalOcr('ppocrv6','install');}},tx('安装所选离线包','Install selected bundle')),
187
+ h('button',{type:'button',className:'vr-btn',disabled:busy||ocrState.status!=='ready'||!pp.canUninstall,onClick:function(){void runOptionalOcr('ppocrv6','uninstall');}},tx('卸载 PP-OCRv6','Remove PP-OCRv6'))
188
+ )
189
+ ),
190
+ ocrState.status==='running'?h('p',{className:'vr-hint',key:'busy',role:'status'},tx('安装或卸载正在进行,请保持此页面打开。','Installation or removal in progress. Keep this page open.')):null,
191
+ ocrState.status==='error'?h('p',{className:'vr-failed',key:'error',role:'alert'},String(ocrState.error||tx('本地 OCR 操作失败','Local OCR operation failed'))):null
192
+ ]);
193
+ }
140
194
  function runTestConnection(){if(!localPage()||typeof fetch!=='function'||testState.status==='running')return Promise.resolve();setTestState({status:'running'});return fetch('/_dsh/vision-router/test-connection',{cache:'no-store'}).then(function(response){return response.json().catch(function(){return undefined;}).then(function(body){if(!response.ok)throw new Error(body&&body.error?body.error:'HTTP '+response.status);return body;});}).then(function(body){setTestState({status:'done',result:body||{ok:false,error:'empty response'}});},function(error){setTestState({status:'done',result:{ok:false,error:error&&error.message?error.message:String(error)}});});}
141
195
  function runUpdateCheck(force){if(!localPage()||typeof fetch!=='function'||updateState.status==='running')return Promise.resolve();setUpdateState({status:'running',result:updateState.result});return fetch('/_dsh/vision-router/update-check'+(force?'?force=1':''),{cache:'no-store'}).then(function(response){return response.json().catch(function(){return undefined;}).then(function(body){if(!response.ok)throw new Error(body&&body.error?body.error:'HTTP '+response.status);return body;});}).then(function(body){setUpdateState({status:'done',result:body});},function(error){setUpdateState({status:'done',result:{ok:false,error:error&&error.message?error.message:String(error)}});});}
142
196
  function runSelfUpdate(){var checked=updateState.result,auto=checked&&checked.autoUpdate;if(!localPage()||selfUpdateState.status==='running'||!checked||checked.ok!==true||checked.updateAvailable!==true||!auto||!auto.token)return Promise.resolve();try{if(typeof window.confirm==='function'&&window.confirm(tx('确认更新 Vision Router?更新完成后需要重启 DSH。','Update Vision Router? Restart DSH after the update.'))!==true)return Promise.resolve();}catch(_){}setSelfUpdateState({status:'running'});return fetch('/_dsh/vision-router/self-update',{method:'POST',cache:'no-store',headers:{'x-dsh-vision-router-update-token':auto.token}}).then(function(response){return response.json().catch(function(){return undefined;}).then(function(body){if(!response.ok||!body||body.ok!==true)throw new Error(body&&body.error?body.error:'HTTP '+response.status);return body;});}).then(function(body){setSelfUpdateState({status:'done',result:body});void runUpdateCheck(true);},function(error){setSelfUpdateState({status:'done',error:error&&error.message?error.message:String(error)});});}
@@ -360,10 +414,10 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
360
414
  );
361
415
  }
362
416
  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]);}
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.'))]));}
417
+ 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'),optionalOcrPanel(),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.'))]));}
364
418
  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')));}
365
419
  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);}
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]));}
420
+ 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('自动(PP-OCRv6 → Tesseract → 视觉模型)','Auto (PP-OCRv6 → 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]));}
367
421
  function diagnosticValue(label,valueText){return h('div',{className:'vr-ia-diag-row',key:label},h('span',null,label),h('strong',null,valueText));}
368
422
  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]);}
369
423
  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());}
@@ -0,0 +1,35 @@
1
+ // Optional local-only subtitle recovery, entered only after weak Tesseract OCR.
2
+ // Derives one lower-region greyscale crop without storing the source image.
3
+ export async function prepareTesseractSubtitleRetry(bytes, {
4
+ loadSharp, signal, remainingMs = 0,
5
+ } = {}) {
6
+ if (signal?.aborted || remainingMs < 900 || typeof loadSharp !== 'function') return null
7
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength > 24 * 1024 * 1024) return null
8
+ const sharp = await loadSharp()
9
+ if (signal?.aborted) return null
10
+ const image = sharp(bytes, { failOn: 'error', limitInputPixels: 16_000_000, animated: false })
11
+ const metadata = await image.metadata()
12
+ const width = metadata.width, height = metadata.height
13
+ if (!Number.isInteger(width) || !Number.isInteger(height) ||
14
+ width < 120 || height < 120 || width * height > 16_000_000) return null
15
+ const top = Math.floor(height * 0.55)
16
+ const crop = { left: 0, top, width, height: height - top }
17
+ const sample = await sharp(bytes, { failOn: 'error', limitInputPixels: 16_000_000, animated: false })
18
+ .extract(crop).resize(64, 32, { fit: 'fill' }).grayscale().raw().toBuffer()
19
+ if (signal?.aborted) return null
20
+ const mean = sample.reduce((sum, value) => sum + value, 0) / sample.length
21
+ // Invert only when the actual subtitle region is predominantly dark.
22
+ const inverted = mean < 108
23
+ const scale = Math.min(3.2, 1000 / width, 1500 / crop.height)
24
+ const outWidth = Math.max(1, Math.round(width * scale))
25
+ const outHeight = Math.max(1, Math.round(crop.height * scale))
26
+ let pipeline = sharp(bytes, { failOn: 'error', limitInputPixels: 16_000_000, animated: false })
27
+ .extract(crop).resize(outWidth, outHeight).grayscale().normalize()
28
+ if (inverted) pipeline = pipeline.negate()
29
+ const prepared = await pipeline.png().toBuffer()
30
+ if (signal?.aborted) return null
31
+ if (prepared.length > 16 * 1024 * 1024) return null
32
+ return {
33
+ bytes: prepared, variant: inverted ? 'subtitle-inverted' : 'subtitle-grayscale',
34
+ }
35
+ }
@@ -0,0 +1,133 @@
1
+ import { fork } from 'node:child_process'
2
+
3
+ // Avoid unbounded Host-memory retention and process storms under hostile
4
+ // concurrent tool calls. Waiting consumes the caller's original deadline.
5
+ const MAX_ACTIVE_TRACE_PROCESSES = 3
6
+ const MAX_WAITING_TRACE_PROCESSES = 8
7
+ let active = 0
8
+ const waiting = []
9
+
10
+ function dispatchWaiting() {
11
+ while (active < MAX_ACTIVE_TRACE_PROCESSES && waiting.length > 0) {
12
+ const next = waiting.shift()
13
+ if (next.finished()) continue
14
+ active++
15
+ next.start()
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Own one VTracer child process without sharing native/WASM address space
21
+ * with the Host. The injected childUrl is an internal test seam, never a
22
+ * user-provided path or executable.
23
+ */
24
+ export function runIsolatedTraceProcess({
25
+ mode,
26
+ payload,
27
+ timeoutMs,
28
+ signal,
29
+ abortReason,
30
+ childUrl = new URL('./trace-vtracer-process.js', import.meta.url),
31
+ }) {
32
+ const aborted = () => abortReason?.() ?? new Error('vector trace aborted')
33
+ if (signal?.aborted) return Promise.reject(aborted())
34
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
35
+ return Promise.reject(new Error('vector trace timed out'))
36
+ }
37
+ if (waiting.length >= MAX_WAITING_TRACE_PROCESSES && active >= MAX_ACTIVE_TRACE_PROCESSES) {
38
+ return Promise.reject(new Error('vector trace process capacity exceeded'))
39
+ }
40
+
41
+ return new Promise((resolve, reject) => {
42
+ let child
43
+ let timer
44
+ let finished = false
45
+ let started = false
46
+ let slotHeld = false
47
+ let pendingSvg
48
+
49
+ const release = () => {
50
+ if (!slotHeld) return
51
+ slotHeld = false
52
+ active--
53
+ dispatchWaiting()
54
+ }
55
+ const finish = (error, svg) => {
56
+ if (finished) return
57
+ finished = true
58
+ if (timer !== undefined) clearTimeout(timer)
59
+ signal?.removeEventListener?.('abort', onAbort)
60
+ if (!started) {
61
+ const index = waiting.indexOf(entry)
62
+ if (index >= 0) waiting.splice(index, 1)
63
+ }
64
+ // Cancellation, timeouts, and native crashes stay inside the child.
65
+ if (error && child && !child.killed) {
66
+ try { child.kill() } catch { /* a closing child is already terminal */ }
67
+ }
68
+ if (error) reject(error)
69
+ else resolve(svg)
70
+ }
71
+ const onAbort = () => finish(aborted())
72
+
73
+ const entry = {
74
+ finished: () => finished,
75
+ start: () => {
76
+ if (finished) { release(); return }
77
+ started = true
78
+ slotHeld = true
79
+ try {
80
+ // No inherited Host CLI/test loader flags or NODE_OPTIONS preload.
81
+ const childEnv = { ...process.env, NODE_OPTIONS: '' }
82
+ if (process.versions?.electron) childEnv.ELECTRON_RUN_AS_NODE = '1'
83
+ child = fork(childUrl, [], {
84
+ execArgv: [],
85
+ serialization: 'advanced',
86
+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
87
+ windowsHide: true,
88
+ env: childEnv,
89
+ })
90
+ child.once('message', (message) => {
91
+ const svg = message?.svg
92
+ // The subprocess is a trust boundary, not an output validator.
93
+ // Native faults must never let bogus or oversized markup reach
94
+ // the Host artifact writer, even if IPC closes with status zero.
95
+ if (
96
+ message?.ok === true && typeof svg === 'string' &&
97
+ svg.length > 0 && svg.length <= 16 * 1024 * 1024 &&
98
+ /<svg[\s>]/.test(svg) && Buffer.byteLength(svg) <= 16 * 1024 * 1024
99
+ ) {
100
+ pendingSvg = svg
101
+ } else {
102
+ finish(new Error('vector trace process returned an invalid result'))
103
+ }
104
+ })
105
+ child.once('error', () => finish(new Error('vector trace process startup failed')))
106
+ child.once('close', (code, termSignal) => {
107
+ // Do not resolve a healthy result before the IPC pipe is closed
108
+ // and this process' concurrency slot has actually been released.
109
+ release()
110
+ if (finished) return
111
+ if (code === 0 && typeof pendingSvg === 'string') finish(undefined, pendingSvg)
112
+ else finish(new Error('vector trace process exited before producing SVG (' +
113
+ (code === null ? String(termSignal ?? 'signal') : String(code)) + ')'))
114
+ })
115
+ child.send({ type: 'trace', mode, payload }, (error) => {
116
+ if (error) finish(new Error('vector trace process IPC failed'))
117
+ })
118
+ } catch {
119
+ finish(new Error('vector trace process launch failed'))
120
+ if (!child) release()
121
+ }
122
+ },
123
+ }
124
+
125
+ signal?.addEventListener?.('abort', onAbort, { once: true })
126
+ if (signal?.aborted) { finish(aborted()); return }
127
+ timer = setTimeout(() => finish(new Error(
128
+ 'vector trace timed out — crop the image or reduce its complexity',
129
+ )), timeoutMs)
130
+ waiting.push(entry)
131
+ dispatchWaiting()
132
+ })
133
+ }