dsh-vt-web-chat 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -2,11 +2,15 @@
2
2
  * Browser half of dsh-vt-web-chat.
3
3
  *
4
4
  * 面板里就是官方开源 chat-demo 的界面本身:插件把自己的 `/webchat/` 路由托管给同源
5
- * `iframe`,请求由 Host 用 DSH 的 DeepSeek 凭据代发。这里只负责三件事:
5
+ * `iframe`,请求由 Host 用 DSH 的 DeepSeek 凭据代发。这里负责三件事:
6
6
  * 侧栏入口、整页面板、设置页里的会话保留策略。
7
7
  *
8
- * 为什么不再用桌面壳的 webview 租约:本插件的页面由自己托管,
9
- * 不受站点 `frame-ancestors` 限制,Web 端与桌面端可以用同一条路径。
8
+ * 2.1 起多了一层「Chat 模式」:选中网页对话面板时,侧栏的品牌名、会话浏览区和底部动作
9
+ * 换成 Chat 自己的内容(历史、返回 Harness),离开面板时恢复宿主侧栏。接管只发生在
10
+ * 子座位(brand.name / workspaces / footer.action)上,宿主骨架与「新会话」按钮都保留。
11
+ *
12
+ * 为什么用模式切换而不是把面板做成独立窗口:历史与新建对话都在同一个 iframe 里,
13
+ * 侧栏只是它的导航面;两者由同一份状态驱动,用户不会看到两套互相不同步的列表。
10
14
  */
