zcode-pro 1.10.0 → 1.12.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.
@@ -1,8 +1,10 @@
1
1
  // “ZCode Pro 增强设置”弹窗:功能开关 + 外观 + 运行状态。
2
2
  // 顶部标签页切换(视觉参考侧栏“分组/项目”切换);配置写入 helper(~/.zcode/zcodepro.json)。
3
3
  import { h, t, rpc, getConfig, clearConfigCache, errText, HELPER_URL, liveBoot, isZhLocale, uiLocale, isCjkLocale, isNewProjectSidebar, DEFAULT_SHORTCUTS, DEFAULT_STATUS_ITEMS, DEFAULT_TURN_ITEMS, STATUS_SESSION_IDS, STATUS_GLOBAL_IDS } from '../core.js';
4
- import { openDialog, dialogFooter, btnPrimary, btnSecondary, btnSmall, settingRow, ensureStyle, showToast, numberField, unitField } from '../ui.js';
5
- import { comboField, providerOptionsOf, modelOptionsOf, modelPlaceholderOf, isManualConn } from '../provider-fields.js';
4
+ import { openDialog, dialogFooter, btnPrimary, btnSecondary, btnSmall, settingRow, ensureStyle, showToast, numberField, unitField, confirmTip } from '../ui.js';
5
+ import { isManualConn } from '../provider-fields.js';
6
+ import { providerModelThinkingFields } from '../provider-model-thinking.js';
7
+ import { resolveThinkingOptions } from '../thinking-levels.js';
6
8
  import { refreshAliases } from './alias.js';
7
9
  import { migrationCard } from './alias-migration.js';
8
10
  import { applyStyles, STYLE_DEFAULTS, showStyleHighlight, hideStyleHighlight } from './styles.js';
@@ -152,7 +154,40 @@ function makeUpgradeControls({ endpoint, metaRefresh, idleText }) {
152
154
  return { btn, state, stop: stopPoll };
153
155
  }
154
156
 
