zcode-pro 1.7.0 → 1.8.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,367 @@
1
+ // 设置弹窗的“导入会话”标签页:列出来源会话、筛选、多选导入。
2
+ import { h, t, rpc, errText } from '../core.js';
3
+ import { btnSmall, showToast } from '../ui.js';
4
+ import { findServices } from './ws-running.js';
5
+
6
+ const INPUT_CLS = 'h-8 w-full rounded-lg border border-border bg-input px-2.5 text-ui-sm text-foreground outline-none transition-shadow placeholder:text-foreground-subtle focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40';
7
+
8
+ function tag(text, title = '') {
9
+ return h('span', { class: 'shrink-0 rounded border border-border px-1 text-ui-xs text-foreground-subtle', title: title || undefined }, text);
10
+ }
11
+
12
+ function when(ms) {
13
+ if (!ms) return '';
14
+ try { return new Date(ms).toLocaleString(); } catch { return ''; }
15
+ }
16
+
17
+ export function createSessionImportPane() {
18
+ const L = t();
19
+ const root = h('div', { role: 'tabpanel', style: 'display:none' });
20
+
21
+ let sources = [];
22
+ let active = '';
23
+ let sessions = [];
24
+ let selected = new Set();
25
+ let projects = [];
26
+ let projectId = '';
27
+ let showAll = false;
28
+ let onlyProject = false;
29
+ let search = '';
30
+ let loading = false;
31
+ let importing = false;
32
+ let loaded = false;
33
+ let pendingReload = false;
34
+ let searchTimer = null;
35
+
36
+ const statusEl = h('div', { class: 'mt-2 min-h-4 text-ui-xs/relaxed text-foreground-subtle' });
37
+ const listEl = h('div', { class: 'max-h-80 overflow-auto divide-y divide-border' });
38
+ const sourceTabs = h('div', { role: 'tablist', 'aria-orientation': 'horizontal', class: 'zcodepro-tablist' });
39
+ const searchInput = h('input', {
40
+ type: 'text', class: INPUT_CLS + ' min-w-0 flex-1', placeholder: L.importSearch,
41
+ spellcheck: 'false', autocomplete: 'off',
42
+ });
43
+ const projectSelect = h('select', { class: INPUT_CLS + ' min-w-0 max-w-56' });
44
+ const onlyProjectBox = h('input', { type: 'checkbox' });
45
+ const showAllBox = h('input', { type: 'checkbox', title: L.importShowAllTip });
46
+ const selectAllBox = h('input', { type: 'checkbox' });
47
+ const refreshBtn = btnSmall(L.importRefresh, () => { void loadList(); });
48
+ const importBtn = btnSmall(L.importSelected.replace('{n}', '0'), () => { void doImport(); }, 'shrink-0', 'primary');
49
+ importBtn.disabled = true;
50
+
51
+ const setStatus = (text, kind = '') => {
52
+ statusEl.textContent = text || '';
53
+ statusEl.className = 'mt-2 min-h-4 text-ui-xs/relaxed '
54
+ + (kind === 'error' ? 'text-destructive' : 'text-foreground-subtle');
55
+ };
56
+
57
+ const selectedProject = () => projects.find((p) => p.id === projectId) || null;
58
+ const projectRoots = () => (selectedProject()?.roots || []).map((r) => r.path).filter(Boolean);
59
+
60
+ // 侧边栏的任务树由页面里的控制器维护,直接写库不会通知它。导入完成后在 React
61
+ // 树里找到持有 tree/factTree 的控制器,调用它的 refresh(),项目列表和“任务”
62
+ // 区就会重新拉取;任务索引里已经写了 unread_at,原生未读蓝点随之出现。
63
+ const refreshTaskTree = async () => {
64
+ const rootEl = document.getElementById('root');
65
+ const containerKey = rootEl && Object.keys(rootEl).find((k) => k.startsWith('__reactContainer$'));
66
+ if (!containerKey) return false;
67
+ const seen = new Set();
68
+ let found = null;
69
+ const scan = (o) => {
70
+ if (!o || typeof o !== 'object' || seen.has(o) || found) return;
71
+ seen.add(o);
72
+ try {
73
+ if (typeof o.refresh === 'function' && 'factTree' in o && 'tree' in o) found = o;
74
+ } catch { /* ignore */ }
75
+ };
76
+ let visited = 0;
77
+ const visit = (f) => {
78
+ if (!f || found || visited > 60000) return;
79
+ visited++;
80
+ for (const h of [f.memoizedProps, f.memoizedState]) {
81
+ if (!h || typeof h !== 'object') continue;
82
+ scan(h);
83
+ for (const v of Object.values(h)) if (v && typeof v === 'object') scan(v);
84
+ }
85
+ visit(f.child);
86
+ visit(f.sibling);
87
+ };
88
+ visit(rootEl[containerKey]);
89
+ if (!found) return false;
90
+ try {
91
+ await found.refresh();
92
+ return true;
93
+ } catch {
94
+ return false;
95
+ }
96
+ };
97
+
98
+ // 导入任务只写了库,对应会话的工作区没有准备过,任务列表服务里没有这个来源;
99
+ // 用户点归档/置顶/未读时 mutation 会报“无法解析唯一 source”。导入后对每个
100
+ // 来源工作区恢复一次会话,注册工作区,再做树刷新,让原生操作可用。
101
+ const prepareWorkspaces = async (imported) => {
102
+ const ag = findServices()?.zcodeAgentService;
103
+ if (!ag || typeof ag.resumeSession !== 'function') return;
104
+ const seen = new Set();
105
+ for (const item of imported) {
106
+ if (!item.workspace || seen.has(item.workspace)) continue;
107
+ seen.add(item.workspace);
108
+ try {
109
+ await ag.resumeSession({ workspacePath: item.workspace, sessionId: item.taskId });
110
+ } catch { /* 单个工作区准备失败不影响其他 */ }
111
+ }
112
+ };
113
+
114
+ const renderSources = () => {
115
+ sourceTabs.replaceChildren(...sources.filter((s) => s.available).map((s) => h('button', {
116
+ type: 'button', role: 'tab', class: 'zcodepro-tab',
117
+ 'aria-selected': String(active === s.id),
118
+ 'data-state': active === s.id ? 'active' : 'inactive',
119
+ disabled: !s.available,
120
+ title: s.available ? '' : L.importSourceMissing,
121
+ onClick: () => {
122
+ if (!s.available || active === s.id) return;
123
+ active = s.id;
124
+ selected = new Set();
125
+ sessions = [];
126
+ renderSources();
127
+ void loadList();
128
+ },
129
+ }, s.label)));
130
+ };
131
+
132
+ const selectable = () => sessions.filter((s) => !s.imported);
133
+ const allSelected = () => {
134
+ const list = selectable();
135
+ return list.length > 0 && list.every((s) => selected.has(s.sessionId));
136
+ };
137
+
138
+ const renderList = () => {
139
+ selectAllBox.checked = allSelected();
140
+ selectAllBox.disabled = importing || !selectable().length;
141
+ importBtn.textContent = L.importSelected.replace('{n}', String(selected.size));
142
+ importBtn.disabled = importing || !selected.size;
143
+ if (loading) {
144
+ listEl.replaceChildren(h('div', { class: 'px-3 py-6 text-center text-ui-sm text-foreground-subtle' }, L.importLoading));
145
+ return;
146
+ }
147
+ if (!sessions.length) {
148
+ listEl.replaceChildren(h('div', { class: 'px-3 py-6 text-center text-ui-sm text-foreground-subtle' }, L.importNoSessions));
149
+ return;
150
+ }
151
+ listEl.replaceChildren(...sessions.map((s) => {
152
+ const checked = selected.has(s.sessionId);
153
+ const box = h('input', {
154
+ type: 'checkbox', class: 'mt-0.5 shrink-0', checked,
155
+ disabled: importing || s.imported,
156
+ onChange: () => {
157
+ if (box.checked) selected.add(s.sessionId);
158
+ else selected.delete(s.sessionId);
159
+ renderList();
160
+ },
161
+ });
162
+ const tags = [];
163
+ if (s.imported) {
164
+ tags.push(tag(
165
+ s.importedArchived ? L.importAlreadyArchived : L.importAlready,
166
+ s.importedArchived ? L.importArchivedTaskTip : '',
167
+ ));
168
+ }
169
+ if (s.archived) tags.push(tag(L.importArchived));
170
+ if (s.subagent) tags.push(tag(L.importSubagent));
171
+ if (s.codexImport) tags.push(tag(L.importCodexCopy));
172
+ if (s.large) tags.push(tag(L.importLarge));
173
+ if (s.cwdExists === false) tags.push(tag(L.importCwdMissing));
174
+ return h('label', {
175
+ class: 'flex cursor-pointer items-start gap-2 px-3 py-2 transition-colors hover:bg-surface-hover',
176
+ title: s.cwd || '',
177
+ },
178
+ box,
179
+ h('div', { class: 'min-w-0 flex-1' },
180
+ h('div', { class: 'truncate text-ui-sm' }, s.title || s.sessionId),
181
+ h('div', { class: 'mt-0.5 flex items-center gap-2 overflow-hidden' },
182
+ h('span', { class: 'min-w-0 flex-1 truncate text-ui-xs text-foreground-subtle' }, s.cwd || s.sourcePath || ''),
183
+ h('span', { class: 'shrink-0 text-ui-xs text-foreground-subtle' }, when(s.updatedAt)),
184
+ ...tags)));
185
+ }));
186
+ };
187
+
188
+ const loadProjects = async () => {
189
+ const res = await rpc('/projects-v2');
190
+ projects = res.ok && Array.isArray(res.projects) ? res.projects : [];
191
+ const current = projectId;
192
+ projectSelect.replaceChildren(
193
+ h('option', { value: '' }, L.importProjectNone),
194
+ ...projects.map((p) => h('option', { value: p.id }, p.name || p.id)),
195
+ );
196
+ projectSelect.value = projects.some((p) => p.id === current) ? current : '';
197
+ projectId = projectSelect.value;
198
+ onlyProjectBox.disabled = !projectId;
199
+ if (!projectId) { onlyProjectBox.checked = false; onlyProject = false; }
200
+ };
201
+
202
+ const loadList = async () => {
203
+ if (loading || importing) { pendingReload = true; return; }
204
+ loading = true;
205
+ renderList();
206
+ const done = () => {
207
+ loading = false;
208
+ if (pendingReload) {
209
+ pendingReload = false;
210
+ queueMicrotask(() => { void loadList(); });
211
+ }
212
+ };
213
+ if (!sources.length || !sources.some((s) => s.id === active && s.available)) {
214
+ const meta = await rpc('/import/list', { method: 'POST', body: { source: '' } });
215
+ if (meta.ok && Array.isArray(meta.sources)) sources = meta.sources;
216
+ if (!sources.some((s) => s.id === active && s.available)) {
217
+ active = (sources.find((s) => s.available) || {}).id || '';
218
+ }
219
+ renderSources();
220
+ if (!active) {
221
+ sessions = [];
222
+ done();
223
+ renderList();
224
+ setStatus(L.importNoSource);
225
+ return;
226
+ }
227
+ }
228
+ const res = await rpc('/import/list', {
229
+ method: 'POST',
230
+ body: {
231
+ source: active, showAll, search,
232
+ roots: onlyProject && projectId ? projectRoots() : [],
233
+ },
234
+ });
235
+ if (!res.ok) {
236
+ sessions = [];
237
+ done();
238
+ renderList();
239
+ setStatus(errText(res), 'error');
240
+ return;
241
+ }
242
+ sources = res.sources || sources;
243
+ sessions = res.sessions || [];
244
+ const usable = new Set(selectable().map((s) => s.sessionId));
245
+ selected = new Set([...selected].filter((id) => usable.has(id)));
246
+ if (!active || !sources.some((s) => s.id === active)) {
247
+ active = (sources.find((s) => s.available) || {}).id || '';
248
+ }
249
+ done();
250
+ renderSources();
251
+ renderList();
252
+ setStatus(res.unavailable ? L.importNoSource : '');
253
+ };
254
+
255
+ const doImport = async () => {
256
+ if (importing || !selected.size) return;
257
+ const chosen = sessions.filter((s) => selected.has(s.sessionId));
258
+ if (!chosen.length) return;
259
+ if (chosen.some((s) => s.large)) {
260
+ if (!window.confirm(L.importConfirmLarge)) return;
261
+ }
262
+ importing = true;
263
+ renderList();
264
+ setStatus(L.importImporting);
265
+ let summary = '';
266
+ let summaryKind = '';
267
+ try {
268
+ const res = await rpc('/import/run', {
269
+ method: 'POST',
270
+ body: {
271
+ source: active,
272
+ projectId: projectId || null,
273
+ items: chosen.map((s) => ({
274
+ sessionId: s.sessionId, sourcePath: s.sourcePath, title: s.title, cwd: s.cwd,
275
+ })),
276
+ },
277
+ });
278
+ if (!res.ok) {
279
+ setStatus(errText(res), 'error');
280
+ showToast(L.importFailed + ': ' + errText(res), 'error');
281
+ return;
282
+ }
283
+ const imported = Array.isArray(res.imported) ? res.imported : [];
284
+ const skipped = Array.isArray(res.skipped) ? res.skipped : [];
285
+ const failed = Array.isArray(res.failed) ? res.failed : [];
286
+ const msg = L.importDone.replace('{ok}', String(imported.length))
287
+ .replace('{skip}', String(skipped.length)).replace('{fail}', String(failed.length));
288
+ const detail = failed.slice(0, 3).map((f) => `${f.sessionId}: ${f.error}`).join('; ');
289
+ summary = msg + (detail ? ' · ' + detail : '');
290
+ summaryKind = failed.length ? 'error' : '';
291
+ showToast(msg, failed.length ? 'error' : 'success');
292
+ if (imported.length) {
293
+ void (async () => {
294
+ await prepareWorkspaces(imported);
295
+ await refreshTaskTree().catch(() => {});
296
+ })();
297
+ }
298
+ selected = new Set();
299
+ } finally {
300
+ importing = false;
301
+ }
302
+ await loadList();
303
+ setStatus(summary, summaryKind);
304
+ };
305
+
306
+ searchInput.addEventListener('input', () => {
307
+ search = searchInput.value;
308
+ clearTimeout(searchTimer);
309
+ searchTimer = setTimeout(() => { void loadList(); }, 250);
310
+ });
311
+ projectSelect.addEventListener('change', () => {
312
+ projectId = projectSelect.value;
313
+ onlyProjectBox.disabled = !projectId;
314
+ if (!projectId) { onlyProjectBox.checked = false; onlyProject = false; }
315
+ void loadList();
316
+ });
317
+ onlyProjectBox.addEventListener('change', () => {
318
+ onlyProject = onlyProjectBox.checked;
319
+ void loadList();
320
+ });
321
+ showAllBox.addEventListener('change', () => {
322
+ showAll = showAllBox.checked;
323
+ selected = new Set();
324
+ void loadList();
325
+ });
326
+ selectAllBox.addEventListener('change', () => {
327
+ if (selectAllBox.checked) selected = new Set(selectable().map((s) => s.sessionId));
328
+ else selected = new Set();
329
+ renderList();
330
+ });
331
+
332
+ const checkLabel = (box, text, title = '') => h('label', { class: 'flex shrink-0 items-center gap-1.5 text-ui-xs text-foreground-subtle', title: title || undefined }, box, text);
333
+
334
+ root.append(
335
+ h('p', { class: 'text-ui-sm/relaxed text-foreground-subtle' }, L.importDesc),
336
+ h('div', { class: 'mt-3' }, sourceTabs),
337
+ h('div', { class: 'mt-2 flex flex-wrap items-center gap-2' },
338
+ searchInput,
339
+ projectSelect,
340
+ checkLabel(onlyProjectBox, L.importOnlyProject),
341
+ checkLabel(showAllBox, L.importShowAll, L.importShowAllTip),
342
+ refreshBtn),
343
+ h('div', { class: 'mt-2 flex items-center justify-between gap-2' },
344
+ h('div', { class: 'flex items-center gap-2' },
345
+ checkLabel(selectAllBox, L.importSelectAll),
346
+ h('span', { class: 'text-ui-xs text-foreground-subtle' }, L.importProjectHint)),
347
+ importBtn),
348
+ h('div', { class: 'mt-2 rounded-xl border border-border' }, listEl),
349
+ statusEl,
350
+ );
351
+
352
+ root.__onShow = () => {
353
+ if (importing) return;
354
+ if (!loaded) {
355
+ loaded = true;
356
+ setStatus(L.importLoading);
357
+ void (async () => {
358
+ await loadProjects();
359
+ await loadList();
360
+ })();
361
+ } else {
362
+ void loadList();
363
+ }
364
+ };
365
+
366
+ return root;
367
+ }
@@ -9,6 +9,7 @@ import { applyStyles, STYLE_DEFAULTS, showStyleHighlight, hideStyleHighlight } f
9
9
  import { THEME_SKINS, CUSTOM_DEFAULTS } from './theme.js';
