zcode-pro 1.4.1 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,112 @@
1
+ // 输入框模型名前显示供应商名:3.16.0 起官方触发器只显示模型名(如 glm-5.3),
2
+ // 同名模型在不同供应商下无法区分。按钮的 aria-label 本就带全名
3
+ //("BigModel-Max1/glm-5.3 最高"),从那里取 “/” 前的供应商段补到显示文本前,
4
+ // 显示为 “BigModel-Max1 / glm-5.3”。不监听点击、不改官方状态,纯显示增强;
5
+ // 应用重渲染会冲掉文本,MutationObserver 维持。
6
+ import { t, getConfig } from '../core.js';
7
+
8
+ let installed = false;
9
+ let enabled = true; // helper features.composerProvider(默认开)
10
+
11
+ // 从 aria-label 提取 “供应商 / 模型” 显示文本。
12
+ // label 形态:"<供应商>/<模型名> <附加说明(如 最高)>";有的供应商名本身
13
+ // 不含 /、有的官方项可能没有 /(旧版内置项),没有 / 时返回 null 不改
14
+ function labelToDisplay(label) {
15
+ const i = label.indexOf('/');
16
+ if (i <= 0) return null;
17
+ const provider = label.slice(0, i).trim();
18
+ const rest = label.slice(i + 1);
19
+ const model = rest.trim().split(/\s+/)[0];
20
+ if (!provider || !model) return null;
21
+ return `${provider} / ${model}`;
22
+ }
23
+
24
+ function apply() {
25
+ if (!enabled) {
26
+ // 关闭时把此前改写的文本还原为官方模型名(aria-label 的 “/” 后段),
27
+ // 不必等应用重渲染
28
+ for (const btn of document.querySelectorAll('[data-testid="chat-model-select-trigger"]')) {
29
+ if (!btn.dataset.zcodeproProviderShown) continue;
30
+ const label = btn.getAttribute('aria-label') || '';
31
+ const i = label.indexOf('/');
32
+ if (i <= 0) continue;
33
+ const model = label.slice(i + 1).trim().split(/\s+/)[0];
34
+ if (!model) continue;
35
+ for (const sp of btn.querySelectorAll('span[title]')) sp.setAttribute('title', model);
36
+ for (const el of btn.querySelectorAll('span[title] span:not([title])')) {
37
+ if (!el.querySelector('span') && el.textContent.includes('/')) el.textContent = model;
38
+ }
39
+ delete btn.dataset.zcodeproProviderShown;
40
+ }
41
+ return;
42
+ }
43
+ for (const btn of document.querySelectorAll('[data-testid="chat-model-select-trigger"]')) {
44
+ // 只处理 a[data-composer-combined-model] 主触发器;aria-label 缺失时跳过
45
+ const label = btn.getAttribute('aria-label') || '';
46
+ const display = labelToDisplay(label);
47
+ if (!display) continue;
48
+ // 显示 span 是嵌套两层的 title 结构(外层裁剪容器 + 内层相对定位层),
49
+ // 文本都在最内层 span;只改文本与 title,不动结构
50
+ // 官方结构:外层 title 容器 > 内层 title 层 > 纯文本 span(模型名)。
51
+ // 只改 title 链内的文本——按“祖先带 title”识别模型名文本;同级的
52
+ // “最高/开启”说明 span(无 title 祖先链上的 title 层)不属于模型名,
53
+ // 不能碰(首版误把它也替换成全名)
54
+ const titleSpans = [...btn.querySelectorAll('span[title]')];
55
+ if (!titleSpans.length) continue;
56
+ const innermost = titleSpans.filter((sp) => !sp.querySelector('span[title]'));
57
+ if (!innermost.length) continue;
58
+ const holders = [];
59
+ for (const sp of innermost) {
60
+ sp.querySelectorAll('span:not([title])').forEach((el) => {
61
+ if (!el.querySelector('span') && el.textContent.trim() && !el.textContent.includes('/')) holders.push(el);
62
+ });
63
+ }
64
+ if (!holders.length) continue;
65
+ for (const sp of titleSpans) {
66
+ if (sp.getAttribute('title') !== display) sp.setAttribute('title', display);
67
+ }
68
+ for (const el of holders) el.textContent = display;
69
+ btn.dataset.zcodeproProviderShown = '1';
70
+ }
71
+ }
72
+
73
+ export function startComposerProvider() {
74
+ if (installed || typeof document === 'undefined') return;
75
+ installed = true;
76
+ // 先过滤再调度:变更不在输入框工具栏子树(composer 容器)内的批次直接忽略,
77
+ // 连去抖定时器都不排——流式输出的高频文本变更不会叫醒本模块
78
+ const COMPOSER_SEL = '[data-composer-layout], [data-composer-leading-content], [data-testid="chat-model-select-trigger"]';
79
+ const relevant = (muts) => {
80
+ for (const m of muts) {
81
+ if (m.type === 'childList') {
82
+ for (const n of [...m.addedNodes, ...m.removedNodes]) {
83
+ if (n instanceof Element && (n.matches?.(COMPOSER_SEL) || n.querySelector?.(COMPOSER_SEL))) return true;
84
+ }
85
+ } else if (m.type === 'characterData') {
86
+ let el = m.target.parentElement;
87
+ while (el && el !== document.body) {
88
+ if (el.matches?.('[data-composer-layout], [data-composer-leading-actions], [data-composer-leading-content]')) return true;
89
+ el = el.parentElement;
90
+ }
91
+ }
92
+ }
93
+ return false;
94
+ };
95
+ const schedule = () => {
96
+ clearTimeout(schedule.t);
97
+ schedule.t = setTimeout(apply, 120);
98
+ };
99
+ void getConfig().then((cfg) => { enabled = cfg.features ? cfg.features.composerProvider !== false : true; }).catch(() => {});
100
+ window.addEventListener('zcodepro:config-changed', () => {
101
+ void getConfig(true).then((cfg) => {
102
+ const next = cfg.features ? cfg.features.composerProvider !== false : true;
103
+ if (next !== enabled) {
104
+ enabled = next;
105
+ apply(); // 开关切换即时生效:关时还原官方文本,开时补供应商名
106
+ }
107
+ }).catch(() => {});
108
+ });
109
+ const observer = new MutationObserver((muts) => { if (enabled && relevant(muts)) schedule(); });
110
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true });
111
+ apply();
112
+ }
@@ -87,7 +87,9 @@ function sessionScope() {
87
87
  const cur = rows.find((e) => (e.className + '').includes('bg-selected')) || rows[rows.length - 1];
88
88
  const key = cur ? cur.getAttribute('data-task-item-key') : '';
89
89
  if (!key) return null;
90
- const i = key.indexOf(':sess_');
90
+ // task_id 有 sess_ 与 session_ 两种前缀,按最后一个 ':' 切(Windows 盘符的
91
+ // ':' 在最前,id 段在最后且自身不含 ':')
92
+ const i = key.lastIndexOf(':');
91
93
  return i > 0 ? { workspacePath: key.slice(0, i), sessionId: key.slice(i + 1) } : null;
92
94
  }
