@twinsearth/dsh-fang 3.0.8 → 3.0.9

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
@@ -117,6 +117,7 @@ window.__ModuleLoader__.load({
117
117
  'derive-failed': '派生请求失败。',
118
118
  'stop-failed': '分身进程未停止,归档没有生效;任务仍保留。',
119
119
  'derived-session-missing': '会话已不在目录中(可能刚被归档),请刷新。',
120
+ 'capture-failed': '从母体生成元主失败:母体 profile 不可读或补丁解析失败(详情见下方)。',
120
121
  }
121
122
 
122
123
  // ── 通用工具 ──────────────────────────────────────────────────────────
@@ -363,22 +364,41 @@ window.__ModuleLoader__.load({
363
364
 
364
365
  async function api(path, options) {
365
366
  const url = String(path)
366
- const token = await ensureFangAuthToken()
367
+ // Absolute / scheme-relative URLs must never reach fetch(): the install token
368
+ // would travel to a foreign origin. The panel only talks to its own /fang API.
369
+ if (!url.startsWith('/') || url.startsWith('//')) {
370
+ const message = 'api() 只接受同源相对路径:' + url
371
+ diag('bad', message)
372
+ return { status: 0, body: { ok: false, error: 'invalid-api-path' }, diagnostic: { url, message } }
373
+ }
374
+ const request = { ...(options ?? {}) }
375
+ let token = await ensureFangAuthToken()
376
+ const buildHeaders = () => ({
377
+ ...(request.headers ?? {}),
378
+ 'content-type': 'application/json',
379
+ accept: 'application/json',
380
+ ...(token ? { 'x-fang-auth': token } : {}),
381
+ })
367
382
  let res
368
383
  try {
369
- res = await fetch(url, {
370
- headers: {
371
- 'content-type': 'application/json',
372
- accept: 'application/json',
373
- ...(token ? { 'x-fang-auth': token } : {}),
374
- },
375
- ...(options ?? {}),
376
- })
384
+ res = await fetch(url, { ...request, headers: buildHeaders() })
377
385
  } catch (error) {
378
386
  const message = String(error?.message ?? error)
379
387
  diag('bad', '网络请求失败:' + url, message)
380
388
  return { status: 0, body: null, diagnostic: { url, message } }
381
389
  }
390
+ // A host restart can rotate the install token; retry once with the public
391
+ // /fang/api/auth-token bootstrap instead of leaving the panel stuck at 401.
392
+ if (res.status === 401) {
393
+ fangAuthToken = ''
394
+ const fresh = await ensureFangAuthToken()
395
+ if (fresh && fresh !== token) {
396
+ token = fresh
397
+ try {
398
+ res = await fetch(url, { ...request, headers: buildHeaders() })
399
+ } catch { /* keep the original 401 below */ }
400
+ }
401
+ }
382
402
  const etag = (res.headers && typeof res.headers.get === 'function' && res.headers.get('etag')) || ''
383
403
  if (res.status === 304) return { status: 304, body: null, notModified: true, etag }
384
404
  let text = ''
@@ -398,6 +418,12 @@ window.__ModuleLoader__.load({
398
418
  }
399
419
 
400
420
  function resolveMotherOrigin() {
421
+ // In the Electron shell the panel origin is the loopback proxy, which only
422
+ // serves /fang/api/*; the mother portal lives on the upstream DSH origin.
423
+ try {
424
+ const desktop = typeof window !== 'undefined' ? window.__fangDesktopUpstream : ''
425
+ if (typeof desktop === 'string' && /^https?:\/\//i.test(desktop)) return desktop.replace(/\/+$/, '')
426
+ } catch { /* ignore */ }
401
427
  try {
402
428
  const transport = typeof globalThis !== 'undefined' ? globalThis.__DSH_TRANSPORT__ : undefined
403
429
  const streamBaseUrl = transport && typeof transport.streamBaseUrl === 'string' ? transport.streamBaseUrl : ''
@@ -409,14 +435,27 @@ window.__ModuleLoader__.load({
409
435
  } catch { /* ignore */ }
410
436
  return ''
411
437
  }
412
- function openMotherPortal() {
438
+ async function openMotherPortal() {
439
+ // 母体 Web 就是 DSH 客户端本身。Electron 壳优先把 DSH 桌面窗口置前,
440
+ // 而不是打开没有 token 的裸 HTTP URL(那会 401)。
441
+ if (window.fangShell?.focusMother) {
442
+ try {
443
+ const result = await window.fangShell.focusMother()
444
+ if (result?.ok) return
445
+ } catch { /* fall through */ }
446
+ }
447
+ const token = new URLSearchParams(location.search).get('token') || ''
413
448
  const origin = resolveMotherOrigin()
414
- const url = origin ? `${origin}/fang/panel` : '/fang/panel'
449
+ if (!window.fangShell && token && origin) {
450
+ try {
451
+ const win = window.open(`${origin}/?token=${encodeURIComponent(token)}`, '_blank', 'noopener')
452
+ if (win) return
453
+ } catch { /* popup blocked */ }
454
+ }
455
+ // Web 端:母体 Web 就是当前 DSH 客户端,切回瓮城控制台视图即可。
415
456
  try {
416
- const win = window.open(url, '_blank', 'noopener')
417
- if (win) return
418
- } catch { /* 弹窗被拦 → 同页打开 */ }
419
- try { window.location.assign(url) } catch { /* ignore */ }
457
+ window.dispatchEvent(new CustomEvent('fang:mother-portal'))
458
+ } catch { /* ignore */ }
420
459
  }
421
460
 
422
461
  // ── DOM 构造器 h():本文件唯一的视图原语 ──────────────────────────────
@@ -615,7 +654,7 @@ window.__ModuleLoader__.load({
615
654
  .chip--neutral{color:var(--f-text-3);background:var(--f-surface-2);border-color:var(--f-border)}
616
655
 
617
656
  /* layout */
618
- .fang-body{display:grid;grid-template-columns:minmax(300px,3fr) minmax(0,7fr);gap:16px;align-items:start;min-height:0;flex:1 1 auto}
657
+ .fang-body{display:grid;grid-template-columns:minmax(320px,1fr) minmax(0,1fr);gap:16px;align-items:start;min-height:0;flex:1 1 auto}
619
658
  @media (max-width:1100px){.fang-body{grid-template-columns:1fr}}
620
659
  .panel{background:var(--f-surface);border:1px solid var(--f-border);border-radius:var(--f-radius-panel);
621
660
  box-shadow:var(--f-shadow-card);display:flex;flex-direction:column;min-height:0;overflow:hidden;
@@ -1040,6 +1079,15 @@ window.__ModuleLoader__.load({
1040
1079
  collapsed: new Set(['temporary']),
1041
1080
  collapsedTasks: new Set(),
1042
1081
  showTemporary: readPref('fang.panel.showTemporary', true),
1082
+ // 母体会话只读投影:默认只看最近 20 条,可切 50 / 全部(偏好存本机)。
1083
+ sessionWindow: (() => {
1084
+ try {
1085
+ const raw = window?.localStorage?.getItem('fang.panel.sessionWindow')
1086
+ if (raw === 'all') return 'all'
1087
+ const size = Number(raw)
1088
+ return Number.isFinite(size) && size >= 5 ? Math.min(200, Math.floor(size)) : 20
1089
+ } catch { return 20 }
1090
+ })(),
1043
1091
  view: 'console',
1044
1092
  busy: '',
1045
1093
  refreshing: false,
@@ -1100,6 +1148,13 @@ window.__ModuleLoader__.load({
1100
1148
  if (alive) render(true)
1101
1149
  }
1102
1150
  const setNotice = (notice) => { S.notice = notice; render() }
1151
+ const onFangNotice = (event) => notify('warn', String(event?.detail || ''))
1152
+ window.addEventListener('fang:notice', onFangNotice)
1153
+ const onMotherPortal = () => {
1154
+ S.view = 'console'
1155
+ setNotice({ tone: 'ok', title: '母体 Web', message: '母体 Web 就是当前 DSH 客户端,已切回瓮城控制台视图。' })
1156
+ }
1157
+ window.addEventListener('fang:mother-portal', onMotherPortal)
1103
1158
 
1104
1159
  // 渲染:整棵视图重建 + 焦点/滚动/光标恢复;编辑中挂起后台刷新,避免输入被重建。
1105
1160
  function render(force = false) {
@@ -1192,7 +1247,7 @@ window.__ModuleLoader__.load({
1192
1247
  const [statusRes, tasksRes, sessionsRes, essenceRes] = await Promise.all([
1193
1248
  api('/fang/api/status').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1194
1249
  api('/fang/api/tasks').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1195
- api('/fang/api/sessions').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1250
+ api(`/fang/api/sessions?limit=${S.sessionWindow === 'all' ? 1000 : S.sessionWindow}`).catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1196
1251
  api('/fang/api/essence/list').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1197
1252
  ])
1198
1253
  if (!alive || seq !== refreshSeq) return
@@ -1259,6 +1314,13 @@ window.__ModuleLoader__.load({
1259
1314
  // ── 动作 ────────────────────────────────────────────────────────────
1260
1315
  const isBusy = () => S.busy !== ''
1261
1316
 
1317
+ function setSessionWindow(next) {
1318
+ const normalized = next === 'all' ? 'all' : Math.max(5, Math.min(200, Math.floor(Number(next) || 20)))
1319
+ S.sessionWindow = normalized
1320
+ try { window.localStorage?.setItem('fang.panel.sessionWindow', String(normalized)) } catch { /* ignore */ }
1321
+ void refresh({ manual: true })
1322
+ }
1323
+
1262
1324
  async function deriveTask(payload) {
1263
1325
  if (deriveStore.inflight) return
1264
1326
  deriveStore.lastGesture = Date.now()
@@ -1270,7 +1332,7 @@ window.__ModuleLoader__.load({
1270
1332
  setNotice({
1271
1333
  tone: 'ok', title: payload?.sessionId ? '已派发:从会话继续' : '已派生新分身',
1272
1334
  message: `${result.taskId}${result.port ? ' · 端口 ' + result.port : ''}${result.adapter?.ok ? ' · 适配器已就绪' : ' · 适配器尚未就绪,右栏会标出健康状态'}`,
1273
- actions: result.url ? [{ label: '打开分身', href: result.url }] : [],
1335
+ actions: result.taskId ? [{ label: '打开分身', onClick: () => void openTask({ taskId: result.taskId }) }] : [],
1274
1336
  })
1275
1337
  await refresh()
1276
1338
  } else if (result) {
@@ -1353,7 +1415,7 @@ window.__ModuleLoader__.load({
1353
1415
  const body = result.body
1354
1416
  if (result.status === 200 && body?.ok) {
1355
1417
  S.view = 'console'
1356
- setNotice({ tone: 'ok', title: '已还原存档', message: `${task.title || task.taskId} 已重新启动 · 端口 ${body.port ?? '—'}`, actions: body.url ? [{ label: '打开分身', href: body.url }] : [] })
1418
+ setNotice({ tone: 'ok', title: '已还原存档', message: `${task.title || task.taskId} 已重新启动 · 端口 ${body.port ?? '—'}`, actions: [{ label: '打开分身', onClick: () => void openTask({ taskId: task.taskId }) }] })
1357
1419
  } else {
1358
1420
  const code = body?.error || (result.status ? 'http-' + result.status : 'network')
1359
1421
  setNotice({ tone: 'bad', title: '还原失败', message: failureHint(code), detail: body?.detail || diagnosticText(result.diagnostic) })
@@ -1408,16 +1470,557 @@ window.__ModuleLoader__.load({
1408
1470
  })
1409
1471
  }
1410
1472
 
1473
+ function captureEssence() {
1474
+ if (isBusy()) return
1475
+ const profile = String(S.status?.data?.mother?.profile || 'desktop')
1476
+ askPrompt({
1477
+ title: '从母体生成元主',
1478
+ label: '新元主名称',
1479
+ value: `${profile} 元主`,
1480
+ confirmLabel: '生成',
1481
+ hint: '复制母体 profile 的可写层:插件补丁、依赖与设置;不复制凭据、会话和 node_modules。生成后可在元主区设为默认派生基底。',
1482
+ onConfirm: async (name) => {
1483
+ const trimmed = String(name ?? '').trim()
1484
+ if (!trimmed) { S.modal.error = '请填写元主名称'; render(true); return false }
1485
+ S.busy = 'essence:capture'
1486
+ const result = await api('/fang/api/essence/capture', { method: 'POST', body: JSON.stringify({ name: trimmed }) })
1487
+ S.busy = ''
1488
+ const body = result.body
1489
+ if (result.status === 200 && body?.ok) {
1490
+ const status = String(body.status ?? '')
1491
+ const conflicts = Array.isArray(body.conflicts) ? body.conflicts.length : 0
1492
+ const captured = body.captured ?? {}
1493
+ setNotice({
1494
+ tone: status === 'ready' ? 'ok' : 'warn',
1495
+ title: status === 'ready' ? '元主已生成' : '元主已生成(有冲突)',
1496
+ message: `「${body.meta?.name || trimmed}」· 补丁 ${captured.patchEntries ?? 0} 条 · 依赖 ${captured.dependencies ?? 0} 个 · 设置 ${captured.settings ?? 0} 组 · 捆绑 ${captured.bundles ?? 0} 个`,
1497
+ detail: conflicts > 0 ? `${conflicts} 条合并冲突:元主已物化,但需要人工处理后再用于派生。` : '',
1498
+ })
1499
+ } else {
1500
+ const code = body?.error || (result.status ? 'http-' + result.status : 'network')
1501
+ setNotice({ tone: 'bad', title: '生成元主失败', message: failureHint(code), detail: body?.detail || diagnosticText(result.diagnostic) })
1502
+ }
1503
+ await refresh()
1504
+ },
1505
+ })
1506
+ }
1507
+
1508
+ // 升级链路 2.1:克隆母体 profile 到镜像(先自动备份,克隆后元主待同步)。
1509
+ function cloneMotherProfile() {
1510
+ if (isBusy()) return
1511
+ askConfirm({
1512
+ tone: 'info',
1513
+ title: '克隆母体到镜像?',
1514
+ confirm: 'clone-mother',
1515
+ message: '读取本机母体 profile(package.json / cordis.patch.yml / cordis.yml / settings),覆盖镜像 active/profile,并先自动备份当前镜像。\n\n克隆后所有元主会变成「🔼 待同步」——不会自动改它们的配置。',
1516
+ confirmLabel: '克隆母体',
1517
+ onConfirm: async () => {
1518
+ S.busy = 'mirror:clone'
1519
+ const result = await api('/fang/api/mirror/clone-profile', { method: 'POST', body: JSON.stringify({}) })
1520
+ S.busy = ''
1521
+ const body = result.body
1522
+ if (result.status === 200 && body?.ok) {
1523
+ setNotice({
1524
+ tone: 'ok', title: '母体已克隆到镜像',
1525
+ message: `版本 ${body.version} · ${(body.files || []).length} 个文件 → active/profile`,
1526
+ detail: body.backup ? `已自动备份:${body.backup.id}` : '',
1527
+ })
1528
+ } else {
1529
+ const code = body?.error || (result.status ? 'http-' + result.status : 'network')
1530
+ setNotice({ tone: 'bad', title: '克隆母体失败', message: failureHint(code), detail: body?.detail || diagnosticText(result.diagnostic) })
1531
+ }
1532
+ await refresh()
1533
+ },
1534
+ })
1535
+ }
1536
+
1537
+ // 升级链路 3:把元主 overlay 重放到当前镜像(配置不动)。
1538
+ async function syncEssence(essenceId) {
1539
+ if (isBusy()) return
1540
+ S.busy = 'essence:sync:' + essenceId
1541
+ const result = await api('/fang/api/essence/sync', { method: 'POST', body: JSON.stringify({ essenceId }) })
1542
+ S.busy = ''
1543
+ const body = result.body
1544
+ if (result.status === 200 && body?.ok) {
1545
+ setNotice({ tone: body.status === 'ready' ? 'ok' : 'warn', title: '元主已同步', message: `${essenceId} · ${body.status}${body.recomputed ? '(已重新物化)' : '(无需重算)'}` })
1546
+ } else {
1547
+ setNotice({ tone: 'bad', title: '元主同步失败', message: failureHint(body?.error || 'sync-failed'), detail: body?.detail || diagnosticText(result.diagnostic) })
1548
+ }
1549
+ await refresh()
1550
+ }
1551
+
1552
+ async function syncEssences() {
1553
+ if (isBusy()) return
1554
+ S.busy = 'essence:sync:all'
1555
+ const result = await api('/fang/api/essence/sync', { method: 'POST', body: JSON.stringify({}) })
1556
+ S.busy = ''
1557
+ const body = result.body
1558
+ if (result.status === 200 && body?.ok) {
1559
+ setNotice({
1560
+ tone: (body.conflicted || []).length > 0 ? 'warn' : 'ok',
1561
+ title: '元主批量同步完成',
1562
+ message: `重算 ${(body.recomputed || []).length} · 跳过 ${(body.skipped || []).length} · 冲突 ${(body.conflicted || []).length} · 失败 ${(body.failed || []).length}`,
1563
+ detail: (body.failed || []).length ? (body.failed || []).map((item) => `${item.id}: ${item.error}`).join('\n') : '',
1564
+ })
1565
+ } else {
1566
+ setNotice({ tone: 'bad', title: '元主批量同步失败', message: failureHint(body?.error || 'sync-failed'), detail: body?.detail || diagnosticText(result.diagnostic) })
1567
+ }
1568
+ await refresh()
1569
+ }
1570
+
1571
+ // 原身运行态:隔离 home 的配置态实例(不写母体 sessions)。
1572
+ async function essenceRuntime(action, essenceId) {
1573
+ if (isBusy()) return
1574
+ S.busy = 'essence:runtime:' + essenceId
1575
+ const result = await api('/fang/api/essence/runtime', { method: 'POST', body: JSON.stringify({ action, essenceId }) })
1576
+ S.busy = ''
1577
+ const body = result.body
1578
+ if (result.status === 200 && body?.ok) {
1579
+ setNotice({
1580
+ tone: 'ok',
1581
+ title: action === 'stop' ? '元主运行时已停止' : '元主运行时已启动',
1582
+ message: action === 'stop'
1583
+ ? '进程已停止(overlay 与数据保留)'
1584
+ : `端口 ${body.port ?? '—'} · 隔离 home:${body.sandboxHome ?? '—'}`,
1585
+ })
1586
+ } else {
1587
+ setNotice({ tone: 'bad', title: '元主运行态操作失败', message: failureHint(body?.error || 'runtime-failed'), detail: body?.detail || diagnosticText(result.diagnostic) })
1588
+ }
1589
+ await refresh()
1590
+ }
1591
+
1592
+ // 打开前选会话:多选 1–5 个进行中会话(归档会话不出现)。
1593
+ function showSessionPicker(sessions, onPick) {
1594
+ const doc = document
1595
+ const select = h('select', {
1596
+ multiple: true, size: 8,
1597
+ style: { width: '100%', minHeight: 160, marginTop: 10, font: '12px/1.4 inherit', borderRadius: 8, padding: 6 },
1598
+ }, ...sessions.map((session) => h('option', { value: session.sessionId },
1599
+ `${session.title || session.sessionId}${session.workspaceTitle ? ' · ' + session.workspaceTitle : ''}`)))
1600
+ const hint = h('div', { style: { fontSize: 12, opacity: .7, marginTop: 6 } },
1601
+ 'Ctrl/⌘ 多选,最多 5 个**进行中**会话;归档会话不会出现在这里。')
1602
+ const btn = (label, primary) => h('button', {
1603
+ type: 'button',
1604
+ style: {
1605
+ height: 30, padding: '0 12px', borderRadius: 8, cursor: 'pointer', fontSize: 12,
1606
+ border: primary ? '1px solid #17803D' : '1px solid rgba(255,255,255,.24)',
1607
+ background: primary ? '#17803D' : 'transparent', color: '#fff',
1608
+ },
1609
+ }, label)
1610
+ const startBtn = btn('启动并导入', true)
1611
+ const skipBtn = btn('仅启动', false)
1612
+ const cancelBtn = btn('取消', false)
1613
+ const card = h('div', {
1614
+ role: 'dialog', 'aria-modal': 'true',
1615
+ style: { width: 'min(560px, 92vw)', padding: 18, borderRadius: 14, background: '#1D1D1F', color: '#fff' },
1616
+ },
1617
+ h('div', { style: { fontSize: 14, fontWeight: 600 } }, '打开元主 Web:导入进行中会话'),
1618
+ hint,
1619
+ select,
1620
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } }, startBtn, skipBtn, cancelBtn))
1621
+ const backdrop = h('div', {
1622
+ style: {
1623
+ position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
1624
+ alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,.55)',
1625
+ },
1626
+ }, card)
1627
+ const close = () => backdrop.remove()
1628
+ startBtn.addEventListener('click', () => {
1629
+ const ids = [...(select.selectedOptions || [])].map((option) => option.value)
1630
+ if (ids.length > 5) { hint.textContent = '最多选择 5 个会话'; return }
1631
+ close()
1632
+ onPick(ids)
1633
+ })
1634
+ skipBtn.addEventListener('click', () => { close(); onPick([]) })
1635
+ cancelBtn.addEventListener('click', close)
1636
+ backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close() })
1637
+ doc.body.appendChild(backdrop)
1638
+ }
1639
+
1640
+ function showDerivePicker(sessions, essenceName, onPick) {
1641
+ const doc = document
1642
+ const select = h('select', {
1643
+ size: Math.min(8, Math.max(4, sessions.length)),
1644
+ style: { width: '100%', minHeight: 150, marginTop: 10, font: '12px/1.4 inherit', borderRadius: 8, padding: 6 },
1645
+ }, ...sessions.map((session) => h('option', { value: session.sessionId },
1646
+ `${session.title || session.sessionId}${session.workspaceTitle ? ' · ' + session.workspaceTitle : ''}`)))
1647
+ const hint = h('div', { style: { fontSize: 12, opacity: .7, marginTop: 6 } },
1648
+ '选择一个进行中的 DSH 会话,整目录复制进新分身的沙箱(归档会话不列出)。')
1649
+ const btn = (label, primary) => h('button', {
1650
+ type: 'button',
1651
+ style: {
1652
+ height: 30, padding: '0 12px', borderRadius: 8, cursor: 'pointer', fontSize: 12,
1653
+ border: primary ? '1px solid #17803D' : '1px solid rgba(255,255,255,.24)',
1654
+ background: primary ? '#17803D' : 'transparent', color: '#fff',
1655
+ },
1656
+ }, label)
1657
+ const startBtn = btn('派 生', true)
1658
+ const cancelBtn = btn('取消', false)
1659
+ const card = h('div', {
1660
+ role: 'dialog', 'aria-modal': 'true',
1661
+ style: { width: 'min(560px, 92vw)', padding: 18, borderRadius: 14, background: '#1D1D1F', color: '#fff' },
1662
+ },
1663
+ h('div', { style: { fontSize: 14, fontWeight: 600 } }, `派生分身 · 基于「${essenceName}」`),
1664
+ hint,
1665
+ select,
1666
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } }, startBtn, cancelBtn))
1667
+ const backdrop = h('div', {
1668
+ style: {
1669
+ position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
1670
+ alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,.55)',
1671
+ },
1672
+ }, card)
1673
+ const close = () => backdrop.remove()
1674
+ startBtn.addEventListener('click', () => {
1675
+ const picked = String(select.value || '')
1676
+ if (!picked) { hint.textContent = '请选择一个会话'; return }
1677
+ close()
1678
+ onPick(picked)
1679
+ })
1680
+ cancelBtn.addEventListener('click', close)
1681
+ backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close() })
1682
+ doc.body.appendChild(backdrop)
1683
+ }
1684
+
1685
+ async function deriveFromEssence(essence) {
1686
+ if (isBusy()) return
1687
+ S.busy = 'essence:derive:' + essence.id
1688
+ const res = await api('/fang/api/sessions?limit=200')
1689
+ S.busy = ''
1690
+ const sessions = Array.isArray(res.body?.sessions)
1691
+ ? res.body.sessions.filter((session) => session.archived !== true)
1692
+ : []
1693
+ if (sessions.length === 0) {
1694
+ setNotice({ tone: 'warn', title: '没有可复制的会话', message: '先在 DSH 里有一个进行中的会话,再派生。' })
1695
+ return
1696
+ }
1697
+ showDerivePicker(sessions, essence.name || essence.id, async (sessionId) => {
1698
+ const session = sessions.find((item) => String(item.sessionId) === String(sessionId))
1699
+ const title = String(session?.title || essence.name || '派生分身').slice(0, 60)
1700
+ S.busy = 'essence:derive:run:' + essence.id
1701
+ const out = await api('/fang/api/tasks/create', {
1702
+ method: 'POST',
1703
+ body: JSON.stringify({ title, essenceId: essence.id, importSession: { sessionId } }),
1704
+ })
1705
+ S.busy = ''
1706
+ if (out.status === 200 && out.body?.ok) {
1707
+ setNotice({ tone: 'ok', title: '已派生分身', message: `模板「${essence.name || essence.id}」· 会话 ${short(String(sessionId), 8)}` })
1708
+ } else {
1709
+ setNotice({ tone: 'bad', title: '派生失败', message: failureHint(out.body?.error || 'http-' + out.status), detail: out.body?.detail || '' })
1710
+ }
1711
+ await refresh()
1712
+ })
1713
+ }
1714
+
1715
+ async function startEssenceRuntime(essenceId, sessionIds) {
1716
+ S.busy = 'essence:start:' + essenceId
1717
+ const started = await api('/fang/api/essence/runtime', {
1718
+ method: 'POST',
1719
+ body: JSON.stringify({ action: 'start', essenceId, sessionIds }),
1720
+ })
1721
+ S.busy = ''
1722
+ if (started.status === 200 && started.body?.ok) {
1723
+ const imported = Array.isArray(started.body.importedSessions) ? started.body.importedSessions.length : 0
1724
+ setNotice({ tone: 'ok', title: '元主 Web 已启动', message: `端口 ${started.body.port ?? '—'} · 导入会话 ${imported} 个` })
1725
+ if (started.body.url) { try { window.open(String(started.body.url), '_blank', 'noopener') } catch { /* 弹层被拦 */ } }
1726
+ } else {
1727
+ setNotice({ tone: 'bad', title: '启动元主 Web 失败', message: failureHint(started.body?.error || 'runtime-failed'), detail: started.body?.detail || '' })
1728
+ }
1729
+ await refresh()
1730
+ }
1731
+
1732
+ // 打开&设置:已在跑 → 直接开带 token 的 URL;没跑 → 选会话后启动再打开。
1733
+ async function openEssence(essenceId) {
1734
+ if (isBusy()) return
1735
+ S.busy = 'essence:open:' + essenceId
1736
+ const st = await api(`/fang/api/essence/runtime?essenceId=${encodeURIComponent(essenceId)}`)
1737
+ const runtime = st.body?.runtime ?? null
1738
+ const running = Boolean(runtime && (runtime.running === true || String(runtime.status) === 'running'))
1739
+ S.busy = ''
1740
+ if (running) {
1741
+ const opened = await api(`/fang/api/essence/runtime/open?essenceId=${encodeURIComponent(essenceId)}`)
1742
+ if (opened.status === 200 && opened.body?.url) { try { window.open(String(opened.body.url), '_blank', 'noopener') } catch { /* 弹层被拦 */ } }
1743
+ else setNotice({ tone: 'bad', title: '无法打开元主 Web', message: '实例在跑但拿不到带 token 的地址' })
1744
+ return
1745
+ }
1746
+ const candidates = await api('/fang/api/essence/open/candidates')
1747
+ const sessions = Array.isArray(candidates.body?.sessions) ? candidates.body.sessions : []
1748
+ showSessionPicker(sessions, (sessionIds) => void startEssenceRuntime(essenceId, sessionIds))
1749
+ }
1750
+
1751
+ async function copyEssence(essence) {
1752
+ if (isBusy()) return
1753
+ askPrompt({
1754
+ title: '复制元主', label: '新元主名称', value: `${essence.name || essence.id} 副本`, confirmLabel: '复制',
1755
+ hint: '深复制该元主的整份沙盒目录(overlay + merged + 自定义数据)到新文件夹;不复制凭据、运行态与备份。',
1756
+ onConfirm: async (name) => {
1757
+ const trimmed = String(name ?? '').trim()
1758
+ if (!trimmed) { S.modal.error = '请填写名称'; render(true); return false }
1759
+ const result = await api('/fang/api/essence/copy', { method: 'POST', body: JSON.stringify({ essenceId: essence.id, name: trimmed }) })
1760
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已复制', message: trimmed })
1761
+ else setNotice({ tone: 'bad', title: '复制失败', message: failureHint(result.body?.error || 'http-' + result.status) })
1762
+ await refresh()
1763
+ },
1764
+ })
1765
+ }
1766
+
1767
+ function archiveEssence(essence) {
1768
+ if (isBusy()) return
1769
+ askConfirm({
1770
+ tone: 'info', title: '归档元主?', confirm: 'essence-archive',
1771
+ message: `「${essence.name || essence.id}」将归档:只改元数据,不删目录;归档后不能派生/配置。`,
1772
+ confirmLabel: '归档',
1773
+ onConfirm: async () => {
1774
+ const result = await api('/fang/api/essence/archive', { method: 'POST', body: JSON.stringify({ essenceId: essence.id, archived: true }) })
1775
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已归档', message: essence.name || essence.id })
1776
+ else setNotice({ tone: 'bad', title: '归档失败', message: failureHint(result.body?.error || 'http-' + result.status) })
1777
+ await refresh()
1778
+ },
1779
+ })
1780
+ }
1781
+
1782
+ async function stopEssenceRuntime(essence) {
1783
+ if (isBusy()) return
1784
+ S.busy = 'essence:stop'
1785
+ const result = await api('/fang/api/essence/runtime', { method: 'POST', body: JSON.stringify({ action: 'stop', essenceId: essence.id }) })
1786
+ S.busy = ''
1787
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '运行实例已停止', message: essence.name || essence.id })
1788
+ else setNotice({ tone: 'bad', title: '停止失败', message: failureHint(result.body?.error || 'http-' + result.status), detail: result.body?.detail || '' })
1789
+ await refresh()
1790
+ }
1791
+
1792
+ async function openBranches(task) {
1793
+ if (isBusy()) return
1794
+ S.busy = 'branches:' + task.taskId
1795
+ const res = await api('/fang/api/tasks/branches?taskId=' + encodeURIComponent(task.taskId))
1796
+ S.busy = ''
1797
+ const body = res.body ?? {}
1798
+ S.modal = {
1799
+ kind: 'branches',
1800
+ taskId: task.taskId,
1801
+ taskTitle: task.title || task.taskId,
1802
+ sessionId: body.sessionId ?? '',
1803
+ activeBranchId: body.activeBranchId ?? '',
1804
+ branches: Array.isArray(body.branches) ? body.branches : [],
1805
+ error: res.status === 200 && body.ok === true ? '' : failureHint(body.error || 'http-' + res.status),
1806
+ }
1807
+ render(true)
1808
+ }
1809
+
1810
+ async function forkBranch(task) {
1811
+ if (isBusy()) return
1812
+ S.busy = 'branch-fork:' + task.taskId
1813
+ const res = await api('/fang/api/tasks/branches/fork', { method: 'POST', body: JSON.stringify({ taskId: task.taskId }) })
1814
+ S.busy = ''
1815
+ if (res.status === 200 && res.body?.ok) {
1816
+ setNotice({ tone: 'ok', title: '已派生分支', message: res.body.branch?.branchId || '' })
1817
+ await openBranches(task)
1818
+ } else {
1819
+ setNotice({ tone: 'bad', title: '派生分支失败', message: failureHint(res.body?.error || 'http-' + res.status), detail: res.body?.detail || '' })
1820
+ render(true)
1821
+ }
1822
+ }
1823
+
1824
+ async function activateBranch(task, branchId) {
1825
+ if (isBusy()) return
1826
+ S.busy = 'branch-activate:' + task.taskId
1827
+ const res = await api('/fang/api/tasks/branches/activate', { method: 'POST', body: JSON.stringify({ taskId: task.taskId, branchId }) })
1828
+ S.busy = ''
1829
+ if (res.status === 200 && res.body?.ok) setNotice({ tone: 'ok', title: '已激活分支', message: branchId })
1830
+ else setNotice({ tone: 'bad', title: '激活分支失败', message: failureHint(res.body?.error || 'http-' + res.status) })
1831
+ await openBranches(task)
1832
+ }
1833
+
1834
+ function unfreezeEssence(essence) {
1835
+ if (isBusy()) return
1836
+ askConfirm({
1837
+ tone: 'info', title: '还原(解冻)元主?', confirm: 'essence-unfreeze',
1838
+ message: `「${essence.name || essence.id}」将从冻结态恢复为活跃:可打开/设置/派生;备份内容不变,删除仍可用。`,
1839
+ confirmLabel: '还原',
1840
+ onConfirm: async () => {
1841
+ S.busy = 'essence:unfreeze'
1842
+ const result = await api('/fang/api/essence/archive', { method: 'POST', body: JSON.stringify({ essenceId: essence.id, archived: false }) })
1843
+ S.busy = ''
1844
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已还原(解冻)', message: essence.name || essence.id })
1845
+ else setNotice({ tone: 'bad', title: '还原失败', message: failureHint(result.body?.error || 'http-' + result.status), detail: result.body?.detail || '' })
1846
+ await refresh()
1847
+ },
1848
+ })
1849
+ }
1850
+
1851
+ function deleteEssence(essence) {
1852
+ if (isBusy()) return
1853
+ if (essence.archived !== true) {
1854
+ setNotice({ tone: 'warn', title: '需先归档才能删除', message: '元主必须先归档(冻结)后,删除按钮才可用。' })
1855
+ return
1856
+ }
1857
+ // 两次确认:第一次说明后果,第二次必须输入元主名称。
1858
+ askConfirm({
1859
+ tone: 'bad', title: '删除元主?', confirm: 'delete-once',
1860
+ message: `「${essence.name || essence.id}」已冻结。删除会移除 essences/${essence.id}(overlay + merged),不可撤销,也不会删除会话。`,
1861
+ confirmLabel: '继续',
1862
+ onConfirm: () => {
1863
+ askConfirm({
1864
+ tone: 'bad', title: '再次确认:永久删除', confirm: 'delete', strong: true,
1865
+ expected: String(essence.name || essence.id),
1866
+ message: `最后一步:输入「${essence.name || essence.id}」以永久删除该元主。`,
1867
+ confirmLabel: '永久删除',
1868
+ onConfirm: async () => {
1869
+ S.busy = 'essence:delete:' + essence.id
1870
+ const result = await api('/fang/api/essence/delete', { method: 'POST', body: JSON.stringify({ essenceId: essence.id }) })
1871
+ S.busy = ''
1872
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已删除', message: essence.name || essence.id })
1873
+ else setNotice({ tone: 'bad', title: '删除元主失败', message: failureHint(result.body?.error || 'http-' + result.status), detail: result.body?.detail || '' })
1874
+ await refresh()
1875
+ },
1876
+ })
1877
+ },
1878
+ })
1879
+ }
1880
+
1881
+ async function saveBlob(blob, suggestedName) {
1882
+ try {
1883
+ if (typeof window.showSaveFilePicker === 'function') {
1884
+ const handle = await window.showSaveFilePicker({
1885
+ suggestedName,
1886
+ types: [{ description: '元主整包', accept: { 'application/json': ['.json'] } }],
1887
+ })
1888
+ const writable = await handle.createWritable()
1889
+ await writable.write(blob)
1890
+ await writable.close()
1891
+ return { ok: true, mode: 'picker' }
1892
+ }
1893
+ } catch (error) {
1894
+ if (String(error?.name) === 'AbortError') return { ok: false, aborted: true }
1895
+ }
1896
+ const link = h('a', { href: URL.createObjectURL(blob), download: suggestedName })
1897
+ document.body.appendChild(link)
1898
+ link.click()
1899
+ link.remove()
1900
+ return { ok: true, mode: 'download' }
1901
+ }
1902
+
1903
+ async function downloadEssence(essence) {
1904
+ try {
1905
+ const token = await ensureFangAuthToken()
1906
+ const res = await fetch(`/fang/api/essence/download?essenceId=${encodeURIComponent(essence.id)}&full=1`, {
1907
+ headers: token ? { 'x-fang-auth': token } : {},
1908
+ })
1909
+ if (!res.ok) throw new Error('HTTP ' + res.status)
1910
+ const blob = await res.blob()
1911
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '')
1912
+ const name = `essence-${String(essence.name || essence.id).replace(/[\\/:*?"<>|\s]+/g, '-')}-${stamp}.json`
1913
+ const saved = await saveBlob(blob, name)
1914
+ if (saved.aborted) return
1915
+ setNotice({
1916
+ tone: 'ok',
1917
+ title: '元主整包已下载',
1918
+ message: `${name}(${Math.round(blob.size / 1024)} KB)`,
1919
+ detail: saved.mode === 'picker' ? '已保存到你选择的文件夹;包内含 IMPORT-GUIDE.md 与 manifest.json。' : '已保存到下载目录;包内含导入引导与清单。',
1920
+ })
1921
+ } catch (error) {
1922
+ setNotice({ tone: 'bad', title: '下载元主失败', message: String(error?.message ?? error) })
1923
+ }
1924
+ }
1925
+
1926
+ async function essenceBackup(essence) {
1927
+ const result = await api('/fang/api/essence/backup', { method: 'POST', body: JSON.stringify({ essenceId: essence.id }) })
1928
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已备份', message: `Backup/ · ${Math.round((result.body.bytes || 0) / 1024)} KB(只保留一份)` })
1929
+ else setNotice({ tone: 'bad', title: '备份失败', message: failureHint(result.body?.error || 'backup-failed'), detail: result.body?.detail || '' })
1930
+ await refresh()
1931
+ }
1932
+
1933
+ async function essenceRestore(essence) {
1934
+ if (isBusy()) return
1935
+ askConfirm({
1936
+ tone: 'info', title: '还原最新备份?', confirm: 'essence-restore',
1937
+ message: `用「${essence.name || essence.id}/Backup」覆盖当前 overlay 与 merged,还原后需重新同步/派生。`,
1938
+ confirmLabel: '还原',
1939
+ onConfirm: async () => {
1940
+ const result = await api('/fang/api/essence/restore', { method: 'POST', body: JSON.stringify({ essenceId: essence.id }) })
1941
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '已还原最新备份', message: essence.name || essence.id })
1942
+ else setNotice({ tone: 'bad', title: '还原失败', message: failureHint(result.body?.error || 'restore-failed'), detail: result.body?.detail || '' })
1943
+ await refresh()
1944
+ },
1945
+ })
1946
+ }
1947
+
1948
+ function essenceImport() {
1949
+ const input = h('input', { type: 'file', accept: '.json,application/json', style: { display: 'none' } })
1950
+ input.addEventListener('change', async () => {
1951
+ const file = input.files?.[0]
1952
+ input.remove()
1953
+ if (!file) return
1954
+ try {
1955
+ const bundle = JSON.parse(await file.text())
1956
+ S.busy = 'essence:import'
1957
+ const result = await api('/fang/api/essence/import', { method: 'POST', body: JSON.stringify({ bundle }) })
1958
+ S.busy = ''
1959
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已导入', message: `${result.body.essence?.name || '导入的元主'} · ${result.body.files} 个文件` })
1960
+ else setNotice({ tone: 'bad', title: '导入失败', message: failureHint(result.body?.error || 'import-failed'), detail: result.body?.detail || '' })
1961
+ await refresh()
1962
+ } catch (error) {
1963
+ S.busy = ''
1964
+ setNotice({ tone: 'bad', title: '导入失败', message: String(error?.message ?? error) })
1965
+ }
1966
+ })
1967
+ document.body.appendChild(input)
1968
+ input.click()
1969
+ }
1970
+
1971
+ // 单个元主详情页:设置 / 插件 / 运行日志 三个 tab。
1972
+ async function loadEssenceDetail() {
1973
+ const modal = S.modal
1974
+ if (!modal || modal.kind !== 'essence') return
1975
+ const result = await api(`/fang/api/essence/detail?essenceId=${encodeURIComponent(modal.essenceId)}`)
1976
+ if (!S.modal || S.modal !== modal) return
1977
+ modal.loading = false
1978
+ if (result.status === 200 && result.body?.ok) modal.detail = result.body
1979
+ else modal.error = result.body?.error || 'http-' + result.status
1980
+ render(true)
1981
+ }
1982
+
1983
+ function openEssenceDetail(essence) {
1984
+ lockScroll()
1985
+ S.modal = { kind: 'essence', essenceId: essence.id, tab: 'settings', detail: null, loading: true, error: '' }
1986
+ render(true)
1987
+ void loadEssenceDetail()
1988
+ }
1989
+
1411
1990
  async function openTask(task) {
1412
1991
  const taskId = String(task?.taskId ?? '')
1413
- if (taskId) {
1414
- const result = await api(`/fang/api/tasks/open-url?taskId=${encodeURIComponent(taskId)}`)
1415
- if (result.status === 200 && result.body?.url) {
1416
- try { window.open(result.body.url, '_blank', 'noopener'); return } catch { /* 弹层被拦 */ }
1992
+ if (!taskId) { notify('warn', '该分身没有 taskId,无法打开。'); return }
1993
+ const result = await api(`/fang/api/tasks/open-url?taskId=${encodeURIComponent(taskId)}`)
1994
+ if (result.status === 200 && result.body?.url) {
1995
+ try { window.open(result.body.url, '_blank', 'noopener'); return } catch { /* 弹层被拦 */ }
1996
+ }
1997
+ const code = result.body?.error || (result.status ? 'http-' + result.status : 'network')
1998
+ if (code === 'not-running') {
1999
+ notify('warn', '分身已停止,正在启动…')
2000
+ let restored = await api('/fang/api/tasks/restore', { method: 'POST', body: JSON.stringify({ taskId }) })
2001
+ // A stopped (but not archived) fork cannot be restored directly; archive it
2002
+ // first (keeps home), then restore spawns from the same home.
2003
+ if (restored.body?.error === 'not-archived' && String(task?.status || '') !== 'running') {
2004
+ const archived = await api('/fang/api/tasks/archive', { method: 'POST', body: JSON.stringify({ taskId }) })
2005
+ if (archived.status === 200 && archived.body?.ok !== false) {
2006
+ restored = await api('/fang/api/tasks/restore', { method: 'POST', body: JSON.stringify({ taskId }) })
2007
+ }
2008
+ }
2009
+ if (restored.status !== 200 || restored.body?.ok === false) {
2010
+ notify('bad', `启动分身失败:${restored.body?.error || 'restore-failed'}`)
2011
+ return
1417
2012
  }
2013
+ for (let i = 0; i < 20; i += 1) {
2014
+ await new Promise((resolve) => setTimeout(resolve, 800))
2015
+ const retry = await api(`/fang/api/tasks/open-url?taskId=${encodeURIComponent(taskId)}`)
2016
+ if (retry.status === 200 && retry.body?.url) {
2017
+ try { window.open(retry.body.url, '_blank', 'noopener'); return } catch { /* 弹层被拦 */ }
2018
+ }
2019
+ }
2020
+ notify('warn', '分身已启动,但 Web URL 尚未就绪;稍后点“打开”再试。')
2021
+ return
1418
2022
  }
1419
- if (!task?.url) { notify('warn', '该分身没有可打开的 URL(可能已停止);可归档回收。'); return }
1420
- try { window.open(task.url, '_blank', 'noopener') } catch { /* ignore */ }
2023
+ notify('bad', `打开分身失败:${code}`)
1421
2024
  }
1422
2025
 
1423
2026
  async function copyText(text, label) {
@@ -1598,7 +2201,11 @@ window.__ModuleLoader__.load({
1598
2201
 
1599
2202
  const app = {
1600
2203
  state: S, view, render, schedule, refresh, deriveTask, openMother, closeModal,
1601
- archiveTask, restoreTask, deleteArchive, promoteTask, openTask, copyText,
2204
+ archiveTask, restoreTask, deleteArchive, promoteTask, openTask, copyText, captureEssence,
2205
+ cloneMotherProfile, syncEssence, syncEssences, setSessionWindow, essenceRuntime,
2206
+ openEssence, copyEssence, archiveEssence, deleteEssence, downloadEssence, essenceImport,
2207
+ essenceBackup, essenceRestore, openEssenceDetail, unfreezeEssence, stopEssenceRuntime,
2208
+ openBranches, forkBranch, activateBranch, deriveFromEssence,
1602
2209
  beginRename, commitRename, cancelRename, selectSession, toggleSet, toggleForkGroup,
1603
2210
  toggleTemporary, setView: (next) => { S.view = next; schedule(true) },
1604
2211
  loadForkSessions, loadMirror, mirrorAction, loadLink, probeMother, notify, announce,
@@ -1622,6 +2229,8 @@ window.__ModuleLoader__.load({
1622
2229
  if (pollTimer) window.clearInterval(pollTimer)
1623
2230
  if (toastTimer) window.clearTimeout(toastTimer)
1624
2231
  if (deriveTicker) window.clearInterval(deriveTicker)
2232
+ window.removeEventListener('fang:notice', onFangNotice)
2233
+ window.removeEventListener('fang:mother-portal', onMotherPortal)
1625
2234
  unsubscribe()
1626
2235
  root.remove()
1627
2236
  },
@@ -1976,19 +2585,39 @@ window.__ModuleLoader__.load({
1976
2585
  const all = S.sessions.items
1977
2586
  const query = S.query.trim().toLowerCase()
1978
2587
  const filtered = query ? all.filter((session) => sessionSearchText(session).includes(query)) : all
1979
- const groups = groupMotherWorkspaces(filtered, S.aliases)
1980
- const split = classifyMotherSessions(filtered)
2588
+ // 空会话(无用户消息)不进列表:它们没有任何内容可看。
2589
+ const visible = filtered.filter((session) => session?.empty !== true)
2590
+ const groups = groupMotherWorkspaces(visible, S.aliases)
2591
+ const split = classifyMotherSessions(visible)
1981
2592
  const selected = all.find((session) => String(session.sessionId) === S.selectedSessionId) || null
1982
2593
  const countText = query
1983
- ? `${filtered.length}/${all.length}`
1984
- : `${all.length}${S.sessions.total > all.length ? '/' + S.sessions.total : ''}`
2594
+ ? `${visible.length}/${all.length}`
2595
+ : `${visible.length}${S.sessions.total > all.length ? '/' + S.sessions.total : ''}`
1985
2596
  const sessionState = S.sessions.state
1986
2597
 
1987
2598
  const head = h('div', { class: 'panel-head' },
1988
2599
  h('div', { class: 'panel-title-row' },
1989
2600
  h('h2', { class: 'panel-title' }, '母体'),
1990
2601
  h('span', { class: 'panel-sub' }, '元主 · 项目 & 会话'),
1991
- h('span', { class: 'panel-count', title: '已加载 / 宿主返回的会话总数' }, `${countText} 会话`)),
2602
+ h('span', { class: 'panel-count', title: '已加载 / 宿主返回的会话总数' }, `${countText} 会话`),
2603
+ (() => {
2604
+ const stale = Number(S.essenceList?.data?.staleCount) || 0
2605
+ const update = S.mirror?.data?.updateAvailable === true
2606
+ const conflicted = (S.essenceList?.data?.essences || []).filter((item) => item.status === 'conflicted').length
2607
+ const tone2 = (conflicted > 0) ? 'red' : (stale > 0 || update) ? 'yellow' : 'green'
2608
+ const label2 = tone2 === 'red' ? '红灯' : tone2 === 'yellow' ? '黄灯' : '绿灯'
2609
+ const reasons = []
2610
+ if (update) reasons.push('母体有新版本')
2611
+ if (stale > 0) reasons.push(`${stale} 个元主待同步`)
2612
+ if (conflicted > 0) reasons.push(`${conflicted} 个元主冲突`)
2613
+ return h('span', {
2614
+ class: 'chip', 'data-lamp': tone2,
2615
+ title: reasons.length ? reasons.join(';') : '母体 / 元主 / 分身状态正常',
2616
+ style: { display: 'inline-flex', alignItems: 'center', gap: 6 },
2617
+ },
2618
+ h('span', { 'aria-hidden': 'true', style: { width: 8, height: 8, borderRadius: '50%', background: tone2 === 'red' ? '#C8102E' : tone2 === 'yellow' ? '#B45309' : '#17803D' } }),
2619
+ label2)
2620
+ })()),
1992
2621
  (() => {
1993
2622
  const data = S.status.data
1994
2623
  const tone = S.status.state === 'ready' ? 'ok' : data ? 'info' : 'neutral'
@@ -2001,6 +2630,11 @@ window.__ModuleLoader__.load({
2001
2630
  chip(tone, label, { state: S.status.state === 'ready' ? 'running' : 'unknown' }),
2002
2631
  data?.version ? h('span', { class: 'hint', style: { fontFamily: 'var(--f-mono)' } }, 'v' + String(data.version).replace(/^v/, '')) : null),
2003
2632
  h('div', { class: 'mother-control-sub' }, '只读访问:不写入、不改写母体会话')),
2633
+ button('克隆母体', {
2634
+ size: 'sm', variant: 'quiet', dataBtnId: 'M-07',
2635
+ title: '把本机母体 profile(package.json / cordis.patch.yml / settings)克隆到镜像 active/,先自动备份;克隆后元主会黄灯待同步',
2636
+ onClick: () => void app.cloneMotherProfile(),
2637
+ }),
2004
2638
  button('打开门户', {
2005
2639
  size: 'sm', variant: 'quiet', icon: icon('globe', 12), dataBtnId: 'M-06',
2006
2640
  title: '在新窗口打开 /fang/panel 独立门户(不关闭母体)',
@@ -2022,8 +2656,26 @@ window.__ModuleLoader__.load({
2022
2656
  h('div', { class: 'panel-tools' },
2023
2657
  h('span', null, `进行中 ${split.active.length}`),
2024
2658
  h('span', { class: 'spacer' }),
2025
- h('span', null, `临时 ${split.temporary.length} · 归档 ${split.archived.length}`),
2659
+ h('span', { class: 'session-window', 'data-zone': 'session-window', style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
2660
+ h('span', { class: 'hint' }, '显示'),
2661
+ ...[[20, '20'], [50, '50'], ['all', '全部']].map(([value, label]) => {
2662
+ const on = S.sessionWindow === value
2663
+ return h('button', {
2664
+ type: 'button',
2665
+ 'data-window': String(value),
2666
+ 'aria-pressed': on ? 'true' : 'false',
2667
+ title: value === 'all' ? '加载宿主返回的全部会话(只读投影)' : `只显示最近 ${label} 条会话`,
2668
+ onClick: () => app.setSessionWindow(value),
2669
+ style: {
2670
+ height: 22, padding: '0 7px', borderRadius: 6, cursor: 'pointer', fontSize: 11,
2671
+ border: '1px solid ' + (on ? 'rgba(127,127,127,.55)' : 'transparent'),
2672
+ background: on ? 'rgba(127,127,127,.16)' : 'transparent',
2673
+ color: 'inherit',
2674
+ },
2675
+ }, label)
2676
+ })),
2026
2677
  h('span', { class: 'spacer' }),
2678
+ h('span', null, `临时 ${split.temporary.length} · 归档 ${split.archived.length}`),
2027
2679
  h('span', { title: '没有写接口的动作会明确禁用并说明原因,不会假装成功' }, '只读')))
2028
2680
 
2029
2681
  const scroll = h('div', { class: 'panel-scroll', 'data-sk': 'left' })
@@ -2034,7 +2686,7 @@ window.__ModuleLoader__.load({
2034
2686
  scroll.append(emptyBlock('母体会话不可读', failureHint(S.sessions.error), [
2035
2687
  button('重试', { size: 'sm', variant: 'ghost', onClick: () => void app.refresh({ manual: true }) }),
2036
2688
  ]))
2037
- } else if (filtered.length === 0) {
2689
+ } else if (visible.length === 0) {
2038
2690
  scroll.append(emptyBlock(
2039
2691
  query ? `没有匹配「${clampText(S.query, 20)}」的会话` : '还没有母体会话',
2040
2692
  query ? '搜索标题、会话 ID 或工作区名;Esc 清空搜索。' : '在本机开一个新对话后刷新,它会出现在这里。选择会话是只读元数据,母体会话不会被改写。',
@@ -2044,7 +2696,7 @@ window.__ModuleLoader__.load({
2044
2696
  // 元主工作区的新建/归档/删除/下载是宿主职责:DOM 中不出现这些控件(不是禁用)。
2045
2697
  scroll.append(h('div', { class: 'section-head' },
2046
2698
  h('span', { class: 'section-title', style: { cursor: 'default' } }, '元主'),
2047
- h('span', { class: 'section-sub' }, `${groups.length} 个工作区`),
2699
+ h('span', { class: 'section-sub' }, `${groups.length} 个工作区 · ${visible.length} 条会话`),
2048
2700
  h('span', { class: 'spacer' }),
2049
2701
  h('span', { class: 'section-hint', title: '工作区 CRUD 属于 DSH 宿主;fang 不复制宿主职责' }, '宿主管理 · 只读')))
2050
2702
 
@@ -2058,18 +2710,112 @@ window.__ModuleLoader__.load({
2058
2710
  }
2059
2711
 
2060
2712
  const essences = Array.isArray(S.essenceList?.data?.essences) ? S.essenceList.data.essences : []
2061
- const essenceList = essences.length
2062
- ? h('div', { class: 'essence-list', 'data-zone': 'essence-list', style: { display: 'flex', flexWrap: 'wrap', gap: '8px', padding: '4px 8px' } },
2063
- ...essences.map((essence) => h('div', { class: 'essence-row', 'data-essence-id': essence.id, style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
2064
- essence.locked
2065
- ? h('span', { class: 'hint' }, essence.name || essence.id)
2066
- : editableText(S, app, { key: 'essence:' + essence.id, label: '元主', value: essence.name || essence.id }),
2067
- essence.locked ? h('span', { class: 'chip' }, '锁定') : null)))
2068
- : null
2713
+ const defaultEssenceId = String(S.essenceList?.data?.defaultId ?? '')
2714
+ const staleCount = Number(S.essenceList?.data?.staleCount) || 0
2715
+ const essenceHead = h('div', { class: 'section-head', 'data-zone': 'essence-head' },
2716
+ h('span', { class: 'section-title', style: { cursor: 'default' } }, '元主'),
2717
+ h('span', { class: 'section-sub' }, `${essences.length} 个 · 默认 ${defaultEssenceId ? short(defaultEssenceId, 18) : '—'}${staleCount > 0 ? ` · ${staleCount} 待同步` : ''}`),
2718
+ h('span', { class: 'spacer' }),
2719
+ staleCount > 0
2720
+ ? button('全部同步', {
2721
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-02',
2722
+ title: '把所有待同步元主重放到新母体:只重建底层,用户插件配置与设置保持不变',
2723
+ onClick: () => void app.syncEssences(),
2724
+ })
2725
+ : null,
2726
+ button('导入', {
2727
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-11',
2728
+ title: '导入元主整包(自己或他人下载的 JSON):生成新元主文件夹并重算,可直接继续开发',
2729
+ onClick: () => void app.essenceImport(),
2730
+ }),
2731
+ button('从母体生成元主', {
2732
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-01',
2733
+ title: '克隆母体 profile 的可写层(插件补丁/依赖/设置)生成新元主;不复制凭据与会话',
2734
+ onClick: () => void app.captureEssence(),
2735
+ }))
2736
+ const essenceList = h('div', { class: 'essence-list', 'data-zone': 'essence-list', style: { display: 'flex', flexWrap: 'wrap', gap: '8px', padding: '4px 8px' } },
2737
+ essences.length === 0
2738
+ ? h('span', { class: 'hint' }, '还没有自定义元主;点上方「从母体生成元主」克隆当前母体配置。')
2739
+ : null,
2740
+ ...essences.map((essence) => h('div', { class: 'essence-row', 'data-essence-id': essence.id, style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
2741
+ essence.locked
2742
+ ? h('span', { class: 'hint' }, essence.name || essence.id)
2743
+ : editableText(S, app, { key: 'essence:' + essence.id, label: '元主', value: essence.name || essence.id }),
2744
+ essence.id === defaultEssenceId ? h('span', { class: 'chip' }, '默认') : null,
2745
+ essence.locked ? h('span', { class: 'chip' }, '锁定') : null,
2746
+ essence.stale ? h('span', { class: 'chip', title: '母体镜像已变化,此元主仍在旧镜像上' }, '🔼 待同步') : null,
2747
+ essence.stale && essence.locked !== true
2748
+ ? button('同步', {
2749
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-03',
2750
+ title: '重放该元主的插件/设置到新母体(配置不变)',
2751
+ onClick: () => void app.syncEssence(essence.id),
2752
+ })
2753
+ : null,
2754
+ essence.status === 'conflicted' ? h('span', { class: 'chip' }, '冲突') : null,
2755
+ essence.archived === true ? h('span', { class: 'chip', title: '已归档(冻结):只能还原或删除' }, '冻结') : null,
2756
+ h('span', { style: { display: 'inline-flex', gap: 4 } },
2757
+ essence.archived === true ? null : button('派生', {
2758
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-05',
2759
+ title: '派生:以该元主为模板创建分身(继承其插件&配置),可复制一个现有会话进分身沙箱',
2760
+ onClick: () => void app.deriveFromEssence(essence),
2761
+ }),
2762
+ essence.archived === true
2763
+ ? button('还原', {
2764
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-15',
2765
+ title: '解冻(恢复活跃态,可打开/设置/派生);不还原备份内容',
2766
+ onClick: () => void app.unfreezeEssence(essence),
2767
+ })
2768
+ : button(essence.runtime?.running === true ? '停止' : '打开', {
2769
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-06',
2770
+ title: essence.runtime?.running === true
2771
+ ? '停止该元主的运行实例(端口释放;会话/沙盒文件保留)'
2772
+ : '打开&设置:启动或打开该元主的隔离配置态实例(不写母体 sessions)',
2773
+ onClick: () => essence.runtime?.running === true ? void app.stopEssenceRuntime(essence) : void app.openEssence(essence.id),
2774
+ }),
2775
+ essence.runtime?.running === true && essence.archived !== true ? button('进入', {
2776
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-21',
2777
+ title: '在新标签打开运行中的实例(临时 token,不落盘)',
2778
+ onClick: () => void app.openEssence(essence.id),
2779
+ }) : null,
2780
+ essence.archived === true ? null : button('复制', {
2781
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-07',
2782
+ title: essence.actions?.copy?.reason || '深复制整份沙盒到新文件夹(不含凭据/运行态/备份)',
2783
+ disabled: essence.actions?.copy?.enabled === false,
2784
+ onClick: () => void app.copyEssence(essence),
2785
+ }),
2786
+ essence.archived === true ? null : button('归档', {
2787
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-08',
2788
+ title: essence.actions?.archive?.reason || '归档元主(冻结,只改元数据)',
2789
+ disabled: essence.actions?.archive?.enabled === false,
2790
+ onClick: () => void app.archiveEssence(essence),
2791
+ }),
2792
+ button('删除', {
2793
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-09',
2794
+ title: essence.actions?.delete?.reason || '永久删除 essences/<id>(须先归档;不删会话)',
2795
+ disabled: essence.actions?.delete?.enabled === false,
2796
+ onClick: () => void app.deleteEssence(essence),
2797
+ }),
2798
+ essence.archived === true ? null : button('备份', {
2799
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-12',
2800
+ title: '在 essences/<id>/Backup 存档(只保留一份,旧备份覆盖)',
2801
+ onClick: () => void app.essenceBackup(essence),
2802
+ }),
2803
+ essence.archived === true ? null : button('还原备份', {
2804
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-13',
2805
+ title: '用最新 Backup 覆盖当前 overlay/merged(需二次确认)',
2806
+ onClick: () => void app.essenceRestore(essence),
2807
+ }),
2808
+ essence.archived === true ? null : button('下载', {
2809
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-10',
2810
+ title: essence.actions?.download?.reason || '下载元主整包 JSON(不含凭据)',
2811
+ disabled: essence.actions?.download?.enabled === false,
2812
+ onClick: () => void app.downloadEssence(essence),
2813
+ })))))
2069
2814
 
2070
2815
  return h('section', { class: 'panel', 'data-zone': 'mother', 'data-freshness': freshness, 'aria-labelledby': 'fang-mother-title' },
2071
2816
  head,
2072
2817
  h('div', { class: 'mother-slots' }, renderSlotStrip(projectCapacity(S.status.data, S.tasks.items))),
2818
+ essenceHead,
2073
2819
  essenceList,
2074
2820
  scroll)
2075
2821
  }
@@ -2346,7 +3092,8 @@ window.__ModuleLoader__.load({
2346
3092
  h('div', { class: 'fork-chips' },
2347
3093
  chip(health.tone, health.label, { state: health.phase, danger: health.tone === 'bad' && health.anomaly }),
2348
3094
  archived ? null : chip(health.adapterTone, health.adapterLabel, { health: health.adapter }),
2349
- task.importedSession ? chip('info', '已导入会话', { title: '派生时导入了母体会话历史/摘要' }) : null)),
3095
+ task.importedSession ? chip('info', '已导入会话', { title: '派生时导入了母体会话历史/摘要' }) : null,
3096
+ task.essenceDeleted ? chip('warn', '原身已删除(仅运行/归档)', { title: '来源原身已删除:不能再从该原身派生,但本分身可继续运行/归档/还原/删除' }) : null)),
2350
3097
  h('div', { class: 'fork-actions' },
2351
3098
  archived
2352
3099
  ? [button('还原', {
@@ -2365,8 +3112,13 @@ window.__ModuleLoader__.load({
2365
3112
  onClick: () => void app.openTask(task),
2366
3113
  fk: 'open:' + taskId,
2367
3114
  }),
2368
- textAction('提升插件', {
2369
- title: '把分身里验证过的插件目录提升到母体(需目录名)', dataBtnId: 'C-02',
3115
+ button('分支', {
3116
+ size: 'sm', variant: 'ghost', dataBtnId: 'C-06',
3117
+ title: '物理分支:在分身内 fork 当前会话,挂回同一分身(可多分支、可激活)',
3118
+ onClick: () => void app.openBranches(task),
3119
+ fk: 'branches:' + taskId,
3120
+ }),
3121
+ textAction('提升插件', { title: '把分身里验证过的插件目录提升到母体(需目录名)', dataBtnId: 'C-02',
2370
3122
  softDisabled: busyPromote, busy: busyPromote,
2371
3123
  onClick: () => app.promoteTask(task),
2372
3124
  }),
@@ -2490,6 +3242,8 @@ window.__ModuleLoader__.load({
2490
3242
  kv('官方最新', data.officialLatest == null ? '未配置官方源' : String(data.officialLatest)),
2491
3243
  kv('上次备份', meta.lastBackupAt ? fmtClock(meta.lastBackupAt) : '从未'),
2492
3244
  kv('下次备份', meta.nextBackupAt ? fmtClock(meta.nextBackupAt) : '未安排'),
3245
+ kv('上次同步', data.sync?.lastSyncAt ? fmtClock(data.sync.lastSyncAt) : '从未'),
3246
+ kv('自动同步', (() => { const v = String(data.preferences?.syncIntervalHours ?? 'off'); return v === 'off' ? '关闭' : `${v} 小时` })()),
2493
3247
  kv('磁盘占用', fmtBytes(Number(data.diskUsageBytes) || 0)),
2494
3248
  kv('自动备份', `${Number(meta.backupIntervalHours) || 24} 小时`)))
2495
3249
 
@@ -2511,6 +3265,22 @@ window.__ModuleLoader__.load({
2511
3265
  app.render(true)
2512
3266
  },
2513
3267
  }),
3268
+ button('克隆母体', {
3269
+ size: 'sm', variant: 'quiet', dataBtnId: 'M-07',
3270
+ title: '把本机母体 profile(package.json / cordis.patch.yml / settings)克隆到镜像 active/profile,先自动备份',
3271
+ onClick: () => void app.mirrorAction('clone', async () => (await api('/fang/api/mirror/clone-profile', { method: 'POST', body: '{}' })).body),
3272
+ }),
3273
+ button('空白母体', {
3274
+ size: 'sm', variant: 'quiet', dataBtnId: 'M-08',
3275
+ title: '重置为初始盘(清空 active/profile);会先自动备份,需重新克隆或升级',
3276
+ onClick: () => {
3277
+ S.modal.pending = {
3278
+ text: '把镜像重置为空白母体(初始盘)?会先自动备份;之后需要重新克隆或升级才能恢复基础配置。',
3279
+ run: () => app.mirrorAction('blank', async () => (await api('/fang/api/mirror/blank', { method: 'POST', body: '{}' })).body),
3280
+ }
3281
+ app.render(true)
3282
+ },
3283
+ }),
2514
3284
  button('打开母体门户', {
2515
3285
  size: 'sm', variant: 'quiet', icon: icon('globe', 13),
2516
3286
  title: '在新窗口打开 /fang/panel 独立门户(桌面壳使用真实 HTTP 源)',
@@ -2524,6 +3294,13 @@ window.__ModuleLoader__.load({
2524
3294
  onClick: () => void app.mirrorAction('interval:' + hours, async () => (await api('/fang/api/mirror/backup-interval', { method: 'POST', body: JSON.stringify({ hours }) })).body),
2525
3295
  })))))
2526
3296
 
3297
+ section.append(h('div', { class: 'glass-section-title', style: { marginTop: '4px' } }, '母体自动同步',
3298
+ ...(['off', '6', '12', '24'].map((value) => button(value === 'off' ? '关闭' : value + 'h', {
3299
+ size: 'sm', variant: String(data.preferences?.syncIntervalHours ?? 'off') === value ? 'config' : 'quiet',
3300
+ title: value === 'off' ? '关闭自动同步' : `每 ${value} 小时从本机母体 profile 同步到镜像(同步前自动备份)`,
3301
+ onClick: () => void app.mirrorAction('sync:' + value, async () => (await api('/fang/api/mirror/preferences/set', { method: 'POST', body: JSON.stringify({ syncIntervalHours: value }) })).body),
3302
+ })))))
3303
+
2527
3304
  if (pending) {
2528
3305
  section.append(h('div', { class: 'notice notice--warn', role: 'alertdialog', 'aria-label': '确认操作' },
2529
3306
  h('div', { class: 'notice-main' }, h('div', { class: 'notice-text' }, pending.text)),
@@ -2617,6 +3394,78 @@ window.__ModuleLoader__.load({
2617
3394
  return section
2618
3395
  }
2619
3396
 
3397
+ // 元主详情页(设置 / 插件 / 运行日志)
3398
+ function renderEssenceModal(S, app) {
3399
+ const modal = S.modal
3400
+ const detail = modal.detail
3401
+ const meta = detail?.meta ?? null
3402
+ const tabs = [['settings', '设置'], ['plugins', '插件'], ['logs', '运行日志']]
3403
+ const body = h('div', { class: 'glass-body' })
3404
+ if (modal.loading) {
3405
+ body.append(h('div', { class: 'loading-line' }, icon('spinner', 14), '读取元主详情…'))
3406
+ } else if (modal.error) {
3407
+ body.append(h('div', { class: 'notice notice--warn' }, h('div', { class: 'notice-main' },
3408
+ h('div', { class: 'notice-title' }, icon('alert', 14), '读取失败'),
3409
+ h('div', { class: 'notice-text' }, failureHint(modal.error) + ' · ' + modal.error))))
3410
+ } else if (detail) {
3411
+ if (modal.tab === 'settings') {
3412
+ const rows = [
3413
+ ['状态', String(meta.status ?? 'unknown')],
3414
+ ['等级', String(meta.tier ?? '—')],
3415
+ ['插件条目', String(detail.overlay?.patchEntries?.length ?? 0)],
3416
+ ['设置项', (detail.overlay?.settings || []).join(', ') || '—'],
3417
+ ['备份', detail.backup ? '有(Backup/,只保留一份)' : '无'],
3418
+ ['进行中会话', `${detail.sessions?.used ?? 0} / ${detail.sessions?.limit ?? 10}${detail.sessions?.over ? '(已满,归档后再开)' : ''}`],
3419
+ ['运行态', detail.runtime?.running ? `运行中 · :${detail.runtime.port ?? '—'} · pid ${detail.runtime.pid ?? '—'}` : '未运行'],
3420
+ ['镜像指纹', String(meta.lastMergedFingerprint ?? '—').slice(0, 16)],
3421
+ ['归档', meta.archived === true ? '已冻结(只能删除)' : '活跃'],
3422
+ ]
3423
+ body.append(h('div', { style: { display: 'grid', gap: 6, padding: '6px 2px' } },
3424
+ ...rows.map(([key, value]) => h('div', { style: { display: 'flex', gap: 12 } },
3425
+ h('span', { style: { width: 88, opacity: .65 } }, key),
3426
+ h('span', null, value)))))
3427
+ } else if (modal.tab === 'plugins') {
3428
+ const entries = detail.overlay?.patchEntries || []
3429
+ body.append(entries.length
3430
+ ? h('div', null, ...entries.map((entry) => h('div', {
3431
+ style: { display: 'flex', gap: 8, alignItems: 'center', padding: '5px 0', borderBottom: '1px solid rgba(127,127,127,.15)' },
3432
+ },
3433
+ h('b', { style: { fontFamily: 'var(--f-mono)' } }, entry.id),
3434
+ h('span', { class: 'hint' }, entry.name || ''),
3435
+ entry.disabled ? h('span', { class: 'chip' }, '禁用') : null)))
3436
+ : h('div', { class: 'hint' }, '该元主还没有插件补丁条目;在「打开」起的实例里安装插件后再同步。'))
3437
+ } else {
3438
+ body.append(h('pre', {
3439
+ style: { maxHeight: '46vh', overflow: 'auto', fontSize: 11, lineHeight: 1.5, whiteSpace: 'pre-wrap', margin: 0 },
3440
+ }, detail.logs || '(暂无运行日志;先点「打开」启动该元主的隔离实例)'))
3441
+ }
3442
+ }
3443
+ const tabBar = h('div', { class: 'panel-tools', style: { borderTop: 'none' } },
3444
+ ...tabs.map(([id, label]) => button(label, {
3445
+ size: 'sm', variant: modal.tab === id ? 'primary' : 'ghost',
3446
+ onClick: () => { if (!S.modal || S.modal.kind !== 'essence') return; S.modal.tab = id; render(true) },
3447
+ })))
3448
+ const closeBtn = button('关闭', { size: 'sm', variant: 'quiet', onClick: () => app.closeModal() })
3449
+ const id = modal.essenceId
3450
+ return h('div', {
3451
+ class: 'overlay', 'data-overlay': '1',
3452
+ onClick: (event) => { if (event.target === event.currentTarget) app.closeModal() },
3453
+ },
3454
+ h('div', { class: 'glass', role: 'dialog', 'aria-modal': 'true', style: { width: 'min(880px, 94vw)' } },
3455
+ h('div', { class: 'glass-head' },
3456
+ h('div', { class: 'glass-head-main' },
3457
+ h('div', { class: 'glass-title', id: 'fang-essence-title' }, icon('gate', 16), meta?.name || id),
3458
+ h('div', { class: 'glass-sub' }, `${id} · ${meta?.archived === true ? '冻结' : '活跃'}${meta?.locked === true ? ' · 官方锁定' : ''}`)),
3459
+ closeBtn),
3460
+ tabBar,
3461
+ body,
3462
+ h('div', { class: 'glass-foot' },
3463
+ button('打开', { size: 'sm', variant: 'ghost', onClick: () => { app.closeModal(); void app.openEssence(id) } }),
3464
+ button('同步', { size: 'sm', variant: 'ghost', onClick: () => { app.closeModal(); void app.syncEssence(id) } }),
3465
+ button('备份', { size: 'sm', variant: 'ghost', onClick: () => { const name = S.modal?.detail?.meta?.name; app.closeModal(); void app.essenceBackup({ id, name }) } }),
3466
+ button('下载', { size: 'sm', variant: 'ghost', onClick: () => { const name = S.modal?.detail?.meta?.name; app.closeModal(); void app.downloadEssence({ id, name }) } }))))
3467
+ }
3468
+
2620
3469
  function renderMotherModal(S, app) {
2621
3470
  const data = S.status.data
2622
3471
  const mirror = S.mirror.data
@@ -2668,10 +3517,17 @@ window.__ModuleLoader__.load({
2668
3517
  function renderConfirmModal(S, app) {
2669
3518
  const modal = S.modal
2670
3519
  const expected = String(modal.expected || '')
2671
- const matches = !modal.strong || String(modal.typed || '').trim() === expected
2672
- const level = modal.strong ? 'strong' : 'once'
2673
3520
  const inputId = 'fang-confirm-input'
2674
3521
  const reasonId = 'fang-confirm-reason'
3522
+ // 输入框是就地改 DOM 的,点击时必须以输入框当前值为准,
3523
+ // 否则首次渲染算出的 matches=false 会把「已输入正确名称」的点击吞掉。
3524
+ const inputValue = () => {
3525
+ if (!modal.strong) return ''
3526
+ const node = app.view.querySelector('#' + inputId)
3527
+ return String(node?.value ?? modal.typed ?? '').trim()
3528
+ }
3529
+ const confirmed = () => !modal.strong || inputValue() === expected
3530
+ const level = modal.strong ? 'strong' : 'once'
2675
3531
  return h('div', { class: 'overlay', 'data-overlay': '1', onClick: (event) => { if (event.target === event.currentTarget) app.closeModal() } },
2676
3532
  h('div', {
2677
3533
  class: 'glass glass--sm', role: 'alertdialog', 'aria-modal': 'true',
@@ -2722,10 +3578,15 @@ window.__ModuleLoader__.load({
2722
3578
  }),
2723
3579
  button(modal.confirmLabel || '确认', {
2724
3580
  size: 'sm', variant: modal.tone === 'info' ? 'info' : 'danger', fk: 'confirm-ok',
2725
- disabled: !matches,
3581
+ disabled: modal.strong,
2726
3582
  describedBy: modal.strong ? reasonId : undefined,
2727
3583
  onClick: () => {
2728
- if (!matches) return
3584
+ if (!confirmed()) {
3585
+ // 名称还没对上:把焦点送回输入框,别让点击静默丢失。
3586
+ const node = app.view.querySelector('#' + inputId)
3587
+ if (node) node.focus({ preventScroll: true })
3588
+ return
3589
+ }
2729
3590
  const run = modal.onConfirm
2730
3591
  app.closeModal()
2731
3592
  void run()
@@ -2736,6 +3597,48 @@ window.__ModuleLoader__.load({
2736
3597
  : null))
2737
3598
  }
2738
3599
 
3600
+ function renderBranchModal(S, app) {
3601
+ const modal = S.modal
3602
+ const branches = Array.isArray(modal.branches) ? modal.branches : []
3603
+ return h('div', { class: 'overlay', 'data-overlay': '1', onClick: (event) => { if (event.target === event.currentTarget) app.closeModal() } },
3604
+ h('div', { class: 'glass', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'fang-branch-title' },
3605
+ h('div', { class: 'glass-head' },
3606
+ h('div', { class: 'glass-head-main' },
3607
+ h('div', { class: 'glass-title', id: 'fang-branch-title' }, '分支 · ' + (modal.taskTitle || '')),
3608
+ h('div', { class: 'glass-sub' }, '会话 ' + (modal.sessionId || '—') + ' · 当前分支 ' + (modal.activeBranchId || '—'))),
3609
+ button('', { variant: 'quiet', size: 'sm', iconOnly: true, icon: icon('close', 15), ariaLabel: '关闭', onClick: () => app.closeModal() })),
3610
+ h('div', { class: 'glass-body' },
3611
+ modal.error ? h('div', { class: 'hint', style: { color: 'var(--f-red)' }, role: 'alert' }, modal.error) : null,
3612
+ h('div', { style: { display: 'flex', gap: 8, margin: '4px 0 12px' } },
3613
+ button('派生分支', { size: 'sm', variant: 'primary', dataBtnId: 'B-01', onClick: () => void app.forkBranch({ taskId: modal.taskId, title: modal.taskTitle }) }),
3614
+ button('刷新', { size: 'sm', variant: 'ghost', onClick: () => void app.openBranches({ taskId: modal.taskId, title: modal.taskTitle }) })),
3615
+ branches.length === 0
3616
+ ? h('p', { class: 'glass-sub' }, '还没有分支。派生分支会在分身内 fork 当前会话(物理分支,子会话挂回同一分身)。')
3617
+ : h('div', { style: { display: 'grid', gap: 6 } },
3618
+ branches.map((branch) => h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'space-between', padding: '6px 8px', border: '1px solid var(--f-border)', borderRadius: 10 } },
3619
+ h('span', null,
3620
+ String(branch.branchId) + ' · ' + String(branch.status ?? '')
3621
+ + (branch.sessionId ? ' · ' + short(String(branch.sessionId), 8) : '')
3622
+ + (branch.branchId === modal.activeBranchId ? ' · 当前' : '')),
3623
+ branch.branchId !== modal.activeBranchId && branch.status === 'active'
3624
+ ? button('激活', { size: 'sm', variant: 'ghost', onClick: () => void app.activateBranch({ taskId: modal.taskId, title: modal.taskTitle }, branch.branchId) })
3625
+ : null,
3626
+ button('打开分身', {
3627
+ size: 'sm', variant: 'ghost', title: '打开分身 Web UI(DSH 暂不支持会话深链,子会话在左侧会话列表中)',
3628
+ onClick: () => void app.openTask({ taskId: modal.taskId, title: modal.taskTitle }),
3629
+ }),
3630
+ branch.sessionId ? button('复制会话 ID', {
3631
+ size: 'sm', variant: 'ghost', title: branch.sessionId,
3632
+ onClick: () => {
3633
+ const text = String(branch.sessionId || '')
3634
+ const done = () => setNotice({ tone: 'ok', title: '已复制会话 ID', message: short(text, 12) })
3635
+ try { void navigator.clipboard.writeText(text).then(done, done) } catch { done() }
3636
+ },
3637
+ }) : null)))),
3638
+ h('div', { class: 'glass-foot' },
3639
+ button('关闭', { size: 'sm', variant: 'ghost', onClick: () => app.closeModal() }))))
3640
+ }
3641
+
2739
3642
  function renderPromptModal(S, app) {
2740
3643
  const modal = S.modal
2741
3644
  const submit = () => {
@@ -2833,6 +3736,8 @@ window.__ModuleLoader__.load({
2833
3736
  }
2834
3737
  }
2835
3738
  if (S.modal.kind === 'mother') frag.append(renderMotherModal(S, app))
3739
+ else if (S.modal.kind === 'essence') frag.append(renderEssenceModal(S, app))
3740
+ else if (S.modal.kind === 'branches') frag.append(renderBranchModal(S, app))
2836
3741
  else if (S.modal.kind === 'confirm') frag.append(renderConfirmModal(S, app))
2837
3742
  else if (S.modal.kind === 'prompt') frag.append(renderPromptModal(S, app))
2838
3743
  }
@@ -2854,15 +3759,17 @@ window.__ModuleLoader__.load({
2854
3759
  return React.createElement('div', { ref, className: 'fang-mount', style: props.style || { display: 'block', minWidth: 0 } })
2855
3760
  }
2856
3761
 
2857
- function mountDiagnostics(app) {
2858
- const doc = document
3762
+ function mountDiagnostics(app, host) {
3763
+ const doc = host?.ownerDocument ?? document
3764
+ const parent = host ?? doc.body
3765
+ if (host) { host.style.position = host.style.position || 'relative' }
2859
3766
  const btn = doc.createElement('button')
2860
3767
  btn.id = 'fang-diag-btn'
2861
3768
  btn.setAttribute('data-btn-id', 'LOG-01')
2862
3769
  btn.type = 'button'
2863
3770
  btn.textContent = '日志'
2864
3771
  Object.assign(btn.style, {
2865
- position: 'fixed', right: '16px', bottom: '16px', zIndex: '9999',
3772
+ position: 'absolute', right: '16px', bottom: '16px', zIndex: '9999',
2866
3773
  height: '34px', padding: '0 12px', borderRadius: '10px',
2867
3774
  border: '1px solid rgba(127,127,127,.4)', background: '#fff', color: '#111',
2868
3775
  font: '600 13px/1 system-ui, sans-serif', cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,.18)',
@@ -2871,7 +3778,7 @@ window.__ModuleLoader__.load({
2871
3778
  overlay.id = 'fang-diag-panel'
2872
3779
  overlay.hidden = true
2873
3780
  Object.assign(overlay.style, {
2874
- position: 'fixed', right: '16px', bottom: '58px', zIndex: '9999',
3781
+ position: 'absolute', right: '16px', bottom: '58px', zIndex: '9999',
2875
3782
  width: 'min(520px, calc(100vw - 32px))', maxHeight: '60vh', overflow: 'auto',
2876
3783
  background: '#fff', color: '#111', border: '1px solid rgba(127,127,127,.35)',
2877
3784
  borderRadius: '12px', boxShadow: '0 12px 40px rgba(0,0,0,.25)', padding: '10px',
@@ -2945,7 +3852,7 @@ window.__ModuleLoader__.load({
2945
3852
  window.addEventListener('fang:diag', onDiag)
2946
3853
  window.addEventListener('error', onError)
2947
3854
  window.addEventListener('unhandledrejection', onRejection)
2948
- doc.body.append(btn, overlay)
3855
+ parent.append(btn, overlay)
2949
3856
  renderLogs()
2950
3857
  return () => {
2951
3858
  window.removeEventListener('fang:diag', onDiag)
@@ -2956,15 +3863,17 @@ window.__ModuleLoader__.load({
2956
3863
  }
2957
3864
  }
2958
3865
 
2959
- function mountConnectionInfo(app) {
2960
- const doc = document
3866
+ function mountConnectionInfo(app, host) {
3867
+ const doc = host?.ownerDocument ?? document
3868
+ const parent = host ?? doc.body
3869
+ if (host) { host.style.position = host.style.position || 'relative' }
2961
3870
  const trigger = doc.createElement('button')
2962
3871
  trigger.id = 'fang-conn-trigger'
2963
3872
  trigger.type = 'button'
2964
3873
  trigger.setAttribute('data-btn-id', 'CONN-00')
2965
3874
  trigger.textContent = '连接信息'
2966
3875
  Object.assign(trigger.style, {
2967
- position: 'fixed', left: '16px', bottom: '16px', zIndex: '9999',
3876
+ position: 'absolute', left: '16px', bottom: '16px', zIndex: '9999',
2968
3877
  height: '34px', padding: '0 12px', borderRadius: '10px',
2969
3878
  border: '1px solid rgba(127,127,127,.4)', background: '#fff', color: '#111',
2970
3879
  font: '600 13px/1 system-ui, sans-serif', cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,.18)',
@@ -2973,7 +3882,7 @@ window.__ModuleLoader__.load({
2973
3882
  popup.id = 'fang-conn-popup'
2974
3883
  popup.hidden = true
2975
3884
  Object.assign(popup.style, {
2976
- position: 'fixed', left: '16px', bottom: '58px', zIndex: '9999',
3885
+ position: 'absolute', left: '16px', bottom: '58px', zIndex: '9999',
2977
3886
  display: 'none', alignItems: 'center', gap: '6px', maxWidth: 'calc(100vw - 32px)',
2978
3887
  padding: '6px 8px', borderRadius: '10px', background: '#fff', color: '#111',
2979
3888
  border: '1px solid rgba(127,127,127,.35)', boxShadow: '0 4px 14px rgba(0,0,0,.14)',
@@ -2982,6 +3891,10 @@ window.__ModuleLoader__.load({
2982
3891
  const label = doc.createElement('span')
2983
3892
  label.id = 'fang-conn-url'
2984
3893
  label.style.cssText = 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:42vw'
3894
+ // Web 模式需要第二行显示安装 token;桌面模式保持原来的单行样子。
3895
+ const labelWrap = doc.createElement('div')
3896
+ labelWrap.style.cssText = 'display:flex;flex-direction:column;gap:2px;min-width:0'
3897
+ labelWrap.append(label)
2985
3898
  const eye = doc.createElement('button')
2986
3899
  eye.type = 'button'
2987
3900
  eye.setAttribute('data-btn-id', 'CONN-01')
@@ -2999,6 +3912,9 @@ window.__ModuleLoader__.load({
2999
3912
  }
3000
3913
  let full = ''
3001
3914
  let baseUrl = ''
3915
+ let tokenValue = ''
3916
+ let tokenLabel = null
3917
+ let copyToken = null
3002
3918
  let revealed = false
3003
3919
  let opened = false
3004
3920
  let loaded = false
@@ -3008,12 +3924,42 @@ window.__ModuleLoader__.load({
3008
3924
  return String(url).replace(/([?&]token=)[^&]*/, (_, prefix) => prefix + '•'.repeat(Math.min(16, token.length || 8)))
3009
3925
  } catch { return url }
3010
3926
  }
3927
+ // 桌面壳里 token 由主进程保管;纯 Web 里没有 fangShell,
3928
+ // 连接地址就是当前页面地址本身(同源打开,token 已在地址栏里)。
3929
+ const isDesktopShell = () => typeof window !== 'undefined' && typeof window.fangShell?.revealToken === 'function'
3930
+ const resolveFull = async () => {
3931
+ if (full) return full
3932
+ if (isDesktopShell()) {
3933
+ try {
3934
+ const info = await window.fangShell.revealToken()
3935
+ if (info?.token) { full = baseUrl + '/?token=' + encodeURIComponent(String(info.token)); return full }
3936
+ } catch { /* 主进程拒绝就退回页面地址 */ }
3937
+ }
3938
+ try {
3939
+ const result = await api('/fang/api/connection')
3940
+ const url = result?.body?.url
3941
+ if (typeof url === 'string' && url) { full = url; return full }
3942
+ } catch { /* 宿主没这个路由时继续兜底 */ }
3943
+ if (typeof location !== 'undefined' && location.href) full = String(location.href)
3944
+ return full
3945
+ }
3946
+ const maskedText = () => {
3947
+ if (full) return mask(full)
3948
+ if (baseUrl) return baseUrl + '/?token=••••••••'
3949
+ return '连接信息加载中…'
3950
+ }
3011
3951
  const render = () => {
3012
3952
  popup.hidden = !opened
3013
3953
  popup.style.display = opened ? 'flex' : 'none'
3014
- if (!opened) { label.textContent = ''; label.title = ''; return }
3015
- label.textContent = full && revealed ? full : (baseUrl ? baseUrl + '/?token=••••••••' : '连接信息加载中…')
3954
+ if (!opened) { label.textContent = ''; label.title = ''; if (tokenLabel) { tokenLabel.textContent = ''; tokenLabel.title = '' } return }
3955
+ label.textContent = full && revealed ? full : maskedText()
3016
3956
  label.title = revealed ? full : ''
3957
+ if (tokenLabel) {
3958
+ tokenLabel.textContent = tokenValue
3959
+ ? (revealed ? tokenValue : 'Token ' + '•'.repeat(Math.min(16, tokenValue.length)))
3960
+ : 'Token 未获取(宿主未就绪)'
3961
+ tokenLabel.title = revealed ? tokenValue : ''
3962
+ }
3017
3963
  eye.textContent = revealed ? '隐藏' : '显示'
3018
3964
  }
3019
3965
  const load = async () => {
@@ -3024,6 +3970,51 @@ window.__ModuleLoader__.load({
3024
3970
  if (info?.upstream) baseUrl = String(info.upstream).replace(/\/+$/, '')
3025
3971
  } catch { /* ignore */ }
3026
3972
  if (!baseUrl) baseUrl = String(location.origin || '')
3973
+ // 宿主侧 /fang/api/connection 给出带进程 token 的完整地址;
3974
+ // 拿不到就用当前页面地址兜底(同源,能用就能复制)。
3975
+ try {
3976
+ const result = await api('/fang/api/connection')
3977
+ const url = result?.body?.url
3978
+ if (typeof url === 'string' && url) full = url
3979
+ } catch { /* ignore */ }
3980
+ if (!isDesktopShell()) {
3981
+ // 纯 Web:宿主没有桌面壳桥,token 走同源的 /fang/api/auth-token。
3982
+ try {
3983
+ const result = await api('/fang/api/auth-token')
3984
+ const token = result?.body?.token
3985
+ if (typeof token === 'string' && token) tokenValue = token
3986
+ } catch { /* ignore */ }
3987
+ tokenLabel = doc.createElement('span')
3988
+ tokenLabel.id = 'fang-conn-token'
3989
+ tokenLabel.style.cssText = 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:42vw;color:#6E6E73'
3990
+ labelWrap.append(tokenLabel)
3991
+ copyToken = doc.createElement('button')
3992
+ copyToken.type = 'button'
3993
+ copyToken.setAttribute('data-btn-id', 'CONN-04')
3994
+ copyToken.textContent = '复制 Token'
3995
+ copyToken.style.cssText = 'height:28px;padding:0 8px;border-radius:8px;border:1px solid rgba(127,127,127,.4);background:transparent;color:inherit;cursor:pointer;font:inherit'
3996
+ copyToken.onclick = async () => {
3997
+ if (!tokenValue) { app.notify('warn', '还没拿到 Token:宿主可能未就绪'); return }
3998
+ const ok = await writeClipboard(tokenValue)
3999
+ app.notify(ok ? 'ok' : 'warn', ok ? '已复制 Token' : '复制失败:浏览器未授权剪贴板')
4000
+ }
4001
+ popup.insertBefore(copyToken, close)
4002
+ if (!full && typeof location !== 'undefined' && location.href) full = String(location.href)
4003
+ }
4004
+ }
4005
+ // 老 Electron / 无剪贴板权限时退回 execCommand。
4006
+ const writeClipboard = async (text) => {
4007
+ try { await navigator.clipboard.writeText(text); return true } catch { /* fall through */ }
4008
+ try {
4009
+ const area = doc.createElement('textarea')
4010
+ area.value = text
4011
+ area.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0'
4012
+ doc.body.appendChild(area)
4013
+ area.select()
4014
+ const ok = doc.execCommand('copy')
4015
+ area.remove()
4016
+ return Boolean(ok)
4017
+ } catch { return false }
3027
4018
  }
3028
4019
  trigger.onclick = async () => {
3029
4020
  opened = !opened
@@ -3033,25 +4024,35 @@ window.__ModuleLoader__.load({
3033
4024
  }
3034
4025
  eye.onclick = async () => {
3035
4026
  if (!revealed) {
3036
- try {
3037
- const info = await window.fangShell?.revealToken?.()
3038
- if (info?.token) full = baseUrl + '/?token=' + encodeURIComponent(String(info.token))
3039
- } catch { /* ignore */ }
4027
+ const text = await resolveFull()
4028
+ if (!text) { app.notify('warn', '还没拿到连接地址:宿主可能未就绪'); return }
3040
4029
  }
3041
4030
  revealed = !revealed
3042
4031
  render()
3043
4032
  }
3044
4033
  copy.onclick = async () => {
3045
- try { await navigator.clipboard.writeText(full); app.notify('ok', '已复制连接地址') } catch { app.notify('warn', '复制失败:浏览器未授权剪贴板') }
4034
+ const text = await resolveFull()
4035
+ if (!text) { app.notify('warn', '还没拿到连接地址:宿主可能未就绪'); return }
4036
+ const ok = await writeClipboard(text)
4037
+ app.notify(ok ? 'ok' : 'warn', ok ? '已复制连接地址' : '复制失败:浏览器未授权剪贴板')
3046
4038
  }
3047
4039
  close.onclick = () => { opened = false; revealed = false; render() }
3048
- popup.append(label, eye, copy, close)
3049
- doc.body.append(trigger, popup)
4040
+ popup.append(labelWrap, eye, copy, close)
4041
+ parent.append(trigger, popup)
3050
4042
  render()
3051
4043
  return () => { trigger.remove(); popup.remove() }
3052
4044
  }
3053
4045
 
3054
4046
  function mountPanel(host) {
4047
+ // Electron: remember the real upstream origin so "打开母体 Web" does not
4048
+ // open the loopback proxy (which intentionally serves only /fang/api/*).
4049
+ try {
4050
+ window.fangShell?.desktopInfo?.().then((info) => {
4051
+ if (info && typeof info.upstream === 'string' && /^https?:\/\//i.test(info.upstream)) {
4052
+ window.__fangDesktopUpstream = info.upstream.replace(/\/+$/, '')
4053
+ }
4054
+ }).catch(() => {})
4055
+ } catch { /* web host: no shell bridge */ }
3055
4056
  // v3.0.7 UI 分析日志:记录面板挂载与所有按钮/链接点击,供自动冒烟/诊断读取
3056
4057
  try {
3057
4058
  const doc = host?.ownerDocument ?? document
@@ -3072,8 +4073,8 @@ window.__ModuleLoader__.load({
3072
4073
  window.__fangUiLog.push({ at: Date.now(), kind: 'panel-mount' })
3073
4074
  } catch { /* 宿主无 window 时忽略 */ }
3074
4075
  const app = createConsole(host)
3075
- const unmountDiagnostics = mountDiagnostics(app)
3076
- const unmountConnection = mountConnectionInfo(app)
4076
+ const unmountDiagnostics = mountDiagnostics(app, host)
4077
+ const unmountConnection = mountConnectionInfo(app, host)
3077
4078
  try { host.ownerDocument?.getElementById('fang-fallback')?.remove() } catch { /* ignore */ }
3078
4079
  return () => { unmountConnection(); unmountDiagnostics(); app.destroy() }
3079
4080
  }
@@ -3116,7 +4117,11 @@ window.__ModuleLoader__.load({
3116
4117
  const layout = ctx?.layout
3117
4118
  if (layout && typeof layout.selectPanel === 'function') { layout.selectPanel('fang'); return }
3118
4119
  } catch { /* fall through */ }
3119
- try { window.open('/fang/panel', '_blank', 'noopener') } catch { /* ignore */ }
4120
+ try {
4121
+ window.dispatchEvent(new CustomEvent('fang:notice', {
4122
+ detail: '瓮城面板未在当前视图打开;请从 DSH 左侧栏「瓮城」进入,或使用 PC 端。',
4123
+ }))
4124
+ } catch { /* ignore */ }
3120
4125
  }
3121
4126
  label.addEventListener('click', openPanel)
3122
4127
  label.addEventListener('dblclick', (event) => {
@@ -3189,12 +4194,310 @@ window.__ModuleLoader__.load({
3189
4194
  }
3190
4195
  }
3191
4196
 
4197
+ // ── 截图(内置客户端模块,不再作为独立子插件)──────────────────────────
4198
+ // 结果一律落在一个 body 级预览层里:看得见、能复制、说得清失败原因。
4199
+ // 面板未挂载时 fang:notice 没有监听者,所以失败提示不能只靠事件。
4200
+ const SHOT_NAME = () => `wengcheng-${Date.now()}.png`
4201
+ let shotOverlay = null
4202
+
4203
+ function closeShotOverlay() {
4204
+ if (!shotOverlay) return
4205
+ try { shotOverlay.off() } catch { /* ignore */ }
4206
+ try { shotOverlay.node.remove() } catch { /* ignore */ }
4207
+ try { URL.revokeObjectURL(shotOverlay.url) } catch { /* ignore */ }
4208
+ shotOverlay = null
4209
+ }
4210
+
4211
+ function showShotOverlay({ blob = null, message = '', hint = '', extraActions = [] } = {}) {
4212
+ closeShotOverlay()
4213
+ const doc = typeof document !== 'undefined' ? document : null
4214
+ if (!doc?.body) return
4215
+ const url = blob ? URL.createObjectURL(blob) : ''
4216
+ const status = h('div', {
4217
+ style: { fontSize: 13, lineHeight: 1.5, color: '#EFEFEF', whiteSpace: 'pre-wrap' },
4218
+ text: message,
4219
+ })
4220
+ const actions = h('div', { style: { display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' } })
4221
+ const mkBtn = (label, primary) => h('button', {
4222
+ type: 'button',
4223
+ style: {
4224
+ height: 30, padding: '0 12px', borderRadius: 8, cursor: 'pointer', fontSize: 12,
4225
+ border: primary ? '1px solid #17803D' : '1px solid rgba(255,255,255,.24)',
4226
+ background: primary ? '#17803D' : 'transparent', color: '#fff',
4227
+ },
4228
+ }, label)
4229
+ if (blob) {
4230
+ const copyBtn = mkBtn('复制到剪贴板', true)
4231
+ copyBtn.addEventListener('click', async () => {
4232
+ try {
4233
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
4234
+ copyBtn.textContent = '已复制 ✓'
4235
+ status.textContent = '已复制到剪贴板,在输入框里 Ctrl+V 即可粘贴图片。'
4236
+ } catch (error) {
4237
+ status.textContent = '复制失败:' + String(error?.message ?? error) + '\n可点「下载 PNG」,或右键预览图选「复制图片」。'
4238
+ }
4239
+ })
4240
+ const dlBtn = mkBtn('下载 PNG', false)
4241
+ dlBtn.addEventListener('click', () => {
4242
+ const link = h('a', { href: url, download: SHOT_NAME() })
4243
+ doc.body.appendChild(link)
4244
+ link.click()
4245
+ link.remove()
4246
+ status.textContent = '已下载 PNG,去浏览器的下载目录取文件。'
4247
+ })
4248
+ actions.append(copyBtn, dlBtn)
4249
+ }
4250
+ for (const extra of Array.isArray(extraActions) ? extraActions : []) {
4251
+ if (!extra || typeof extra.onClick !== 'function') continue
4252
+ const btn = mkBtn(String(extra.label ?? '操作'), extra.primary === true)
4253
+ btn.setAttribute('data-fang-shot-action', String(extra.label ?? 'action'))
4254
+ btn.addEventListener('click', () => { try { extra.onClick() } catch { /* ignore */ } })
4255
+ actions.append(btn)
4256
+ }
4257
+ const closeBtn = mkBtn('关闭', false)
4258
+ actions.append(closeBtn)
4259
+ const preview = blob ? h('img', {
4260
+ src: url,
4261
+ alt: '截图预览',
4262
+ style: { display: 'block', width: '100%', maxHeight: '58vh', objectFit: 'contain', borderRadius: 10, background: '#111', marginTop: 12 },
4263
+ }) : null
4264
+ const parts = [
4265
+ h('div', { style: { fontSize: 14, fontWeight: 600, color: '#fff', marginBottom: 8 } }, '瓮城截图'),
4266
+ status,
4267
+ ]
4268
+ if (preview) parts.push(preview)
4269
+ if (hint) parts.push(h('div', { style: { marginTop: 8, fontSize: 12, color: '#9A9AA0' }, text: hint }))
4270
+ parts.push(actions)
4271
+ const card = h('div', {
4272
+ role: 'dialog',
4273
+ 'aria-modal': 'true',
4274
+ 'aria-label': '瓮城截图',
4275
+ style: {
4276
+ width: 'min(760px, 92vw)', padding: 18, borderRadius: 14, background: '#1D1D1F',
4277
+ boxShadow: '0 24px 64px -12px rgba(0,0,0,.6)', pointerEvents: 'auto',
4278
+ },
4279
+ }, parts)
4280
+ const backdrop = h('div', {
4281
+ style: {
4282
+ position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
4283
+ alignItems: 'center', justifyContent: 'center', padding: 24,
4284
+ background: 'rgba(0,0,0,.55)', pointerEvents: 'auto',
4285
+ },
4286
+ }, card)
4287
+ backdrop.addEventListener('click', (event) => { if (event.target === backdrop) closeShotOverlay() })
4288
+ closeBtn.addEventListener('click', () => closeShotOverlay())
4289
+ const onKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); closeShotOverlay() } }
4290
+ doc.addEventListener('keydown', onKey, true)
4291
+ doc.body.appendChild(backdrop)
4292
+ shotOverlay = { node: backdrop, url, off: () => doc.removeEventListener('keydown', onKey, true) }
4293
+ }
4294
+
4295
+ // DSH 桌面端的渲染进程是 Electron:没有 setDisplayMediaRequestHandler 时
4296
+ // getDisplayMedia 会直接 reject,用户看到的就是「没有选择共享内容」。
4297
+ // 第一次 getDisplayMedia 被拒后记住:这个窗口没有共享选择器,之后直接走系统截图。
4298
+ let webCaptureBlocked = false
4299
+ const isEmbeddedDesktop = () => {
4300
+ try { return /Electron\//i.test(String(navigator?.userAgent ?? '')) } catch { return false }
4301
+ }
4302
+
4303
+ /** 调 Windows「屏幕截图」URI(与 Win+Shift+S 同一入口);被拦截时返回 false。 */
4304
+ function requestSystemSnip() {
4305
+ try {
4306
+ const link = h('a', { href: 'ms-screenclip:', rel: 'noopener', style: { display: 'none' } })
4307
+ document.body.appendChild(link)
4308
+ link.click()
4309
+ link.remove()
4310
+ return true
4311
+ } catch { return false }
4312
+ }
4313
+
4314
+ async function readClipboardImage() {
4315
+ try {
4316
+ if (!navigator.clipboard?.read) return { ok: false, error: '当前环境不支持读取剪贴板图片' }
4317
+ const items = await navigator.clipboard.read()
4318
+ for (const item of items) {
4319
+ const type = (item.types || []).find((candidate) => String(candidate).startsWith('image/'))
4320
+ if (type) return { ok: true, blob: await item.getType(type) }
4321
+ }
4322
+ return { ok: false, error: '剪贴板里还没有图片(先按 Win+Shift+S 截图)' }
4323
+ } catch (error) {
4324
+ return { ok: false, error: String(error?.message ?? error) }
4325
+ }
4326
+ }
4327
+
4328
+ async function readClipboardIntoOverlay() {
4329
+ const result = await readClipboardImage()
4330
+ if (!result.ok) {
4331
+ showShotOverlay({
4332
+ message: '读取剪贴板失败:' + result.error,
4333
+ hint: '先按 Win+Shift+S 拖选区域截图,再回来点「读取剪贴板」;也可以直接 Ctrl+V 粘贴。',
4334
+ })
4335
+ return
4336
+ }
4337
+ showShotOverlay({
4338
+ blob: result.blob,
4339
+ message: '已从剪贴板读到截图:直接 Ctrl+V 就能粘贴到输入框。',
4340
+ hint: '要换一张,再按一次 Win+Shift+S。',
4341
+ })
4342
+ }
4343
+
4344
+ function showSnipGuidance(reason) {
4345
+ showShotOverlay({
4346
+ message: reason || '这个窗口不提供网页屏幕共享选择器,浏览器抓屏不可用。',
4347
+ hint: '按 Win+Shift+S 拖选区域,截图会直接进剪贴板,然后 Ctrl+V 粘贴;也可以点下面的按钮。',
4348
+ extraActions: [
4349
+ {
4350
+ label: '打开系统截图', primary: true,
4351
+ onClick: () => {
4352
+ const ok = requestSystemSnip()
4353
+ showShotOverlay({
4354
+ message: ok ? '已请求打开 Windows 截图:拖选区域后点「读取剪贴板」。' : '系统截图没有打开:请直接按 Win+Shift+S。',
4355
+ hint: ok ? '截完图直接 Ctrl+V 粘贴;或点「读取剪贴板」先预览。' : '',
4356
+ extraActions: [{ label: '读取剪贴板', primary: true, onClick: () => void readClipboardIntoOverlay() }],
4357
+ })
4358
+ },
4359
+ },
4360
+ { label: '读取剪贴板', onClick: () => void readClipboardIntoOverlay() },
4361
+ ],
4362
+ })
4363
+ }
4364
+
4365
+ async function captureScreenshot() {
4366
+ if (typeof window.fangShell?.captureScreen === 'function') {
4367
+ try {
4368
+ const result = await window.fangShell.captureScreen()
4369
+ if (result?.ok) notifyScreenshot('已截图并复制到剪贴板,可直接 Ctrl+V 粘贴')
4370
+ else showShotOverlay({ message: '桌面端没有拿到屏幕图像。', hint: '可改用 Win+Shift+S 截图后粘贴。' })
4371
+ return Boolean(result?.ok)
4372
+ } catch (error) {
4373
+ showShotOverlay({ message: '截图失败:' + String(error?.message ?? error) })
4374
+ return false
4375
+ }
4376
+ }
4377
+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getDisplayMedia) {
4378
+ showSnipGuidance('当前页面不支持网页截屏。')
4379
+ return false
4380
+ }
4381
+ // Electron 宿主不会弹共享选择器:先走系统截图(Ctrl+X ≈ Win+Shift+S),别再让用户看失败框。
4382
+ if (isEmbeddedDesktop() || webCaptureBlocked) {
4383
+ const requested = requestSystemSnip()
4384
+ showShotOverlay({
4385
+ message: requested
4386
+ ? '已请求 Windows 系统截图(等同 Win+Shift+S):拖选区域后,直接 Ctrl+V 粘贴。'
4387
+ : '这个窗口不能网页抓屏。请按 Win+Shift+S 截图。',
4388
+ hint: 'DSH 桌面端不提供屏幕共享选择器,所以浏览器抓屏会直接失败;系统截图走的是 Windows 自己的剪贴板。',
4389
+ extraActions: requested
4390
+ ? [{ label: '读取剪贴板', primary: true, onClick: () => void readClipboardIntoOverlay() }]
4391
+ : [{ label: '打开系统截图', primary: true, onClick: () => { requestSystemSnip() } }, { label: '读取剪贴板', onClick: () => void readClipboardIntoOverlay() }],
4392
+ })
4393
+ return requested
4394
+ }
4395
+ let stream = null
4396
+ try {
4397
+ // 浏览器会弹一次「选择要共享的内容」,选当前标签页/窗口/屏幕均可。
4398
+ stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false })
4399
+ const video = document.createElement('video')
4400
+ video.srcObject = stream
4401
+ video.muted = true
4402
+ await video.play()
4403
+ await new Promise((resolve) => { if (video.videoWidth) resolve(); else video.onloadedmetadata = resolve })
4404
+ const canvas = document.createElement('canvas')
4405
+ canvas.width = video.videoWidth
4406
+ canvas.height = video.videoHeight
4407
+ canvas.getContext('2d').drawImage(video, 0, 0)
4408
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
4409
+ if (!blob) throw new Error('截图内容为空')
4410
+ webCaptureBlocked = false
4411
+ let copied = false
4412
+ try {
4413
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
4414
+ copied = true
4415
+ } catch { /* 预览层里还有手动复制按钮 */ }
4416
+ showShotOverlay({
4417
+ blob,
4418
+ message: copied
4419
+ ? '已截图并复制到剪贴板,在输入框里 Ctrl+V 即可粘贴。'
4420
+ : '已截到图,但浏览器拒绝了自动写入剪贴板,请点下面的「复制到剪贴板」。',
4421
+ hint: copied ? '' : '也可以点「下载 PNG」,或右键预览图选「复制图片」。',
4422
+ })
4423
+ return true
4424
+ } catch (error) {
4425
+ const name = String(error?.name ?? '')
4426
+ if (name === 'NotAllowedError') {
4427
+ webCaptureBlocked = true
4428
+ showSnipGuidance('浏览器拒绝了屏幕捕获:这个窗口没有共享选择器。')
4429
+ } else if (name === 'AbortError') {
4430
+ showShotOverlay({
4431
+ message: '截图已取消(没有选择共享内容)。',
4432
+ hint: '再按一次 Ctrl+X 重试,或改用 Win+Shift+S 截图后 Ctrl+V 粘贴。',
4433
+ })
4434
+ } else {
4435
+ showShotOverlay({ message: '截图失败:' + String(error?.message ?? error), hint: '可以改用 Win+Shift+S 截图后 Ctrl+V 粘贴。' })
4436
+ }
4437
+ return false
4438
+ } finally {
4439
+ for (const track of stream?.getTracks?.() ?? []) { try { track.stop() } catch { /* ignore */ } }
4440
+ }
4441
+ }
4442
+
4443
+ function notifyScreenshot(message) {
4444
+ try { window.dispatchEvent(new CustomEvent('fang:notice', { detail: message })) } catch { /* ignore */ }
4445
+ }
4446
+
4447
+ function isScreenshotShortcut(event) {
4448
+ const key = String(event?.key || '').toLowerCase()
4449
+ if (key !== 'x' || !event.ctrlKey || event.altKey || event.metaKey) return false
4450
+ return true
4451
+ }
4452
+
4453
+ // 插槽返回的必须是 React 元素;直接返回 DOM 节点会让宿主判为异常而关掉该项。
4454
+ function ScreenshotDock() {
4455
+ return React.createElement(DomMount, {
4456
+ style: { display: 'inline-flex', alignItems: 'center' },
4457
+ mount: (host) => {
4458
+ const btn = h('button', {
4459
+ type: 'button',
4460
+ 'data-fang-entry': 'screenshot',
4461
+ title: '截图并复制到剪贴板:Ctrl+X(桌面端走 Windows 系统截图,浏览器走屏幕共享)',
4462
+ style: {
4463
+ height: 26, padding: '0 8px', borderRadius: 7, cursor: 'pointer',
4464
+ border: '1px solid rgba(127,127,127,.35)', background: 'transparent', color: 'inherit', fontSize: 12,
4465
+ },
4466
+ }, '截图 Ctrl+X')
4467
+ btn.addEventListener('click', () => { void captureScreenshot() })
4468
+ host.replaceChildren(btn)
4469
+ return () => { host.replaceChildren() }
4470
+ },
4471
+ })
4472
+ }
4473
+
3192
4474
  // ── 插件入口 ──────────────────────────────────────────────────────────
3193
4475
  return {
3194
4476
  mountPanel,
3195
4477
  inject: ['slots'],
3196
4478
  apply(ctx) {
3197
4479
  const disposers = []
4480
+ // 母体 Web = DSH 主会话视图;Web 端直接切回 conversation 面板。
4481
+ const goMother = () => {
4482
+ try {
4483
+ if (ctx?.layout && typeof ctx.layout.selectPanel === 'function') ctx.layout.selectPanel('conversation')
4484
+ } catch { /* fall back to panel notice */ }
4485
+ }
4486
+ window.addEventListener('fang:mother-portal', goMother)
4487
+ disposers.push(() => window.removeEventListener('fang:mother-portal', goMother))
4488
+ const onScreenshotKey = (event) => {
4489
+ if (!isScreenshotShortcut(event)) return
4490
+ event.preventDefault()
4491
+ event.stopPropagation()
4492
+ void captureScreenshot()
4493
+ }
4494
+ window.addEventListener('keydown', onScreenshotKey, true)
4495
+ disposers.push(() => window.removeEventListener('keydown', onScreenshotKey, true))
4496
+ disposers.push(ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
4497
+ name: 'conversation.composer.dock',
4498
+ id: 'fang-screenshot-inline',
4499
+ order: 91,
4500
+ }, ScreenshotDock)))
3198
4501
  // 左侧导航「瓮城」:图标组件即登记项组件(外壳只给 {size, active})
3199
4502
  disposers.push(ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
3200
4503
  name: 'sidebar.panellist',