dsh-vision-router 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/README.zh.md +21 -6
- package/THIRD_PARTY_NOTICES.md +167 -0
- package/assets/licenses/apache-2.0.txt +202 -0
- package/assets/licenses/llvm-mingw-LICENSE.txt +279 -0
- package/assets/licenses/mingw-w64-runtime-COPYING.txt +265 -0
- package/assets/licenses/moxcms-BSD-3-Clause.txt +26 -0
- package/assets/licenses/ncnn-LICENSE.txt +86 -0
- package/assets/licenses/roots-BSD-2-Clause.txt +24 -0
- package/assets/licenses/unicode-ident-Unicode-3.0.txt +39 -0
- package/assets/licenses/vtracer-MIT.txt +25 -0
- package/assets/licenses/zlib-rs-Zlib.txt +19 -0
- package/docs/architecture/dsh-support-window.md +25 -6
- package/docs/compatibility/dsh-0.2.2-rc2-audit.md +40 -0
- package/docs/compatibility/dsh-0.2.2-rc3-audit.md +131 -0
- package/docs/compliance/vtracer-alpha4-provenance.md +47 -0
- package/docs/compliance/vtracer-alpha4-reconstructed-Cargo.lock +567 -0
- package/docs/compliance/vtracer-alpha4-rust-inventory.json +421 -0
- package/docs/compliance/vtracer-alpha4-rust-license-texts.md +13018 -0
- package/docs/releases/v3.2.1.md +21 -0
- package/docs/releases/v3.2.2.md +25 -0
- package/docs/releases/v3.3.0.md +34 -0
- package/docs/remote-settings.md +83 -8
- package/index.js +280 -169
- package/lib/client.js +17 -17
- package/lib/core-primitives.js +155 -214
- package/lib/dsh-support-window.js +6 -3
- package/lib/native-ocr-annotation-risk.js +33 -0
- package/lib/native-ocr-canary.js +156 -0
- package/lib/native-ocr-chemistry-review.js +37 -0
- package/lib/native-ocr-document.js +243 -0
- package/lib/native-ocr-installation.js +17 -0
- package/lib/native-ocr-integrity.js +93 -0
- package/lib/native-ocr-question-labels.js +167 -0
- package/lib/native-ocr-supervisor.js +268 -0
- package/lib/remote-settings-bridge.js +93 -57
- package/lib/remote-settings-risk-client-boundary.js +2 -2
- package/lib/runtime-reliability.js +7 -0
- package/lib/session-query-readers.js +8 -2
- package/lib/session-vision-attachment-index.js +61 -14
- package/lib/settings-client-017-compat.js +4 -2
- package/lib/settings-ia-client-prelude.js +26 -10
- package/lib/tesseract-image-preprocess.js +35 -0
- package/lib/trace-vtracer-process-runtime.js +133 -0
- package/lib/trace-vtracer-process.js +43 -0
- package/lib/trace-vtracer-worker.js +163 -0
- package/lib/vision-attachment-handle-runtime.js +11 -2
- package/lib/vision-backend-runtime-policy.js +5 -3
- package/lib/vision-image-input-reader.js +67 -0
- package/lib/vision-image-input-verdict.js +24 -3
- package/lib/vision-tool-runtime-boundary.js +7 -10
- package/lib/vision-tool-stage.js +58 -0
- package/lib/web/dsh-settings-017-root-transport.js +52 -6
- package/lib/web-capability-boundary.js +6 -0
- package/package.json +10 -6
- package/scripts/install-native-ocr.mjs +144 -0
|
@@ -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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
|
80
|
-
|
|
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
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
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,
|
|
@@ -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
|
-
|
|
219
|
-
|
|
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';
|
|
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(
|
|
208
|
-
|
|
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('
|
|
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(){
|
|
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()]),
|
|
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('自动(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]));}
|
|
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'),
|
|
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,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
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads'
|
|
2
|
+
|
|
3
|
+
// Trusted, one-shot VTracer child. All native/WASM work lives outside the Host
|
|
4
|
+
// process; a native access violation kills this child, not the Host.
|
|
5
|
+
let sent = false
|
|
6
|
+
function reply(message) {
|
|
7
|
+
if (sent) return
|
|
8
|
+
sent = true
|
|
9
|
+
if (typeof process.send !== 'function') {
|
|
10
|
+
process.exitCode = 1
|
|
11
|
+
return
|
|
12
|
+
}
|
|
13
|
+
process.send(message, (error) => {
|
|
14
|
+
if (error) process.exitCode = 1
|
|
15
|
+
process.disconnect?.()
|
|
16
|
+
})
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
process.once('message', (task) => {
|
|
20
|
+
if (task?.type !== 'trace' || !['grayscale', 'color'].includes(task.mode)) {
|
|
21
|
+
reply({ ok: false, error: 'invalid trace task' })
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
let pendingSvg
|
|
25
|
+
try {
|
|
26
|
+
const worker = new Worker(new URL('./trace-vtracer-worker.js', import.meta.url), {
|
|
27
|
+
execArgv: [],
|
|
28
|
+
workerData: { mode: task.mode, ...task.payload },
|
|
29
|
+
resourceLimits: { maxOldGenerationSizeMb: 192, maxYoungGenerationSizeMb: 32 },
|
|
30
|
+
})
|
|
31
|
+
worker.once('message', (message) => {
|
|
32
|
+
if (message?.ok === true && typeof message.svg === 'string') pendingSvg = message.svg
|
|
33
|
+
else reply({ ok: false, error: 'vector trace worker returned an error' })
|
|
34
|
+
})
|
|
35
|
+
worker.once('error', () => reply({ ok: false, error: 'vector trace worker failed' }))
|
|
36
|
+
worker.once('exit', (code) => {
|
|
37
|
+
if (code === 0 && typeof pendingSvg === 'string') reply({ ok: true, svg: pendingSvg })
|
|
38
|
+
else reply({ ok: false, error: 'vector trace worker exited before producing SVG' })
|
|
39
|
+
})
|
|
40
|
+
} catch {
|
|
41
|
+
reply({ ok: false, error: 'vector trace worker startup failed' })
|
|
42
|
+
}
|
|
43
|
+
})
|