93
95
 
@@ -1,13 +1,13 @@
1
1
  // 会话快捷切换:alt+z 立即切到上次使用的会话(再按切回);按住 alt 按 x/c 打开
2
2
  // MRU 弹窗前后移动高亮(x 更早 / c 更新,c 到底且还有更多时加载 5 条并选中新
3
3
  // 加载的第一条),alt+e 直接打开同一弹窗(初始显示最近 10 条),alt+r 打开
4
- // “运行中 / 运行完未查看”任务弹窗,松开 alt 切换,Esc / 点弹窗外取消,点行即切。
4
+ // “运行中 / 运行完未查看”任务弹窗,Enter 或点击行切换,Esc / 点弹窗外取消。
5
5
  // MRU(最近使用序)从注入起记录(不回填历史库,上限 50 条),
6
6
  // 与侧栏展示顺序无关;当前会话靠侧栏条目的 bg-selected 类识别(实测标记),
7
7
  // 事件驱动扫描(会话行增删/选中标记移动才触发)+ 低频兜底轮询——
8
8
  // 点击、新建任务自动跳转等任何方式的切换都能捕捉,聊天区流式输出不产生扫描。
9
9
  // 目标条目在折叠项目下时先展开项目行再点击(展开先例见 pinned-expand.js)。
10
- import { h, t, getConfig, DEFAULT_SHORTCUTS } from '../core.js';
10
+ import { h, t, rpc, getConfig, DEFAULT_SHORTCUTS } from '../core.js';
11
11
  import { ensureStyle, showToast } from '../ui.js';
12
12
  import { findProjectRow } from './ws-rows.js';
13
13
  import { wsRunningKeys } from './ws-running.js';
@@ -30,7 +30,6 @@ let popupMode = 'mru'; // 'mru':最近使用(x/c/e);'attention':运
30
30
  let visibleCount = INITIAL_COUNT;
31
31
  let unseen = new Set(); // 运行结束以来未再切入查看的会话键
32
32
  let lastRunKeys = null; // 上次采样的运行键集合(用于识别“运行→结束”的转变)
33
- let movedSinceOpen = false; // 打开弹窗后是否移动过高亮(决定松开 alt 是提交还是保持)
34
33
  // 键位(alt+字母/数字):默认见 core.js,可在设置 → 快捷键修改;
35
34
  // 设置保存时会派发 zcodepro:config-changed,这里刷新缓存
36
35
  let hotkeys = { ...DEFAULT_SHORTCUTS };
@@ -52,9 +51,9 @@ function firstLineOf(item) {
52
51
  }
53
52
 