155
- export function openSettingsDialog() {
157
+ // 记住上次停留的标签页(一级 + 各级二级),下次打开恢复到原位。
158
+ // 存 localStorage 而不是配置文件:属于纯界面状态,不需要同步到别的机器。
159
+ // initialTab 显式指定时(如翻译面板的 ⚙ 直达“翻译”)优先用它,不读记忆值。
160
+ const SETTINGS_TAB_KEY = 'zcodepro-settings-tab';
161
+ const SETTINGS_SUBTAB_KEY = 'zcodepro-settings-subtab';
162
+ function readTabMemory(key) {
163
+ try {
164
+ const v = JSON.parse(localStorage.getItem(key) || 'null');
165
+ return v && typeof v === 'object' ? v : {};
166
+ } catch { return {}; }
167
+ }
168
+ function writeTabMemory(key, patch) {
169
+ try {
170
+ const cur = readTabMemory(key);
171
+ localStorage.setItem(key, JSON.stringify({ ...cur, ...patch }));
172
+ } catch { /* ignore */ }
173
+ }
174
+
175
+ // initialTab 默认空串而不是 'features':要区分“调用方没指定”(回到上次停留的
176
+ // tab)与“调用方明确要求打开功能页”两种意图。之前默认 'features' 会让
177
+ // explicitTab 永远有值,记忆功能失效、每次都停在功能页
178
+ // 当前打开着的设置弹窗。同一时刻只应有一个:再调用时先把旧的关掉再重开,不叠开新的。
179
+ // 叠开过一次:设置弹窗的遮罩不拦点击(pointer-events:none),两个弹窗同时开着时,
180
+ // 点在旧弹窗上的操作照常生效——用户看着新弹窗,实际改的是底下那个。
181
+ // 关掉再重开(而不是复用旧弹窗切页签):重开会按当前状态重新读配置,
182
+ // 旧弹窗里过时的内容不会被带到新弹窗里。不做定时刷新:为少见的场景每几秒读一次
183
+ // 配置不值当,弹窗开着时别处改了配置,重新打开就是最新的
184
+ let openSettingsHandle = null;
185
+
186
+ export function openSettingsDialog(initialTab = '', initialSub = '') {
187
+ if (openSettingsHandle && document.contains(openSettingsHandle.el)) {
188
+ try { openSettingsHandle.close(); } catch { /* ignore */ }
189
+ openSettingsHandle = null;
190
+ }
156
191
  ensureStyle();
157
192
  const L = t();
158
193
  // Headroom / rtk 升级进度轮询的停止句柄:面板代码在 onMount 里赋值,关弹窗时停掉
@@ -168,10 +203,16 @@ export function openSettingsDialog() {
168
203
  overlay: 'none',
169
204
  draggable: true,
170
205
  posKey: 'settings',
206
+ // 与翻译面板一致:四边/四角可拖动改尺寸,尺寸单独记住(不影响已存的拖动位置)
207
+ resizable: true,
208
+ sizeKey: 'settings',
171
209
  dismissOnOutside: false,
172
210
  onClose: () => {
211
+ openSettingsHandle = null;
173
212
  if (hrUpgradePollStop) hrUpgradePollStop();
174
213
  if (rtkUpgradePollStop) rtkUpgradePollStop();
214
+ // 通知外部(翻译面板等)设置已关闭:它们可能在打开期间临时降了层级
215
+ window.dispatchEvent(new CustomEvent('zcodepro:settings-closed'));
175
216
  },
176
217
  onMount: async ({ body, close, content }) => {
177
218
  // 标记设置弹窗:showToast 据此把弹窗内触发的提示居中叠在弹窗上
@@ -216,9 +257,9 @@ export function openSettingsDialog() {
216
257
  }, '✕');
217
258
  titleEl.replaceChildren(titleLeft, closeX);
218
259
  }
219
- // 九个只读请求相互独立:并行取(串行时 headroom 的版本探测一项就约
260
+ // 十一个只读请求相互独立:并行取(串行时 headroom 的版本探测一项就约
220
261
  // 700ms,弹窗打开明显卡顿)
221
- const [health, config, agentsRes, visionRes, titleGenRes, titleGenProvidersRes, rtkRes, headroomRes, zcodeConfigRes] = await Promise.all([
262
+ const [health, config, agentsRes, visionRes, titleGenRes, titleGenProvidersRes, rtkRes, headroomRes, zcodeConfigRes, translateRes, translateProvidersRes, translateSessionRes] = await Promise.all([
222
263
  rpc('/health'),
223
264
  getConfig(true),
224
265
  rpc('/agents'),
@@ -228,6 +269,9 @@ export function openSettingsDialog() {
228
269
  rpc('/rtk'),
229
270
  rpc('/headroom'),
230
271
  rpc('/zcode-config'),
272
+ rpc('/translate'),
273
+ rpc('/translate/providers'),
274
+ rpc('/translate/session-model'),
231
275
  ]);
232
276
  // 供应商表(含各供应商可选模型):视觉代理的模型下拉也用这份
233
277
  const titleGenProviders = titleGenProvidersRes.ok && Array.isArray(titleGenProvidersRes.providers)
@@ -387,6 +431,11 @@ export function openSettingsDialog() {
387
431
  if (await setFeature('tableCopy', next)) f.tableCopy = next;
388
432
  refreshRows();
389
433
  }),
434
+ settingRow(L.featureTranslate, L.featureTranslateDesc, f.translate !== false, async () => {
435
+ const next = !(f.translate !== false);
436
+ if (await setFeature('translate', next)) f.translate = next;
437
+ refreshRows();
438
+ }),
390
439
  settingRow(L.featureSessionLink, L.featureSessionLinkDesc, f.sessionLink !== false, async () => {
391
440
  const next = !(f.sessionLink !== false);
392
441
  if (await setFeature('sessionLink', next)) f.sessionLink = next;
@@ -498,9 +547,17 @@ export function openSettingsDialog() {
498
547
  }));
499
548
 
500
549
  // 标签页切换:功能(现有内容)/ 外观 / 全局提示词 / 视觉代理
501
- let activeTab = 'features';
550
+ // initialTab 供面板等入口直达指定标签(如翻译面板的 ⚙ 打开“翻译”页);
551
+ // 未显式指定时恢复上次停留的一级 tab(tabDefs 建好后再校验合法性)
552
+ const explicitTab = typeof initialTab === 'string' && initialTab ? initialTab : '';
553
+ const tabMemory = readTabMemory(SETTINGS_TAB_KEY);
554
+ let activeTab = explicitTab || (typeof tabMemory.last === 'string' ? tabMemory.last : '') || 'features';
502
555
  // 二级 tab 栏(外观 / 行为各一条):登记后统一放到滚动区上方的固定区
503
556
  const subTabBars = {};
557
+ // 二级 tab 记忆:每页一条 key(styles / agents / proxy),默认值保持原行为
558
+ const subMemory = readTabMemory(SETTINGS_SUBTAB_KEY);
559
+ const savedSub = (key, fallback) => (typeof subMemory[key] === 'string' && subMemory[key]) || fallback;
560
+ const rememberSub = (key, value) => writeTabMemory(SETTINGS_SUBTAB_KEY, { [key]: value });
504
561
  // 插件更新卡片:显示 duanluan-zcode-plugins 市场状态,一键更新(helper /plugins/* 端点);
505
562
  // 状态异步加载,打开弹窗不等待
506
563
 
@@ -615,8 +672,9 @@ export function openSettingsDialog() {
615
672
  const paneHeadroom = h('div', { role: 'tabpanel', style: 'display:none' });
616
673
  const paneAutoContinue = h('div', { role: 'tabpanel', style: 'display:none' });
617
674
  const paneTitleGen = h('div', { role: 'tabpanel', style: 'display:none' });
675
+ const paneTranslate = h('div', { role: 'tabpanel', style: 'display:none' });
618
676
  const paneDebug = h('div', { role: 'tabpanel', style: 'display:none' });
619
- const panes = { features: paneFeatures, shortcuts: paneShortcuts, styles: paneStyles, perf: panePerf, agents: paneAgents, proxy: paneProxy, sync: paneSync, import: paneImport, vision: paneVision, headroom: paneHeadroom, rtk: paneRtk, debug: paneDebug };
677
+ const panes = { features: paneFeatures, shortcuts: paneShortcuts, styles: paneStyles, perf: panePerf, agents: paneAgents, proxy: paneProxy, sync: paneSync, import: paneImport, vision: paneVision, translate: paneTranslate, headroom: paneHeadroom, rtk: paneRtk, debug: paneDebug };
620
678
  // 一级 tab 顺序:功能 → 外观 → 行为 → 性能 → 快捷键 → 代理/同步/插件页
621
679
  const tabDefs = [
622
680
  ['features', L.tabFeatures],
@@ -626,6 +684,7 @@ export function openSettingsDialog() {
626
684
  ['shortcuts', L.tabShortcuts],
627
685
  ['proxy', L.tabProxy],
628
686
  ['sync', L.tabSync],
687
+ ['translate', L.tabTranslate],
629
688
  ...(config.features.sessionImport !== false ? [['import', L.tabImport]] : []),
630
689
  ['vision', L.tabVision],
631
690
  ['headroom', L.tabHeadroom],
@@ -634,7 +693,74 @@ export function openSettingsDialog() {
634
693
  // 普通用户不可见
635
694
  ...(config.devMode === true || config.devActive === true ? [['debug', L.tabDebug]] : []),
636
695
  ];
637
- const tablist = h('div', { role: 'tablist', 'aria-orientation': 'horizontal', class: 'zcodepro-tablist mt-1' });
696
+ // 一级 tab 加 scrollable:tab 数量多时横向滚动而不是被裁掉(二级 tab 栏不加)
697
+ const tablist = h('div', { role: 'tablist', 'aria-orientation': 'horizontal', class: 'zcodepro-tablist zcodepro-tablist-scroll mt-1' });
698
+ // 一级 tab 栏的滚动增强:
699
+ // - 只在内容真正溢出时给数据属性(控制两端渐隐),能全部显示时无遮罩
700
+ // - 滚到某一端时那端不再渐隐
701
+ // - 鼠标滚轮(含纵向滚轮)在 tab 栏上转为横向滚动
702
+ // - 按住 tab 左右拖动滚动(click 会被抑制,避免拖动误切页)
703
+ const bindTabScroll = () => {
704
+ const updateOverflow = () => {
705
+ const overflow = tablist.scrollWidth - tablist.clientWidth;
706
+ if (overflow <= 1) {
707
+ delete tablist.dataset.overflow;
708
+ return;
709
+ }
710
+ const atStart = tablist.scrollLeft <= 1;
711
+ const atEnd = tablist.scrollLeft >= overflow - 1;
712
+ tablist.dataset.overflow = atStart ? 'start' : atEnd ? 'end' : '1';
713
+ };
714
+ tablist.addEventListener('scroll', updateOverflow, { passive: true });
715
+ new ResizeObserver(updateOverflow).observe(tablist);
716
+ // 纵向滚轮转横向
717
+ tablist.addEventListener('wheel', (e) => {
718
+ if (tablist.scrollWidth <= tablist.clientWidth + 1) return;
719
+ const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
720
+ if (!delta) return;
721
+ e.preventDefault();
722
+ tablist.scrollLeft += delta;
723
+ }, { passive: false });
724
+ // 按住拖动滚动
725
+ let drag = null;
726
+ let suppressClick = false;
727
+ tablist.addEventListener('pointerdown', (e) => {
728
+ if (e.button !== 0) return;
729
+ if (tablist.scrollWidth <= tablist.clientWidth + 1) return;
730
+ drag = { x: e.clientX, left: tablist.scrollLeft, moved: false };
731
+ suppressClick = false;
732
+ });
733
+ tablist.addEventListener('pointermove', (e) => {
734
+ if (!drag) return;
735
+ const dx = e.clientX - drag.x;
736
+ if (!drag.moved && Math.abs(dx) < 4) return; // 小抖动不算拖动
737
+ if (!drag.moved) {
738
+ drag.moved = true;
739
+ tablist.dataset.dragging = '1';
740
+ }
741
+ tablist.scrollLeft = drag.left - dx;
742
+ e.preventDefault();
743
+ });
744
+ const endDrag = () => {
745
+ if (!drag) return;
746
+ suppressClick = drag.moved;
747
+ drag = null;
748
+ delete tablist.dataset.dragging;
749
+ };
750
+ tablist.addEventListener('pointerup', endDrag);
751
+ tablist.addEventListener('pointercancel', endDrag);
752
+ tablist.addEventListener('pointerleave', endDrag);
753
+ // 拖动结束后紧跟的 click 要吞掉,否则会误切到松手位置的 tab
754
+ tablist.addEventListener('click', (e) => {
755
+ if (!suppressClick) return;
756
+ suppressClick = false;
757
+ e.stopPropagation();
758
+ e.preventDefault();
759
+ }, true);
760
+ updateOverflow();
761
+ };
762
+ bindTabScroll();
763
+
638
764
  const renderTabs = () => tablist.replaceChildren(...tabDefs.map(([id, label]) =>
639
765
  h('button', {
640
766
  type: 'button', role: 'tab', class: 'zcodepro-tab',
@@ -642,16 +768,33 @@ export function openSettingsDialog() {
642
768
  'data-state': activeTab === id ? 'active' : 'inactive',
643
769
  onClick: () => switchTab(id),
644
770
  }, label)));
771
+ // 重建按钮后重算是否需要渐隐
772
+ requestAnimationFrame(() => {
773
+ const overflow = tablist.scrollWidth - tablist.clientWidth;
774
+ if (overflow <= 1) delete tablist.dataset.overflow;
775
+ });
645
776
  const switchTab = (name) => {
646
777
  activeTab = name;
778
+ // 记住一级 tab,下次打开回到这里
779
+ writeTabMemory(SETTINGS_TAB_KEY, { last: name });
647
780
  // 切走“快捷键”标签页时结束键位录制:否则在其它标签页打字会被录制监听吞掉
648
781
  if (name !== 'shortcuts' && hkRecording) stopHkRecording();
649
782
  for (const [id, pane] of Object.entries(panes)) pane.style.display = id === name ? '' : 'none';
650
783
  for (const [id, bar] of Object.entries(subTabBars)) bar.style.display = id === name ? '' : 'none';
651
784
  if (name === 'import') paneImport.__onShow?.();
652
785
  renderTabs();
786
+ // 激活的 tab 滚进视野:横向滚动后,从外部直达的 tab 可能在可视区外
787
+ try {
788
+ const el = tablist.querySelector('[data-state="active"]');
789
+ el?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
790
+ } catch { /* ignore */ }
653
791
  };
654
- renderTabs();
792
+ // 登记给单实例逻辑用:已开着时再打开,先把它关掉
793
+ openSettingsHandle = { el: content.closest('.zcodepro-overlay') || content, close };
794
+ // 记忆的 tab 可能已不存在(版本升级删了某页、导入会话被关掉等):退回“功能”
795
+ activeTab = tabDefs.some(([id]) => id === activeTab) ? activeTab : 'features';
796
+ // 注意:真正的首次切换推迟到 onMount 末尾(所有 pane 都建好并 append 之后)。
797
+ // 这里只渲染一次 tab 按钮,避免内容区在 pane 未就绪时切过去留下空白。
655
798
 
656
799
  // “样式”:一行两项、相关项同行;无描述文字,悬停名称显示 tip;
657
800
  // 数字框滚轮/手输调节,改完即存即生效
@@ -984,7 +1127,14 @@ export function openSettingsDialog() {
984
1127
  custom: patch.custom !== undefined ? patch.custom : themeCfg.custom,
985
1128
  bg: { ...themeCfg.bg, ...(patch.bg || {}) },
986
1129
  };
987
- const res = await rpc('/config', { method: 'POST', body: { theme: themeCfg } });
1130
+ // 只提交本次改动的字段(后端按字段合并):整对象提交会把弹窗打开期间
1131
+ // 别处(另一窗口、壁纸 CLI/技能)刚改的主题字段退回旧值。
1132
+ // skin/custom 没动就不带;bg 只带 patch 里出现过的子字段
1133
+ const bodyTheme = {};
1134
+ if (patch.skin !== undefined) bodyTheme.skin = themeCfg.skin;
1135
+ if (patch.custom !== undefined) bodyTheme.custom = themeCfg.custom;
1136
+ if (patch.bg && Object.keys(patch.bg).length) bodyTheme.bg = patch.bg;
1137
+ const res = await rpc('/config', { method: 'POST', body: Object.keys(bodyTheme).length ? { theme: bodyTheme } : {} });
988
1138
  clearConfigCache();
989
1139
  window.dispatchEvent(new CustomEvent('zcodepro:config-changed'));
990
1140
  if (!res.ok) showToast(L.failed + ': ' + errText(res), 'error');
@@ -1480,7 +1630,8 @@ export function openSettingsDialog() {
1480
1630
  void refreshBgFiles();
1481
1631
  void refreshFolderInfo();
1482
1632
 
1483
- let stylesSubTab = 'bgimg'; // 默认停在第一个子页(壁纸)
1633
+ const STYLES_SUBS = ['bgimg', 'colors', 'styles', 'status'];
1634
+ let stylesSubTab = STYLES_SUBS.includes(savedSub('styles', '')) ? savedSub('styles', '') : 'bgimg';
1484
1635
  const stylesSubTablist = h('div', { role: 'tablist', 'aria-orientation': 'horizontal', class: 'zcodepro-tablist' });
1485
1636
  const renderStylesSubTabs = () => stylesSubTablist.replaceChildren(...[
1486
1637
  ['bgimg', L.themeBgPane],
@@ -1493,6 +1644,7 @@ export function openSettingsDialog() {
1493
1644
  'data-state': stylesSubTab === id ? 'active' : 'inactive',
1494
1645
  onClick: () => {
1495
1646
  stylesSubTab = id;
1647
+ rememberSub('styles', id);
1496
1648
  paneStylesSub1.style.display = id === 'styles' ? '' : 'none';
1497
1649
  paneStylesSub2.style.display = id === 'status' ? '' : 'none';
1498
1650
  paneStylesSub3.style.display = id === 'colors' ? '' : 'none';
@@ -1500,6 +1652,11 @@ export function openSettingsDialog() {
1500
1652
  renderStylesSubTabs();
1501
1653
  },
1502
1654
  }, label)));
1655
+ // 按记住的子页设置初始可见性(首次打开时四个 pane 都会显示,必须显式关掉)
1656
+ paneStylesSub1.style.display = stylesSubTab === 'styles' ? '' : 'none';
1657
+ paneStylesSub2.style.display = stylesSubTab === 'status' ? '' : 'none';
1658
+ paneStylesSub3.style.display = stylesSubTab === 'colors' ? '' : 'none';
1659
+ paneStylesSub4.style.display = stylesSubTab === 'bgimg' ? '' : 'none';
1503
1660
  renderStylesSubTabs();
1504
1661
  subTabBars.styles = stylesSubTablist;
1505
1662
  paneStyles.append(paneStylesSub1, paneStylesSub2, paneStylesSub3, paneStylesSub4);
@@ -1551,6 +1708,52 @@ export function openSettingsDialog() {
1551
1708
  // “行为 → ZCode CLI”:zcode-cli 运行时的行为配置(写 ~/.zcode/cli/config.json)+
1552
1709
  // 技能清单检查。开关与预算数字框改动即存,每次只提交自己那个键;
1553
1710
  // 目录列表显式保存
1711
+ // 工具名合规检查
1712
+ const toolNameState = h('p', { class: 'mt-2 text-ui-xs/relaxed text-foreground-subtle' });
1713
+ let toolNameBusy = false;
1714
+ const toolNameBtn = btnSmall(L.toolNameCheckBtn, () => { void runToolNameCheck(); }, 'shrink-0', 'primary');
1715
+ const runToolNameCheck = async () => {
1716
+ if (toolNameBusy) return;
1717
+ toolNameBusy = true;
1718
+ toolNameBtn.disabled = true;
1719
+ toolNameBtn.textContent = L.toolNameCheckRunning;
1720
+ toolNameState.textContent = '';
1721
+ toolNameState.className = 'mt-2 text-ui-xs/relaxed text-foreground-subtle';
1722
+ const res = await rpc('/tool-names/check', { method: 'POST', body: {} });
1723
+ toolNameBusy = false;
1724
+ toolNameBtn.disabled = false;
1725
+ toolNameBtn.textContent = L.toolNameCheckBtn;
1726
+ if (!res.ok) {
1727
+ toolNameState.className = 'mt-2 text-ui-xs/relaxed text-destructive';
1728
+ toolNameState.textContent = L.toolNameCheckFailed + ': ' + errText(res);
1729
+ return;
1730
+ }
1731
+ toolNameState.className = 'mt-2 text-ui-xs/relaxed ' + (res.warnings && res.warnings.length ? 'text-amber-500' : 'text-foreground-subtle');
1732
+ toolNameState.textContent = res.summary || '';
1733
+ };
1734
+ let toolNameAutoOn = config.toolNameAuto !== false;
1735
+ const toolNameAutoWrap = h('div', { class: 'ml-auto flex shrink-0 items-center gap-1.5' });
1736
+ const renderToolNameAuto = () => {
1737
+ const toggle = async () => {
1738
+ const next = !toolNameAutoOn;
1739
+ const res = await rpc('/config', { method: 'POST', body: { toolNameAuto: next } });
1740
+ if (!res.ok) { showToast(L.failed + ': ' + errText(res), 'error'); return; }
1741
+ toolNameAutoOn = (res.config && typeof res.config.toolNameAuto === 'boolean') ? res.config.toolNameAuto : next;
1742
+ renderToolNameAuto();
1743
+ };
1744
+ toolNameAutoWrap.replaceChildren(
1745
+ h('span', { class: 'text-ui-xs text-foreground-subtle', title: L.toolNameAutoDesc }, L.toolNameAuto),
1746
+ h('button', {
1747
+ type: 'button', role: 'switch', 'aria-checked': String(toolNameAutoOn),
1748
+ class: 'relative inline-flex shrink-0 cursor-pointer items-center',
1749
+ title: L.toolNameAutoDesc,
1750
+ onClick: () => { void toggle(); },
1751
+ }, h('span', { class: 'zcodepro-switch', 'data-zcodepro-switch': '', 'data-state': toolNameAutoOn ? 'on' : 'off' },
1752
+ h('span', { class: 'zcodepro-switch-knob' }))),
1753
+ );
1754
+ };
1755
+ renderToolNameAuto();
1756
+
1554
1757
  const paneZcode = h('div', { class: 'mt-2' });
1555
1758
  let snap = zcodeConfigRes;
1556
1759
  const setZcode = async (body) => {
@@ -1668,11 +1871,108 @@ export function openSettingsDialog() {
1668
1871
  h('div', { class: 'mt-0.5 text-ui-xs/relaxed text-foreground-subtle' }, L.zcodeSkillRootsDesc),
1669
1872
  h('div', { class: 'mt-2' }, rootsArea),
1670
1873
  h('div', { class: 'mt-2 flex justify-end' }, rootsSaveBtn)),
1874
+ h('div', { class: 'mt-2 rounded-xl border border-border p-3' },
1875
+ h('div', { class: 'text-ui-sm font-medium text-foreground' }, L.toolNameCheckTitle),
1876
+ h('p', { class: 'mt-1 text-ui-xs/relaxed text-foreground-subtle' }, L.toolNameCheckDesc),
1877
+ h('div', { class: 'mt-2 flex items-center gap-2' }, toolNameBtn, toolNameAutoWrap),
1878
+ toolNameState),
1671
1879
  );
1672
1880
  }
1673
1881
  // “行为”标签页:二级标签切换“ZCode / 全局提示词 / 任务名”。全局提示词编辑
1674
1882
  // ~/.zcode/AGENTS.md;任务名(智能起名)面板复用 paneTitleGen(原本是
1675
1883
  // 一级标签页,收进来后不再单独出现在顶部标签栏)
1884
+ // 提示词注入:与上面的 AGENTS.md 并排放在同一页,用户能直接看出两者的差别
1885
+ // (一个进对话层、一个进系统层)。正文只在点保存时提交;“也注入子代理”开关
1886
+ // 立即生效。长度不截断,超过 20000 字符只给一句提醒。
1887
+ const piCfg = (config && config.promptInjection) || { text: '', subagents: false };
1888
+ let piText = typeof piCfg.text === 'string' ? piCfg.text : '';
1889
+ let piSubagents = piCfg.subagents === true;
1890
+ // 卡片第一行的说明,后面跟着当前状态(已生效几家供应商)。只在打开弹窗时算一次,
1891
+ // 不做定时刷新
1892
+ const piChainHintText = h('span', { class: 'min-w-0 flex-1 text-ui-xs/relaxed text-foreground-subtle' }, L.injectChainHint);
1893
+ // 开关与卡片都用功能页同款样式,这里各自定义一份(主题页里的同名函数是局部作用域)
1894
+ const piSwitch = (checked) => h('button', {
1895
+ type: 'button', role: 'switch', 'aria-checked': String(checked),
1896
+ class: 'relative inline-flex shrink-0 cursor-pointer items-center',
1897
+ }, h('span', { class: 'zcodepro-switch', 'data-zcodepro-switch': '', 'data-state': checked ? 'on' : 'off' },
1898
+ h('span', { class: 'zcodepro-switch-knob' })));
1899
+ const piCard = (titleText, body) => h('div', { class: 'rounded-xl border border-border p-3' },
1900
+ h('div', { class: 'text-ui-sm font-medium text-foreground' }, titleText),
1901
+ body);
1902
+ const piCount = h('span', { class: 'text-ui-xs text-foreground-subtle' });
1903
+ const piLongHint = h('span', { class: 'text-ui-xs text-foreground-subtle' }, L.injectLongHint);
1904
+ const piArea = h('textarea', {
1905
+ class: 'zcodepro-textarea zcodepro-textarea-lg',
1906
+ placeholder: L.injectPlaceholder,
1907
+ spellcheck: 'false',
1908
+ });
1909
+ piArea.value = piText;
1910
+ const piSaveBtn = btnSmall(L.agentsSave, () => { void saveInjectionText(); }, '', 'primary');
1911
+ const renderPiMeta = () => {
1912
+ piCount.textContent = L.injectChars.replace('{n}', String(piArea.value.length));
1913
+ piLongHint.style.display = piArea.value.length > 20000 ? '' : 'none';
1914
+ piSaveBtn.disabled = piArea.value === piText;
1915
+ };
1916
+ piArea.addEventListener('input', renderPiMeta);
1917
+ renderPiMeta();
1918
+ // 状态:问一次 helper 当前有多少已启用供应商真的在走转发,接在第一行说明的后面。
1919
+ // 几种状态的说法各自带着句读,拼起来就是一句完整的话
1920
+ const refreshPiStatus = async () => {
1921
+ const st = await rpc('/prompt-injection/status');
1922
+ if (!st.ok) { piChainHintText.textContent = L.injectChainHint; return; }
1923
+ let extra;
1924
+ if (!st.providers) extra = L.injectChainNone;
1925
+ else extra = L.injectChainStatus.replace('{active}', String(st.active || 0)).replace('{providers}', String(st.providers));
1926
+ piChainHintText.textContent = L.injectChainHint + extra;
1927
+ };
1928
+ const saveInjection = async (patch) => {
1929
+ const res = await rpc('/config', { method: 'POST', body: { promptInjection: patch } });
1930
+ if (!res.ok) { showToast(L.failed + ': ' + errText(res), 'error'); return false; }
1931
+ clearConfigCache();
1932
+ if (res.config && res.config.promptInjection) {
1933
+ piText = typeof res.config.promptInjection.text === 'string' ? res.config.promptInjection.text : piText;
1934
+ piSubagents = res.config.promptInjection.subagents === true;
1935
+ }
1936
+ // 对齐转发器要一点时间(拉起新端口、改写供应商地址),稍等再看状态
1937
+ setTimeout(() => { void refreshPiStatus(); }, 1200);
1938
+ return true;
1939
+ };
1940
+ const saveInjectionText = async () => {
1941
+ piSaveBtn.disabled = true;
1942
+ if (await saveInjection({ text: piArea.value })) {
1943
+ piText = piArea.value;
1944
+ showToast(L.injectSaved, 'success');
1945
+ }
1946
+ renderPiMeta();
1947
+ };
1948
+ // “也注入子代理”开关行
1949
+ const piSubLabel = h('span', {}, L.injectSubagents);
1950
+ const piSubKnob = h('span', {}, piSwitch(piSubagents));
1951
+ const renderPiSub = () => piSubKnob.replaceChildren(piSwitch(piSubagents));
1952
+ const piSubRow = h('div', {
1953
+ class: 'mt-2 flex cursor-pointer items-center gap-2 text-ui-sm text-foreground-subtle',
1954
+ onClick: () => {
1955
+ piSubagents = !piSubagents;
1956
+ renderPiSub();
1957
+ void saveInjection({ subagents: piSubagents });
1958
+ },
1959
+ }, piSubLabel, piSubKnob);
1960
+ void refreshPiStatus();
1961
+ // 注入只对在“代理 → 代理链”里勾选的供应商生效:卡片第一行给一句说明和一个跳转按钮
1962
+ //(原来这一行是注入开关,开关已去掉,位置留给这句说明)。showProxySub 定义在本段
1963
+ // 之后,点击时才调用
1964
+ const piChainGo = btnSmall(L.injectGoChain, () => { showProxySub('vendor'); switchTab('proxy'); }, 'shrink-0');
1965
+ const injectBlock = piCard(L.injectTitle, h('div', { class: 'mt-1' },
1966
+ h('p', { class: 'text-ui-sm/relaxed text-foreground-subtle' }, L.injectDesc),
1967
+ h('div', { class: 'mt-2 flex items-center justify-between gap-2' },
1968
+ piChainHintText,
1969
+ piChainGo),
1970
+ h('div', { class: 'mt-3' }, piArea),
1971
+ h('div', { class: 'mt-2 flex items-center justify-between gap-2' },
1972
+ h('div', { class: 'flex items-center gap-2' }, piCount, piLongHint),
1973
+ piSaveBtn),
1974
+ piSubRow));
1975
+
1676
1976
  const agentsPromptPane = h('div', { class: 'mt-2' });
1677
1977
  agentsPromptPane.append(
1678
1978
  h('p', { class: 'text-ui-sm/relaxed text-foreground-subtle' }, L.agentsDesc),
@@ -1681,8 +1981,13 @@ export function openSettingsDialog() {
1681
1981
  : []),
1682
1982
  h('div', { class: 'mt-3' }, agentsArea),
1683
1983
  h('div', { class: 'mt-3 flex justify-end' }, agentsSaveBtn),
1984
+ h('div', { class: 'mt-5' }, injectBlock),
1684
1985
  );
1685
- let agentsSubTab = 'zcode';
1986
+ const AGENTS_SUBS = ['zcode', 'prompt', 'titleGen', 'autoContinue'];
1987
+ // 从外面直达行为页时(右下角卡片的“去自动重命名设置”“去运行时设置”)用指定的
1988
+ // 二级页签,与代理页的规则一致;否则用记住的
1989
+ const wantedAgentsSub = (initialTab === 'agents' && AGENTS_SUBS.includes(initialSub)) ? initialSub : savedSub('agents', '');
1990
+ let agentsSubTab = AGENTS_SUBS.includes(wantedAgentsSub) ? wantedAgentsSub : 'zcode';
1686
1991
  const agentsSubPanes = { zcode: paneZcode, prompt: agentsPromptPane, titleGen: paneTitleGen, autoContinue: paneAutoContinue };
1687
1992
  const agentsSubList = h('div', { role: 'tablist', 'aria-orientation': 'horizontal', class: 'zcodepro-tablist' });
1688
1993
  const renderAgentsSubTabs = () => {
@@ -1697,6 +2002,7 @@ export function openSettingsDialog() {
1697
2002
  'data-state': agentsSubTab === id ? 'active' : 'inactive',
1698
2003
  onClick: () => {
1699
2004
  agentsSubTab = id;
2005
+ rememberSub('agents', id);
1700
2006
  for (const [pid, pane] of Object.entries(agentsSubPanes)) pane.style.display = pid === id ? '' : 'none';
1701
2007
  renderAgentsSubTabs();
1702
2008
  },
@@ -1789,7 +2095,44 @@ export function openSettingsDialog() {
1789
2095
  );
1790
2096
  };
1791
2097
  renderProxyScopes();
1792
- paneProxy.append(
2098
+ // 两级 tab:软件代理(原有界面)/ 供应商代理(按供应商转发 + 工具名检查)
2099
+ const PROXY_SUBS = ['software', 'vendor'];
2100
+ // 从外面直达代理页时(比如右下角卡片的“去代理链”)用指定的二级页签,否则用记住的
2101
+ const wantedProxySub = (initialTab === 'proxy' && PROXY_SUBS.includes(initialSub)) ? initialSub : savedSub('proxy', '');
2102
+ let proxySubTab = PROXY_SUBS.includes(wantedProxySub) ? wantedProxySub : 'software';
2103
+ const proxySubTablist = h('div', { role: 'tablist', 'aria-orientation': 'horizontal', class: 'zcodepro-tablist' });
2104
+ // mt-2 与“行为”二级 tab 保持一致:内容面板与上方 tab 栏之间留出间距
2105
+ const paneProxySoftware = h('div', { class: 'mt-2' });
2106
+ const proxyChainPane = h('div', { class: 'mt-2' });
2107
+ const renderProxySubTabs = () => proxySubTablist.replaceChildren(...[
2108
+ ['software', L.proxySubSoftware],
2109
+ ['vendor', L.proxySubVendor],
2110
+ ].map(([id, label]) => h('button', {
2111
+ type: 'button', role: 'tab', class: 'zcodepro-tab',
2112
+ 'aria-selected': String(proxySubTab === id),
2113
+ 'data-state': proxySubTab === id ? 'active' : 'inactive',
2114
+ onClick: () => showProxySub(id),
2115
+ }, label)));
2116
+ // 切换代理页的二级页签。refreshChainStatus 定义在本段之后(const 有暂时性死区),
2117
+ // 只能在事件回调里调;提示词注入那边的“去代理链勾选”按钮也走这里
2118
+ const showProxySub = (id) => {
2119
+ if (!PROXY_SUBS.includes(id)) return;
2120
+ proxySubTab = id;
2121
+ rememberSub('proxy', id);
2122
+ paneProxySoftware.style.display = id === 'software' ? '' : 'none';
2123
+ proxyChainPane.style.display = id === 'vendor' ? '' : 'none';
2124
+ if (id === 'vendor') void refreshChainStatus();
2125
+ renderProxySubTabs();
2126
+ };
2127
+ renderProxySubTabs();
2128
+ subTabBars.proxy = proxySubTablist;
2129
+ paneProxy.append(proxySubTablist, paneProxySoftware, proxyChainPane);
2130
+ // 按记住的子页设置初始可见性。refreshChainStatus 定义在本段之后
2131
+ // (const 有暂时性死区),这里不能直接调;延到下一个微任务再触发
2132
+ paneProxySoftware.style.display = proxySubTab === 'software' ? '' : 'none';
2133
+ proxyChainPane.style.display = proxySubTab === 'vendor' ? '' : 'none';
2134
+ if (proxySubTab === 'vendor') queueMicrotask(() => { try { void refreshChainStatus(); } catch { /* ignore */ } });
2135
+ paneProxySoftware.append(
1793
2136
  h('p', { class: 'text-ui-sm/relaxed text-foreground-subtle' }, L.proxyDesc),
1794
2137
  h('div', { class: 'mt-3 flex items-center gap-2' },
1795
2138
  proxyInput,
@@ -1800,6 +2143,434 @@ export function openSettingsDialog() {
1800
2143
  h('div', { class: 'mt-3 divide-y divide-border rounded-xl border border-border' }, proxyScopeWrap),
1801
2144
  );
1802
2145
 
2146
+ // —— 代理链:链是独立实体,可关联多个供应商 ——
2147
+ // 每条链有自己的有序节点(headroom / 注入 / 自定义代理),顺序即执行顺序。
2148
+ // 关联到同一条链的供应商共用这份配置和一个转发器。
2149
+ // 只写 headroom.json 的 chainTarget,绝不改供应商 baseURL。
2150
+ let chainProviders = []; // ZCode 供应商列表(/title-gen/providers)
2151
+ let chainList = Array.isArray(config.proxyChains) ? JSON.parse(JSON.stringify(config.proxyChains)) : [];
2152
+ let chainShared = Array.isArray(config.sharedProxies) ? [...config.sharedProxies] : [];
2153
+ let chainLastRun = null;
2154
+ let chainHeadroomPort = 8787;
2155
+ let chainPorts = new Map(); // chainId → helper 实际分配的端口(新建的链配置里还没有 port)
2156
+ const chainStatusText = h('p', { class: 'mt-2 text-ui-xs/relaxed text-foreground-subtle' });
2157
+ const chainListWrap = h('div', { class: 'mt-3 flex flex-col gap-2' });
2158
+
2159
+ // —— 代理链总开关 ——
2160
+ // 默认关:升级装上代理链的老用户,供应商地址不被自动改动;想用链再打开
2161
+ //(升级时仍在用旧“逐家转发”的供应商会被转成链里的勾选,并自动打开)。
2162
+ // 关=一键还原:链配置原样保留,所有勾选供应商的地址还原为真实上游、停止转发。
2163
+ // 开=勾在链上的供应商地址按链入口对齐。保存立即触发对齐,稍后刷状态
2164
+ const chainMasterWrap = h('div', {});
2165
+ const renderChainMaster = () => {
2166
+ chainMasterWrap.replaceChildren(
2167
+ settingRow(L.chainMasterSwitch, L.chainMasterSwitchDesc, config.proxyChainEnabled === true, async () => {
2168
+ const next = config.proxyChainEnabled !== true;
2169
+ const res = await rpc('/config', { method: 'POST', body: { proxyChainEnabled: next } });
2170
+ if (res.ok && res.config) {
2171
+ config.proxyChainEnabled = res.config.proxyChainEnabled === true;
2172
+ clearConfigCache();
2173
+ } else {
2174
+ showToast(L.failed + ': ' + errText(res), 'error');
2175
+ }
2176
+ renderChainMaster();
2177
+ setTimeout(() => { void refreshChainStatus(); }, 1200);
2178
+ }),
2179
+ );
2180
+ };
2181
+ renderChainMaster();
2182
+
2183
+ // —— OpenCode Go 兼容(默认开)——
2184
+ // OpenCode Go 套餐的端点要求请求带会话请求头,ZCode 只在供应商地址正好是它的
2185
+ // 网址时才加;供应商走链(地址是本机 8787)时由 zcode-pro 的转发器补上。
2186
+ // 关掉后这类供应商经链会被端点拒绝,只能直连。改了下发到链转发器,立即生效
2187
+ const chainGoWrap = h('div', {});
2188
+ const renderChainGo = () => {
2189
+ chainGoWrap.replaceChildren(
2190
+ settingRow(L.chainGoCompat, L.chainGoCompatDesc, config.opencodeGoCompat !== false, async () => {
2191
+ const next = config.opencodeGoCompat === false;
2192
+ const res = await rpc('/config', { method: 'POST', body: { opencodeGoCompat: next } });
2193
+ if (res.ok && res.config) {
2194
+ config.opencodeGoCompat = res.config.opencodeGoCompat !== false;
2195
+ clearConfigCache();
2196
+ } else {
2197
+ showToast(L.failed + ': ' + errText(res), 'error');
2198
+ }
2199
+ renderChainGo();
2200
+ }),
2201
+ );
2202
+ };
2203
+ renderChainGo();
2204
+
2205
+ const fieldCls = 'h-7 rounded-lg border border-border bg-input px-2 text-ui-xs text-foreground outline-none transition-shadow placeholder:text-foreground-subtle focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40';
2206
+ const providerName = (id) => (chainProviders.find((x) => x.id === id) || {}).name || id;
2207
+ // 链的转发端口:以 helper 对齐结果为准(新建的链配置里还没有 port),其次配置值
2208
+ const chainPortOf = (c) => chainPorts.get(c.id) || c.port || null;
2209
+
2210
+ // 三段式代理编辑器(协议 + 地址 + 端口),共享代理与自定义节点共用
2211
+ const proxyFields = ({ url = '', onCommit }) => {
2212
+ const parsed = /^(https?):\/\/([^/:]+):(\d+)$/.exec(url || '');
2213
+ const protoSel = h('select', { class: fieldCls + ' shrink-0' },
2214
+ h('option', { value: 'http' }, 'http'),
2215
+ h('option', { value: 'https' }, 'https'));
2216
+ protoSel.value = parsed ? parsed[1] : 'http';
2217
+ const hostInput = h('input', {
2218
+ type: 'text', value: parsed ? parsed[2] : '', placeholder: '127.0.0.1',
2219
+ spellcheck: 'false', class: fieldCls + ' min-w-0 flex-1',
2220
+ });
2221
+ const portInput = h('input', {
2222
+ type: 'text', value: parsed ? parsed[3] : '', placeholder: '7890',
2223
+ spellcheck: 'false', class: fieldCls + ' w-16 shrink-0',
2224
+ });
2225
+ const commit = () => {
2226
+ const host = hostInput.value.trim();
2227
+ const portText = portInput.value.trim();
2228
+ if (!host && !portText) return;
2229
+ if (!host) { showToast(L.failed + ': ' + L.proxySharedInvalid, 'error'); return; }
2230
+ const portNum = portText === '' ? 7890 : Number(portText);
2231
+ if (portText !== '' && (!/^\d+$/.test(portText) || !Number.isInteger(portNum) || portNum < 1 || portNum > 65535)) {
2232
+ showToast(L.failed + ': ' + L.proxySharedInvalid, 'error');
2233
+ return;
2234
+ }
2235
+ onCommit(`${protoSel.value}://${host}:${portNum}`);
2236
+ };
2237
+ protoSel.addEventListener('change', commit);
2238
+ hostInput.addEventListener('change', commit);
2239
+ portInput.addEventListener('change', commit);
2240
+ return h('div', { class: 'flex min-w-0 flex-1 items-center gap-1' }, protoSel, hostInput, portInput);
2241
+ };
2242
+
2243
+ // —— 共享代理 ——
2244
+ const sharedWrap = h('div', { class: 'flex flex-col gap-1.5' });
2245
+ // 共享代理整表提交前先取服务端最新列表:弹窗长开时 chainShared 是打开
2246
+ // 那一刻的快照,直接拿它覆盖会把别处(另一窗口/同步拉取)的修改退回去。
2247
+ // mutate 在最新列表上算出目标列表,提交仍是整表(后端按全量校验)
2248
+ const saveShared = async (mutate) => {
2249
+ const cur = await rpc('/config');
2250
+ const fresh = (cur.ok && cur.config && Array.isArray(cur.config.sharedProxies))
2251
+ ? JSON.parse(JSON.stringify(cur.config.sharedProxies))
2252
+ : chainShared.map((e) => JSON.parse(JSON.stringify(e)));
2253
+ const list = mutate(fresh);
2254
+ const res = await rpc('/config', { method: 'POST', body: { sharedProxies: list } });
2255
+ if (!res.ok) { showToast(L.failed + ': ' + errText(res), 'error'); return false; }
2256
+ chainShared = Array.isArray(res.config && res.config.sharedProxies) ? res.config.sharedProxies : list;
2257
+ if (res.config && Array.isArray(res.config.proxyChains)) chainList = res.config.proxyChains;
2258
+ renderShared();
2259
+ renderChains();
2260
+ return true;
2261
+ };
2262
+ const renderShared = () => {
2263
+ const rows = chainShared.map((sp) => {
2264
+ const displayName = (sp.name && sp.name !== sp.url) ? sp.name : '';
2265
+ const nameInput = h('input', { type: 'text', value: displayName, placeholder: L.proxySharedName, spellcheck: 'false', class: fieldCls + ' w-24 shrink-0' });
2266
+ const fields = proxyFields({
2267
+ url: sp.url || '',
2268
+ onCommit: (url) => {
2269
+ const name = nameInput.value.trim();
2270
+ void saveShared((fresh) => fresh.map((e) => (e.id === sp.id ? { ...e, name: name || url, url } : e)));
2271
+ },
2272
+ });
2273
+ nameInput.addEventListener('change', () => {
2274
+ const name = nameInput.value.trim();
2275
+ if (name === displayName) return;
2276
+ void saveShared((fresh) => fresh.map((e) => (e.id === sp.id ? { ...e, name: name || e.url, url: e.url } : e)));
2277
+ });
2278
+ return h('div', { class: 'flex items-center gap-1.5' },
2279
+ nameInput, fields,
2280
+ btnSmall(L.proxySharedDelete, () => { void saveShared((fresh) => fresh.filter((e) => e.id !== sp.id)); }, 'shrink-0'));
2281
+ });
2282
+ sharedWrap.replaceChildren(
2283
+ ...rows,
2284
+ ...(chainShared.length ? [] : [h('p', { class: 'text-ui-xs/relaxed text-foreground-subtle' }, L.proxySharedEmpty)]),
2285
+ h('div', { class: 'flex justify-end' },
2286
+ btnSmall('+ ' + L.proxySharedAdd, () => {
2287
+ const id = `sp${Date.now().toString(36)}`;
2288
+ void saveShared((fresh) => [...fresh, { id, name: '', url: 'http://127.0.0.1:7890' }]);
2289
+ }, 'shrink-0')),
2290
+ );
2291
+ };
2292
+
2293
+ // —— 代理链 ——
2294
+ // 链整表提交前先取服务端最新列表(理由同 saveShared)。供应商勾选框
2295
+ // 的增删以最新列表里该链的 providers 为底,避免把对齐摘掉的已删供应商
2296
+ // 用旧快照写回去
2297
+ const saveChains = async (mutate) => {
2298
+ const cur = await rpc('/config');
2299
+ const fresh = (cur.ok && cur.config && Array.isArray(cur.config.proxyChains))
2300
+ ? JSON.parse(JSON.stringify(cur.config.proxyChains))
2301
+ : chainList.map((c) => JSON.parse(JSON.stringify(c)));
2302
+ const list = mutate(fresh);
2303
+ // 取消勾选即退出压缩:对被移出链的供应商删 headroom 登记并还原 baseUrl
2304
+ //(勾回来时对齐的自动登记会补上,跨链移动=先退再进,中间窗口无害)
2305
+ const removed = [];
2306
+ for (const before of fresh) {
2307
+ const after = list.find((c) => c.id === before.id);
2308
+ if (!after) {
2309
+ // 整条链被删:它勾着的供应商全部退出(删链=退出压缩,与取消勾选同语义)
2310
+ for (const pid of before.providers || []) {
2311
+ if (!removed.includes(pid)) removed.push(pid);
2312
+ }
2313
+ continue;
2314
+ }
2315
+ for (const pid of before.providers || []) {
2316
+ if (!(after.providers || []).includes(pid) && !removed.includes(pid)) removed.push(pid);
2317
+ }
2318
+ }
2319
+ const res = await rpc('/config', { method: 'POST', body: { proxyChains: list } });
2320
+ if (!res.ok) { showToast(L.failed + ': ' + errText(res), 'error'); return false; }
2321
+ chainList = Array.isArray(res.config && res.config.proxyChains) ? res.config.proxyChains : list;
2322
+ if (removed.length) {
2323
+ void rpc('/headroom/restore', { method: 'POST', body: { ids: removed } }).then((r) => {
2324
+ if (!r.ok) showToast(L.chainLeaveHint + ': ' + errText(r), 'warning');
2325
+ });
2326
+ }
2327
+ renderChains();
2328
+ setTimeout(() => { void refreshChainStatus(); }, 1200);
2329
+ return true;
2330
+ };
2331
+ const updateChain = (id, patch) => saveChains((fresh) => fresh.map((c) => (c.id === id ? { ...c, ...patch } : c)));
2332
+ // 删链先确认:一点就删、而且链上勾选的供应商会全部还原成直连并退出 headroom,
2333
+ // 误触的代价太大(出过一次:叠着的两个弹窗里,点击落到了底下那个的删除按钮上)。
2334
+ // 用贴着按钮的确认小弹窗(confirmTip),不另开全局对话框
2335
+ const confirmDeleteChain = (c, anchor) => {
2336
+ const n = (c.providers || []).length;
2337
+ confirmTip(anchor, {
2338
+ title: L.chainDeleteConfirmTitle,
2339
+ desc: n > 0 ? L.chainDeleteConfirmDesc.replace('{n}', String(n)) : L.chainDeleteConfirmDescEmpty,
2340
+ confirmLabel: L.chainDeleteConfirmGo,
2341
+ onConfirm: () => { void saveChains((fresh) => fresh.filter((x) => x.id !== c.id)); },
2342
+ });
2343
+ };
2344
+
2345
+ const renderChains = () => {
2346
+ if (!chainList.length) {
2347
+ chainListWrap.replaceChildren(h('p', { class: 'rounded-xl border border-border px-3 py-3 text-ui-sm text-foreground-subtle' }, L.chainEmpty));
2348
+ return;
2349
+ }
2350
+ chainListWrap.replaceChildren(...chainList.map((c) => {
2351
+ const nodes = Array.isArray(c.nodes) ? c.nodes : [];
2352
+ const chainRows = [];
2353
+
2354
+ const rowEl = (index, label, right, opts = {}) => h('div', {
2355
+ class: 'flex items-center gap-2 rounded-lg px-2 py-0.5 ' + (opts.muted ? 'opacity-50' : ''),
2356
+ },
2357
+ h('span', { class: 'w-4 shrink-0 text-ui-xs text-foreground-subtle' }, String(index)),
2358
+ h('span', { class: 'w-24 shrink-0 text-ui-xs text-foreground-subtle' }, label),
2359
+ h('div', { class: 'min-w-0 flex-1' }, right),
2360
+ ...(opts.actions || []));
2361
+
2362
+ // 锁定图标:lucide 描边(与翻译面板一致),不用 emoji
2363
+ const lockIcon = () => {
2364
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2365
+ svg.setAttribute('viewBox', '0 0 24 24');
2366
+ svg.setAttribute('fill', 'none');
2367
+ svg.setAttribute('stroke', 'currentColor');
2368
+ svg.setAttribute('stroke-width', '2');
2369
+ svg.setAttribute('stroke-linecap', 'round');
2370
+ svg.setAttribute('stroke-linejoin', 'round');
2371
+ svg.setAttribute('width', '12');
2372
+ svg.setAttribute('height', '12');
2373
+ svg.setAttribute('aria-hidden', 'true');
2374
+ svg.innerHTML = '<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>';
2375
+ return svg;
2376
+ };
2377
+ const pinned = () => h('span', { class: 'inline-flex shrink-0 items-center opacity-40', title: L.chainNodePinned }, lockIcon());
2378
+
2379
+ nodes.forEach((n, i) => {
2380
+ const move = async (delta) => {
2381
+ const j = i + delta;
2382
+ if (j < 0 || j >= nodes.length) return;
2383
+ const list = nodes.slice();
2384
+ [list[i], list[j]] = [list[j], list[i]];
2385
+ await updateChain(c.id, { nodes: list });
2386
+ };
2387
+ const actions = [
2388
+ btnSmall('↑', () => { void move(-1); }, 'shrink-0' + (i === 0 ? ' opacity-30' : '')),
2389
+ btnSmall('↓', () => { void move(1); }, 'shrink-0' + (i === nodes.length - 1 ? ' opacity-30' : '')),
2390
+ btnSmall(L.proxyVendorRemove, () => {
2391
+ void updateChain(c.id, { nodes: nodes.filter((_, k) => k !== i) });
2392
+ }, 'shrink-0'),
2393
+ ];
2394
+ if (n.type === 'headroom') {
2395
+ chainRows.push(rowEl(chainRows.length + 1, 'headroom',
2396
+ h('span', { class: 'text-ui-xs text-foreground-subtle' }, `127.0.0.1:${chainHeadroomPort}`),
2397
+ { actions }));
2398
+ return;
2399
+ }
2400
+ if (n.type === 'inject') {
2401
+ // 注入功能没有启停开关(在链里勾选就是唯一开关),这一行不再显示启停状态
2402
+ chainRows.push(rowEl(chainRows.length + 1, L.proxyChainInjection, null, { actions }));
2403
+ return;
2404
+ }
2405
+ // 自定义代理节点
2406
+ const hit = n.proxyId ? chainShared.find((e) => e.id === n.proxyId) : null;
2407
+ const sel = h('select', { class: fieldCls + ' w-28 shrink-0' },
2408
+ h('option', { value: '' }, L.proxyChainCustom),
2409
+ ...chainShared.map((sp) => h('option', { value: 'sp:' + sp.id }, sp.name || sp.url)));
2410
+ sel.value = n.proxyId ? 'sp:' + n.proxyId : '';
2411
+ const sharedView = h('span', {
2412
+ class: 'min-w-0 flex-1 truncate text-ui-xs text-foreground-subtle',
2413
+ title: hit ? hit.url : '',
2414
+ }, hit ? hit.url : (n.proxyId ? L.proxyChainSharedGone : ''));
2415
+ const fields = proxyFields({
2416
+ url: n.proxyId ? '' : (n.proxy || ''),
2417
+ onCommit: (v) => {
2418
+ const list = nodes.slice();
2419
+ list[i] = { type: 'custom', proxy: v };
2420
+ void updateChain(c.id, { nodes: list });
2421
+ },
2422
+ });
2423
+ fields.style.display = n.proxyId ? 'none' : '';
2424
+ sharedView.style.display = n.proxyId ? '' : 'none';
2425
+ sel.addEventListener('change', () => {
2426
+ const list = nodes.slice();
2427
+ list[i] = sel.value ? { type: 'custom', proxyId: sel.value.slice(3) } : { type: 'custom', proxy: '' };
2428
+ void updateChain(c.id, { nodes: list });
2429
+ });
2430
+ // 不显示「自定义」文本:把来源下拉放在原来 label 的位置
2431
+ chainRows.push(h('div', { class: 'flex items-center gap-2 rounded-lg px-2 py-0.5' },
2432
+ h('span', { class: 'w-4 shrink-0 text-ui-xs text-foreground-subtle' }, String(chainRows.length + 1)),
2433
+ sel,
2434
+ h('div', { class: 'flex min-w-0 flex-1 items-center gap-1.5' }, sharedView, fields),
2435
+ ...actions));
2436
+ });
2437
+
2438
+ // 关联的供应商:多选,勾上即归属这条链
2439
+ const owner = new Map();
2440
+ for (const other of chainList) {
2441
+ for (const pid of other.providers || []) owner.set(pid, other.id);
2442
+ }
2443
+ // ZCode 自带的套餐供应商(id 以 builtin: 开头,比如 Start Plan、Coding Plan)不在
2444
+ // 可勾选列表里:链只改 provider_config.json 里有条目的供应商的地址,自带的没有条目,
2445
+ // 勾上也不会走链。已经在某条链里的照常显示,用户能看到并取消
2446
+ const selectableProviders = chainProviders.filter((p) => !String(p.id || '').startsWith('builtin:') || (c.providers || []).includes(p.id));
2447
+ const provBox = h('div', { class: 'mt-1 flex flex-wrap gap-x-3 gap-y-1' },
2448
+ ...selectableProviders.map((p) => {
2449
+ const ownedByOther = owner.has(p.id) && owner.get(p.id) !== c.id;
2450
+ const box = h('input', {
2451
+ type: 'checkbox',
2452
+ ...(ownedByOther ? { disabled: 'true', title: L.chainOwnedByOther } : {}),
2453
+ });
2454
+ box.checked = (c.providers || []).includes(p.id);
2455
+ box.addEventListener('change', () => {
2456
+ void saveChains((fresh) => fresh.map((ch) => {
2457
+ if (ch.id !== c.id) return ch;
2458
+ const cur = new Set(ch.providers || []);
2459
+ if (box.checked) cur.add(p.id); else cur.delete(p.id);
2460
+ return { ...ch, providers: [...cur] };
2461
+ }));
2462
+ });
2463
+ return h('label', { class: 'flex items-center gap-1 text-ui-xs' + (ownedByOther ? ' opacity-40' : '') },
2464
+ box, h('span', {}, p.name || p.id));
2465
+ }),
2466
+ ...(selectableProviders.length ? [] : [h('span', { class: 'text-ui-xs text-foreground-subtle' }, L.chainNoProviders)]));
2467
+
2468
+ const head = h('div', { class: 'flex items-center gap-2' },
2469
+ h('input', {
2470
+ type: 'text', value: c.name || c.id, spellcheck: 'false',
2471
+ class: 'min-w-0 flex-1 rounded-lg border border-border bg-input px-2 py-1 text-ui-sm font-medium text-foreground outline-none',
2472
+ }).also?.() || h('input', {
2473
+ type: 'text', value: c.name || c.id, spellcheck: 'false',
2474
+ class: 'min-w-0 flex-1 rounded-lg border border-border bg-input px-2 py-1 text-ui-sm font-medium text-foreground outline-none',
2475
+ onChange: (e) => { void updateChain(c.id, { name: e.target.value.trim() || c.id }); },
2476
+ }),
2477
+ h('button', {
2478
+ type: 'button', role: 'switch', 'aria-checked': String(c.enabled !== false),
2479
+ title: L.chainSwitchHint,
2480
+ class: 'relative inline-flex shrink-0 cursor-pointer items-center',
2481
+ onClick: () => { void updateChain(c.id, { enabled: c.enabled === false }); },
2482
+ }, h('span', { class: 'zcodepro-switch', 'data-zcodepro-switch': '', 'data-state': c.enabled !== false ? 'on' : 'off' },
2483
+ h('span', { class: 'zcodepro-switch-knob' }))),
2484
+ btnSmall(L.proxyVendorRemove, (e) => { confirmDeleteChain(c, e.currentTarget); }, 'shrink-0'),
2485
+ );
2486
+
2487
+ const addNode = (type) => {
2488
+ const list = nodes.slice();
2489
+ list.push(type === 'custom' ? { type: 'custom', proxy: '' } : { type });
2490
+ void updateChain(c.id, { nodes: list });
2491
+ };
2492
+ const addRow = h('div', { class: 'mt-1 flex flex-wrap items-center justify-end gap-1.5' },
2493
+ ...(nodes.some((n) => n.type === 'headroom') ? [] : [btnSmall('+ headroom', () => addNode('headroom'), 'shrink-0')]),
2494
+ ...(nodes.some((n) => n.type === 'inject') ? [] : [btnSmall('+ ' + L.proxyChainInjection, () => addNode('inject'), 'shrink-0')]),
2495
+ btnSmall('+ ' + L.proxyChainAddNode, () => addNode('custom'), 'shrink-0'));
2496
+
2497
+ return h('div', { class: 'rounded-xl border border-border px-2.5 py-2' },
2498
+ head,
2499
+ h('div', { class: 'mt-1 flex flex-col' }, ...chainRows),
2500
+ addRow,
2501
+ h('div', { class: 'mt-2 border-t border-border pt-1.5' },
2502
+ h('div', { class: 'text-ui-xs text-foreground-subtle' }, L.chainProvidersLabel),
2503
+ provBox),
2504
+ h('div', { class: 'mt-1 text-ui-xs text-foreground-subtle' },
2505
+ `${L.chainForwardPort} ${chainPortOf(c) || '—'}`),
2506
+ );
2507
+ }));
2508
+ };
2509
+
2510
+ const refreshChainStatus = async () => {
2511
+ const res = await rpc('/provider-proxies/status');
2512
+ if (!res.ok) return;
2513
+ chainLastRun = res.chainLastRun || null;
2514
+ // 链列表以服务端为准:对齐可能改了它(比如供应商地址被手动改过,自动退出了链)
2515
+ const cfgRes = await rpc('/config');
2516
+ if (cfgRes.ok && cfgRes.config && Array.isArray(cfgRes.config.proxyChains)) chainList = cfgRes.config.proxyChains;
2517
+ if (Number.isFinite(Number(res.headroomPort))) chainHeadroomPort = Number(res.headroomPort);
2518
+ // 端口以对齐结果为准:新建的链配置里没有 port,helper 拉起转发器后才分配
2519
+ chainPorts = new Map();
2520
+ for (const s of (chainLastRun && chainLastRun.started) || []) {
2521
+ if (s && s.id && Number.isFinite(Number(s.port))) chainPorts.set(s.id, Number(s.port));
2522
+ }
2523
+ renderChains();
2524
+ const errs = (chainLastRun && chainLastRun.errors) || [];
2525
+ chainStatusText.className = 'mt-2 text-ui-xs/relaxed ' + (errs.length ? 'text-amber-500' : 'text-foreground-subtle');
2526
+ // 总开关关闭时链全部不生效,优先提示这个(比对齐报错更可能是用户想找的答案)
2527
+ const auto = (chainLastRun && chainLastRun.autoUnchecked) || [];
2528
+ const autoText = auto.length
2529
+ ? L.chainAutoUnchecked.replace('{list}', auto.map((a) => `${providerName(a.id)} → ${a.url}`).join(';'))
2530
+ : '';
2531
+ chainStatusText.textContent = errs.length ? errs.join(';')
2532
+ : (config.proxyChainEnabled !== true ? L.chainMasterOffHint : autoText);
2533
+ };
2534
+
2535
+
2536
+ proxyChainPane.append(
2537
+ // 说明放最上面(二级页签正下方):链怎么工作 + 勾选的规则都在这一块,全页只写一次
2538
+ //(以前这两行规则挂在每条链下,几条链就重复几遍)
2539
+ h('p', { class: 'mt-2 text-ui-sm/relaxed text-foreground-subtle' }, L.chainDesc),
2540
+ h('div', { class: 'mt-1 text-ui-xs/relaxed text-foreground-subtle' }, L.chainProvidersHint),
2541
+ h('div', { class: 'text-ui-xs/relaxed text-foreground-subtle' }, L.chainManualEditHint),
2542
+ h('div', { class: 'mt-3 rounded-xl border border-border p-1' }, chainMasterWrap),
2543
+ h('div', { class: 'mt-2 rounded-xl border border-border p-1' }, chainGoWrap),
2544
+ h('div', { class: 'mt-3 rounded-xl border border-border p-3' },
2545
+ h('div', { class: 'text-ui-sm font-medium text-foreground' }, L.proxySharedTitle),
2546
+ h('p', { class: 'mt-1 text-ui-xs/relaxed text-foreground-subtle' }, L.proxySharedDesc),
2547
+ h('div', { class: 'mt-2' }, sharedWrap)),
2548
+ chainListWrap,
2549
+ h('div', { class: 'mt-2 flex justify-end' },
2550
+ btnSmall('+ ' + L.chainAdd, () => {
2551
+ const id = `chain${Date.now().toString(36)}`;
2552
+ // 没装 headroom 插件时默认模板不带 headroom 节点——带了整条链会被跳过,
2553
+ // 新建出来就是哑的;装了插件(或读不到安装状态)才按 压缩 + 注入 起步
2554
+ void (async () => {
2555
+ let nodes = [{ type: 'headroom' }, { type: 'inject' }];
2556
+ try {
2557
+ const meta = await rpc('/headroom');
2558
+ if (meta && meta.ok && !meta.hook) nodes = [{ type: 'inject' }];
2559
+ } catch { /* 读不到按带 headroom 的模板,节点可以随时增删 */ }
2560
+ void saveChains((fresh) => [...fresh, { id, name: L.chainDefaultName, providers: [], nodes, enabled: true }]);
2561
+ })();
2562
+ }, 'shrink-0', 'primary')),
2563
+ chainStatusText,
2564
+ );
2565
+ renderShared();
2566
+ renderChains();
2567
+ void (async () => {
2568
+ const provRes = await rpc('/title-gen/providers');
2569
+ if (provRes.ok && Array.isArray(provRes.providers)) chainProviders = provRes.providers;
2570
+ renderChains();
2571
+ })();
2572
+ void refreshChainStatus();
2573
+
1803
2574
  // “性能”:空闲项目内存回收(开关 + 两个时长)与子代理活动判定时长。
1804
2575
  // idleReclaimStartupMinutes 允许 0(启动后立即回收一次),取值不能用
1805
2576
  // “|| 默认值”的写法回退
@@ -2478,39 +3249,38 @@ export function openSettingsDialog() {
2478
3249
  }, i === visionCfg.proxies.length - 1 ? 'pointer-events-none opacity-40' : ''),
2479
3250
  smallBtn(L.visionRemove, () => { visionCfg.proxies.splice(i, 1); void persistVision(); renderVision(); }),
2480
3251
  ),
2481
- h('div', { class: 'mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2' },
2482
- // 供应商与模型走 provider-fields 共用逻辑:跟随会话时模型下拉为
2483
- // 全部供应商模型汇总,具体供应商为其模型列表;已删 id 标注“已删除”
2484
- field(L.visionUseProvider, comboField(p.useProvider || '',
2485
- providerOptionsOf(titleGenProviders, L),
2486
- (v, src) => {
2487
- p.useProvider = v;
3252
+ (() => {
3253
+ // 供应商 + 模型 + 思考级别走统一封装(与翻译页、自动重命名同一实现)
3254
+ const pmt = providerModelThinkingFields({
3255
+ providers: titleGenProviders,
3256
+ L,
3257
+ provider: p.useProvider || '',
3258
+ model: p.model || '',
3259
+ thinking: p.thinking || 'off',
3260
+ sessionInfo: translateSessionRes.ok ? translateSessionRes.session : null,
3261
+ withManual: true,
3262
+ labels: { provider: L.visionUseProvider, model: L.visionModel, thinking: L.translateThinking },
3263
+ onChange: (patch) => {
3264
+ p.useProvider = patch.provider;
3265
+ p.model = patch.model;
3266
+ p.thinking = patch.thinking;
2488
3267
  saveVisionSoon();
2489
- // 下拉切换后重渲染整个面板:模型下拉选项随新供应商变化,接口
2490
- // 地址/API Key 字段按“不跟随或供应商已删才显示”重新显隐
2491
- if (src === 'select') renderVision();
2492
3268
  },
2493
- { placeholder: L.titleGenProviderSession, staleLabel: L.titleGenProviderDeleted })),
2494
- // 跟随会话时模型下拉头部有“跟随当前会话当前模型”(值为空,
2495
- // 插件 ≥1.6.1 在调用时解析为会话当前模型);具体供应商为其模型列表
2496
- field(L.visionModel, comboField(p.model || '',
2497
- modelOptionsOf(p.useProvider, titleGenProviders, {
2498
- followSession: (p.useProvider || '').trim() === 'session',
2499
- followSessionLabel: L.titleGenModelFollowSession,
2500
- }),
2501
- (v) => { p.model = v; saveVisionSoon(); },
2502
- {
2503
- placeholder: modelPlaceholderOf(p.useProvider, L),
2504
- emptyLabel: (p.useProvider || '').trim() === 'session'
2505
- ? L.titleGenModelFollowSession : L.titleGenModelEmpty,
2506
- })),
2507
- ),
3269
+ requestRender: () => renderVision(),
3270
+ });
3271
+ // 三件套一行显示(与自动重命名页一致):窄屏单列、sm 以上三列
3272
+ return h('div', { class: 'mt-2 grid grid-cols-1 gap-2 sm:grid-cols-3' }, ...pmt.fields);
3273
+ })(),
2508
3274
  ...manualConnCard,
2509
3275
  (() => {
2510
3276
  const n = h('textarea', { class: 'zcodepro-textarea zcodepro-textarea-sm', rows: '3', placeholder: L.visionPrompt });
2511
3277
  n.value = p.prompt || '';
2512
3278
  n.addEventListener('input', () => { p.prompt = n.value; saveVisionSoon(); });
2513
- return field(L.visionPrompt, n);
3279
+ // 上间距:与上方三件套/手动连接卡之间留出空隙(原来紧贴)。
3280
+ // 加在外层 label 上而不是 textarea,保证标签文字也跟着下移
3281
+ const f = field(L.visionPrompt, n);
3282
+ f.classList.add('mt-2');
3283
+ return f;
2514
3284
  })(),
2515
3285
  ]);
2516
3286
  });
@@ -2604,6 +3374,195 @@ export function openSettingsDialog() {
2604
3374
  visionTestPre,
2605
3375
  );
2606
3376
  };
3377
+
3378
+ // “翻译”标签页:触发方式、目标语言、面板尺寸、历史与机翻密钥。
3379
+ // 通道与提示词的快捷切换在翻译面板上完成(写的是同一个配置文件),
3380
+ // 这里放整块设置;嵌套键(panel/history 等)提交完整对象,防止合并写
3381
+ // 顶层替换时丢掉同组的其余键
3382
+ const TR_INPUT_CLS = 'h-7 w-full rounded-lg border border-border bg-input px-2 text-ui-xs text-foreground outline-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40';
3383
+ const TR_MT_FIELDS = {
3384
+ youdao: [['appKey', 'App Key'], ['key', 'Secret']],
3385
+ baidu: [['appId', 'App ID'], ['secret', 'Secret']],
3386
+ caiyun: [['token', 'Token']],
3387
+ deepl: [['authKey', 'Auth Key']],
3388
+ deeplx: [['apiUrl', 'API URL'], ['token', 'Token']],
3389
+ niu: [['apiKey', 'API Key']],
3390
+ tencent: [['secretId', 'Secret ID'], ['secretKey', 'Secret Key']],
3391
+ aliyun: [['accessKeyId', 'Access Key ID'], ['accessKeySecret', 'Access Key Secret']],
3392
+ volc: [['accessKeyId', 'Access Key ID'], ['secretAccessKey', 'Secret Access Key']],
3393
+ };
3394
+ const TR_MT_IDS = Object.keys(TR_MT_FIELDS);
3395
+ // 各家获取密钥的官方入口:来源是沙拉查词(crimx/ext-saladict)各机翻
3396
+ // 组件 auth.ts 的 url 字段;两处例外——腾讯的是带返利参数的推广短链,
3397
+ // 换成机器翻译控制台直达;有道的旧网关地址会跳到新版控制台,直接用域名根
3398
+ const TR_MT_URLS = {
3399
+ youdao: 'https://ai.youdao.com/',
3400
+ baidu: 'https://api.fanyi.baidu.com/api/trans/product/prodinfo',
3401
+ caiyun: 'https://fanyi.caiyunapp.com/#/api',
3402
+ deepl: 'https://www.deepl.com/pro-api',
3403
+ deeplx: 'https://github.com/OwO-Network/DeepLX',
3404
+ niu: 'https://niutrans.com/documents/contents/trans_detection',
3405
+ tencent: 'https://console.cloud.tencent.com/tmt',
3406
+ aliyun: 'https://help.aliyun.com/zh/machine-translation/developer-reference/api-alimt-2018-10-12-overview',
3407
+ volc: 'https://www.volcengine.com/docs/4640/65067',
3408
+ };
3409
+ const trSvcStatus = translateProvidersRes.ok && Array.isArray(translateProvidersRes.services) ? translateProvidersRes.services : [];
3410
+ const renderTranslate = () => {
3411
+ const field = (labelText, node) => h('label', { class: 'block min-w-0' },
3412
+ h('span', { class: 'mb-1 block text-ui-xs font-medium text-foreground-subtle' }, labelText), node);
3413
+ if (!translateRes.ok) {
3414
+ paneTranslate.replaceChildren(
3415
+ h('p', { class: 'text-ui-sm/relaxed text-foreground-subtle' }, L.translateDesc),
3416
+ h('p', { class: 'mt-2 text-ui-sm text-destructive' }, L.failed + ': ' + errText(translateRes)));
3417
+ return;
3418
+ }
3419
+ const tr = translateRes.config || {};
3420
+ let saveTimer = null;
3421
+ let pendingCfg = {};
3422
+ const persist = (partial) => {
3423
+ // 防抖期间的多次改动合并提交,且嵌套键展开成完整对象后再并入
3424
+ Object.assign(pendingCfg, partial);
3425
+ clearTimeout(saveTimer);
3426
+ saveTimer = setTimeout(async () => {
3427
+ const body = pendingCfg;
3428
+ pendingCfg = {};
3429
+ const res = await rpc('/translate', { method: 'POST', body: { config: body } });
3430
+ if (res.ok && res.config) {
3431
+ translateRes.config = res.config;
3432
+ showToast(L.translateSaved, 'success');
3433
+ // 通知翻译面板立即按新配置刷新
3434
+ window.dispatchEvent(new CustomEvent('zcodepro:config-changed'));
3435
+ } else {
3436
+ showToast(L.failed + ': ' + errText(res), 'error');
3437
+ }
3438
+ }, 400);
3439
+ };
3440
+ // title 可选:下拉的悬停说明(如“该模型不支持思考”)
3441
+ const selIn = (value, options, onPick, title = '') => {
3442
+ const n = h('select', {
3443
+ class: 'h-7 w-40 rounded-lg border border-border bg-input px-2 text-ui-xs text-foreground outline-none',
3444
+ ...(title ? { title, disabled: true } : {}),
3445
+ });
3446
+ for (const [v, label] of options) {
3447
+ const o = h('option', { value: v }, label);
3448
+ if (v === value) o.selected = true;
3449
+ n.append(o);
3450
+ }
3451
+ n.addEventListener('change', () => onPick(n.value));
3452
+ return n;
3453
+ };
3454
+ const numIn = (value, dflt, min, max, onCommit) => {
3455
+ const n = h('input', { type: 'number', min: String(min), max: String(max), class: TR_INPUT_CLS, style: 'width:7rem' });
3456
+ n.value = String(Number.isFinite(value) ? value : dflt);
3457
+ n.addEventListener('change', () => onCommit(Math.max(min, Math.min(max, Math.round(Number(n.value) || dflt)))));
3458
+ return n;
3459
+ };
3460
+ const testBtn = btnSmall(L.translateTest, async () => {
3461
+ const ch = (translateRes.config && translateRes.config.channel) || {};
3462
+ const res = await rpc('/translate/test', { method: 'POST', body: { channel: ch } });
3463
+ if (res.ok) showToast(res.output || '✓', 'success');
3464
+ else showToast(L.failed + ': ' + errText(res), 'error');
3465
+ });
3466
+ const panel0 = tr.panel || {};
3467
+ const history0 = tr.history || {};
3468
+ // 默认通道(LLM):供应商与模型照视觉代理页的接法(下拉+手输),
3469
+ // 但不含“不跟随(自填地址)”——翻译通道只认 会话/供应商 两种来源
3470
+ const chNow = () => (translateRes.config && translateRes.config.channel) || {};
3471
+ // 供应商 + 模型 + 思考级别在三处共用同一封装(见 provider-model-thinking.js)
3472
+
3473
+ // 通用设置放最前(一行三个);翻译服务 = AI 翻译或某家机翻,选哪个
3474
+ // 出现哪组选项(AI:供应商/模型/思考等级;机翻:该服务的密钥)
3475
+ const ch0 = chNow();
3476
+ const isLlm = ch0.type !== 'mt';
3477
+ const setChannel = (patch) => {
3478
+ const merged = { ...chNow(), ...patch };
3479
+ // 保存前把档位自适应映射到该通道支持的档位
3480
+ if (merged.type !== 'mt') {
3481
+ const opts = resolveThinkingOptions(titleGenProviders, merged, translateSessionRes.ok ? translateSessionRes.session : null);
3482
+ merged.thinking = opts.current;
3483
+ }
3484
+ translateRes.config = { ...translateRes.config, channel: merged };
3485
+ persist({ channel: merged });
3486
+ renderTranslate();
3487
+ };
3488
+ const mtServiceName = (id) => L['translateMt' + id.charAt(0).toUpperCase() + id.slice(1)] || id;
3489
+ const mtSvc = ch0.service && TR_MT_FIELDS[ch0.service] ? ch0.service : 'deepl';
3490
+ const serviceSel = selIn(isLlm ? 'llm' : mtSvc, [
3491
+ ['llm', L.translateEngineLlm],
3492
+ ...TR_MT_IDS.map((id) => {
3493
+ const s2 = trSvcStatus.find((s) => s.id === id);
3494
+ return [id, mtServiceName(id) + (s2 && !s2.configured ? '(' + L.translateUnconfigured + ')' : '')];
3495
+ }),
3496
+ ], (v) => { if (v === 'llm') setChannel({ type: 'llm' }); else setChannel({ type: 'mt', service: v }); });
3497
+ // 三件套:供应商 / 模型 / 思考级别(统一封装,档位随模型自适应)
3498
+ const translatePmt = providerModelThinkingFields({
3499
+ providers: titleGenProviders,
3500
+ L,
3501
+ provider: ch0.provider || 'session',
3502
+ model: ch0.model || '',
3503
+ thinking: ch0.thinking || 'off',
3504
+ sessionInfo: translateSessionRes.ok ? translateSessionRes.session : null,
3505
+ // 翻译通道不提供“不跟随(自填地址)”:只认 会话/供应商 两种来源
3506
+ withManual: false,
3507
+ labels: { provider: L.translateProvider, model: L.translateModelLabel, thinking: L.translateThinking },
3508
+ onChange: (patch) => {
3509
+ const merged = { ...chNow(), type: 'llm', ...patch };
3510
+ translateRes.config = { ...translateRes.config, channel: merged };
3511
+ persist({ channel: merged });
3512
+ },
3513
+ requestRender: () => renderTranslate(),
3514
+ });
3515
+ const engineArea = isLlm
3516
+ ? h('div', { class: 'mt-2 grid grid-cols-1 gap-3 sm:grid-cols-3' },
3517
+ ...translatePmt.fields)
3518
+ : (() => {
3519
+ const mtCur = (tr.mt && tr.mt.services && tr.mt.services[mtSvc]) || {};
3520
+ return h('div', { class: 'mt-2 flex flex-wrap gap-2' },
3521
+ ...TR_MT_FIELDS[mtSvc].map(([k, label]) => {
3522
+ const inp = h('input', { type: 'text', value: mtCur[k] || '', placeholder: label, class: TR_INPUT_CLS, style: 'width:12rem' });
3523
+ inp.addEventListener('change', () => {
3524
+ mtCur[k] = inp.value.trim();
3525
+ persist({ mt: { services: { ...((tr.mt && tr.mt.services) || {}), [mtSvc]: { ...mtCur } } } });
3526
+ });
3527
+ return inp;
3528
+ }));
3529
+ })();
3530
+ paneTranslate.replaceChildren(
3531
+ h('div', { class: 'flex flex-wrap items-center justify-between gap-2' },
3532
+ h('p', { class: 'min-w-0 flex-1 text-ui-sm/relaxed text-foreground-subtle' }, L.translateDesc),
3533
+ testBtn),
3534
+ h('div', { class: 'mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3' },
3535
+ field(L.translateTrigger, selIn((tr.trigger && tr.trigger.mode) || 'ctrl-drag', [
3536
+ ['ctrl-drag', L.translateTriggerCtrlDrag],
3537
+ ['ctrl-tap', L.translateTriggerCtrlTap],
3538
+ ['alt-drag', L.translateTriggerAltDrag],
3539
+ ], (v) => persist({ trigger: { mode: v } }))),
3540
+ field(L.translateTargetLang, selIn(tr.targetLang || 'zh', [
3541
+ ['zh', '简体中文'], ['en', 'English'], ['ja', '日本語'], ['ko', '한국어'],
3542
+ ['fr', 'Français'], ['de', 'Deutsch'], ['ru', 'Русский'], ['es', 'Español'],
3543
+ ], (v) => persist({ targetLang: v }))),
3544
+ field(L.translatePanelWidth, numIn(panel0.width, 450, 280, 800, (v) => persist({ panel: { ...panel0, width: v } })))),
3545
+ h('div', { class: 'mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3' },
3546
+ field(L.translatePanelHeight, numIn(panel0.maxHeightPct, 80, 40, 95, (v) => persist({ panel: { ...panel0, maxHeightPct: v } }))),
3547
+ field(L.translateTheme, selIn(panel0.theme || 'follow', [
3548
+ ['follow', L.translateThemeFollow],
3549
+ ['light', L.translateThemeLight],
3550
+ ['dark', L.translateThemeDark],
3551
+ ], (v) => persist({ panel: { ...panel0, theme: v } }))),
3552
+ field(L.translateHistoryLimit, numIn(history0.limit, 100, 10, 1000, (v) => persist({ history: { ...history0, limit: v } })))),
3553
+ h('div', { class: 'mt-4 flex flex-wrap items-center gap-2' },
3554
+ h('span', { class: 'text-ui-sm font-medium' }, L.translateEngine),
3555
+ serviceSel,
3556
+ // 机翻时紧挨下拉放“获取密钥”入口,不另起一行
3557
+ isLlm ? null : h('span', {
3558
+ class: 'cursor-pointer text-ui-xs underline-offset-4 hover:underline',
3559
+ title: TR_MT_URLS[mtSvc],
3560
+ onClick: () => openExternal(TR_MT_URLS[mtSvc]),
3561
+ }, '↗ ' + L.translateGetKey)),
3562
+ engineArea,
3563
+ );
3564
+ };
3565
+ renderTranslate();
2607
3566
  renderVision();
2608
3567
 
2609
3568
  // “rtk 压缩”:编辑 rtk 插件状态(~/.zcode-rtk 的 mode 与 whitelist,
@@ -2996,14 +3955,36 @@ export function openSettingsDialog() {
2996
3955
  fact(L.headroomWatcher, s.watcherRunning == null ? '—' : (s.watcherRunning ? L.headroomWatcherOn : L.headroomWatcherOff)),
2997
3956
  fact(L.headroomSaverDetect, HR_DETECT[s.saverDetect] || s.saverDetect),
2998
3957
  );
2999
- // 多实例模式:列出各压缩实例(端口/格式/上游/供应商)与运行状态
3958
+ // 多实例模式:列出各压缩实例(端口/出口/供应商)与运行状态。
3959
+ // 走代理链时出口显示「链 <地址>」,因为真实发出方是链转发器、不是厂商域名;
3960
+ // 一个实例承载多个厂商时不能只显示第一个(转发器按 key 分流),
3961
+ // 改成「N 个上游」并用悬浮提示列出全部
3000
3962
  const insts = Array.isArray(s.instances) ? s.instances : [];
3001
- hrInstList.replaceChildren(...insts.map((it) => h('div', { class: 'flex min-w-0 items-center gap-2' },
3002
- h('span', { class: 'shrink-0 font-mono text-ui-xs text-foreground-subtle' }, `:${it.port}`),
3003
- h('span', { class: 'min-w-0 flex-1 truncate text-ui-xs text-foreground-subtle', title: `${it.upstream} | ${it.providers}` },
3004
- `${it.format} → ${it.upstream}`),
3005
- h('span', { class: 'max-w-[40%] shrink-0 truncate text-ui-xs text-foreground-subtle/70', title: it.providers }, it.providers),
3006
- h('span', { class: 'shrink-0 text-ui-xs ' + (it.up ? 'text-emerald-600' : 'text-destructive') }, it.up ? L.hrInstRunning : L.hrInstStopped))));
3963
+ const outletOf = (it) => (it.onChain ? `${L.hrInstChain} ${it.target}` : it.upstream);
3964
+ const outletTitle = (it) => {
3965
+ const lines = [];
3966
+ if (it.onChain) {
3967
+ lines.push(`${L.hrInstChain} ${it.target}`);
3968
+ const ups = Array.isArray(it.upstreams) && it.upstreams.length ? it.upstreams : [it.upstream];
3969
+ lines.push(`${L.hrInstUpstreams}: ${ups.join('、')}`);
3970
+ if (Array.isArray(it.proxies) && it.proxies.length) lines.push(`${L.hrInstVia}: ${it.proxies.join('、')}`);
3971
+ } else {
3972
+ lines.push(`${L.hrInstUpstreams}: ${it.upstream}`);
3973
+ }
3974
+ lines.push(`${L.hrInstProviders}: ${it.providers}`);
3975
+ return lines.join('\n');
3976
+ };
3977
+ hrInstList.replaceChildren(...insts.map((it) => {
3978
+ const ups = Array.isArray(it.upstreams) ? it.upstreams.filter(Boolean) : [];
3979
+ const many = ups.length > 1;
3980
+ return h('div', { class: 'flex min-w-0 items-center gap-2' },
3981
+ h('span', { class: 'shrink-0 font-mono text-ui-xs text-foreground-subtle' }, `:${it.port}`),
3982
+ h('span', { class: 'min-w-0 flex-1 truncate text-ui-xs text-foreground-subtle', title: outletTitle(it) },
3983
+ `${it.format} → ${outletOf(it)}${many ? ` (+${ups.length - 1})` : ''}`),
3984
+ h('span', { class: 'max-w-[40%] shrink-0 truncate text-ui-xs text-foreground-subtle/70', title: it.providers }, it.providers),
3985
+ h('span', { class: 'shrink-0 text-ui-xs ' + (it.up ? 'text-emerald-600' : 'text-destructive') }, it.up ? L.hrInstRunning : L.hrInstStopped),
3986
+ ...(rb ? [rb] : []));
3987
+ }));
3007
3988
  hrInstList.style.display = insts.length ? '' : 'none';
3008
3989
  hrHintLine.textContent = s.saverHint || '';
3009
3990
  hrHintLine.style.display = s.saverHint ? '' : 'none';
@@ -3253,29 +4234,24 @@ export function openSettingsDialog() {
3253
4234
  // 手动输入过的模型保留(不在新列表里时显示为“手动输入”项,是否改选
3254
4235
  // 由用户决定)
3255
4236
  const showInlineConn = isManualConn(titleGenCfg.provider, titleGenProviders);
3256
- const providerCombo = comboField(
3257
- titleGenCfg.provider || '',
3258
- providerOptionsOf(titleGenProviders, L),
3259
- (v, src) => {
3260
- titleGenCfg.provider = v;
3261
- if (src === 'select') { void persistTitleGen(); renderTitleGenPane(); }
3262
- else saveTitleGenSoon();
4237
+ // 供应商 + 模型 + 思考级别走统一封装(与翻译页、视觉代理同一实现)
4238
+ const titleGenPmt = providerModelThinkingFields({
4239
+ providers: titleGenProviders,
4240
+ L,
4241
+ provider: titleGenCfg.provider || '',
4242
+ model: titleGenCfg.model || '',
4243
+ thinking: titleGenCfg.thinking || 'off',
4244
+ sessionInfo: translateSessionRes.ok ? translateSessionRes.session : null,
4245
+ withManual: true,
4246
+ labels: { provider: L.titleGenProvider, model: L.titleGenModel, thinking: L.translateThinking },
4247
+ onChange: (patch) => {
4248
+ titleGenCfg.provider = patch.provider;
4249
+ titleGenCfg.model = patch.model;
4250
+ titleGenCfg.thinking = patch.thinking;
4251
+ saveTitleGenSoon();
3263
4252
  },
3264
- { placeholder: L.titleGenProviderSession, staleLabel: L.titleGenProviderDeleted });
3265
- const modelCombo = comboField(
3266
- titleGenCfg.model || '',
3267
- // 跟随会话时选项表头部有“跟随当前会话当前模型”(值为空,生成时用
3268
- // 会话当前模型),选了具体模型后也能再切回它
3269
- modelOptionsOf(titleGenCfg.provider, titleGenProviders, {
3270
- followSession: true,
3271
- followSessionLabel: L.titleGenModelFollowSession,
3272
- }),
3273
- (v) => { titleGenCfg.model = v; saveTitleGenSoon(); },
3274
- {
3275
- placeholder: modelPlaceholderOf(titleGenCfg.provider, L),
3276
- emptyLabel: (titleGenCfg.provider || '').trim() === 'session'
3277
- ? L.titleGenModelFollowSession : L.titleGenModelEmpty,
3278
- });
4253
+ requestRender: () => { void persistTitleGen(); renderTitleGenPane(); },
4254
+ });
3279
4255
  // 接口地址 / API Key / 协议(显隐见上方 showInlineConn):不跟随时由
3280
4256
  // 用户填写;供应商被删时展示保存的副本,仍可直连或改填
3281
4257
  const textIn = (value, onInput, { type = 'text', placeholder = '' } = {}) => {
@@ -3349,10 +4325,9 @@ export function openSettingsDialog() {
3349
4325
  await persistTitleGen();
3350
4326
  renderTitleGenPane();
3351
4327
  }))),
3352
- // 供应商 + 模型
3353
- h('div', { class: 'mt-2 grid grid-cols-1 gap-2 rounded-xl border border-border p-2 sm:grid-cols-2' },
3354
- field(L.titleGenProvider, providerCombo),
3355
- field(L.titleGenModel, modelCombo)),
4328
+ // 供应商 + 模型 + 思考级别
4329
+ h('div', { class: 'mt-2 grid grid-cols-1 gap-2 rounded-xl border border-border p-2 sm:grid-cols-3' },
4330
+ ...titleGenPmt.fields),
3356
4331
  inlineConnCard,
3357
4332
  // 提示词 + 载入默认
3358
4333
  h('div', { class: 'mt-2 rounded-xl border border-border p-2' },
@@ -3427,20 +4402,26 @@ export function openSettingsDialog() {
3427
4402
  // 空的已保存值保持为空:改其它开关时不能把当前语言的默认提示词写进配置,
3428
4403
  // 否则之后切换语言就不会再跟随(运行时空值才取当前语言默认)
3429
4404
  continueText: typeof raw.continueText === 'string' && raw.continueText.trim() ? raw.continueText : '',
3430
- maxRetries: Number.isFinite(raw.maxRetries) ? raw.maxRetries : 8,
3431
- cooldownBaseSec: Number.isFinite(raw.cooldownBaseSec) ? raw.cooldownBaseSec : 10,
4405
+ maxRetries: Number.isFinite(raw.maxRetries) ? raw.maxRetries : 10,
4406
+ continueDelaySec: Number.isFinite(raw.continueDelaySec) ? raw.continueDelaySec : 120,
4407
+ continueDelayFactor: Number.isFinite(raw.continueDelayFactor) ? raw.continueDelayFactor : 1.3,
3432
4408
  stuckAfterMin: Number.isFinite(raw.stuckAfterMin) ? raw.stuckAfterMin : 30,
3433
4409
  failedAfterMin: Number.isFinite(raw.failedAfterMin) ? raw.failedAfterMin : 3,
3434
4410
  };
3435
4411
  }
3436
- // numberField 返回 { el, set, reset, get },取 .el 嵌入
3437
- const numRow = (labelText, hint, value, min, max, commit) => h('label', {
3438
- class: 'flex shrink-0 items-center gap-1.5', title: hint,
3439
- }, h('span', { class: 'text-ui-xs text-foreground-subtle' }, labelText),
3440
- numberField({
3441
- value, fallback: min, min, max,
3442
- onCommit: (v) => { commit(v); saveAcSoon(); },
3443
- }).el);
4412
+ // 每项独占一行:标题与说明在左,数值输入在右。step 支持小数(递增倍数 1.3);
4413
+ // fallback 用当前值,空输入回落到现有值而不是最小值
4414
+ const numRow = (labelText, hint, value, min, max, commit, step = 1) => h('div', {
4415
+ class: 'flex items-center gap-2 p-2',
4416
+ },
4417
+ h('div', { class: 'min-w-0 flex-1' },
4418
+ h('div', { class: 'text-ui-sm font-medium text-foreground' }, labelText),
4419
+ hint ? h('div', { class: 'mt-0.5 text-ui-xs/relaxed text-foreground-subtle', title: hint }, hint) : null),
4420
+ h('div', { class: 'shrink-0' },
4421
+ numberField({
4422
+ value, fallback: value, min, max, step,
4423
+ onCommit: (v) => { commit(v); saveAcSoon(); },
4424
+ }).el));
3444
4425
  const area = h('textarea', { class: 'zcodepro-textarea zcodepro-textarea-sm', rows: '3', placeholder: L.acPrompt, title: L.acPrompt });
3445
4426
  area.value = acCfg.continueText || defaultContinueText(); // 空值显示当前语言默认,但保存时仍为空
3446
4427
  area.addEventListener('input', () => { acCfg.continueText = area.value; saveAcSoon(); });
@@ -3459,11 +4440,12 @@ export function openSettingsDialog() {
3459
4440
  h('div', { class: 'mt-3 rounded-xl border border-border p-2' },
3460
4441
  h('div', { class: 'mb-1 text-ui-xs font-medium text-foreground-subtle' }, L.acPrompt),
3461
4442
  area),
3462
- h('div', { class: 'mt-2 flex flex-wrap items-center gap-x-4 gap-y-1.5 rounded-xl border border-border p-2' },
4443
+ h('div', { class: 'mt-2 divide-y divide-border rounded-xl border border-border' },
3463
4444
  numRow(L.acMaxRetries, L.acMaxRetriesHint, acCfg.maxRetries, 1, 50, (v) => { acCfg.maxRetries = v; }),
3464
- numRow(L.acCooldown, L.acCooldownHint, acCfg.cooldownBaseSec, 0, 600, (v) => { acCfg.cooldownBaseSec = v; }),
3465
- numRow(L.acStuckAfterMin, L.acStuckAfterMinHint, acCfg.stuckAfterMin, 5, 720, (v) => { acCfg.stuckAfterMin = v; }),
3466
- numRow(L.acFailedAfterMin, L.acFailedAfterMinHint, acCfg.failedAfterMin, 1, 60, (v) => { acCfg.failedAfterMin = v; })),
4445
+ numRow(L.acContinueDelay, L.acContinueDelayHint, acCfg.continueDelaySec, 0, 3600, (v) => { acCfg.continueDelaySec = v; }),
4446
+ numRow(L.acContinueDelayFactor, L.acContinueDelayFactorHint, acCfg.continueDelayFactor, 1, 10, (v) => { acCfg.continueDelayFactor = v; }, 0.1),
4447
+ numRow(L.acFailedAfterMin, L.acFailedAfterMinHint, acCfg.failedAfterMin, 1, 60, (v) => { acCfg.failedAfterMin = v; }),
4448
+ numRow(L.acStuckAfterMin, L.acStuckAfterMinHint, acCfg.stuckAfterMin, 5, 720, (v) => { acCfg.stuckAfterMin = v; })),
3467
4449
  );
3468
4450
  paneAutoContinue.replaceChildren(...parts);
3469
4451
  };
@@ -3490,12 +4472,16 @@ export function openSettingsDialog() {
3490
4472
  panePerf,
3491
4473
  paneProxy,
3492
4474
  paneSync,
4475
+ paneTranslate,
3493
4476
  paneImport,
3494
4477
  paneVision,
3495
4478
  paneHeadroom,
3496
4479
  paneRtk,
3497
4480
  paneDebug,
3498
4481
  );
4482
+ // 所有 pane 就绪后再切到目标 tab:pane 与二级 pane 的初始可见性都已在上面
4483
+ // 设好,此后 switchTab 只会调整显示,不会出现“内容区空白”
4484
+ switchTab(activeTab);
3499
4485
  },
3500
4486
  });
3501
4487
  }