10
10
  import { copyToClipboard, hCopyIcon } from './copy-path.js';
11
11
  import { claimAutoUpdateRun } from './plugin-updates.js';
12
+ import { createSessionImportPane } from './session-import.js';
12
13
 
13
14
  // 调宿主桥在系统浏览器打开外链;宿主没暴露该能力时静默忽略
14
15
  function openExternal(url) {
@@ -395,6 +396,11 @@ export function openSettingsDialog() {
395
396
  if (await setFeature('composerProvider', next)) f.composerProvider = next;
396
397
  refreshRows();
397
398
  }),
399
+ settingRow(L.featureSessionImport, L.featureSessionImportDesc, f.sessionImport !== false, async () => {
400
+ const next = !(f.sessionImport !== false);
401
+ if (await setFeature('sessionImport', next)) f.sessionImport = next;
402
+ refreshRows();
403
+ }),
398
404
  settingRow(L.featureSandboxReclaim, L.featureSandboxReclaimDesc, f.sandboxReclaim !== false, async () => {
399
405
  const next = !(f.sandboxReclaim !== false);
400
406
  if (await setFeature('sandboxReclaim', next)) f.sandboxReclaim = next;
@@ -597,12 +603,13 @@ export function openSettingsDialog() {
597
603
  const paneAgents = h('div', { role: 'tabpanel', style: 'display:none' });
598
604
  const paneProxy = h('div', { role: 'tabpanel', style: 'display:none' });
599
605
  const paneSync = h('div', { role: 'tabpanel', style: 'display:none' });
606
+ const paneImport = createSessionImportPane();
600
607
  const paneVision = h('div', { role: 'tabpanel', style: 'display:none' });
601
608
  const paneRtk = h('div', { role: 'tabpanel', style: 'display:none' });
602
609
  const paneHeadroom = h('div', { role: 'tabpanel', style: 'display:none' });
603
610
  const paneTitleGen = h('div', { role: 'tabpanel', style: 'display:none' });
604
611
  const paneDebug = h('div', { role: 'tabpanel', style: 'display:none' });
605
- const panes = { features: paneFeatures, shortcuts: paneShortcuts, styles: paneStyles, perf: panePerf, agents: paneAgents, proxy: paneProxy, sync: paneSync, vision: paneVision, headroom: paneHeadroom, rtk: paneRtk, debug: paneDebug };
612
+ 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 };
606
613
  // 一级 tab 顺序:功能 → 外观 → 行为 → 性能 → 快捷键 → 代理/同步/插件页
607
614
  const tabDefs = [
608
615
  ['features', L.tabFeatures],
@@ -612,6 +619,7 @@ export function openSettingsDialog() {
612
619
  ['shortcuts', L.tabShortcuts],
613
620
  ['proxy', L.tabProxy],
614
621
  ['sync', L.tabSync],
622
+ ...(config.features.sessionImport !== false ? [['import', L.tabImport]] : []),
615
623
  ['vision', L.tabVision],
616
624
  ['headroom', L.tabHeadroom],
617
625
  ['rtk', L.tabRtk],
@@ -633,6 +641,7 @@ export function openSettingsDialog() {
633
641
  if (name !== 'shortcuts' && hkRecording) stopHkRecording();
634
642
  for (const [id, pane] of Object.entries(panes)) pane.style.display = id === name ? '' : 'none';
635
643
  for (const [id, bar] of Object.entries(subTabBars)) bar.style.display = id === name ? '' : 'none';
644
+ if (name === 'import') paneImport.__onShow?.();
636
645
  renderTabs();
637
646
  };
638
647
  renderTabs();
@@ -1304,6 +1313,10 @@ export function openSettingsDialog() {
1304
1313
  void saveTheme({ bg: { dialogFrost: !(themeCfg.bg.dialogFrost !== false) } });
1305
1314
  });
1306
1315
  };
1316
+ // 插件卡片遮罩:壁纸开着时垫在插件卡片页底下的主题色遮罩,
1317
+ // 0 = 壁纸原样透出,越大卡片越实在、越暗。默认 20%。没壁纸时整行不显示
1318
+ const cardVeilRow = () => sliderRow(L.themeBgCardVeil, '', 0, 100, 1, Math.round(numOr(themeCfg.bg.cardVeil, 0.2) * 100), '%',
1319
+ (v) => { void saveTheme({ bg: { cardVeil: v / 100 } }); }, L.themeBgCardVeilHint);
1307
1320
  // 图片网址输入:change 提交;空值回无壁纸
1308
1321
  const urlInput = h('input', { type: 'url', value: themeCfg.bg.url, class: themeInputCls, placeholder: 'https://...' });
1309
1322
  urlInput.addEventListener('change', () => {
@@ -1448,6 +1461,7 @@ export function openSettingsDialog() {
1448
1461
  pauseCheck('pauseOnHidden', L.themeBgPauseHidden),
1449
1462
  pauseCheck('pauseOnBlur', L.themeBgPauseBlur),
1450
1463
  pauseCheck('pauseOnBattery', L.themeBgPauseBattery)),
1464
+ themeCfg.bg.mode !== 'none' ? cardVeilRow() : null,
1451
1465
  dialogFrostRow())),
1452
1466
  bgInput,
1453
1467
  );
@@ -3384,6 +3398,7 @@ export function openSettingsDialog() {
3384
3398
  panePerf,
3385
3399
  paneProxy,
3386
3400
  paneSync,
3401
+ paneImport,
3387
3402
  paneVision,
3388
3403
  paneHeadroom,
3389
3404
  paneRtk,
@@ -16,7 +16,8 @@ let tickSeq = 0; // 在途请求序号:过期响应丢弃,不覆盖新值
16
16
 
17
17
  // 流式输出速率估算:usage 缺失的模型(部分供应商不回传 token 数)和长调用
18
18
  // 生成期间没有真实数据,按最后一行回答的文本增长估算(约 2 字符/token 折算,
19
- // 标 ≈)。调用完成后有真实 usage 的会话切回真实值,没有的停在最后的估算值
19
+ // 标 ≈)。长调用生成中官方 60 秒窗口值要等调用结束才更新,会长时间不动;
20
+ // 文本在增长时优先用估算,流停止后切回官方真实值
20
21
  const EST_CHARS_PER_TOKEN = 2;
21
22
  let streamSample = null; // 上一次采样 { len, at }
22
23
  let streamEst = null; // 最近一次估算 { value, at }
@@ -220,17 +221,23 @@ function itemContent(id, L) {
220
221
  // 官方净生成口径:本会话树(含子代理)最近 60 秒窗内主轮请求的
221
222
  // Σ输出 ÷ Σ净生成秒数(与 Token 调试/每轮标注同款公式);usage 全缺
222
223
  //(供应商不回传 token)才用文本增长估算兜底——估算按 2 字符/token 折算,
223
- // 实测虚高 2-4 倍,有真实数据时绝不能让它抢显示
224
+ // 实测虚高 2-4 倍,有真实数据时绝不能让它抢显示。
225
+ // 例外:长调用正在生成时官方值要等调用结束才更新,文本还在增长的这
226
+ // 几秒内先用估算,流停止后自动切回官方值
224
227
  const s = (lastStats && statsSid === sid) ? lastStats.sessionSummary : null;
225
228
  const tps = s && s.tps != null ? s.tps : null;
226
229
  const est = streamEst ? streamEst.value : null;
227
- const shown = tps != null ? tps : est;
230
+ const streaming = !!(streamEst && Date.now() - streamEst.at < 5000);
231
+ const useEst = streaming && est != null;
232
+ const shown = useEst ? est : (tps != null ? tps : est);
228
233
  if (shown == null) return null;
229
234
  const zh = isZhLocale();
230
- const estMark = tps == null && est != null ? '≈' : '';
231
- const detail = tps != null
232
- ? `${L.sbLabelOut} ${tps.toLocaleString()} tok/s${zh ? '(官方净生成口径,本会话树)' : ' (net generation, session tree)'}`
233
- : (zh ? '无 usage 数据,按文本增长估算' : 'no usage data, estimated from text growth');
235
+ const estMark = useEst || tps == null ? '≈' : '';
236
+ const detail = useEst
237
+ ? (zh ? '流式生成中,按文本增长估算(约 2 字符/token)' : 'streaming; estimated from text growth (~2 chars/token)')
238
+ : tps != null
239
+ ? `${L.sbLabelOut} ${tps.toLocaleString()} tok/s${zh ? '(官方净生成口径,本会话树)' : ' (net generation, session tree)'}`
240
+ : (zh ? '无 usage 数据,按文本增长估算' : 'no usage data, estimated from text growth');
234
241
  return {
235
242
  html: sbIcon('tokRate') + label(L.sbLabelOut) + `<b>${estMark}${fmtNum(Math.round(shown * 10) / 10)} tok/s</b>`,
236
243
  title: `${L.sbItemTokRate}${zh ? '(本会话):' : ' (this session): '}${detail}`,
@@ -311,34 +318,59 @@ function renderBar() {
311
318
  barEl.style.marginBottom = hasSession ? '-14px' : '0';
312
319
  barEl.style.paddingBottom = hasSession ? '0' : '7px';
313
320
  const L = t();
314
- const parts = [];
315
- let lastGroup = '';
321
+ const entries = [];
316
322
  for (const it of items) {
317
323
  if (!it.on) continue;
318
324
  const c = itemContent(it.id, L);
319
325
  if (!c) continue;
320
- const group = GLOBAL_GROUP.has(it.id) ? 'g' : 's';
321
- // 会话项与全局项之间用竖线分隔(比项间的 · 更强的分界)
322
- if (lastGroup && group !== lastGroup) parts.push('<span class="zcodepro-statusbar-groupsep"></span>');
323
- lastGroup = group;
324
- parts.push(`<span title="${c.title.replace(/"/g, '&quot;')}"${c.tone ? ` data-tone="${c.tone}"` : ''}>${c.html}</span>`);
326
+ entries.push({ id: it.id, group: GLOBAL_GROUP.has(it.id) ? 'g' : 's', ...c });
325
327
  }
326
- // 组内项之间用 ·,跨组竖线两侧不再叠加 ·
328
+ // 会话项与全局项之间用竖线分隔(比项间的 · 更强的分界);组内项之间用 ·,
329
+ // 跨组竖线两侧不再叠加 ·。隐藏的项在拼 html 之前就排除,圆点与竖线随
330
+ // 重建渲染,不会悬空在行首行尾
327
331
  const SEP = '<span class="zcodepro-statusbar-sep">·</span>';
328
332
  const GROUPSEP = '<span class="zcodepro-statusbar-groupsep"></span>';
333
+ const buildHtml = (hidden) => {
334
+ const parts = [];
335
+ let lastGroup = '';
336
+ for (const e of entries) {
337
+ if (hidden.has(e.id)) continue;
338
+ if (lastGroup && e.group !== lastGroup) parts.push(GROUPSEP);
339
+ lastGroup = e.group;
340
+ parts.push(`<span title="${e.title.replace(/"/g, '&quot;')}"${e.tone ? ` data-tone="${e.tone}"` : ''}>${e.html}</span>`);
341
+ }
342
+ return parts.reduce((acc, p, i) => {
343
+ if (i === 0) return p;
344
+ if (p === GROUPSEP || parts[i - 1] === GROUPSEP) return acc + p;
345
+ return acc + SEP + p;
346
+ }, '');
347
+ };
329
348
  // 数值没变就不重写 DOM:每 2 秒 tick 全量重建会在流式渲染期持续触发布局
330
349
  //(CPU 剖析中 renderBar 是我们唯一上榜的函数)
331
- const html = parts.reduce((acc, p, i) => {
332
- if (i === 0) return p;
333
- if (p === GROUPSEP || parts[i - 1] === GROUPSEP) return acc + p;
334
- return acc + SEP + p;
335
- }, '');
336
- barEl.style.display = parts.length ? '' : 'none';
337
- if (html === lastRenderedHtml) return;
338
- lastRenderedHtml = html;
339
- barEl.innerHTML = html;
350
+ // 超宽自适应:单行不折行,放不下就按 HIDE_ORDER 隐藏次要项直到放下;
351
+ // 输出/平均命中/上下文 三项不参与隐藏(必够放)
352
+ const hidden = new Set();
353
+ for (let guard = 0; guard <= HIDE_ORDER.length; guard++) {
354
+ const html = buildHtml(hidden);
355
+ barEl.style.display = html ? '' : 'none';
356
+ if (html !== lastRenderedHtml) {
357
+ lastRenderedHtml = html;
358
+ barEl.innerHTML = html;
359
+ }
360
+ // 子项 flex-shrink:0,子项宽度求和即真实内容宽(scrollWidth 量不出被压缩的)
361
+ const gap = 8;
362
+ let sum = 0;
363
+ for (const c of barEl.children) sum += c.getBoundingClientRect().width + gap;
364
+ if (sum - gap <= host.clientWidth + 2) break;
365
+ const next = HIDE_ORDER.find((id) => !hidden.has(id));
366
+ if (!next) break;
367
+ hidden.add(next);
368
+ }
340
369
  }
341
370
 
371
+ // 超宽时的隐藏顺序(先隐左边的):剩 输出/平均命中/上下文 三项必够放
372
+ const HIDE_ORDER = ['tasks', 'questions', 'totalTokens', 'todayTokens', 'inOut'];
373
+
342
374
  async function tick() {
343
375
  if (!enabled || document.hidden) return;
344
376
  refreshOfficial();
@@ -74,6 +74,15 @@ function buildCss(styles) {
74
74
  // 工具/状态卡片(“N 个文件已更改”等)上方间距下限 8px:
75
75
  // 段落间距调到 0 时也不至于贴死(gap 与 margin 在弹性布局里相加)
76
76
  `${CONV} .flex.flex-col.gap-5 > [data-slot="collapsible"]{margin-block-start:max(0px, calc(8px - ${n}px)) !important;margin-top:max(0px, calc(8px - ${n}px)) !important;}`,
77
+ // 3.18 的“工作中”槽位带 -8px 上边距(默认 gap 20 → 实际 12px);行间距调小后
78
+ // 这层负边距会把槽位拉得贴住上面的内容(gap 7 → 实际 -1px)。清掉负边距,
79
+ // 让它跟其它块一样按设置的行间距排
80
+ `${CONV} .flex.flex-col.gap-5 > [data-zcode-chat-loading-slot]:not(:first-child){margin-block-start:0 !important;margin-top:0 !important;}`,
81
+ // 过程视图(思考/工具摘要/过程正文)的行块:应用给容器 4px gap + 每行
82
+ // 12px 上内边距(共 16px)。段落间距设置时直接接管:gap 归零、上内边距
83
+ // 按设置值,总间距等于设置值(设 0 就完全贴紧)
84
+ `${CONV} [data-conversation-work-items]{gap:0 !important;}`,
85
+ `${CONV} [data-conversation-work-items] > * + *{padding-top:${n}px !important;}`,
77
86
  );
78
87
  }
79
88
  // 特殊块(列表/引用块/表格)自身间距项未设置时跟随段落间距,
@@ -140,12 +149,24 @@ function buildCss(styles) {
140
149
  }
141
150
  const tlh = styles.thinkingLineHeight;
142
151
  if (typeof tlh === 'number' && Number.isFinite(tlh) && tlh >= 0.8) {
143
- // “思考行高”管“已工作/工作中 N 秒”过程视图的行距(读取/编辑/查阅/终端等
144
- // 条目行、流式思考预览,默认 1.5):行高挂在历史内容容器上由各行继承;
145
- // 过程里的叙述正文走 .space-y-4(回答行高,选择器更具体压过这里的继承)。
146
- // 单独展开的“思考·持续了 N 秒”块内内容不在此设置范围内
152
+ // “思考行高”管“已工作/工作中 N 秒”过程视图与思考正文的行距(读取/编辑/查阅/
153
+ // 终端条目行、流式思考预览,默认 1.5):行高挂在历史内容容器上由各行继承;
154
+ // 过程里的叙述正文(.space-y-4)按“已工作展开块内算思考”的规则也走思考行高
147
155
  parts.push(
148
156
  `[data-testid^="chat-assistant-history-content"]{line-height:${tlh} !important;}`,
157
+ // 历史回合顶部的“已工作 N 秒”触发行在历史内容容器外,按钮自带 text-ui-base
158
+ // 的行高,只靠容器继承改不到;直接覆盖,否则调“思考行高”时这行不变
159
+ `[class~="group/history-message"]{line-height:${tlh} !important;}`,
160
+ // 用户要求:“已工作”展开块内的内容算思考,块外的才算回答。
161
+ // 历史视图整轮消息(含回答正文)都在历史内容容器里,容器内的 .space-y-4
162
+ // 改用思考行高;正在回答的回合里,展开块外的回答正文仍用回答行高。
163
+ // 放在回答行高规则之后(同特异性,后写的生效)
164
+ `[data-testid^="chat-assistant-history-content"] .space-y-4{line-height:${tlh} !important;}`,
165
+ `[data-conversation-work-items] .space-y-4{line-height:${tlh} !important;}`,
166
+ // 3.18 实时回合的思考正文与“工作中”行在历史容器外,且自带 text-ui-base 的
167
+ // 行高,只靠继承改不动;直接覆盖,调“思考行高”时正在生成的回合也生效
168
+ `[data-testid="chat-reasoning-content"] .whitespace-pre-wrap{line-height:${tlh} !important;}`,
169
+ `[data-testid="chat-loading"] *{line-height:${tlh} !important;}`,
149
170
  );
150
171
  }
151
172
  const ulh = styles.userLineHeight;
@@ -275,10 +296,9 @@ const HL_SELECTORS = {
275
296
  tableCellPaddingV: `${CONV} td, ${CONV} th`,
276
297
  tableCellPaddingH: `${CONV} td, ${CONV} th`,
277
298
  codeLineHeight: `${CONV} diffs-container, ${CONV} pre`,
278
- lineHeight: `${CONV} .space-y-4:not([data-reasoning-content] *)`,
279
- // 思考行高作用在“已工作/工作中”过程视图容器上;视图折叠未挂载时不标
280
- // (触发行不属此设置范围,不额外描边)
281
- thinkingLineHeight: `[data-testid^="chat-assistant-history-content"]`,
299
+ lineHeight: `${CONV} .space-y-4:not([data-reasoning-content] *):not([data-testid^="chat-assistant-history-content"] *):not([data-conversation-work-items] *)`,
300
+ // 思考行高作用在“已工作/工作中”过程视图、触发行与思考正文上;视图折叠未挂载时不标
301
+ thinkingLineHeight: `[data-testid^="chat-assistant-history-content"], [class~="group/history-message"], [data-testid="chat-loading"], [data-testid="chat-reasoning-content"]`,
282
302
  userLineHeight: `${CONV} [class*="user-row"] .whitespace-pre-wrap`,
283
303
  contentWidth: '[data-v4-timeline-content-column]',
284
304
  // 双结构:新侧栏项目行 / 旧 testid 行