11
15
  window.__ModuleLoader__.load({
12
16
  id: 'dsh-vt-web-chat',
@@ -15,7 +19,7 @@ window.__ModuleLoader__.load({
15
19
  const h = React.createElement;
16
20
 
17
21
  const PLUGIN_ID = 'dsh-vt-web-chat';
18
- const VERSION = '2.0.0';
22
+ const VERSION = '2.1.0';
19
23
  const NS = PLUGIN_ID;
20
24
  /** 侧栏行与主面板共用的 id。 */
21
25
  const PANEL_ID = 'vt-web-chat';
@@ -23,6 +27,30 @@ window.__ModuleLoader__.load({
23
27
  const ROUTE_PREFIX = '/webchat';
24
28
  /** 保留天数档位;0 表示永不清理。 */
25
29
  const RETENTION_CHOICES = [30, 60, 90, 0];
30
+ /** 面板与宿主之间的消息来源标记。 */
31
+ const HOST_SOURCE = 'vt-webchat-host';
32
+ const SHELL_SOURCE = 'vt-webchat-shell';
33
+ /** 离开 Chat 模式时给侧栏留出的淡出时间,需与 CSS 里的退场动画一致。 */
34
+ const LEAVE_MS = 150;
35
+ /** 返回 Harness 时选中的主面板 key。 */
36
+ const CONVERSATION_PANEL = 'conversation';
37
+ /**
38
+ * 官方字标在 24px 高度下「deepseek」部分的像素宽度。
39
+ * 字标 SVG 的 viewBox 从 x=26 开始,HARNESS 徽标从 x=129.348 开始,
40
+ * 所以裁到 129.348 - 26 = 103.348px 时只剩下文字本身,徽标由我们自己画。
41
+ */
42
+ const WORDMARK_WIDTH = 103.35;
43
+
44
+ /**
45
+ * 官方品牌字标与鲸鱼标。取不到时品牌名退回纯文字、品牌标不接管,
46
+ * 不能因为一个可选依赖让整个侧栏起不来。
47
+ */
48
+ let primitives = null;
49
+ try {
50
+ primitives = require('@deepseek-ai/dsh-client-ui-primitives');
51
+ } catch (error) {
52
+ console.warn(`[${PLUGIN_ID}] shared UI primitives unavailable`, error);
53
+ }
26
54
 
27
55
  const DICT = {
28
56
  zh: {
@@ -31,6 +59,18 @@ window.__ModuleLoader__.load({
31
59
  'entry': '网页对话',
32
60
  'panel.title': '网页对话',
33
61
  'panel.hint': '滚动、复制、上传都在面板内完成;对话保存在本机,不会写入 DSH 会话。',
62
+ 'back': '返回 Harness',
63
+ 'back.hint': '退出 Chat 模式,回到 DSH 会话',
64
+ 'history.label': '对话历史',
65
+ 'history.today': '今天',
66
+ 'history.yesterday': '昨天',
67
+ 'history.week': '7 天内',
68
+ 'history.month': '30 天内',
69
+ 'history.empty': '还没有对话',
70
+ 'history.emptyHint': '点上方「新会话」开始第一个对话。',
71
+ 'history.error': '会话列表读取失败',
72
+ 'history.retry': '重试',
73
+ 'history.untitled': '新对话',
34
74
  'settings.nav': '网页对话',
35
75
  'settings.title': '会话保留',
36
76
  'settings.description': '超过所选天数没有继续聊的会话,会在下次打开面板时自动删除。',
@@ -52,6 +92,18 @@ window.__ModuleLoader__.load({
52
92
  'entry': 'Web Chat',
53
93
  'panel.title': 'Web Chat',
54
94
  'panel.hint': 'Scrolling, copying and uploads stay inside the panel; chats are stored locally and never written to a DSH session.',
95
+ 'back': 'Back to Harness',
96
+ 'back.hint': 'Leave Chat mode and return to your DSH session',
97
+ 'history.label': 'Chat history',
98
+ 'history.today': 'Today',
99
+ 'history.yesterday': 'Yesterday',
100
+ 'history.week': 'Previous 7 days',
101
+ 'history.month': 'Previous 30 days',
102
+ 'history.empty': 'No chats yet',
103
+ 'history.emptyHint': 'Start one with New Session above.',
104
+ 'history.error': 'Could not read the chat list',
105
+ 'history.retry': 'Retry',
106
+ 'history.untitled': 'New chat',
55
107
  'settings.nav': 'Web Chat',
56
108
  'settings.title': 'Chat retention',
57
109
  'settings.description': 'Chats untouched for longer than the chosen period are deleted the next time the panel opens.',
@@ -69,6 +121,321 @@ window.__ModuleLoader__.load({
69
121
  },
70
122
  };
71
123
 
124
+ // ---------------------------------------------------------------------
125
+ // 小状态仓库:React 用 useSyncExternalStore 订阅,侧栏与面板共用同一份快照。
126
+ // ---------------------------------------------------------------------
127
+
128
+ /**
129
+ * 建一个只放对象快照的订阅仓库。
130
+ * @param initial - 初始快照。
131
+ * @returns `{ get, set, subscribe }`。
132
+ */
133
+ function createStore(initial) {
134
+ let value = initial;
135
+ const listeners = new Set();
136
+ return {
137
+ get: () => value,
138
+ set: (next) => {
139
+ if (Object.is(next, value)) return;
140
+ value = next;
141
+ for (const listener of Array.from(listeners)) {
142
+ try {
143
+ listener();
144
+ } catch (error) {
145
+ console.error(`[${PLUGIN_ID}] store listener failed`, error);
146
+ }
147
+ }
148
+ },
149
+ subscribe: (listener) => {
150
+ listeners.add(listener);
151
+ return () => {
152
+ listeners.delete(listener);
153
+ };
154
+ },
155
+ };
156
+ }
157
+
158
+ /**
159
+ * 订阅仓库;宿主 React 一定带 useSyncExternalStore,缺失时退回 useState。
160
+ * @param store - createStore 的返回值。
161
+ * @returns 当前快照。
162
+ */
163
+ function useStore(store) {
164
+ if (typeof React.useSyncExternalStore === 'function') {
165
+ return React.useSyncExternalStore(store.subscribe, store.get, store.get);
166
+ }
167
+ const [value, setValue] = React.useState(store.get);
168
+ React.useEffect(() => store.subscribe(() => setValue(store.get())), [store]);
169
+ return value;
170
+ }
171
+
172
+ /** Chat 模式:active 接管侧栏,leaving 播放退场。 */
173
+ const surface = createStore({ active: false, leaving: false });
174
+ let leaveTimer = null;
175
+
176
+ /** 进入 Chat 模式;如果正在退场则取消退场。 */
177
+ function enterSurface() {
178
+ if (leaveTimer !== null) {
179
+ clearTimeout(leaveTimer);
180
+ leaveTimer = null;
181
+ }
182
+ const current = surface.get();
183
+ if (current.active && !current.leaving) return;
184
+ surface.set({ active: true, leaving: false });
185
+ }
186
+
187
+ /** 离开 Chat 模式:先淡出,再让宿主侧栏回来。 */
188
+ function leaveSurface() {
189
+ const current = surface.get();
190
+ if (!current.active || current.leaving) return;
191
+ surface.set({ active: true, leaving: true });
192
+ leaveTimer = setTimeout(() => {
193
+ leaveTimer = null;
194
+ surface.set({ active: false, leaving: false });
195
+ }, LEAVE_MS);
196
+ }
197
+
198
+ /** 立即恢复 Harness 侧栏,不走淡出。用于「返回 Harness」这种要求跟手的路径。 */
199
+ function exitSurfaceNow() {
200
+ if (leaveTimer !== null) {
201
+ clearTimeout(leaveTimer);
202
+ leaveTimer = null;
203
+ }
204
+ if (!surface.get().active) return;
205
+ surface.set({ active: false, leaving: false });
206
+ }
207
+
208
+ /**
209
+ * 返回 Harness 后,指针通常还停在原来的坐标上;新出现的额度环/DS Bot 返回
210
+ * 与返回行位置、hover 底色完全一样,轻微移动就会点亮,看起来像状态没释放。
211
+ * 这里短暂压掉这两行的 hover 底色,直到指针离开底栏或超时,再恢复正常。
212
+ */
213
+ let returnHoverTimer = null;
214
+ let returnHoverCleanup = null;
215
+ let returnHoverToken = 0;
216
+
217
+ function clearReturnedHover() {
218
+ returnHoverToken += 1;
219
+ document.documentElement.removeAttribute('data-vtwc-returning');
220
+ if (returnHoverTimer !== null) {
221
+ clearTimeout(returnHoverTimer);
222
+ returnHoverTimer = null;
223
+ }
224
+ if (returnHoverCleanup !== null) {
225
+ returnHoverCleanup();
226
+ returnHoverCleanup = null;
227
+ }
228
+ }
229
+
230
+ function suppressReturnedHover() {
231
+ clearReturnedHover();
232
+ const token = returnHoverToken;
233
+ document.documentElement.setAttribute('data-vtwc-returning', 'true');
234
+ const finish = () => clearReturnedHover();
235
+ returnHoverTimer = setTimeout(finish, 1200);
236
+ // 底栏要等侧栏提交后才存在;下一帧再挂 pointerleave。
237
+ window.requestAnimationFrame(() => {
238
+ if (token !== returnHoverToken) return;
239
+ const footer = document.querySelector('[class*="footerActions"]');
240
+ if (footer === null) return;
241
+ footer.addEventListener('pointerleave', finish, { once: true });
242
+ footer.addEventListener('pointerdown', finish, { once: true });
243
+ returnHoverCleanup = () => {
244
+ footer.removeEventListener('pointerleave', finish);
245
+ footer.removeEventListener('pointerdown', finish);
246
+ };
247
+ });
248
+ }
249
+
250
+ /** 面板同步过来的会话历史。 */
251
+ const chatData = createStore({ ready: false, sessions: [], activeId: null, error: false });
252
+
253
+ // ---------------------------------------------------------------------
254
+ // 面板桥:父页面只认 iframe 的 contentWindow,子页面只认 window.parent。
255
+ // ---------------------------------------------------------------------
256
+
257
+ const panelLink = {
258
+ target: null,
259
+ ready: false,
260
+ queue: [],
261
+ /** 记下当前面板窗口;换窗口时清掉旧的 ready 与待发命令。 */
262
+ attach(target) {
263
+ if (this.target === target) return;
264
+ this.target = target ?? null;
265
+ this.ready = false;
266
+ this.queue = [];
267
+ },
268
+ detach(target) {
269
+ if (target !== undefined && this.target !== target) return;
270
+ this.target = null;
271
+ this.ready = false;
272
+ this.queue = [];
273
+ },
274
+ /** 发给面板;还没挂上时先排队,就绪后重放。 */
275
+ post(message) {
276
+ if (this.target === null) {
277
+ if (this.queue.length < 24) this.queue.push(message);
278
+ return;
279
+ }
280
+ try {
281
+ this.target.postMessage({ source: SHELL_SOURCE, ...message }, '*');
282
+ } catch (error) {
283
+ console.warn(`[${PLUGIN_ID}] panel frame unavailable`, error);
284
+ }
285
+ },
286
+ markReady() {
287
+ if (this.ready) return;
288
+ this.ready = true;
289
+ const pending = this.queue;
290
+ this.queue = [];
291
+ for (const message of pending) this.post(message);
292
+ },
293
+ };
294
+
295
+ /** 侧栏里点一条历史:交给面板切换会话。模块级引用,供 memo 行复用。 */
296
+ function openChat(id) {
297
+ panelLink.post({ type: 'open-session', id });
298
+ }
299
+
300
+ /**
301
+ * 把面板发来的同步消息收敛成可渲染的会话摘要。
302
+ * @param data - 面板消息。
303
+ * @returns 新快照;字段不合法时返回 null,保留旧列表。
304
+ */
305
+ function readSync(data) {
306
+ const current = chatData.get();
307
+ let sessions = current.sessions;
308
+ if (Array.isArray(data.sessions)) {
309
+ sessions = [];
310
+ for (const item of data.sessions) {
311
+ if (item === null || typeof item !== 'object' || typeof item.id !== 'string') continue;
312
+ sessions.push({
313
+ id: item.id,
314
+ title: typeof item.title === 'string' ? item.title : '',
315
+ createdAt: Number(item.createdAt) || 0,
316
+ updatedAt: Number(item.updatedAt) || 0,
317
+ });
318
+ }
319
+ }
320
+ // 增量消息可能只带 activeId:其余字段沿用上一份快照。
321
+ const activeId =
322
+ typeof data.activeId === 'string'
323
+ ? data.activeId
324
+ : data.activeId === null
325
+ ? null
326
+ : current.activeId;
327
+ const ready = typeof data.ready === 'boolean' ? data.ready : current.ready;
328
+ const error = typeof data.error === 'boolean' ? data.error : current.error;
329
+ if (
330
+ sessions === current.sessions &&
331
+ activeId === current.activeId &&
332
+ ready === current.ready &&
333
+ error === current.error
334
+ ) {
335
+ return null;
336
+ }
337
+ return { ready, sessions, activeId, error };
338
+ }
339
+
340
+ /**
341
+ * 处理面板发来的消息。
342
+ * @param data - postMessage 的 data。
343
+ */
344
+ function handleHostMessage(data) {
345
+ if (data === null || typeof data !== 'object' || data.source !== HOST_SOURCE) return;
346
+ if (data.type === 'ready') {
347
+ panelLink.markReady();
348
+ panelLink.post({ type: 'request-sync' });
349
+ return;
350
+ }
351
+ if (data.type === 'sync') {
352
+ const next = readSync(data);
353
+ if (next === null) return;
354
+ chatData.set(next);
355
+ if (next.ready) panelLink.markReady();
356
+ }
357
+ }
358
+
359
+ const DAY_MS = 86_400_000;
360
+
361
+ /**
362
+ * 当天零点的时间戳。
363
+ * @param value - 毫秒时间戳。
364
+ * @returns 当天 00:00 的时间戳。
365
+ */
366
+ function startOfDay(value) {
367
+ const date = new Date(value);
368
+ date.setHours(0, 0, 0, 0);
369
+ return date.getTime();
370
+ }
371
+
372
+ /**
373
+ * 会话历史按月分组的键。
374
+ * @param value - 毫秒时间戳。
375
+ * @returns `YYYY-MM`;时间无效时为空串。
376
+ */
377
+ function monthKey(value) {
378
+ const date = new Date(value);
379
+ if (Number.isNaN(date.getTime())) return '';
380
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
381
+ }
382
+
383
+ /**
384
+ * 按 chat-demo 的同一规则分组:今天 / 昨天 / 7 天内 / 30 天内 / 月份。
385
+ * @param sessions - 会话摘要,已按更新时间倒序。
386
+ * @param now - 当前时间。
387
+ * @param t - 翻译函数。
388
+ * @returns 分组数组。
389
+ */
390
+ function groupSessions(sessions, now, t) {
391
+ const groups = [];
392
+ for (const session of sessions) {
393
+ const diff = Math.floor((now - startOfDay(session.updatedAt)) / DAY_MS);
394
+ let key = null;
395
+ let label = '';
396
+ if (diff <= 0) {
397
+ key = 'today';
398
+ label = t('history.today');
399
+ } else if (diff <= 1) {
400
+ key = 'yesterday';
401
+ label = t('history.yesterday');
402
+ } else if (diff < 7) {
403
+ key = 'week';
404
+ label = t('history.week');
405
+ } else if (diff < 30) {
406
+ key = 'month';
407
+ label = t('history.month');
408
+ } else {
409
+ key = `m:${monthKey(session.updatedAt)}`;
410
+ label = monthKey(session.updatedAt);
411
+ }
412
+ const last = groups.at(-1);
413
+ if (last !== undefined && last.key === key) last.sessions.push(session);
414
+ else groups.push({ key, label, sessions: [session] });
415
+ }
416
+ return groups;
417
+ }
418
+
419
+ /** 每分钟刷新一次「今天/昨天」边界;窗口重新可见时也刷新。 */
420
+ function useClock() {
421
+ const [now, setNow] = React.useState(() => Date.now());
422
+ React.useEffect(() => {
423
+ const tick = () => setNow(Date.now());
424
+ const timer = setInterval(tick, 60_000);
425
+ const onVisible = () => {
426
+ if (document.visibilityState === 'visible') tick();
427
+ };
428
+ document.addEventListener('visibilitychange', onVisible);
429
+ window.addEventListener('focus', tick);
430
+ return () => {
431
+ clearInterval(timer);
432
+ document.removeEventListener('visibilitychange', onVisible);
433
+ window.removeEventListener('focus', tick);
434
+ };
435
+ }, []);
436
+ return now;
437
+ }
438
+
72
439
  /**
73
440
  * 面板地址。桌面壳的静态页面通过 `__DSH_TRANSPORT__` 拿到 Host 的 HTTP origin,
74
441
  * 浏览器页面直接用当前 origin;两者都没有时退回根路径。
@@ -162,9 +529,67 @@ window.__ModuleLoader__.load({
162
529
  return response.json();
163
530
  }
164
531
 
165
- /** 面板本体:一个占满主内容区的同源 iframe。 */
532
+ /** 侧栏图标:与 icon.svg 同形,用 currentColor 跟随侧栏配色。 */
533
+ function Glyph(props) {
534
+ const size = typeof props?.size === 'number' ? props.size : 16;
535
+ return h(
536
+ 'svg',
537
+ {
538
+ viewBox: '0 0 24 24',
539
+ width: size,
540
+ height: size,
541
+ fill: 'none',
542
+ stroke: 'currentColor',
543
+ 'aria-hidden': true,
544
+ 'data-vtwc-glyph': 'true',
545
+ style: { display: 'block' },
546
+ },
547
+ h('path', {
548
+ d: 'M20.25 11.5c0 4.28-3.7 7.75-8.25 7.75-.53 0-1.05-.05-1.55-.14l-4.1 1.9c-.6.28-1.26-.22-1.18-.87l.5-3.93C4.4 14.9 3.75 13.27 3.75 11.5c0-4.28 3.7-7.75 8.25-7.75s8.25 3.47 8.25 7.75Z',
549
+ strokeWidth: 1.3,
550
+ strokeLinejoin: 'round',
551
+ }),
552
+ h('path', {
553
+ d: 'M8.5 11.5h.01M12 11.5h.01M15.5 11.5h.01',
554
+ strokeWidth: 1.6,
555
+ strokeLinecap: 'round',
556
+ }),
557
+ );
558
+ }
559
+
560
+ /**
561
+ * 返回箭头:DSH 官方 onboarding-back.svg 的路径与描边。
562
+ * 路径按 16px 图标网格缩放(不是铺满 24px 占位槽);
563
+ * non-scaling-stroke 让 1.18823 的描边粗细不随缩放变细。
564
+ */
565
+ function BackIcon() {
566
+ return h(
567
+ 'svg',
568
+ {
569
+ viewBox: '0 0 20.2792 16.825',
570
+ width: 16,
571
+ height: 16,
572
+ preserveAspectRatio: 'xMidYMid meet',
573
+ fill: 'none',
574
+ 'aria-hidden': true,
575
+ style: { display: 'block' },
576
+ },
577
+ h('path', {
578
+ d: 'M1.01986 8.58958H20.2792M8.54303 0.407656L0.825554 8.58958L8.54303 16.4077',
579
+ stroke: 'currentColor',
580
+ strokeWidth: 1.18823,
581
+ vectorEffect: 'non-scaling-stroke',
582
+ }),
583
+ );
584
+ }
585
+
586
+ /**
587
+ * 面板本体:一个占满主内容区的同源 iframe。
588
+ * @param props - locale、inset、hostRef、frameRef。
589
+ * @returns 面板容器。
590
+ */
166
591
  function Panel(props) {
167
- const frameRef = React.useRef(null);
592
+ const frameRef = props.frameRef;
168
593
  const inset = props.inset ?? 0;
169
594
 
170
595
  // 座位高度用 postMessage 传进去:面板是独立文档,读不到宿主的布局状态。
@@ -176,10 +601,16 @@ window.__ModuleLoader__.load({
176
601
  } catch {
177
602
  // 面板还没准备好:等 onLoad 再发一次。
178
603
  }
179
- }, [inset]);
604
+ }, [frameRef, inset]);
180
605
 
181
606
  React.useEffect(pushSeat, [pushSeat]);
182
607
 
608
+ const onLoad = () => {
609
+ panelLink.attach(frameRef.current === null ? null : frameRef.current.contentWindow);
610
+ panelLink.post({ type: 'request-sync' });
611
+ pushSeat();
612
+ };
613
+
183
614
  return h(
184
615
  'div',
185
616
  {
@@ -194,7 +625,7 @@ window.__ModuleLoader__.load({
194
625
  },
195
626
  h('iframe', {
196
627
  ref: frameRef,
197
- onLoad: pushSeat,
628
+ onLoad,
198
629
  src: panelUrl(props.locale ?? 'zh-CN'),
199
630
  title: 'DeepSeek',
200
631
  allow: 'clipboard-write; microphone',
@@ -203,31 +634,78 @@ window.__ModuleLoader__.load({
203
634
  );
204
635
  }
205
636
 
206
- /** 侧栏图标:与 icon.svg 同形,用 currentColor 跟随侧栏配色。 */
207
- function Glyph(props) {
208
- const size = typeof props?.size === 'number' ? props.size : 16;
209
- return h(
210
- 'svg',
211
- {
212
- viewBox: '0 0 24 24',
213
- width: size,
214
- height: size,
215
- fill: 'none',
216
- stroke: 'currentColor',
217
- 'aria-hidden': true,
218
- style: { display: 'block' },
219
- },
220
- h('path', {
221
- d: 'M20.25 11.5c0 4.28-3.7 7.75-8.25 7.75-.53 0-1.05-.05-1.55-.14l-4.1 1.9c-.6.28-1.26-.22-1.18-.87l.5-3.93C4.4 14.9 3.75 13.27 3.75 11.5c0-4.28 3.7-7.75 8.25-7.75s8.25 3.47 8.25 7.75Z',
222
- strokeWidth: 1.3,
223
- strokeLinejoin: 'round',
224
- }),
225
- h('path', {
226
- d: 'M8.5 11.5h.01M12 11.5h.01M15.5 11.5h.01',
227
- strokeWidth: 1.6,
228
- strokeLinecap: 'round',
229
- }),
230
- );
637
+ /**
638
+ * 主面板外壳:挂载即进入 Chat 模式,卸载即退出;
639
+ * 同时负责把 iframe 的窗口登记给侧栏桥,并转发面板消息。
640
+ * @returns 面板。
641
+ */
642
+ function PanelShell(props) {
643
+ const ctx = props.ctx;
644
+ const frameRef = React.useRef(null);
645
+ const hostRef = React.useRef(null);
646
+ const [locale, setLocale] = React.useState(() => hostLocale(ctx));
647
+ const [inset, setInset] = React.useState(() => measureSeatInset(null));
648
+
649
+ React.useEffect(() => ctx.locale.subscribe(() => setLocale(hostLocale(ctx))), [ctx]);
650
+
651
+ // 主面板只在被选中时挂载:挂载/卸载就是 Chat 模式的开关。
652
+ React.useEffect(() => {
653
+ enterSurface();
654
+ return () => leaveSurface();
655
+ }, []);
656
+
657
+ React.useEffect(() => {
658
+ const frame = frameRef.current;
659
+ const win = frame === null ? null : frame.contentWindow;
660
+ panelLink.attach(win);
661
+
662
+ const onMessage = (event) => {
663
+ const current = frameRef.current;
664
+ if (current === null || event.source !== current.contentWindow) return;
665
+ handleHostMessage(event.data);
666
+ };
667
+ window.addEventListener('message', onMessage);
668
+
669
+ // 面板脚本可能在监听装好之前就完成了首帧:几次请求同步兜住这个窗口。
670
+ const request = () => panelLink.post({ type: 'request-sync' });
671
+ const timers = [0, 300, 1200, 3000].map((delay) => setTimeout(request, delay));
672
+
673
+ return () => {
674
+ for (const timer of timers) clearTimeout(timer);
675
+ window.removeEventListener('message', onMessage);
676
+ panelLink.detach(win);
677
+ };
678
+ }, []);
679
+
680
+ React.useEffect(() => {
681
+ let timer;
682
+ const schedule = () => {
683
+ if (timer !== undefined) return;
684
+ timer = setTimeout(() => {
685
+ timer = undefined;
686
+ setInset(measureSeatInset(hostRef.current));
687
+ }, 120);
688
+ };
689
+ // 侧栏开合会换掉框架的子节点,座位随之出现或消失。
690
+ const observer = new MutationObserver(schedule);
691
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });
692
+ const resizer = new ResizeObserver(schedule);
693
+ resizer.observe(document.documentElement);
694
+ window.addEventListener('resize', schedule);
695
+ const onMessage = (event) => {
696
+ if (event.data?.type === 'vt-webchat:hello') setInset(measureSeatInset(hostRef.current));
697
+ };
698
+ window.addEventListener('message', onMessage);
699
+ return () => {
700
+ if (timer !== undefined) clearTimeout(timer);
701
+ observer.disconnect();
702
+ resizer.disconnect();
703
+ window.removeEventListener('resize', schedule);
704
+ window.removeEventListener('message', onMessage);
705
+ };
706
+ }, []);
707
+
708
+ return h(Panel, { locale, inset, hostRef, frameRef });
231
709
  }
232
710
 
233
711
  /**
@@ -381,8 +859,198 @@ window.__ModuleLoader__.load({
381
859
  }
382
860
  }
383
861
 
862
+ /** Chat 模式的样式。用宿主 token,深浅色和字体大小自动跟随。 */
863
+ const CHAT_CSS = `
864
+ /* Chat 模式下,全局面板行让位给 Chat 自己的动线。
865
+ 座位 API 只能追加,不能删掉别的插件已经注册的行,所以这里按稳定的业务标识
866
+ 精确隐藏:全局面板行、DS Bot 的返回按钮、额度条。离开 Chat 模式后属性移除,
867
+ 这些行原样恢复;账号/设置行保持可用。 */
868
+ html[data-vtwc-surface='chat'] [class*="panelList"] { display: none; }
869
+ html[data-vtwc-surface='chat'] .bt-return { display: none !important; }
870
+ html[data-vtwc-surface='chat'] [data-plugin='dsh-vt-quote-bar'] { display: none !important; }
871
+ /* 返回后短暂压掉底栏两行的 hover 底色,避免看起来像返回按钮的状态滞留。 */
872
+ html[data-vtwc-returning='true'] .vtq-collapsed:hover { background-color: transparent !important; }
873
+ html[data-vtwc-returning='true'] .bt-return:hover { background-color: var(--bt-return-fill, transparent) !important; }
874
+ .vtwc-brand {
875
+ display: inline-flex;
876
+ align-items: center;
877
+ min-width: 0;
878
+ height: 24px;
879
+ cursor: default;
880
+ animation: vtwc-brand-in 200ms cubic-bezier(.2, .8, .2, 1);
881
+ }
882
+ .vtwc-brand[data-vtwc-leaving='true'] { animation: vtwc-brand-out 150ms ease forwards; }
883
+ .vtwc-brand-wordmark { display: inline-flex; flex: none; width: 103.35px; height: 24px; overflow: hidden; }
884
+ .vtwc-brand-wordmark > svg { display: block; flex: none; }
885
+ .vtwc-brand-fallback {
886
+ font-size: 18px;
887
+ font-weight: 600;
888
+ line-height: 24px;
889
+ letter-spacing: .04em;
890
+ color: var(--dsw-alias-label-primary);
891
+ }
892
+ .vtwc-brand-badge {
893
+ display: inline-flex;
894
+ align-items: center;
895
+ justify-content: center;
896
+ flex: none;
897
+ width: 52px;
898
+ height: 14px;
899
+ border-radius: 2px;
900
+ background: var(--dsw-alias-label-primary);
901
+ color: var(--dsw-specific-sidebar-fill);
902
+ font-family: var(--ds-font-family-code);
903
+ font-size: 10px;
904
+ font-weight: 500;
905
+ line-height: 14px;
906
+ letter-spacing: .08em;
907
+ }
908
+ .vtwc-region {
909
+ display: flex;
910
+ flex-direction: column;
911
+ min-height: 0;
912
+ height: 100%;
913
+ padding-top: 6px;
914
+ animation: vtwc-in 200ms cubic-bezier(.2, .8, .2, 1);
915
+ }
916
+ .vtwc-region[data-vtwc-leaving='true'] { animation: vtwc-out 150ms ease forwards; }
917
+ .vtwc-list {
918
+ flex: 1;
919
+ min-height: 0;
920
+ margin: 0 -2px;
921
+ padding: 0 2px 8px;
922
+ overflow-y: auto;
923
+ overscroll-behavior: contain;
924
+ scrollbar-color: var(--dsh-scrollbar-thumb) transparent;
925
+ }
926
+ .vtwc-group { margin-top: 16px; }
927
+ .vtwc-group:first-child { margin-top: 0; }
928
+ .vtwc-group-label {
929
+ position: sticky;
930
+ top: 0;
931
+ z-index: 1;
932
+ padding: 2px 10px;
933
+ background: var(--dsw-specific-sidebar-fill);
934
+ color: var(--dsw-alias-label-tertiary);
935
+ font-size: 12px;
936
+ font-weight: 500;
937
+ line-height: 18px;
938
+ user-select: none;
939
+ }
940
+ .vtwc-row {
941
+ box-sizing: border-box;
942
+ display: flex;
943
+ align-items: center;
944
+ width: 100%;
945
+ height: 40px;
946
+ padding: 9px 6px 9px 10px;
947
+ border: 0;
948
+ border-radius: 12px;
949
+ background: transparent;
950
+ color: var(--dsw-alias-label-primary);
951
+ font: inherit;
952
+ font-size: 14px;
953
+ line-height: 22px;
954
+ text-align: left;
955
+ cursor: pointer;
956
+ }
957
+ .vtwc-row:hover { background: var(--dsw-specific-sidebar-nav-item-hover); }
958
+ .vtwc-row-active,
959
+ .vtwc-row-active:hover {
960
+ background: var(--dsw-specific-sidebar-nav-item-active-accent);
961
+ color: var(--dsw-alias-brand-primary-invert);
962
+ }
963
+ .vtwc-row:focus-visible { outline: 2px solid var(--dsw-alias-label-primary); outline-offset: -2px; }
964
+ .vtwc-row-title { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; line-height: 18px; }
965
+ .vtwc-skeleton { display: flex; flex-direction: column; gap: 14px; padding: 14px 10px 0; }
966
+ .vtwc-skeleton-row {
967
+ height: 12px;
968
+ border-radius: 6px;
969
+ background: var(--dsw-alias-interactive-bg-hover);
970
+ animation: vtwc-pulse 1.4s ease-in-out infinite;
971
+ }
972
+ .vtwc-empty {
973
+ display: flex;
974
+ flex-direction: column;
975
+ align-items: center;
976
+ gap: 6px;
977
+ padding: 32px 16px;
978
+ text-align: center;
979
+ color: var(--dsw-alias-label-tertiary);
980
+ font-size: 12px;
981
+ line-height: 20px;
982
+ }
983
+ .vtwc-empty-title { color: var(--dsw-alias-label-secondary); font-size: 13px; font-weight: 500; }
984
+ .vtwc-retry {
985
+ margin-top: 4px;
986
+ padding: 4px 12px;
987
+ border: 1px solid var(--dsw-alias-border-l2);
988
+ border-radius: 999px;
989
+ background: transparent;
990
+ color: var(--dsw-alias-label-primary);
991
+ font: inherit;
992
+ font-size: 12px;
993
+ cursor: pointer;
994
+ }
995
+ .vtwc-retry:hover { background: var(--dsw-alias-interactive-bg-hover); }
996
+ /* 与侧栏账号行同一套排版:44px 行高、6px 内边距、24px 图标槽、8px 间距、
997
+ 14px 字号、label-primary 文本色;只去掉账号行的圆形底。 */
998
+ .vtwc-back {
999
+ box-sizing: border-box;
1000
+ display: flex;
1001
+ align-items: center;
1002
+ gap: 8px;
1003
+ width: calc(100% - 4px);
1004
+ height: 44px;
1005
+ margin: 0 2px 2px;
1006
+ padding: 6px;
1007
+ border: 0;
1008
+ border-radius: var(--dsw-radius-md);
1009
+ background: transparent;
1010
+ color: var(--dsw-alias-label-primary);
1011
+ font: inherit;
1012
+ font-size: 14px;
1013
+ line-height: 22px;
1014
+ text-align: left;
1015
+ cursor: pointer;
1016
+ animation: vtwc-in 200ms cubic-bezier(.2, .8, .2, 1);
1017
+ }
1018
+ .vtwc-back[data-vtwc-leaving='true'] { animation: vtwc-out 150ms ease forwards; }
1019
+ .vtwc-back:hover { background: var(--dsw-alias-interactive-bg-hover); }
1020
+ .vtwc-back:focus-visible { outline: 2px solid var(--dsw-alias-label-primary); outline-offset: -2px; }
1021
+ .vtwc-back-rail { width: 36px; height: 36px; margin: 0; padding: 0; justify-content: center; gap: 0; }
1022
+ .vtwc-back-icon { display: inline-flex; flex: none; align-items: center; justify-content: center; width: 24px; height: 24px; }
1023
+ .vtwc-back-label { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
1024
+ .vtwc-rail {
1025
+ display: inline-flex;
1026
+ align-items: center;
1027
+ justify-content: center;
1028
+ width: 36px;
1029
+ height: 36px;
1030
+ margin-top: 2px;
1031
+ padding: 0;
1032
+ border: 0;
1033
+ border-radius: 8px;
1034
+ background: transparent;
1035
+ color: var(--dsw-alias-label-secondary);
1036
+ cursor: pointer;
1037
+ }
1038
+ .vtwc-rail:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
1039
+ @keyframes vtwc-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
1040
+ @keyframes vtwc-out { from { opacity: 1; transform: none; } to { opacity: 0; transform: translateY(4px); } }
1041
+ @keyframes vtwc-brand-in { from { opacity: 0; transform: translateX(-4px); } to { opacity: 1; transform: none; } }
1042
+ @keyframes vtwc-brand-out { to { opacity: 0; } }
1043
+ @keyframes vtwc-pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
1044
+ @media (prefers-reduced-motion: reduce) {
1045
+ .vtwc-region,
1046
+ .vtwc-brand,
1047
+ .vtwc-back,
1048
+ .vtwc-skeleton-row { animation: none !important; }
1049
+ }
1050
+ `;
1051
+
384
1052
  return {
385
- inject: ['slots', 'locale'],
1053
+ inject: ['slots', 'locale', 'layout'],
386
1054
  apply(ctx) {
387
1055
  ctx.effect(() => {
388
1056
  const offZh = ctx.locale.register(NS, 'zh', DICT.zh);
@@ -393,6 +1061,61 @@ window.__ModuleLoader__.load({
393
1061
  };
394
1062
  }, `${PLUGIN_ID}: locale`);
395
1063
 
1064
+ ctx.effect(() => {
1065
+ const style = document.createElement('style');
1066
+ style.dataset.plugin = PLUGIN_ID;
1067
+ style.dataset.pluginCss = `${PLUGIN_ID}/chat-mode`;
1068
+ style.textContent = CHAT_CSS;
1069
+ document.head.appendChild(style);
1070
+ return () => style.remove();
1071
+ }, `${PLUGIN_ID}: chat mode styles`);
1072
+
1073
+ ctx.effect(() => {
1074
+ const root = document.documentElement;
1075
+ const sync = () => {
1076
+ if (surface.get().active) root.setAttribute('data-vtwc-surface', 'chat');
1077
+ else root.removeAttribute('data-vtwc-surface');
1078
+ };
1079
+ const off = surface.subscribe(sync);
1080
+ sync();
1081
+ return () => {
1082
+ off();
1083
+ root.removeAttribute('data-vtwc-surface');
1084
+ };
1085
+ }, `${PLUGIN_ID}: chat surface`);
1086
+
1087
+ // 一次捕获监听处理两件事:
1088
+ // 1) 点「网页对话」入口时,先切侧栏,不等主面板挂载完成;
1089
+ // 2) 收起侧栏后,宿主 frame 左上角的浮动「新建会话」在 Chat 模式下改走新建对话。
1090
+ ctx.effect(() => {
1091
+ const onClick = (event) => {
1092
+ const target = event.target;
1093
+ if (target === null || typeof target.closest !== 'function') return;
1094
+
1095
+ if (surface.get().active) {
1096
+ if (target.closest('[data-shell-leading]') === null) return;
1097
+ const button = target.closest('button');
1098
+ if (button === null || button.hasAttribute('data-sidebar-opener')) return;
1099
+ event.preventDefault();
1100
+ event.stopPropagation();
1101
+ panelLink.post({ type: 'new-chat' });
1102
+ return;
1103
+ }
1104
+
1105
+ // 入口行:按钮里带本插件图标的才算,避免误伤其它面板行。
1106
+ const button = target.closest('button');
1107
+ if (button === null || button.querySelector('[data-vtwc-glyph]') === null) return;
1108
+ enterSurface();
1109
+ };
1110
+ document.addEventListener('click', onClick, true);
1111
+ return () => document.removeEventListener('click', onClick, true);
1112
+ }, `${PLUGIN_ID}: mode entry and leading new session`);
1113
+
1114
+ ctx.effect(
1115
+ () => () => clearReturnedHover(),
1116
+ `${PLUGIN_ID}: returned-hover cleanup`,
1117
+ );
1118
+
396
1119
  const bound = ctx.locale.bind(NS);
397
1120
  const t = (key, ...rest) => {
398
1121
  const raw = bound(key);
@@ -400,51 +1123,290 @@ window.__ModuleLoader__.load({
400
1123
  return typeof value === 'function' ? value(...rest) : value;
401
1124
  };
402
1125
 
403
- // 宿主语言变化时重挂 iframe,让面板文案与新语言一致;
404
- // 同时盯着顶部的悬浮岛,把需要让出的高度实时传进面板。
405
- function PanelShell() {
406
- const [locale, setLocale] = React.useState(() => hostLocale(ctx));
407
- const hostRef = React.useRef(null);
408
- const [inset, setInset] = React.useState(() => measureSeatInset(null));
409
-
410
- React.useEffect(() => ctx.locale.subscribe(() => setLocale(hostLocale(ctx))), []);
411
-
412
- React.useEffect(() => {
413
- let timer;
414
- const schedule = () => {
415
- if (timer !== undefined) return;
416
- timer = setTimeout(() => {
417
- timer = undefined;
418
- setInset(measureSeatInset(hostRef.current));
419
- }, 120);
420
- };
421
- // 侧栏开合会换掉框架的子节点,座位随之出现或消失。
422
- const observer = new MutationObserver(schedule);
423
- observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });
424
- const resizer = new ResizeObserver(schedule);
425
- resizer.observe(document.documentElement);
426
- window.addEventListener('resize', schedule);
427
- const onMessage = (event) => {
428
- if (event.data?.type === 'vt-webchat:hello') setInset(measureSeatInset(hostRef.current));
429
- };
430
- window.addEventListener('message', onMessage);
431
- return () => {
432
- if (timer !== undefined) clearTimeout(timer);
433
- observer.disconnect();
434
- resizer.disconnect();
435
- window.removeEventListener('resize', schedule);
436
- window.removeEventListener('message', onMessage);
437
- };
1126
+ /**
1127
+ * 抢在现有注册之前接管一个 single 座位。
1128
+ * priority 越小越优先;每次都取当前最低值再减一,避免与另一个插件撞车抛错。
1129
+ * @param name - 座位名。
1130
+ * @returns 可用的 priority。
1131
+ */
1132
+ const freePriority = (name) => {
1133
+ try {
1134
+ const entries = ctx.slots.entries(name) ?? [];
1135
+ const values = entries.map((entry) => {
1136
+ const value = entry?.options?.priority;
1137
+ return typeof value === 'number' ? value : 0;
1138
+ });
1139
+ return (values.length > 0 ? Math.min(...values) : 0) - 1;
1140
+ } catch {
1141
+ return -50;
1142
+ }
1143
+ };
1144
+
1145
+ /**
1146
+ * 在 Chat 模式期间向一个座位注册;离开后注销,让宿主内容回来。
1147
+ * @param name - 座位名。
1148
+ * @param options - 注册选项(每次激活时求值,方便带 locale 文案)。
1149
+ * @param Component - 组件。
1150
+ * @param label - effect 标签。
1151
+ */
1152
+ const keepActive = (name, options, Component, label) => {
1153
+ ctx.effect(
1154
+ () =>
1155
+ ctx.slots.inject(name, () => {
1156
+ let dispose = null;
1157
+ const sync = () => {
1158
+ const active = surface.get().active;
1159
+ if (active && dispose === null) {
1160
+ try {
1161
+ dispose = ctx.slots.register({ name, ...options() }, Component);
1162
+ } catch (error) {
1163
+ console.error(`[${PLUGIN_ID}] ${label}`, error);
1164
+ dispose = null;
1165
+ }
1166
+ } else if (!active && dispose !== null) {
1167
+ dispose();
1168
+ dispose = null;
1169
+ }
1170
+ };
1171
+ const off = surface.subscribe(sync);
1172
+ sync();
1173
+ return () => {
1174
+ off();
1175
+ if (dispose !== null) {
1176
+ dispose();
1177
+ dispose = null;
1178
+ }
1179
+ };
1180
+ }),
1181
+ label,
1182
+ );
1183
+ };
1184
+
1185
+ // -- 品牌名:Chat 模式把 HARNESS 徽标换成 chat,字标沿用官方那份 ----------
1186
+
1187
+ function ChatBrandName() {
1188
+ const state = useStore(surface);
1189
+ const stop = (event) => {
1190
+ event.preventDefault();
1191
+ event.stopPropagation();
1192
+ };
1193
+ const wordmark =
1194
+ primitives !== null && primitives.BrandWordmark != null
1195
+ ? h(primitives.BrandWordmark, { includeMark: false })
1196
+ : h('span', { className: 'vtwc-brand-fallback' }, 'deepseek');
1197
+ return h(
1198
+ 'span',
1199
+ {
1200
+ className: 'vtwc-brand',
1201
+ 'data-vtwc-leaving': state.leaving ? 'true' : 'false',
1202
+ // 品牌行本身就是宿主的「新建会话」按钮;Chat 模式下点它不应该建 DSH 会话。
1203
+ onClickCapture: stop,
1204
+ },
1205
+ h('span', { className: 'vtwc-brand-wordmark' }, wordmark),
1206
+ h('span', { className: 'vtwc-brand-badge', 'aria-hidden': true }, 'CHAT'),
1207
+ );
1208
+ }
1209
+
1210
+ // -- 品牌标:只拦 logo 行的点击,收起态里同一个座位还嵌在展开按钮里 --------
1211
+
1212
+ function ChatBrandMark(props) {
1213
+ const size = typeof props?.size === 'number' ? props.size : 24;
1214
+ const stop = (event) => {
1215
+ const current = event.currentTarget;
1216
+ // 收起态的这个座位在「展开侧栏」按钮内部,点了必须让它正常工作。
1217
+ if (current !== null && typeof current.closest === 'function' && current.closest('[class*="toggle"]') !== null) {
1218
+ return;
1219
+ }
1220
+ event.preventDefault();
1221
+ event.stopPropagation();
1222
+ };
1223
+ return h(
1224
+ 'span',
1225
+ { style: { display: 'inline-flex' }, onClickCapture: stop },
1226
+ h(primitives.FishLogo, { size }),
1227
+ );
1228
+ }
1229
+
1230
+ // -- 历史:按 chat-demo 的分组与行高渲染,点击让 iframe 切换会话 ----------
1231
+
1232
+ /** 单条历史行:memo 化,切换选中时只重渲染跨过选中态的两行。 */
1233
+ const ChatRow = React.memo(function ChatRow(props) {
1234
+ return h(
1235
+ 'button',
1236
+ {
1237
+ type: 'button',
1238
+ className: `vtwc-row${props.active ? ' vtwc-row-active' : ''}`,
1239
+ title: props.title || props.untitled,
1240
+ onClick: () => openChat(props.id),
1241
+ },
1242
+ h('span', { className: 'vtwc-row-title' }, props.title || props.untitled),
1243
+ );
1244
+ });
1245
+
1246
+ function ChatHistory(props) {
1247
+ const state = useStore(surface);
1248
+ const data = useStore(chatData);
1249
+ const now = useClock();
1250
+ const wide = props?.wide !== false;
1251
+ const untitled = t('history.untitled');
1252
+ const groups = React.useMemo(
1253
+ () => groupSessions(data.sessions, now, t),
1254
+ [data.sessions, now],
1255
+ );
1256
+
1257
+ if (!wide) {
1258
+ return h(
1259
+ 'button',
1260
+ {
1261
+ type: 'button',
1262
+ className: 'vtwc-rail',
1263
+ title: t('entry'),
1264
+ 'aria-label': t('entry'),
1265
+ onClick: () => {
1266
+ if (typeof props?.expandSidebar === 'function') props.expandSidebar();
1267
+ },
1268
+ },
1269
+ h(Glyph, { size: 18 }),
1270
+ );
1271
+ }
1272
+
1273
+ let content;
1274
+ if (data.error) {
1275
+ content = h(
1276
+ 'div',
1277
+ { className: 'vtwc-empty' },
1278
+ h('span', { className: 'vtwc-empty-title' }, t('history.error')),
1279
+ h(
1280
+ 'button',
1281
+ { type: 'button', className: 'vtwc-retry', onClick: () => panelLink.post({ type: 'retry' }) },
1282
+ t('history.retry'),
1283
+ ),
1284
+ );
1285
+ } else if (!data.ready && data.sessions.length === 0) {
1286
+ content = h(
1287
+ 'div',
1288
+ { className: 'vtwc-skeleton', 'aria-hidden': true },
1289
+ h('div', { className: 'vtwc-skeleton-row', style: { width: '72%' } }),
1290
+ h('div', { className: 'vtwc-skeleton-row', style: { width: '88%' } }),
1291
+ h('div', { className: 'vtwc-skeleton-row', style: { width: '60%' } }),
1292
+ );
1293
+ } else if (data.sessions.length === 0) {
1294
+ content = h(
1295
+ 'div',
1296
+ { className: 'vtwc-empty' },
1297
+ h('span', { className: 'vtwc-empty-title' }, t('history.empty')),
1298
+ h('span', null, t('history.emptyHint')),
1299
+ );
1300
+ } else {
1301
+ content = groups.map((group) =>
1302
+ h(
1303
+ 'section',
1304
+ { key: group.key, className: 'vtwc-group' },
1305
+ h('div', { className: 'vtwc-group-label' }, group.label),
1306
+ group.sessions.map((session) =>
1307
+ h(ChatRow, {
1308
+ key: session.id,
1309
+ id: session.id,
1310
+ title: session.title,
1311
+ active: session.id === data.activeId,
1312
+ untitled,
1313
+ }),
1314
+ ),
1315
+ ),
1316
+ );
1317
+ }
1318
+
1319
+ return h(
1320
+ 'div',
1321
+ { className: 'vtwc-region', 'data-vtwc-leaving': state.leaving ? 'true' : 'false' },
1322
+ h('nav', { className: 'vtwc-list', 'aria-label': t('history.label') }, content),
1323
+ );
1324
+ }
1325
+
1326
+ // -- 底部:返回 Harness -------------------------------------------------
1327
+
1328
+ function BackToHarness(props) {
1329
+ const state = useStore(surface);
1330
+ const wide = props?.wide !== false;
1331
+ const back = () => {
1332
+ // 先恢复侧栏并让它完成一帧绘制,再挂载会话面板:
1333
+ // 会话面板的挂载较重,放在同一帧会把侧栏恢复一起拖慢。
1334
+ // 同时短暂屏蔽底部动作区,避免指针没动却点亮刚出现的额度环。
1335
+ suppressReturnedHover();
1336
+ exitSurfaceNow();
1337
+ window.requestAnimationFrame(() => {
1338
+ window.requestAnimationFrame(() => {
1339
+ if (surface.get().active) return;
1340
+ try {
1341
+ ctx.layout.selectPanel(CONVERSATION_PANEL);
1342
+ } catch (error) {
1343
+ console.error(`[${PLUGIN_ID}] could not return to the conversation`, error);
1344
+ }
1345
+ });
1346
+ });
1347
+ };
1348
+ return h(
1349
+ 'button',
1350
+ {
1351
+ type: 'button',
1352
+ className: `vtwc-back${wide ? '' : ' vtwc-back-rail'}`,
1353
+ 'data-vtwc-back': 'true',
1354
+ 'data-vtwc-leaving': state.leaving ? 'true' : 'false',
1355
+ 'aria-label': t('back'),
1356
+ title: t('back.hint'),
1357
+ onClick: back,
1358
+ },
1359
+ h('span', { className: 'vtwc-back-icon' }, h(BackIcon)),
1360
+ wide ? h('span', { className: 'vtwc-back-label' }, t('back')) : null,
1361
+ );
1362
+ }
1363
+
1364
+ // -- 「新会话」:保留宿主的按钮与样式,Chat 模式下把点击改成新建对话 ------
1365
+
1366
+ function NewSessionLayer(props) {
1367
+ const intercept = React.useCallback((event) => {
1368
+ if (!surface.get().active) return;
1369
+ event.preventDefault();
1370
+ event.stopPropagation();
1371
+ panelLink.post({ type: 'new-chat' });
438
1372
  }, []);
1373
+ return h('span', { style: { display: 'contents' }, onClickCapture: intercept }, props?.children ?? null);
1374
+ }
1375
+
1376
+ // -- 注册:品牌、浏览区、底部动作在模式期间接管;入口在模式外显示 ----------
1377
+
1378
+ keepActive(
1379
+ 'sidebar.brand.name',
1380
+ () => ({ priority: freePriority('sidebar.brand.name'), locale: NS }),
1381
+ ChatBrandName,
1382
+ `${PLUGIN_ID}: chat brand`,
1383
+ );
439
1384
 
440
- return h(Panel, { locale, inset, hostRef });
1385
+ if (primitives !== null && primitives.FishLogo != null) {
1386
+ keepActive(
1387
+ 'sidebar.brand.mark',
1388
+ () => ({ priority: freePriority('sidebar.brand.mark'), locale: NS }),
1389
+ ChatBrandMark,
1390
+ `${PLUGIN_ID}: chat brand mark`,
1391
+ );
441
1392
  }
442
1393
 
443
- ctx.slots.inject('main', () =>
444
- ctx.slots.register({ name: 'main', key: PANEL_ID }, PanelShell),
1394
+ keepActive(
1395
+ 'sidebar.workspaces',
1396
+ () => ({ priority: freePriority('sidebar.workspaces'), locale: NS }),
1397
+ ChatHistory,
1398
+ `${PLUGIN_ID}: chat history`,
1399
+ );
1400
+
1401
+ keepActive(
1402
+ 'sidebar.footer.action',
1403
+ () => ({ id: 'vt-web-chat-back', order: -10, locale: NS }),
1404
+ BackToHarness,
1405
+ `${PLUGIN_ID}: back to harness`,
445
1406
  );
446
1407
 
447
- // order -10 让入口贴着「新会话」;与 1.x 的位置保持一致,升级后用户不会找不到。
1408
+ // 入口行始终注册:Chat 模式下由上面的 panelList 样式整体隐藏,
1409
+ // 这样退出时不必重新注册,宿主的面板列表也不会因为注销而抖动。
448
1410
  ctx.slots.inject('sidebar.panellist', () =>
449
1411
  ctx.slots.register(
450
1412
  { name: 'sidebar.panellist', id: PANEL_ID, order: -10, label: () => t('entry') },
@@ -452,6 +1414,20 @@ window.__ModuleLoader__.load({
452
1414
  ),
453
1415
  );
454
1416
 
1417
+ // HOC 只负责拦截点击;按钮本身、图标、尺寸全部保持宿主原样。
1418
+ ctx.effect(
1419
+ () =>
1420
+ ctx.slots.inject('sidebar.session.action', () =>
1421
+ ctx.slots.register(
1422
+ { name: 'sidebar.session.action', id: 'vt-web-chat-new-session', order: 10, priority: -10 },
1423
+ NewSessionLayer,
1424
+ ),
1425
+ ),
1426
+ `${PLUGIN_ID}: new session click`,
1427
+ );
1428
+
1429
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID }, (props) => h(PanelShell, { ...props, ctx })));
1430
+
455
1431
  ctx.slots.inject('settings.section', () =>
456
1432
  ctx.slots.register(
457
1433
  {