54
53
  function workspaceOf(key) {
55
- // 键格式 <workspace_path>:<sess_id>;sess 段固定以 "sess_" 开头,按其定位分隔符
56
- // (Windows 盘符路径里也有冒号,不能按第一个 ':' 切)
57
- const i = key.indexOf(':sess_');
54
+ // 键格式 <workspace_path>:<task_id>;task_id 有 sess_ 与 session_ 两种前缀
55
+ // (新版应用为 session_),按最后一个 ':' 切(ws-running.js 同款)
56
+ const i = key.lastIndexOf(':');
58
57
  return i > 0 ? key.slice(0, i) : key;
59
58
  }
60
59
 
@@ -115,7 +114,11 @@ function scheduleScan() {
115
114
 
116
115
  // 切到指定会话:条目不在 DOM(项目折叠)时先展开项目行,等条目出现再点击
117
116
  async function switchTo(key) {
118
- const find = () => document.querySelector(`[data-task-item-key="${CSS.escape(key)}"]`);
117
+ // 权威扫描拼出的键(工作区前缀无尾斜杠)可能与行键(可能带尾斜杠)不同形,
118
+ // 精确匹配落空时按会话 id 后缀兜底(会话 id 全局唯一,不会命中别的会话)
119
+ const id = key.slice(key.lastIndexOf(':') + 1);
120
+ const find = () => document.querySelector(`[data-task-item-key="${CSS.escape(key)}"]`)
121
+ || (id ? document.querySelector(`[data-task-item-key$=":${CSS.escape(id)}"]`) : null);
119
122
  let item = find();
120
123
  if (!item) {
121
124
  const ws = workspaceOf(key);
@@ -134,21 +137,30 @@ async function switchTo(key) {
134
137
  return true;
135
138
  }
136
139
 
137
- // —— 切换弹窗(类 alt+tab):居中列表卡,x/c 移动高亮,松开 alt / 点击提交 ——
140
+ // —— 切换弹窗(类 alt+tab):居中列表卡,x/c 移动高亮,Enter / 点击提交 ——
138
141
 
139
142
  // attention 弹窗的列表:正在运行或运行完未查看的任务。MRU 只记录切入过的
140
143
  // 会话,而“未查看”的任务可能从未切入,不在 MRU 里——这部分(先运行中、
141
- // 再未查看,各按发现序)追加在 MRU 命中项之后
144
+ // 再未查看,各按发现序)追加在 MRU 命中项之后。
145
+ // 同一会话有两种键形(行在场与否决定:DOM 行键可能带尾斜杠、权威拼的键
146
+ // 不带),按会话 id 去重——同一会话只出一行,运行中的键形优先(标签按它
147
+ // 判定才是“运行中”,点击也命中在场行)
142
148
  function attentionList() {
143
149
  const run = wsRunningKeys();
150
+ const idOf = (k) => k.slice(k.lastIndexOf(':') + 1);
151
+ const runKeyById = new Map([...run].map((k) => [idOf(k), k]));
144
152
  const listed = new Set();
145
153
  const head = [];
146
154
  for (const k of mru) {
147
- if (run.has(k) || unseen.has(k)) { head.push(k); listed.add(k); }
155
+ const id = idOf(k);
156
+ if (listed.has(id)) continue;
157
+ const runForm = runKeyById.get(id);
158
+ if (run.has(k) || unseen.has(k) || runForm) { head.push(runForm || k); listed.add(id); }
148
159
  }
149
160
  const tail = [];
150
- for (const k of run) if (!listed.has(k)) { tail.push(k); listed.add(k); }
151
- for (const k of unseen) if (!listed.has(k)) { tail.push(k); listed.add(k); }
161
+ const push = (k) => { const id = idOf(k); if (listed.has(id)) return; listed.add(id); tail.push(k); };
162
+ for (const k of run) push(k);
163
+ for (const k of unseen) push(k);
152
164
  return [...head, ...tail];
153
165
  }
154
166
 
@@ -171,10 +183,27 @@ function closePopup(commit) {
171
183
  function findTitle(key) {
172
184
  const item = document.querySelector(`[data-task-item-key="${CSS.escape(key)}"]`);
173
185
  if (item) titles.set(key, firstLineOf(item));
174
- const id = key.slice(key.indexOf(':sess_') + 1);
186
+ const id = key.slice(key.lastIndexOf(':') + 1);
175
187
  return titles.get(key) || `sess ${id.slice(0, 8)}`;
176
188
  }
177
189
 
190
+ // 折叠项目的会话行不在场,标题缓存里没有:打开 attention 弹窗时按会话 id 批量
191
+ // 查任务索引(helper /task-statuses 附带 title);查不到保持 "sess xxx" 兜底
192
+ async function fetchMissingTitles(keys) {
193
+ const sessIdOf = (k) => k.slice(k.lastIndexOf(':') + 1);
194
+ const missing = keys.filter((k) => {
195
+ const id = sessIdOf(k);
196
+ return id && !titles.get(k) && !document.querySelector(`[data-task-item-key$=":${CSS.escape(id)}"]`);
197
+ });
198
+ if (!missing.length) return;
199
+ const st = await rpc('/task-statuses?ids=' + encodeURIComponent(missing.map(sessIdOf).join(','))).catch(() => null);
200
+ if (!st || !st.ok || !st.available || !st.statuses) return;
201
+ for (const k of missing) {
202
+ const rec = st.statuses[sessIdOf(k)];
203
+ if (rec && rec.title) titles.set(k, String(rec.title));
204
+ }
205
+ }
206
+
178
207
  // 项目显示名:优先自定义别名(与侧栏一致),无别名退回目录名
179
208
  function projLabelOf(key, aliases) {
180
209
  const ws = workspaceOf(key);
@@ -212,14 +241,25 @@ function renderPopup() {
212
241
  }
213
242
  }
214
243
 
215
- async function openPopup(mode = 'mru') {
244
+ // 打开进行中的 Promise:连按(r 后紧接 x/c)等同一次打开,等弹窗真正挂载完
245
+ // 再移动——移动若落在打开流程的 await 窗口里,会被打开时的状态重置冲掉
246
+ let openPopupInflight = null;
247
+
248
+ function openPopup(mode = 'mru') {
216
249
  if (popupEl) return;
250
+ if (openPopupInflight) return openPopupInflight;
251
+ openPopupInflight = openPopupInner(mode).finally(() => { openPopupInflight = null; });
252
+ return openPopupInflight;
253
+ }
254
+
255
+ async function openPopupInner(mode) {
217
256
  popupMode = mode;
218
257
  visibleCount = INITIAL_COUNT;
219
258
  highlight = 0;
220
- movedSinceOpen = false;
221
259
  const cfg = await getConfig().catch(() => null);
222
260
  aliasesCache = (cfg && cfg.aliases && typeof cfg.aliases === 'object') ? cfg.aliases : {};
261
+ // attention 模式的行可能整段来自权威扫描(折叠项目),先补齐它们的标题再渲染
262
+ if (mode === 'attention') await fetchMissingTitles(attentionList()).catch(() => {});
223
263
  ensureStyle();
224
264
  const L = t();
225
265
  popupEl = h('div', {
@@ -247,7 +287,6 @@ function moveUp() {
247
287
  const len = Math.min(activeList().length, visibleCount);
248
288
  if (len < 2) return;
249
289
  highlight = highlight > 0 ? highlight - 1 : len - 1; // 到顶循环回已加载的末尾
250
- movedSinceOpen = true;
251
290
  renderPopup();
252
291
  scrollHighlight();
253
292
  }
@@ -265,7 +304,6 @@ function moveDown() {
265
304
  } else {
266
305
  highlight = 0; // 全部加载完后再到底:循环回顶部
267
306
  }
268
- movedSinceOpen = true;
269
307
  renderPopup();
270
308
  scrollHighlight();
271
309
  }
@@ -288,8 +326,13 @@ export function startSessionSwitch() {
288
326
  if (document.hidden) return;
289
327
  const now = wsRunningKeys();
290
328
  if (lastRunKeys) {
329
+ // 按会话 id 判“从运行集合消失”:同一会话的键形会随行挂载/卸载在
330
+ // “权威拼的键”与“DOM 行键”之间切换,按整键比较会把键形切换误判成
331
+ // 运行结束,生成一行点不动的“未查看”幽灵行
332
+ const idOf = (k) => k.slice(k.lastIndexOf(':') + 1);
333
+ const nowIds = new Set([...now].map(idOf));
291
334
  for (const k of lastRunKeys) {
292
- if (!now.has(k) && k !== current) unseen.add(k);
335
+ if (!nowIds.has(idOf(k)) && k !== current) unseen.add(k);
293
336
  }
294
337
  }
295
338
  lastRunKeys = now;
@@ -310,6 +353,16 @@ export function startSessionSwitch() {
310
353
  closePopup(false);
311
354
  return;
312
355
  }
356
+ // 弹窗开着时松开 alt 后裸按 x/c 也移动高亮:提示文案一直是
357
+ // “x / c 或 ↑ / ↓ 选择”,与方向键同规则(下到底加载 5 条)
358
+ const bareK = e.key.toLowerCase();
359
+ if (popupEl && !e.altKey && !e.ctrlKey && !e.metaKey && !e.isComposing
360
+ && (bareK === hotkeys.switchPrev || bareK === hotkeys.switchNext)) {
361
+ e.preventDefault();
362
+ e.stopImmediatePropagation();
363
+ if (bareK === hotkeys.switchPrev) moveUp(); else moveDown();
364
+ return;
365
+ }
313
366
  // 弹窗开着时方向键 / Enter 也可操作(此时用户往往已松开 alt):
314
367
  // ↑/↓ 与 x/c 同规则(下到底加载 5 条),Enter 提交高亮项
315
368
  if (popupEl && (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'Enter')) {
@@ -359,25 +412,34 @@ export function startSessionSwitch() {
359
412
  await openPopup('attention');
360
413
  return;
361
414
  }
362
- // x/c/e:最近使用弹窗(无可导航会话时与 z 一致轻提示)
363
- if (mru.length < 2) { showToast(t().switcherEmpty); return; }
364
- // e 只负责打开(初始显示最近 10 条,c 可继续加载更早的)
415
+ // e 只负责打开(初始显示最近 10 条,c 可继续加载更早的);已开着或正在
416
+ // 打开时不动作。只在 mru 为空(连当前会话都没有,如停在新建任务页)才
417
+ // 提示——首次仅开着当前会话时照常打开,列表里就是它这一条
365
418
  if (k === hotkeys.switchRecent) {
366
- if (!e.repeat && !popupEl) await openPopup('mru');
419
+ if (!e.repeat && !popupEl && !openPopupInflight) {
420
+ if (!mru.length) { showToast(t().switcherEmpty); return; }
421
+ await openPopup('mru');
422
+ }
367
423
  return;
368
424
  }
369
- if (!popupEl) await openPopup('mru');
425
+ // x/c:弹窗已开着(含 attention 模式)直接在当前列表移动——attention 的
426
+ // 列表不是 mru,不能用 mru 的条数门槛拦截;正在打开(r 的异步流程没走完,
427
+ // popupEl 还没挂上)就等它开完再移动,否则要么被 mru 门槛拦成“空”,要么
428
+ // 移动被打开流程的状态重置冲掉;没开则以 mru 打开再移动(mru 为空才提示,
429
+ // 单条=当前会话时打开,移动自然无效)
430
+ if (openPopupInflight) {
431
+ await openPopupInflight;
432
+ } else if (!popupEl) {
433
+ if (!mru.length) { showToast(t().switcherEmpty); return; }
434
+ await openPopup('mru');
435
+ }
370
436
  // 键位对调:alt+x 上移一位(更靠上/更近的键管向上),alt+c 下移
371
437
  if (k === hotkeys.switchPrev) moveUp(); else moveDown();
372
438
  })();
373
439
  }, true);
374
440
 
375
- document.addEventListener('keyup', (e) => {
376
- // 松开 alt:移动过高亮则提交(alt+tab 流);从未移动则保持弹窗打开,
377
- // 让用户继续用方向键选择(alt+e / alt+r 打开后松手查看的场景)
378
- if (e.key === 'Alt' && popupEl && movedSinceOpen) closePopup(true);
379
- }, true);
380
-
381
- // 窗口失焦(alt+tab 到别的应用等)视同取消
441
+ // 松开 alt 不做任何事(曾按 alt+tab 语义在松开时提交,但 Electron 的应用
442
+ // 菜单会抢走按松 Alt 的焦点,keyup 时有时无,行为不可靠,已移除);切换只
443
+ // 认 Enter 与点击行。窗口失焦(alt+tab 到别的应用、系统抢焦点)视同取消
382
444
  window.addEventListener('blur', () => closePopup(false));
383
445
  }
@@ -244,8 +244,17 @@ export function openSettingsDialog() {
244
244
  h('span', { class: 'text-foreground-subtle/70' }, `${health.version} · ${HELPER_URL}`)
245
245
  );
246
246
 
247
- const rows = h('div', { class: 'divide-y divide-border rounded-xl border border-border' });
247
+ // 双列网格:功能开关行短小(名称+开关+折行描述),两列排布把 15+ 行压到
248
+ // 一屏内。列间加分隔线、行距拉开(gap-y-1),格内不留底 padding——
249
+ // 悬停底色由行自身圆角承担,避免一格一格的补丁感
250
+ const rows = h('div', { class: 'grid grid-cols-2 gap-x-0 gap-y-1 rounded-xl border border-border p-2 divide-x divide-border' });
248
251
  const pluginsStatusLine = h('span', { class: 'max-w-40 truncate text-ui-xs/relaxed text-foreground-subtle' }, '…');
252
+ // 状态文字写入统一入口:文本与悬停 title 一起更新(描述位被动态内容替换后
253
+ // 仍保持悬停全文约定)
254
+ const setPluginsStatus = (text) => {
255
+ setPluginsStatus(text);
256
+ pluginsStatusLine.setAttribute('title', text);
257
+ };
249
258
  const pluginsBtn = btnSmall(L.pluginsCheckNow, () => { void runPluginsUpdate(); });
250
259
  let pluginsUpdating = false;
251
260
  const runPluginsUpdate = async () => {
@@ -253,18 +262,18 @@ export function openSettingsDialog() {
253
262
  if (pluginsUpdating) return;
254
263
  pluginsUpdating = true;
255
264
  pluginsBtn.disabled = true;
256
- pluginsStatusLine.textContent = L.pluginsUpdating;
265
+ setPluginsStatus(L.pluginsUpdating);
257
266
  const res = await rpc('/plugins/update', { method: 'POST', body: {} });
258
267
  pluginsUpdating = false;
259
268
  pluginsBtn.disabled = false;
260
269
  if (!res.ok) {
261
- pluginsStatusLine.textContent = '';
270
+ setPluginsStatus('');
262
271
  showToast(L.pluginsUpdateFailed + ': ' + errText(res), 'error');
263
272
  return;
264
273
  }
265
- pluginsStatusLine.textContent = res.updated > 0
274
+ setPluginsStatus(res.updated > 0
266
275
  ? L.pluginsUpdatedDone.replaceAll('{n}', String(res.updated))
267
- : L.pluginsUpToDate;
276
+ : L.pluginsUpToDate);
268
277
  showToast(pluginsStatusLine.textContent, 'success');
269
278
  };
270
279
  void (async () => {
@@ -272,15 +281,15 @@ export function openSettingsDialog() {
272
281
  // 状态行如实显示过程与结果;开关关闭时只检查并显示“N 个可更新”
273
282
  const cfg = await getConfig(true).catch(() => null);
274
283
  const res = await rpc('/plugins/status');
275
- if (!res.ok) { pluginsStatusLine.textContent = ''; return; }
284
+ if (!res.ok) { setPluginsStatus(''); return; }
276
285
  const n = (res.updates || []).length;
277
286
  if (cfg && (cfg.features || {}).autoUpdatePlugins === true && n > 0) {
278
287
  void runPluginsUpdate();
279
288
  return;
280
289
  }
281
- pluginsStatusLine.textContent = n > 0
290
+ setPluginsStatus(n > 0
282
291
  ? L.pluginsUpdatesFound.replaceAll('{n}', String(n))
283
- : L.pluginsUpToDate;
292
+ : L.pluginsUpToDate);
284
293
  })();
285
294
 
286
295
  // 会话快捷切换:入口键位(“快捷键”标签页可改);此处定义在 refreshRows 之前,
@@ -360,6 +369,16 @@ export function openSettingsDialog() {
360
369
  if (await setFeature('imageCopy', next)) f.imageCopy = next;
361
370
  refreshRows();
362
371
  }),
372
+ settingRow(L.featureTableCopy, L.featureTableCopyDesc, f.tableCopy !== false, async () => {
373
+ const next = !(f.tableCopy !== false);
374
+ if (await setFeature('tableCopy', next)) f.tableCopy = next;
375
+ refreshRows();
376
+ }),
377
+ settingRow(L.featureComposerProvider, L.featureComposerProviderDesc, f.composerProvider !== false, async () => {
378
+ const next = !(f.composerProvider !== false);
379
+ if (await setFeature('composerProvider', next)) f.composerProvider = next;
380
+ refreshRows();
381
+ }),
363
382
  settingRow(L.featureSandboxReclaim, L.featureSandboxReclaimDesc, f.sandboxReclaim !== false, async () => {
364
383
  const next = !(f.sandboxReclaim !== false);
365
384
  if (await setFeature('sandboxReclaim', next)) f.sandboxReclaim = next;
@@ -381,7 +400,7 @@ export function openSettingsDialog() {
381
400
  refreshRows();
382
401
  }),
383
402
  (() => {
384
- // 标题 = “自动更新 duanluan/zcode-plugins 插件”,仓库名可点击跳转仓库
403
+ // 标题 = “自动更新 duanluan/zcode-plugins”,仓库名可点击跳转仓库
385
404
  const repoLink = h('span', {
386
405
  class: 'cursor-pointer underline-offset-4 hover:underline',
387
406
  title: PLUGINS_REPO_URL,
@@ -392,17 +411,19 @@ export function openSettingsDialog() {
392
411
  if (await setFeature('autoUpdatePlugins', next)) f.autoUpdatePlugins = next;
393
412
  refreshRows();
394
413
  }, h('div', { class: 'flex items-center gap-2' }, pluginsBtn));
395
- // 标题行:自动更新 <链接> 插件;描述位放状态字(检查结果/更新进度)
414
+ // 标题行:自动更新 <链接>;描述位放状态字(检查结果/更新进度)
396
415
  const nameEl = row.querySelector('.text-ui-sm.font-medium');
397
416
  if (nameEl) {
398
417
  nameEl.replaceChildren(
399
418
  document.createTextNode(L.featureAutoUpdatePlugins + ' '),
400
419
  repoLink,
401
- document.createTextNode(' 插件'),
402
420
  );
403
421
  }
404
422
  const descEl = row.querySelector('[data-zcodepro-row-desc]');
405
- if (descEl) descEl.replaceChildren(pluginsStatusLine);
423
+ if (descEl) {
424
+ descEl.replaceChildren(pluginsStatusLine);
425
+ descEl.setAttribute('title', descEl.textContent.trim());
426
+ }
406
427
  return row;
407
428
  })(),
408
429
  );
@@ -478,8 +499,7 @@ export function openSettingsDialog() {
478
499
  }),
479
500
  hkCell('↑ / ↓', L.hkArrow.replaceAll('{prev}', keys.switchPrev).replaceAll('{next}', keys.switchNext)),
480
501
  hkCell('Enter', L.hkEnter),
481
- hkCell('Esc', L.hkEsc),
482
- hkCell(L.hkReleaseKey, L.hkRelease));
502
+ hkCell('Esc', L.hkEsc));
483
503
  };
484
504
  const stopHkRecording = () => {
485
505
  hkRecording = null;
@@ -560,12 +580,13 @@ export function openSettingsDialog() {
560
580
  const paneTitleGen = h('div', { role: 'tabpanel', class: 'mt-4', style: 'display:none' });
561
581
  const paneDebug = h('div', { role: 'tabpanel', class: 'mt-4', style: 'display:none' });
562
582
  const panes = { features: paneFeatures, shortcuts: paneShortcuts, styles: paneStyles, perf: panePerf, agents: paneAgents, proxy: paneProxy, sync: paneSync, vision: paneVision, headroom: paneHeadroom, rtk: paneRtk, debug: paneDebug };
583
+ // 一级 tab 顺序:功能 → 外观 → 行为 → 性能 → 快捷键 → 代理/同步/插件页
563
584
  const tabDefs = [
564
585
  ['features', L.tabFeatures],
565
- ['shortcuts', L.tabShortcuts],
566
- ['agents', L.tabBehavior],
567
586
  ['styles', L.tabStyles],
587
+ ['agents', L.tabBehavior],
568
588
  ['perf', L.tabPerformance],
589
+ ['shortcuts', L.tabShortcuts],
569
590
  ['proxy', L.tabProxy],
570
591
  ['sync', L.tabSync],
571
592
  ['vision', L.tabVision],
@@ -0,0 +1,148 @@
1
+ // 回答内容表格工具条的「复制表格」按钮:把表格以富文本(text/html)写入
2
+ // 剪贴板,可粘贴进 Excel / 富文本编辑器并被识别为真正的表格(分列成格)。
3
+ // 官方已有「复制 Markdown / 下载 CSV / 预览」,但没有富文本形态——手动框选
4
+ // 复制虽也是 text/html,但带上了应用给单元格的横线与主题背景色,粘贴出来
5
+ // 脏样式。这里克隆表格后剥掉全部内联样式与 class,只保留表格结构本身。
6
+ // text/plain 同步写 TSV(Tab 分列、换行分行):Excel / Numbers / 粘贴为纯
7
+ // 文本的场景都能正确分列;富文本编辑器取 text/html 得到干净表格。
8
+ import { ensureStyle, showToast } from '../ui.js';
9
+ import { t, getConfig } from '../core.js';
10
+
11
+ let installed = false;
12
+ let enabled = true; // helper features.tableCopy(默认开)
13
+
14
+ // 剥样式:克隆树上去掉 style/class/width 等表现属性,只留结构(含 rowspan/
15
+ // colspan——Excel 识别合并单元格)。thead/tbody 保留,th/td 语义也保留
16
+ function cleanTable(table) {
17
+ const clone = table.cloneNode(false);
18
+ const walk = (src, dst) => {
19
+ for (const node of src.childNodes) {
20
+ if (node.nodeType === Node.TEXT_NODE) {
21
+ if (node.textContent.trim()) dst.append(document.createTextNode(node.textContent));
22
+ continue;
23
+ }
24
+ if (node.nodeType !== Node.ELEMENT_NODE) continue;
25
+ const tag = node.tagName;
26
+ // 嵌套的行内标记(strong/em/code/a/span)保留文本与标签但不带任何属性
27
+ const el = document.createElement(tag.toLowerCase());
28
+ if (tag === 'TD' || tag === 'TH') {
29
+ // 合并单元格信息必须保留(Excel/编辑器据此铺格)
30
+ for (const a of ['colspan', 'rowspan']) {
31
+ const v = node.getAttribute(a);
32
+ if (v && v !== '1') el.setAttribute(a, v);
33
+ }
34
+ }
35
+ dst.append(el);
36
+ walk(node, el);
37
+ }
38
+ };
39
+ walk(table, clone);
40
+ return clone;
41
+ }
42
+
43
+ // TSV 转义:单元格内的 Tab/换行替换为空格(TSV 无法表达内嵌二者)
44
+ function tableToTsv(table) {
45
+ const rows = [];
46
+ for (const tr of table.rows) {
47
+ const cells = [];
48
+ for (const cell of tr.cells) {
49
+ cells.push((cell.textContent || '').replace(/[\t\r\n]+/g, ' ').trim());
50
+ }
51
+ rows.push(cells.join('\t'));
52
+ }
53
+ return rows.join('\n');
54
+ }
55
+
56
+ async function copyTable(table) {
57
+ const L = t();
58
+ const clean = cleanTable(table);
59
+ const html = '<meta charset="utf-8"><table>' + clean.innerHTML + '</table>';
60
+ const tsv = tableToTsv(table);
61
+ try {
62
+ if (typeof ClipboardItem !== 'undefined' && navigator.clipboard && navigator.clipboard.write) {
63
+ await navigator.clipboard.write([
64
+ new ClipboardItem({
65
+ 'text/html': new Blob([html], { type: 'text/html' }),
66
+ 'text/plain': new Blob([tsv], { type: 'text/plain' }),
67
+ }),
68
+ ]);
69
+ showToast(L.tableCopied, 'success');
70
+ return;
71
+ }
72
+ } catch { /* 走下面的兜底 */ }
73
+ // 兜底:自建 Selection + execCommand('copy'),剪贴板由浏览器按 DOM 生成
74
+ // text/html(无样式)与 text/plain
75
+ try {
76
+ const holder = document.createElement('div');
77
+ holder.contentEditable = 'true';
78
+ holder.style.cssText = 'position:fixed;left:-9999px;top:0;';
79
+ holder.append(clean);
80
+ document.body.append(holder);
81
+ const range = document.createRange();
82
+ range.selectNodeContents(holder);
83
+ const sel = window.getSelection();
84
+ sel.removeAllRanges();
85
+ sel.addRange(range);
86
+ const ok = document.execCommand('copy');
87
+ sel.removeAllRanges();
88
+ holder.remove();
89
+ if (ok) { showToast(L.tableCopied, 'success'); return; }
90
+ } catch { /* ignore */ }
91
+ showToast(L.failed, 'error');
92
+ }
93
+
94
+ // 与官方按钮同款的 ghost 图标按钮:lucide table 图标 + tooltip 用 aria-label
95
+ //(应用的 tooltip 组件由 React 挂载,注入按钮只能靠原生 title/aria——这里
96
+ // 用 aria-label 保持与邻居一致的可访问性,悬停提示用原生 title)
97
+ function makeButton(onClick) {
98
+ const L = t();
99
+ const btn = document.createElement('button');
100
+ btn.type = 'button';
101
+ btn.setAttribute('aria-label', L.tableCopyBtn);
102
+ btn.title = L.tableCopyBtn;
103
+ btn.className = 'group/button inline-flex items-center justify-center border border-transparent bg-clip-padding whitespace-nowrap transition-colors outline-none select-none text-foreground hover:bg-hover hover:text-foreground size-7 rounded-lg [&_svg:not([class*=\'size-\'])]:size-4 shrink-0';
104
+ btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-table size-3.5" aria-hidden="true"><path d="M12 3v18"></path><path d="M3 9h18"></path><path d="M3 15h18"></path><path d="M5 21h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2"></path></svg>';
105
+ btn.addEventListener('click', (e) => {
106
+ e.stopPropagation();
107
+ onClick();
108
+ });
109
+ return btn;
110
+ }
111
+
112
+ export function startTableCopy() {
113
+ if (installed || typeof document === 'undefined') return;
114
+ installed = true;
115
+ ensureStyle();
116
+
117
+ // 定位工具条对应的表格:工具条与表格在同一个包裹容器(.my-0.flex 容器,
118
+ // 官方结构)里;先在兄弟里找,找不到再向上两层内找
119
+ const tableOf = (bar) => {
120
+ let scope = bar.parentElement;
121
+ for (let i = 0; i < 3 && scope; i++) {
122
+ const table = scope.querySelector('table');
123
+ if (table) return table;
124
+ scope = scope.parentElement;
125
+ }
126
+ return null;
127
+ };
128
+
129
+ const enhance = (bar) => {
130
+ if (bar.dataset.zcodeproTableCopy) return;
131
+ bar.dataset.zcodeproTableCopy = '1';
132
+ const table = tableOf(bar);
133
+ if (!table) return; // 没有对应表格就没意义(工具条总在表格旁,防御而已)
134
+ bar.append(makeButton(() => { void copyTable(table); }));
135
+ };
136
+
137
+ const scan = () => {
138
+ for (const bar of document.querySelectorAll('[data-markdown-table-toolbar]')) enhance(bar);
139
+ };
140
+ scan();
141
+ // 会话滚动/新回答渲染都会新增表格:body 子树观察器兜底(现有各功能同款模式)
142
+ void getConfig().then((cfg) => { enabled = cfg.features ? cfg.features.tableCopy !== false : true; }).catch(() => {});
143
+ window.addEventListener('zcodepro:config-changed', () => {
144
+ void getConfig(true).then((cfg) => { enabled = cfg.features ? cfg.features.tableCopy !== false : true; }).catch(() => {});
145
+ });
146
+ const observer = new MutationObserver(() => { if (enabled) scan(); });
147
+ observer.observe(document.body, { childList: true, subtree: true });
148
+ }
@@ -32,8 +32,9 @@ const attempted = new Set(); // 已处理过(成功或失败)的会话 id,
32
32
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
33
33
 
34
34
  function sessIdOf(key) {
35
- // 会话键格式 <workspace_path>:<sess_id>;sess 段固定以 "sess_" 开头(见 session-switch.js)
36
- const i = key.indexOf(':sess_');
35
+ // 会话键格式 <workspace_path>:<task_id>;task_id 有 sess_ 与 session_ 两种
36
+ // 前缀,按最后一个 ':' 切(见 session-switch.js 的 workspaceOf)
37
+ const i = key.lastIndexOf(':');
37
38
  return i > 0 ? key.slice(i + 1) : '';
38
39
  }
39
40