@twinsearth/dsh-fang 3.0.8 → 3.0.10

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
  // ── 通用工具 ──────────────────────────────────────────────────────────
@@ -186,6 +187,20 @@ window.__ModuleLoader__.load({
186
187
  window.localStorage.setItem(key, value ? '1' : '0')
187
188
  } catch { /* 隐私模式:偏好只影响本次会话 */ }
188
189
  }
190
+ function readNumberPref(key, fallback) {
191
+ try {
192
+ if (typeof window === 'undefined' || !window.localStorage) return fallback
193
+ const raw = window.localStorage.getItem(key)
194
+ const n = Number(raw)
195
+ return raw !== null && Number.isFinite(n) ? n : fallback
196
+ } catch { return fallback }
197
+ }
198
+ function writeNumberPref(key, value) {
199
+ try {
200
+ if (typeof window === 'undefined' || !window.localStorage) return
201
+ window.localStorage.setItem(key, String(value))
202
+ } catch { /* 隐私模式 */ }
203
+ }
189
204
 
190
205
  // ── 标题降级:绝不把工作区名当会话标题 ────────────────────────────────
191
206
  function sessionTitleInfo(session) {
@@ -363,22 +378,41 @@ window.__ModuleLoader__.load({
363
378
 
364
379
  async function api(path, options) {
365
380
  const url = String(path)
366
- const token = await ensureFangAuthToken()
381
+ // Absolute / scheme-relative URLs must never reach fetch(): the install token
382
+ // would travel to a foreign origin. The panel only talks to its own /fang API.
383
+ if (!url.startsWith('/') || url.startsWith('//')) {
384
+ const message = 'api() 只接受同源相对路径:' + url
385
+ diag('bad', message)
386
+ return { status: 0, body: { ok: false, error: 'invalid-api-path' }, diagnostic: { url, message } }
387
+ }
388
+ const request = { ...(options ?? {}) }
389
+ let token = await ensureFangAuthToken()
390
+ const buildHeaders = () => ({
391
+ ...(request.headers ?? {}),
392
+ 'content-type': 'application/json',
393
+ accept: 'application/json',
394
+ ...(token ? { 'x-fang-auth': token } : {}),
395
+ })
367
396
  let res
368
397
  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
- })
398
+ res = await fetch(url, { ...request, headers: buildHeaders() })
377
399
  } catch (error) {
378
400
  const message = String(error?.message ?? error)
379
401
  diag('bad', '网络请求失败:' + url, message)
380
402
  return { status: 0, body: null, diagnostic: { url, message } }
381
403
  }
404
+ // A host restart can rotate the install token; retry once with the public
405
+ // /fang/api/auth-token bootstrap instead of leaving the panel stuck at 401.
406
+ if (res.status === 401) {
407
+ fangAuthToken = ''
408
+ const fresh = await ensureFangAuthToken()
409
+ if (fresh && fresh !== token) {
410
+ token = fresh
411
+ try {
412
+ res = await fetch(url, { ...request, headers: buildHeaders() })
413
+ } catch { /* keep the original 401 below */ }
414
+ }
415
+ }
382
416
  const etag = (res.headers && typeof res.headers.get === 'function' && res.headers.get('etag')) || ''
383
417
  if (res.status === 304) return { status: 304, body: null, notModified: true, etag }
384
418
  let text = ''
@@ -398,6 +432,12 @@ window.__ModuleLoader__.load({
398
432
  }
399
433
 
400
434
  function resolveMotherOrigin() {
435
+ // In the Electron shell the panel origin is the loopback proxy, which only
436
+ // serves /fang/api/*; the mother portal lives on the upstream DSH origin.
437
+ try {
438
+ const desktop = typeof window !== 'undefined' ? window.__fangDesktopUpstream : ''
439
+ if (typeof desktop === 'string' && /^https?:\/\//i.test(desktop)) return desktop.replace(/\/+$/, '')
440
+ } catch { /* ignore */ }
401
441
  try {
402
442
  const transport = typeof globalThis !== 'undefined' ? globalThis.__DSH_TRANSPORT__ : undefined
403
443
  const streamBaseUrl = transport && typeof transport.streamBaseUrl === 'string' ? transport.streamBaseUrl : ''
@@ -409,14 +449,27 @@ window.__ModuleLoader__.load({
409
449
  } catch { /* ignore */ }
410
450
  return ''
411
451
  }
412
- function openMotherPortal() {
452
+ async function openMotherPortal() {
453
+ // 母体 Web 就是 DSH 客户端本身。Electron 壳优先把 DSH 桌面窗口置前,
454
+ // 而不是打开没有 token 的裸 HTTP URL(那会 401)。
455
+ if (window.fangShell?.focusMother) {
456
+ try {
457
+ const result = await window.fangShell.focusMother()
458
+ if (result?.ok) return
459
+ } catch { /* fall through */ }
460
+ }
461
+ const token = new URLSearchParams(location.search).get('token') || ''
413
462
  const origin = resolveMotherOrigin()
414
- const url = origin ? `${origin}/fang/panel` : '/fang/panel'
463
+ if (!window.fangShell && token && origin) {
464
+ try {
465
+ const win = window.open(`${origin}/?token=${encodeURIComponent(token)}`, '_blank', 'noopener')
466
+ if (win) return
467
+ } catch { /* popup blocked */ }
468
+ }
469
+ // Web 端:母体 Web 就是当前 DSH 客户端,切回瓮城控制台视图即可。
415
470
  try {
416
- const win = window.open(url, '_blank', 'noopener')
417
- if (win) return
418
- } catch { /* 弹窗被拦 → 同页打开 */ }
419
- try { window.location.assign(url) } catch { /* ignore */ }
471
+ window.dispatchEvent(new CustomEvent('fang:mother-portal'))
472
+ } catch { /* ignore */ }
420
473
  }
421
474
 
422
475
  // ── DOM 构造器 h():本文件唯一的视图原语 ──────────────────────────────
@@ -615,8 +668,14 @@ window.__ModuleLoader__.load({
615
668
  .chip--neutral{color:var(--f-text-3);background:var(--f-surface-2);border-color:var(--f-border)}
616
669
 
617
670
  /* 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}
619
- @media (max-width:1100px){.fang-body{grid-template-columns:1fr}}
671
+ .fang-body{position:relative;display:grid;grid-template-columns:minmax(320px,50fr) minmax(0,50fr);gap:16px;align-items:start;min-height:0;flex:1 1 auto}
672
+ .fang-body.is-resizing{cursor:col-resize;user-select:none}
673
+ .fang-body.is-resizing *{user-select:none}
674
+ .fang-split-handle{position:absolute;top:0;bottom:0;left:50%;width:10px;transform:translateX(-50%);cursor:col-resize;z-index:6;border-radius:6px;background:transparent;touch-action:none}
675
+ .fang-split-handle::after{content:"";position:absolute;top:50%;left:50%;width:3px;height:46px;transform:translate(-50%,-50%);border-radius:3px;background:var(--f-border-strong,var(--f-border));opacity:.55;transition:opacity .15s,background .15s}
676
+ .fang-split-handle:hover::after,.fang-split-handle:focus-visible::after,.fang-body.is-resizing .fang-split-handle::after{opacity:1;background:var(--f-blue,#3b82f6)}
677
+ .fang-split-handle:focus-visible{outline:2px solid var(--f-blue,#3b82f6);outline-offset:2px}
678
+ @media (max-width:1100px){.fang-body{grid-template-columns:1fr}.fang-split-handle{display:none}}
620
679
  .panel{background:var(--f-surface);border:1px solid var(--f-border);border-radius:var(--f-radius-panel);
621
680
  box-shadow:var(--f-shadow-card);display:flex;flex-direction:column;min-height:0;overflow:hidden;
622
681
  max-height:calc(100vh - 132px)}
@@ -884,8 +943,8 @@ window.__ModuleLoader__.load({
884
943
  .section-title{min-height:34px}
885
944
  }
886
945
  .btn--sm{min-height:34px}
887
- .expand-btn{width:34px;height:34px}
888
- .section-title{min-height:34px}
946
+ .expand-btn{width:34px;height:34px;min-width:34px}
947
+ .section-title{min-height:34px;min-width:34px}
889
948
  .fork-actions .btn,.fork-actions .text-action{min-height:34px}
890
949
  @media (prefers-reduced-motion:reduce){
891
950
  .fang-console *,.fang-console *::before,.fang-console *::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
@@ -1039,7 +1098,21 @@ window.__ModuleLoader__.load({
1039
1098
  expanded: new Set(),
1040
1099
  collapsed: new Set(['temporary']),
1041
1100
  collapsedTasks: new Set(),
1101
+ // 主工作区比例:元宝工作区 / 分身工作区,默认 50:50,可拖动中间手柄调整。
1102
+ splitRatio: (() => {
1103
+ const n = readNumberPref('fang.panel.split', 0.5)
1104
+ return Math.min(0.75, Math.max(0.25, Number.isFinite(n) ? n : 0.5))
1105
+ })(),
1042
1106
  showTemporary: readPref('fang.panel.showTemporary', true),
1107
+ // 母体会话只读投影:默认只看最近 20 条,可切 50 / 全部(偏好存本机)。
1108
+ sessionWindow: (() => {
1109
+ try {
1110
+ const raw = window?.localStorage?.getItem('fang.panel.sessionWindow')
1111
+ if (raw === 'all') return 'all'
1112
+ const size = Number(raw)
1113
+ return Number.isFinite(size) && size >= 5 ? Math.min(200, Math.floor(size)) : 20
1114
+ } catch { return 20 }
1115
+ })(),
1043
1116
  view: 'console',
1044
1117
  busy: '',
1045
1118
  refreshing: false,
@@ -1100,6 +1173,13 @@ window.__ModuleLoader__.load({
1100
1173
  if (alive) render(true)
1101
1174
  }
1102
1175
  const setNotice = (notice) => { S.notice = notice; render() }
1176
+ const onFangNotice = (event) => notify('warn', String(event?.detail || ''))
1177
+ window.addEventListener('fang:notice', onFangNotice)
1178
+ const onMotherPortal = () => {
1179
+ S.view = 'console'
1180
+ setNotice({ tone: 'ok', title: '母体 Web', message: '母体 Web 就是当前 DSH 客户端,已切回瓮城控制台视图。' })
1181
+ }
1182
+ window.addEventListener('fang:mother-portal', onMotherPortal)
1103
1183
 
1104
1184
  // 渲染:整棵视图重建 + 焦点/滚动/光标恢复;编辑中挂起后台刷新,避免输入被重建。
1105
1185
  function render(force = false) {
@@ -1192,7 +1272,7 @@ window.__ModuleLoader__.load({
1192
1272
  const [statusRes, tasksRes, sessionsRes, essenceRes] = await Promise.all([
1193
1273
  api('/fang/api/status').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1194
1274
  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) } })),
1275
+ api(`/fang/api/sessions?limit=${S.sessionWindow === 'all' ? 1000 : S.sessionWindow}`).catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1196
1276
  api('/fang/api/essence/list').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
1197
1277
  ])
1198
1278
  if (!alive || seq !== refreshSeq) return
@@ -1259,6 +1339,13 @@ window.__ModuleLoader__.load({
1259
1339
  // ── 动作 ────────────────────────────────────────────────────────────
1260
1340
  const isBusy = () => S.busy !== ''
1261
1341
 
1342
+ function setSessionWindow(next) {
1343
+ const normalized = next === 'all' ? 'all' : Math.max(5, Math.min(200, Math.floor(Number(next) || 20)))
1344
+ S.sessionWindow = normalized
1345
+ try { window.localStorage?.setItem('fang.panel.sessionWindow', String(normalized)) } catch { /* ignore */ }
1346
+ void refresh({ manual: true })
1347
+ }
1348
+
1262
1349
  async function deriveTask(payload) {
1263
1350
  if (deriveStore.inflight) return
1264
1351
  deriveStore.lastGesture = Date.now()
@@ -1270,7 +1357,7 @@ window.__ModuleLoader__.load({
1270
1357
  setNotice({
1271
1358
  tone: 'ok', title: payload?.sessionId ? '已派发:从会话继续' : '已派生新分身',
1272
1359
  message: `${result.taskId}${result.port ? ' · 端口 ' + result.port : ''}${result.adapter?.ok ? ' · 适配器已就绪' : ' · 适配器尚未就绪,右栏会标出健康状态'}`,
1273
- actions: result.url ? [{ label: '打开分身', href: result.url }] : [],
1360
+ actions: result.taskId ? [{ label: '打开分身', onClick: () => void openTask({ taskId: result.taskId }) }] : [],
1274
1361
  })
1275
1362
  await refresh()
1276
1363
  } else if (result) {
@@ -1353,7 +1440,7 @@ window.__ModuleLoader__.load({
1353
1440
  const body = result.body
1354
1441
  if (result.status === 200 && body?.ok) {
1355
1442
  S.view = 'console'
1356
- setNotice({ tone: 'ok', title: '已还原存档', message: `${task.title || task.taskId} 已重新启动 · 端口 ${body.port ?? '—'}`, actions: body.url ? [{ label: '打开分身', href: body.url }] : [] })
1443
+ setNotice({ tone: 'ok', title: '已还原存档', message: `${task.title || task.taskId} 已重新启动 · 端口 ${body.port ?? '—'}`, actions: [{ label: '打开分身', onClick: () => void openTask({ taskId: task.taskId }) }] })
1357
1444
  } else {
1358
1445
  const code = body?.error || (result.status ? 'http-' + result.status : 'network')
1359
1446
  setNotice({ tone: 'bad', title: '还原失败', message: failureHint(code), detail: body?.detail || diagnosticText(result.diagnostic) })
@@ -1408,16 +1495,557 @@ window.__ModuleLoader__.load({
1408
1495
  })
1409
1496
  }
1410
1497
 
1498
+ function captureEssence() {
1499
+ if (isBusy()) return
1500
+ const profile = String(S.status?.data?.mother?.profile || 'desktop')
1501
+ askPrompt({
1502
+ title: '从母体生成元主',
1503
+ label: '新元主名称',
1504
+ value: `${profile} 元主`,
1505
+ confirmLabel: '生成',
1506
+ hint: '复制母体 profile 的可写层:插件补丁、依赖与设置;不复制凭据、会话和 node_modules。生成后可在元主区设为默认派生基底。',
1507
+ onConfirm: async (name) => {
1508
+ const trimmed = String(name ?? '').trim()
1509
+ if (!trimmed) { S.modal.error = '请填写元主名称'; render(true); return false }
1510
+ S.busy = 'essence:capture'
1511
+ const result = await api('/fang/api/essence/capture', { method: 'POST', body: JSON.stringify({ name: trimmed }) })
1512
+ S.busy = ''
1513
+ const body = result.body
1514
+ if (result.status === 200 && body?.ok) {
1515
+ const status = String(body.status ?? '')
1516
+ const conflicts = Array.isArray(body.conflicts) ? body.conflicts.length : 0
1517
+ const captured = body.captured ?? {}
1518
+ setNotice({
1519
+ tone: status === 'ready' ? 'ok' : 'warn',
1520
+ title: status === 'ready' ? '元主已生成' : '元主已生成(有冲突)',
1521
+ message: `「${body.meta?.name || trimmed}」· 补丁 ${captured.patchEntries ?? 0} 条 · 依赖 ${captured.dependencies ?? 0} 个 · 设置 ${captured.settings ?? 0} 组 · 捆绑 ${captured.bundles ?? 0} 个`,
1522
+ detail: conflicts > 0 ? `${conflicts} 条合并冲突:元主已物化,但需要人工处理后再用于派生。` : '',
1523
+ })
1524
+ } else {
1525
+ const code = body?.error || (result.status ? 'http-' + result.status : 'network')
1526
+ setNotice({ tone: 'bad', title: '生成元主失败', message: failureHint(code), detail: body?.detail || diagnosticText(result.diagnostic) })
1527
+ }
1528
+ await refresh()
1529
+ },
1530
+ })
1531
+ }
1532
+
1533
+ // 升级链路 2.1:克隆母体 profile 到镜像(先自动备份,克隆后元主待同步)。
1534
+ function cloneMotherProfile() {
1535
+ if (isBusy()) return
1536
+ askConfirm({
1537
+ tone: 'info',
1538
+ title: '克隆母体到镜像?',
1539
+ confirm: 'clone-mother',
1540
+ message: '读取本机母体 profile(package.json / cordis.patch.yml / cordis.yml / settings),覆盖镜像 active/profile,并先自动备份当前镜像。\n\n克隆后所有元主会变成「🔼 待同步」——不会自动改它们的配置。',
1541
+ confirmLabel: '克隆母体',
1542
+ onConfirm: async () => {
1543
+ S.busy = 'mirror:clone'
1544
+ const result = await api('/fang/api/mirror/clone-profile', { method: 'POST', body: JSON.stringify({}) })
1545
+ S.busy = ''
1546
+ const body = result.body
1547
+ if (result.status === 200 && body?.ok) {
1548
+ setNotice({
1549
+ tone: 'ok', title: '母体已克隆到镜像',
1550
+ message: `版本 ${body.version} · ${(body.files || []).length} 个文件 → active/profile`,
1551
+ detail: body.backup ? `已自动备份:${body.backup.id}` : '',
1552
+ })
1553
+ } else {
1554
+ const code = body?.error || (result.status ? 'http-' + result.status : 'network')
1555
+ setNotice({ tone: 'bad', title: '克隆母体失败', message: failureHint(code), detail: body?.detail || diagnosticText(result.diagnostic) })
1556
+ }
1557
+ await refresh()
1558
+ },
1559
+ })
1560
+ }
1561
+
1562
+ // 升级链路 3:把元主 overlay 重放到当前镜像(配置不动)。
1563
+ async function syncEssence(essenceId) {
1564
+ if (isBusy()) return
1565
+ S.busy = 'essence:sync:' + essenceId
1566
+ const result = await api('/fang/api/essence/sync', { method: 'POST', body: JSON.stringify({ essenceId }) })
1567
+ S.busy = ''
1568
+ const body = result.body
1569
+ if (result.status === 200 && body?.ok) {
1570
+ setNotice({ tone: body.status === 'ready' ? 'ok' : 'warn', title: '元主已同步', message: `${essenceId} · ${body.status}${body.recomputed ? '(已重新物化)' : '(无需重算)'}` })
1571
+ } else {
1572
+ setNotice({ tone: 'bad', title: '元主同步失败', message: failureHint(body?.error || 'sync-failed'), detail: body?.detail || diagnosticText(result.diagnostic) })
1573
+ }
1574
+ await refresh()
1575
+ }
1576
+
1577
+ async function syncEssences() {
1578
+ if (isBusy()) return
1579
+ S.busy = 'essence:sync:all'
1580
+ const result = await api('/fang/api/essence/sync', { method: 'POST', body: JSON.stringify({}) })
1581
+ S.busy = ''
1582
+ const body = result.body
1583
+ if (result.status === 200 && body?.ok) {
1584
+ setNotice({
1585
+ tone: (body.conflicted || []).length > 0 ? 'warn' : 'ok',
1586
+ title: '元主批量同步完成',
1587
+ message: `重算 ${(body.recomputed || []).length} · 跳过 ${(body.skipped || []).length} · 冲突 ${(body.conflicted || []).length} · 失败 ${(body.failed || []).length}`,
1588
+ detail: (body.failed || []).length ? (body.failed || []).map((item) => `${item.id}: ${item.error}`).join('\n') : '',
1589
+ })
1590
+ } else {
1591
+ setNotice({ tone: 'bad', title: '元主批量同步失败', message: failureHint(body?.error || 'sync-failed'), detail: body?.detail || diagnosticText(result.diagnostic) })
1592
+ }
1593
+ await refresh()
1594
+ }
1595
+
1596
+ // 原身运行态:隔离 home 的配置态实例(不写母体 sessions)。
1597
+ async function essenceRuntime(action, essenceId) {
1598
+ if (isBusy()) return
1599
+ S.busy = 'essence:runtime:' + essenceId
1600
+ const result = await api('/fang/api/essence/runtime', { method: 'POST', body: JSON.stringify({ action, essenceId }) })
1601
+ S.busy = ''
1602
+ const body = result.body
1603
+ if (result.status === 200 && body?.ok) {
1604
+ setNotice({
1605
+ tone: 'ok',
1606
+ title: action === 'stop' ? '元主运行时已停止' : '元主运行时已启动',
1607
+ message: action === 'stop'
1608
+ ? '进程已停止(overlay 与数据保留)'
1609
+ : `端口 ${body.port ?? '—'} · 隔离 home:${body.sandboxHome ?? '—'}`,
1610
+ })
1611
+ } else {
1612
+ setNotice({ tone: 'bad', title: '元主运行态操作失败', message: failureHint(body?.error || 'runtime-failed'), detail: body?.detail || diagnosticText(result.diagnostic) })
1613
+ }
1614
+ await refresh()
1615
+ }
1616
+
1617
+ // 打开前选会话:多选 1–5 个进行中会话(归档会话不出现)。
1618
+ function showSessionPicker(sessions, onPick) {
1619
+ const doc = document
1620
+ const select = h('select', {
1621
+ multiple: true, size: 8,
1622
+ style: { width: '100%', minHeight: 160, marginTop: 10, font: '12px/1.4 inherit', borderRadius: 8, padding: 6 },
1623
+ }, ...sessions.map((session) => h('option', { value: session.sessionId },
1624
+ `${session.title || session.sessionId}${session.workspaceTitle ? ' · ' + session.workspaceTitle : ''}`)))
1625
+ const hint = h('div', { style: { fontSize: 12, opacity: .7, marginTop: 6 } },
1626
+ 'Ctrl/⌘ 多选,最多 5 个**进行中**会话;归档会话不会出现在这里。')
1627
+ const btn = (label, primary) => h('button', {
1628
+ type: 'button',
1629
+ style: {
1630
+ height: 30, padding: '0 12px', borderRadius: 8, cursor: 'pointer', fontSize: 12,
1631
+ border: primary ? '1px solid #17803D' : '1px solid rgba(255,255,255,.24)',
1632
+ background: primary ? '#17803D' : 'transparent', color: '#fff',
1633
+ },
1634
+ }, label)
1635
+ const startBtn = btn('启动并导入', true)
1636
+ const skipBtn = btn('仅启动', false)
1637
+ const cancelBtn = btn('取消', false)
1638
+ const card = h('div', {
1639
+ role: 'dialog', 'aria-modal': 'true',
1640
+ style: { width: 'min(560px, 92vw)', padding: 18, borderRadius: 14, background: '#1D1D1F', color: '#fff' },
1641
+ },
1642
+ h('div', { style: { fontSize: 14, fontWeight: 600 } }, '打开元主 Web:导入进行中会话'),
1643
+ hint,
1644
+ select,
1645
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } }, startBtn, skipBtn, cancelBtn))
1646
+ const backdrop = h('div', {
1647
+ style: {
1648
+ position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
1649
+ alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,.55)',
1650
+ },
1651
+ }, card)
1652
+ const close = () => backdrop.remove()
1653
+ startBtn.addEventListener('click', () => {
1654
+ const ids = [...(select.selectedOptions || [])].map((option) => option.value)
1655
+ if (ids.length > 5) { hint.textContent = '最多选择 5 个会话'; return }
1656
+ close()
1657
+ onPick(ids)
1658
+ })
1659
+ skipBtn.addEventListener('click', () => { close(); onPick([]) })
1660
+ cancelBtn.addEventListener('click', close)
1661
+ backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close() })
1662
+ doc.body.appendChild(backdrop)
1663
+ }
1664
+
1665
+ function showDerivePicker(sessions, essenceName, onPick) {
1666
+ const doc = document
1667
+ const select = h('select', {
1668
+ size: Math.min(8, Math.max(4, sessions.length)),
1669
+ style: { width: '100%', minHeight: 150, marginTop: 10, font: '12px/1.4 inherit', borderRadius: 8, padding: 6 },
1670
+ }, ...sessions.map((session) => h('option', { value: session.sessionId },
1671
+ `${session.title || session.sessionId}${session.workspaceTitle ? ' · ' + session.workspaceTitle : ''}`)))
1672
+ const hint = h('div', { style: { fontSize: 12, opacity: .7, marginTop: 6 } },
1673
+ '选择一个进行中的 DSH 会话,整目录复制进新分身的沙箱(归档会话不列出)。')
1674
+ const btn = (label, primary) => h('button', {
1675
+ type: 'button',
1676
+ style: {
1677
+ height: 30, padding: '0 12px', borderRadius: 8, cursor: 'pointer', fontSize: 12,
1678
+ border: primary ? '1px solid #17803D' : '1px solid rgba(255,255,255,.24)',
1679
+ background: primary ? '#17803D' : 'transparent', color: '#fff',
1680
+ },
1681
+ }, label)
1682
+ const startBtn = btn('派 生', true)
1683
+ const cancelBtn = btn('取消', false)
1684
+ const card = h('div', {
1685
+ role: 'dialog', 'aria-modal': 'true',
1686
+ style: { width: 'min(560px, 92vw)', padding: 18, borderRadius: 14, background: '#1D1D1F', color: '#fff' },
1687
+ },
1688
+ h('div', { style: { fontSize: 14, fontWeight: 600 } }, `派生分身 · 基于「${essenceName}」`),
1689
+ hint,
1690
+ select,
1691
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } }, startBtn, cancelBtn))
1692
+ const backdrop = h('div', {
1693
+ style: {
1694
+ position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
1695
+ alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,.55)',
1696
+ },
1697
+ }, card)
1698
+ const close = () => backdrop.remove()
1699
+ startBtn.addEventListener('click', () => {
1700
+ const picked = String(select.value || '')
1701
+ if (!picked) { hint.textContent = '请选择一个会话'; return }
1702
+ close()
1703
+ onPick(picked)
1704
+ })
1705
+ cancelBtn.addEventListener('click', close)
1706
+ backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close() })
1707
+ doc.body.appendChild(backdrop)
1708
+ }
1709
+
1710
+ async function deriveFromEssence(essence) {
1711
+ if (isBusy()) return
1712
+ S.busy = 'essence:derive:' + essence.id
1713
+ const res = await api('/fang/api/sessions?limit=200')
1714
+ S.busy = ''
1715
+ const sessions = Array.isArray(res.body?.sessions)
1716
+ ? res.body.sessions.filter((session) => session.archived !== true)
1717
+ : []
1718
+ if (sessions.length === 0) {
1719
+ setNotice({ tone: 'warn', title: '没有可复制的会话', message: '先在 DSH 里有一个进行中的会话,再派生。' })
1720
+ return
1721
+ }
1722
+ showDerivePicker(sessions, essence.name || essence.id, async (sessionId) => {
1723
+ const session = sessions.find((item) => String(item.sessionId) === String(sessionId))
1724
+ const title = String(session?.title || essence.name || '派生分身').slice(0, 60)
1725
+ S.busy = 'essence:derive:run:' + essence.id
1726
+ const out = await api('/fang/api/tasks/create', {
1727
+ method: 'POST',
1728
+ body: JSON.stringify({ title, essenceId: essence.id, importSession: { sessionId } }),
1729
+ })
1730
+ S.busy = ''
1731
+ if (out.status === 200 && out.body?.ok) {
1732
+ setNotice({ tone: 'ok', title: '已派生分身', message: `模板「${essence.name || essence.id}」· 会话 ${short(String(sessionId), 8)}` })
1733
+ } else {
1734
+ setNotice({ tone: 'bad', title: '派生失败', message: failureHint(out.body?.error || 'http-' + out.status), detail: out.body?.detail || '' })
1735
+ }
1736
+ await refresh()
1737
+ })
1738
+ }
1739
+
1740
+ async function startEssenceRuntime(essenceId, sessionIds) {
1741
+ S.busy = 'essence:start:' + essenceId
1742
+ const started = await api('/fang/api/essence/runtime', {
1743
+ method: 'POST',
1744
+ body: JSON.stringify({ action: 'start', essenceId, sessionIds }),
1745
+ })
1746
+ S.busy = ''
1747
+ if (started.status === 200 && started.body?.ok) {
1748
+ const imported = Array.isArray(started.body.importedSessions) ? started.body.importedSessions.length : 0
1749
+ setNotice({ tone: 'ok', title: '元主 Web 已启动', message: `端口 ${started.body.port ?? '—'} · 导入会话 ${imported} 个` })
1750
+ if (started.body.url) { try { window.open(String(started.body.url), '_blank', 'noopener') } catch { /* 弹层被拦 */ } }
1751
+ } else {
1752
+ setNotice({ tone: 'bad', title: '启动元主 Web 失败', message: failureHint(started.body?.error || 'runtime-failed'), detail: started.body?.detail || '' })
1753
+ }
1754
+ await refresh()
1755
+ }
1756
+
1757
+ // 打开&设置:已在跑 → 直接开带 token 的 URL;没跑 → 选会话后启动再打开。
1758
+ async function openEssence(essenceId) {
1759
+ if (isBusy()) return
1760
+ S.busy = 'essence:open:' + essenceId
1761
+ const st = await api(`/fang/api/essence/runtime?essenceId=${encodeURIComponent(essenceId)}`)
1762
+ const runtime = st.body?.runtime ?? null
1763
+ const running = Boolean(runtime && (runtime.running === true || String(runtime.status) === 'running'))
1764
+ S.busy = ''
1765
+ if (running) {
1766
+ const opened = await api(`/fang/api/essence/runtime/open?essenceId=${encodeURIComponent(essenceId)}`)
1767
+ if (opened.status === 200 && opened.body?.url) { try { window.open(String(opened.body.url), '_blank', 'noopener') } catch { /* 弹层被拦 */ } }
1768
+ else setNotice({ tone: 'bad', title: '无法打开元主 Web', message: '实例在跑但拿不到带 token 的地址' })
1769
+ return
1770
+ }
1771
+ const candidates = await api('/fang/api/essence/open/candidates')
1772
+ const sessions = Array.isArray(candidates.body?.sessions) ? candidates.body.sessions : []
1773
+ showSessionPicker(sessions, (sessionIds) => void startEssenceRuntime(essenceId, sessionIds))
1774
+ }
1775
+
1776
+ async function copyEssence(essence) {
1777
+ if (isBusy()) return
1778
+ askPrompt({
1779
+ title: '复制元主', label: '新元主名称', value: `${essence.name || essence.id} 副本`, confirmLabel: '复制',
1780
+ hint: '深复制该元主的整份沙盒目录(overlay + merged + 自定义数据)到新文件夹;不复制凭据、运行态与备份。',
1781
+ onConfirm: async (name) => {
1782
+ const trimmed = String(name ?? '').trim()
1783
+ if (!trimmed) { S.modal.error = '请填写名称'; render(true); return false }
1784
+ const result = await api('/fang/api/essence/copy', { method: 'POST', body: JSON.stringify({ essenceId: essence.id, name: trimmed }) })
1785
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已复制', message: trimmed })
1786
+ else setNotice({ tone: 'bad', title: '复制失败', message: failureHint(result.body?.error || 'http-' + result.status) })
1787
+ await refresh()
1788
+ },
1789
+ })
1790
+ }
1791
+
1792
+ function archiveEssence(essence) {
1793
+ if (isBusy()) return
1794
+ askConfirm({
1795
+ tone: 'info', title: '归档元主?', confirm: 'essence-archive',
1796
+ message: `「${essence.name || essence.id}」将归档:只改元数据,不删目录;归档后不能派生/配置。`,
1797
+ confirmLabel: '归档',
1798
+ onConfirm: async () => {
1799
+ const result = await api('/fang/api/essence/archive', { method: 'POST', body: JSON.stringify({ essenceId: essence.id, archived: true }) })
1800
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已归档', message: essence.name || essence.id })
1801
+ else setNotice({ tone: 'bad', title: '归档失败', message: failureHint(result.body?.error || 'http-' + result.status) })
1802
+ await refresh()
1803
+ },
1804
+ })
1805
+ }
1806
+
1807
+ async function stopEssenceRuntime(essence) {
1808
+ if (isBusy()) return
1809
+ S.busy = 'essence:stop'
1810
+ const result = await api('/fang/api/essence/runtime', { method: 'POST', body: JSON.stringify({ action: 'stop', essenceId: essence.id }) })
1811
+ S.busy = ''
1812
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '运行实例已停止', message: essence.name || essence.id })
1813
+ else setNotice({ tone: 'bad', title: '停止失败', message: failureHint(result.body?.error || 'http-' + result.status), detail: result.body?.detail || '' })
1814
+ await refresh()
1815
+ }
1816
+
1817
+ async function openBranches(task) {
1818
+ if (isBusy()) return
1819
+ S.busy = 'branches:' + task.taskId
1820
+ const res = await api('/fang/api/tasks/branches?taskId=' + encodeURIComponent(task.taskId))
1821
+ S.busy = ''
1822
+ const body = res.body ?? {}
1823
+ S.modal = {
1824
+ kind: 'branches',
1825
+ taskId: task.taskId,
1826
+ taskTitle: task.title || task.taskId,
1827
+ sessionId: body.sessionId ?? '',
1828
+ activeBranchId: body.activeBranchId ?? '',
1829
+ branches: Array.isArray(body.branches) ? body.branches : [],
1830
+ error: res.status === 200 && body.ok === true ? '' : failureHint(body.error || 'http-' + res.status),
1831
+ }
1832
+ render(true)
1833
+ }
1834
+
1835
+ async function forkBranch(task) {
1836
+ if (isBusy()) return
1837
+ S.busy = 'branch-fork:' + task.taskId
1838
+ const res = await api('/fang/api/tasks/branches/fork', { method: 'POST', body: JSON.stringify({ taskId: task.taskId }) })
1839
+ S.busy = ''
1840
+ if (res.status === 200 && res.body?.ok) {
1841
+ setNotice({ tone: 'ok', title: '已派生分支', message: res.body.branch?.branchId || '' })
1842
+ await openBranches(task)
1843
+ } else {
1844
+ setNotice({ tone: 'bad', title: '派生分支失败', message: failureHint(res.body?.error || 'http-' + res.status), detail: res.body?.detail || '' })
1845
+ render(true)
1846
+ }
1847
+ }
1848
+
1849
+ async function activateBranch(task, branchId) {
1850
+ if (isBusy()) return
1851
+ S.busy = 'branch-activate:' + task.taskId
1852
+ const res = await api('/fang/api/tasks/branches/activate', { method: 'POST', body: JSON.stringify({ taskId: task.taskId, branchId }) })
1853
+ S.busy = ''
1854
+ if (res.status === 200 && res.body?.ok) setNotice({ tone: 'ok', title: '已激活分支', message: branchId })
1855
+ else setNotice({ tone: 'bad', title: '激活分支失败', message: failureHint(res.body?.error || 'http-' + res.status) })
1856
+ await openBranches(task)
1857
+ }
1858
+
1859
+ function unfreezeEssence(essence) {
1860
+ if (isBusy()) return
1861
+ askConfirm({
1862
+ tone: 'info', title: '还原(解冻)元主?', confirm: 'essence-unfreeze',
1863
+ message: `「${essence.name || essence.id}」将从冻结态恢复为活跃:可打开/设置/派生;备份内容不变,删除仍可用。`,
1864
+ confirmLabel: '还原',
1865
+ onConfirm: async () => {
1866
+ S.busy = 'essence:unfreeze'
1867
+ const result = await api('/fang/api/essence/archive', { method: 'POST', body: JSON.stringify({ essenceId: essence.id, archived: false }) })
1868
+ S.busy = ''
1869
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已还原(解冻)', message: essence.name || essence.id })
1870
+ else setNotice({ tone: 'bad', title: '还原失败', message: failureHint(result.body?.error || 'http-' + result.status), detail: result.body?.detail || '' })
1871
+ await refresh()
1872
+ },
1873
+ })
1874
+ }
1875
+
1876
+ function deleteEssence(essence) {
1877
+ if (isBusy()) return
1878
+ if (essence.archived !== true) {
1879
+ setNotice({ tone: 'warn', title: '需先归档才能删除', message: '元主必须先归档(冻结)后,删除按钮才可用。' })
1880
+ return
1881
+ }
1882
+ // 两次确认:第一次说明后果,第二次必须输入元主名称。
1883
+ askConfirm({
1884
+ tone: 'bad', title: '删除元主?', confirm: 'delete-once',
1885
+ message: `「${essence.name || essence.id}」已冻结。删除会移除 essences/${essence.id}(overlay + merged),不可撤销,也不会删除会话。`,
1886
+ confirmLabel: '继续',
1887
+ onConfirm: () => {
1888
+ askConfirm({
1889
+ tone: 'bad', title: '再次确认:永久删除', confirm: 'delete', strong: true,
1890
+ expected: String(essence.name || essence.id),
1891
+ message: `最后一步:输入「${essence.name || essence.id}」以永久删除该元主。`,
1892
+ confirmLabel: '永久删除',
1893
+ onConfirm: async () => {
1894
+ S.busy = 'essence:delete:' + essence.id
1895
+ const result = await api('/fang/api/essence/delete', { method: 'POST', body: JSON.stringify({ essenceId: essence.id }) })
1896
+ S.busy = ''
1897
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已删除', message: essence.name || essence.id })
1898
+ else setNotice({ tone: 'bad', title: '删除元主失败', message: failureHint(result.body?.error || 'http-' + result.status), detail: result.body?.detail || '' })
1899
+ await refresh()
1900
+ },
1901
+ })
1902
+ },
1903
+ })
1904
+ }
1905
+
1906
+ async function saveBlob(blob, suggestedName) {
1907
+ try {
1908
+ if (typeof window.showSaveFilePicker === 'function') {
1909
+ const handle = await window.showSaveFilePicker({
1910
+ suggestedName,
1911
+ types: [{ description: '元主整包', accept: { 'application/json': ['.json'] } }],
1912
+ })
1913
+ const writable = await handle.createWritable()
1914
+ await writable.write(blob)
1915
+ await writable.close()
1916
+ return { ok: true, mode: 'picker' }
1917
+ }
1918
+ } catch (error) {
1919
+ if (String(error?.name) === 'AbortError') return { ok: false, aborted: true }
1920
+ }
1921
+ const link = h('a', { href: URL.createObjectURL(blob), download: suggestedName })
1922
+ document.body.appendChild(link)
1923
+ link.click()
1924
+ link.remove()
1925
+ return { ok: true, mode: 'download' }
1926
+ }
1927
+
1928
+ async function downloadEssence(essence) {
1929
+ try {
1930
+ const token = await ensureFangAuthToken()
1931
+ const res = await fetch(`/fang/api/essence/download?essenceId=${encodeURIComponent(essence.id)}&full=1`, {
1932
+ headers: token ? { 'x-fang-auth': token } : {},
1933
+ })
1934
+ if (!res.ok) throw new Error('HTTP ' + res.status)
1935
+ const blob = await res.blob()
1936
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '')
1937
+ const name = `essence-${String(essence.name || essence.id).replace(/[\\/:*?"<>|\s]+/g, '-')}-${stamp}.json`
1938
+ const saved = await saveBlob(blob, name)
1939
+ if (saved.aborted) return
1940
+ setNotice({
1941
+ tone: 'ok',
1942
+ title: '元主整包已下载',
1943
+ message: `${name}(${Math.round(blob.size / 1024)} KB)`,
1944
+ detail: saved.mode === 'picker' ? '已保存到你选择的文件夹;包内含 IMPORT-GUIDE.md 与 manifest.json。' : '已保存到下载目录;包内含导入引导与清单。',
1945
+ })
1946
+ } catch (error) {
1947
+ setNotice({ tone: 'bad', title: '下载元主失败', message: String(error?.message ?? error) })
1948
+ }
1949
+ }
1950
+
1951
+ async function essenceBackup(essence) {
1952
+ const result = await api('/fang/api/essence/backup', { method: 'POST', body: JSON.stringify({ essenceId: essence.id }) })
1953
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已备份', message: `Backup/ · ${Math.round((result.body.bytes || 0) / 1024)} KB(只保留一份)` })
1954
+ else setNotice({ tone: 'bad', title: '备份失败', message: failureHint(result.body?.error || 'backup-failed'), detail: result.body?.detail || '' })
1955
+ await refresh()
1956
+ }
1957
+
1958
+ async function essenceRestore(essence) {
1959
+ if (isBusy()) return
1960
+ askConfirm({
1961
+ tone: 'info', title: '还原最新备份?', confirm: 'essence-restore',
1962
+ message: `用「${essence.name || essence.id}/Backup」覆盖当前 overlay 与 merged,还原后需重新同步/派生。`,
1963
+ confirmLabel: '还原',
1964
+ onConfirm: async () => {
1965
+ const result = await api('/fang/api/essence/restore', { method: 'POST', body: JSON.stringify({ essenceId: essence.id }) })
1966
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '已还原最新备份', message: essence.name || essence.id })
1967
+ else setNotice({ tone: 'bad', title: '还原失败', message: failureHint(result.body?.error || 'restore-failed'), detail: result.body?.detail || '' })
1968
+ await refresh()
1969
+ },
1970
+ })
1971
+ }
1972
+
1973
+ function essenceImport() {
1974
+ const input = h('input', { type: 'file', accept: '.json,application/json', style: { display: 'none' } })
1975
+ input.addEventListener('change', async () => {
1976
+ const file = input.files?.[0]
1977
+ input.remove()
1978
+ if (!file) return
1979
+ try {
1980
+ const bundle = JSON.parse(await file.text())
1981
+ S.busy = 'essence:import'
1982
+ const result = await api('/fang/api/essence/import', { method: 'POST', body: JSON.stringify({ bundle }) })
1983
+ S.busy = ''
1984
+ if (result.status === 200 && result.body?.ok) setNotice({ tone: 'ok', title: '元主已导入', message: `${result.body.essence?.name || '导入的元主'} · ${result.body.files} 个文件` })
1985
+ else setNotice({ tone: 'bad', title: '导入失败', message: failureHint(result.body?.error || 'import-failed'), detail: result.body?.detail || '' })
1986
+ await refresh()
1987
+ } catch (error) {
1988
+ S.busy = ''
1989
+ setNotice({ tone: 'bad', title: '导入失败', message: String(error?.message ?? error) })
1990
+ }
1991
+ })
1992
+ document.body.appendChild(input)
1993
+ input.click()
1994
+ }
1995
+
1996
+ // 单个元主详情页:设置 / 插件 / 运行日志 三个 tab。
1997
+ async function loadEssenceDetail() {
1998
+ const modal = S.modal
1999
+ if (!modal || modal.kind !== 'essence') return
2000
+ const result = await api(`/fang/api/essence/detail?essenceId=${encodeURIComponent(modal.essenceId)}`)
2001
+ if (!S.modal || S.modal !== modal) return
2002
+ modal.loading = false
2003
+ if (result.status === 200 && result.body?.ok) modal.detail = result.body
2004
+ else modal.error = result.body?.error || 'http-' + result.status
2005
+ render(true)
2006
+ }
2007
+
2008
+ function openEssenceDetail(essence) {
2009
+ lockScroll()
2010
+ S.modal = { kind: 'essence', essenceId: essence.id, tab: 'settings', detail: null, loading: true, error: '' }
2011
+ render(true)
2012
+ void loadEssenceDetail()
2013
+ }
2014
+
1411
2015
  async function openTask(task) {
1412
2016
  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 { /* 弹层被拦 */ }
2017
+ if (!taskId) { notify('warn', '该分身没有 taskId,无法打开。'); return }
2018
+ const result = await api(`/fang/api/tasks/open-url?taskId=${encodeURIComponent(taskId)}`)
2019
+ if (result.status === 200 && result.body?.url) {
2020
+ try { window.open(result.body.url, '_blank', 'noopener'); return } catch { /* 弹层被拦 */ }
2021
+ }
2022
+ const code = result.body?.error || (result.status ? 'http-' + result.status : 'network')
2023
+ if (code === 'not-running') {
2024
+ notify('warn', '分身已停止,正在启动…')
2025
+ let restored = await api('/fang/api/tasks/restore', { method: 'POST', body: JSON.stringify({ taskId }) })
2026
+ // A stopped (but not archived) fork cannot be restored directly; archive it
2027
+ // first (keeps home), then restore spawns from the same home.
2028
+ if (restored.body?.error === 'not-archived' && String(task?.status || '') !== 'running') {
2029
+ const archived = await api('/fang/api/tasks/archive', { method: 'POST', body: JSON.stringify({ taskId }) })
2030
+ if (archived.status === 200 && archived.body?.ok !== false) {
2031
+ restored = await api('/fang/api/tasks/restore', { method: 'POST', body: JSON.stringify({ taskId }) })
2032
+ }
2033
+ }
2034
+ if (restored.status !== 200 || restored.body?.ok === false) {
2035
+ notify('bad', `启动分身失败:${restored.body?.error || 'restore-failed'}`)
2036
+ return
1417
2037
  }
2038
+ for (let i = 0; i < 20; i += 1) {
2039
+ await new Promise((resolve) => setTimeout(resolve, 800))
2040
+ const retry = await api(`/fang/api/tasks/open-url?taskId=${encodeURIComponent(taskId)}`)
2041
+ if (retry.status === 200 && retry.body?.url) {
2042
+ try { window.open(retry.body.url, '_blank', 'noopener'); return } catch { /* 弹层被拦 */ }
2043
+ }
2044
+ }
2045
+ notify('warn', '分身已启动,但 Web URL 尚未就绪;稍后点“打开”再试。')
2046
+ return
1418
2047
  }
1419
- if (!task?.url) { notify('warn', '该分身没有可打开的 URL(可能已停止);可归档回收。'); return }
1420
- try { window.open(task.url, '_blank', 'noopener') } catch { /* ignore */ }
2048
+ notify('bad', `打开分身失败:${code}`)
1421
2049
  }
1422
2050
 
1423
2051
  async function copyText(text, label) {
@@ -1598,7 +2226,11 @@ window.__ModuleLoader__.load({
1598
2226
 
1599
2227
  const app = {
1600
2228
  state: S, view, render, schedule, refresh, deriveTask, openMother, closeModal,
1601
- archiveTask, restoreTask, deleteArchive, promoteTask, openTask, copyText,
2229
+ archiveTask, restoreTask, deleteArchive, promoteTask, openTask, copyText, captureEssence,
2230
+ cloneMotherProfile, syncEssence, syncEssences, setSessionWindow, essenceRuntime,
2231
+ openEssence, copyEssence, archiveEssence, deleteEssence, downloadEssence, essenceImport,
2232
+ essenceBackup, essenceRestore, openEssenceDetail, unfreezeEssence, stopEssenceRuntime,
2233
+ openBranches, forkBranch, activateBranch, deriveFromEssence,
1602
2234
  beginRename, commitRename, cancelRename, selectSession, toggleSet, toggleForkGroup,
1603
2235
  toggleTemporary, setView: (next) => { S.view = next; schedule(true) },
1604
2236
  loadForkSessions, loadMirror, mirrorAction, loadLink, probeMother, notify, announce,
@@ -1622,6 +2254,8 @@ window.__ModuleLoader__.load({
1622
2254
  if (pollTimer) window.clearInterval(pollTimer)
1623
2255
  if (toastTimer) window.clearTimeout(toastTimer)
1624
2256
  if (deriveTicker) window.clearInterval(deriveTicker)
2257
+ window.removeEventListener('fang:notice', onFangNotice)
2258
+ window.removeEventListener('fang:mother-portal', onMotherPortal)
1625
2259
  unsubscribe()
1626
2260
  root.remove()
1627
2261
  },
@@ -1976,19 +2610,39 @@ window.__ModuleLoader__.load({
1976
2610
  const all = S.sessions.items
1977
2611
  const query = S.query.trim().toLowerCase()
1978
2612
  const filtered = query ? all.filter((session) => sessionSearchText(session).includes(query)) : all
1979
- const groups = groupMotherWorkspaces(filtered, S.aliases)
1980
- const split = classifyMotherSessions(filtered)
2613
+ // 空会话(无用户消息)不进列表:它们没有任何内容可看。
2614
+ const visible = filtered.filter((session) => session?.empty !== true)
2615
+ const groups = groupMotherWorkspaces(visible, S.aliases)
2616
+ const split = classifyMotherSessions(visible)
1981
2617
  const selected = all.find((session) => String(session.sessionId) === S.selectedSessionId) || null
1982
2618
  const countText = query
1983
- ? `${filtered.length}/${all.length}`
1984
- : `${all.length}${S.sessions.total > all.length ? '/' + S.sessions.total : ''}`
2619
+ ? `${visible.length}/${all.length}`
2620
+ : `${visible.length}${S.sessions.total > all.length ? '/' + S.sessions.total : ''}`
1985
2621
  const sessionState = S.sessions.state
1986
2622
 
1987
2623
  const head = h('div', { class: 'panel-head' },
1988
2624
  h('div', { class: 'panel-title-row' },
1989
2625
  h('h2', { class: 'panel-title' }, '母体'),
1990
2626
  h('span', { class: 'panel-sub' }, '元主 · 项目 & 会话'),
1991
- h('span', { class: 'panel-count', title: '已加载 / 宿主返回的会话总数' }, `${countText} 会话`)),
2627
+ h('span', { class: 'panel-count', title: '已加载 / 宿主返回的会话总数' }, `${countText} 会话`),
2628
+ (() => {
2629
+ const stale = Number(S.essenceList?.data?.staleCount) || 0
2630
+ const update = S.mirror?.data?.updateAvailable === true
2631
+ const conflicted = (S.essenceList?.data?.essences || []).filter((item) => item.status === 'conflicted').length
2632
+ const tone2 = (conflicted > 0) ? 'red' : (stale > 0 || update) ? 'yellow' : 'green'
2633
+ const label2 = tone2 === 'red' ? '红灯' : tone2 === 'yellow' ? '黄灯' : '绿灯'
2634
+ const reasons = []
2635
+ if (update) reasons.push('母体有新版本')
2636
+ if (stale > 0) reasons.push(`${stale} 个元主待同步`)
2637
+ if (conflicted > 0) reasons.push(`${conflicted} 个元主冲突`)
2638
+ return h('span', {
2639
+ class: 'chip', 'data-lamp': tone2,
2640
+ title: reasons.length ? reasons.join(';') : '母体 / 元主 / 分身状态正常',
2641
+ style: { display: 'inline-flex', alignItems: 'center', gap: 6 },
2642
+ },
2643
+ h('span', { 'aria-hidden': 'true', style: { width: 8, height: 8, borderRadius: '50%', background: tone2 === 'red' ? '#C8102E' : tone2 === 'yellow' ? '#B45309' : '#17803D' } }),
2644
+ label2)
2645
+ })()),
1992
2646
  (() => {
1993
2647
  const data = S.status.data
1994
2648
  const tone = S.status.state === 'ready' ? 'ok' : data ? 'info' : 'neutral'
@@ -2001,6 +2655,11 @@ window.__ModuleLoader__.load({
2001
2655
  chip(tone, label, { state: S.status.state === 'ready' ? 'running' : 'unknown' }),
2002
2656
  data?.version ? h('span', { class: 'hint', style: { fontFamily: 'var(--f-mono)' } }, 'v' + String(data.version).replace(/^v/, '')) : null),
2003
2657
  h('div', { class: 'mother-control-sub' }, '只读访问:不写入、不改写母体会话')),
2658
+ button('克隆母体', {
2659
+ size: 'sm', variant: 'quiet', dataBtnId: 'M-07',
2660
+ title: '把本机母体 profile(package.json / cordis.patch.yml / settings)克隆到镜像 active/,先自动备份;克隆后元主会黄灯待同步',
2661
+ onClick: () => void app.cloneMotherProfile(),
2662
+ }),
2004
2663
  button('打开门户', {
2005
2664
  size: 'sm', variant: 'quiet', icon: icon('globe', 12), dataBtnId: 'M-06',
2006
2665
  title: '在新窗口打开 /fang/panel 独立门户(不关闭母体)',
@@ -2022,8 +2681,26 @@ window.__ModuleLoader__.load({
2022
2681
  h('div', { class: 'panel-tools' },
2023
2682
  h('span', null, `进行中 ${split.active.length}`),
2024
2683
  h('span', { class: 'spacer' }),
2025
- h('span', null, `临时 ${split.temporary.length} · 归档 ${split.archived.length}`),
2684
+ h('span', { class: 'session-window', 'data-zone': 'session-window', style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
2685
+ h('span', { class: 'hint' }, '显示'),
2686
+ ...[[20, '20'], [50, '50'], ['all', '全部']].map(([value, label]) => {
2687
+ const on = S.sessionWindow === value
2688
+ return h('button', {
2689
+ type: 'button',
2690
+ 'data-window': String(value),
2691
+ 'aria-pressed': on ? 'true' : 'false',
2692
+ title: value === 'all' ? '加载宿主返回的全部会话(只读投影)' : `只显示最近 ${label} 条会话`,
2693
+ onClick: () => app.setSessionWindow(value),
2694
+ style: {
2695
+ height: 22, padding: '0 7px', borderRadius: 6, cursor: 'pointer', fontSize: 11,
2696
+ border: '1px solid ' + (on ? 'rgba(127,127,127,.55)' : 'transparent'),
2697
+ background: on ? 'rgba(127,127,127,.16)' : 'transparent',
2698
+ color: 'inherit',
2699
+ },
2700
+ }, label)
2701
+ })),
2026
2702
  h('span', { class: 'spacer' }),
2703
+ h('span', null, `临时 ${split.temporary.length} · 归档 ${split.archived.length}`),
2027
2704
  h('span', { title: '没有写接口的动作会明确禁用并说明原因,不会假装成功' }, '只读')))
2028
2705
 
2029
2706
  const scroll = h('div', { class: 'panel-scroll', 'data-sk': 'left' })
@@ -2034,7 +2711,7 @@ window.__ModuleLoader__.load({
2034
2711
  scroll.append(emptyBlock('母体会话不可读', failureHint(S.sessions.error), [
2035
2712
  button('重试', { size: 'sm', variant: 'ghost', onClick: () => void app.refresh({ manual: true }) }),
2036
2713
  ]))
2037
- } else if (filtered.length === 0) {
2714
+ } else if (visible.length === 0) {
2038
2715
  scroll.append(emptyBlock(
2039
2716
  query ? `没有匹配「${clampText(S.query, 20)}」的会话` : '还没有母体会话',
2040
2717
  query ? '搜索标题、会话 ID 或工作区名;Esc 清空搜索。' : '在本机开一个新对话后刷新,它会出现在这里。选择会话是只读元数据,母体会话不会被改写。',
@@ -2044,7 +2721,7 @@ window.__ModuleLoader__.load({
2044
2721
  // 元主工作区的新建/归档/删除/下载是宿主职责:DOM 中不出现这些控件(不是禁用)。
2045
2722
  scroll.append(h('div', { class: 'section-head' },
2046
2723
  h('span', { class: 'section-title', style: { cursor: 'default' } }, '元主'),
2047
- h('span', { class: 'section-sub' }, `${groups.length} 个工作区`),
2724
+ h('span', { class: 'section-sub' }, `${groups.length} 个工作区 · ${visible.length} 条会话`),
2048
2725
  h('span', { class: 'spacer' }),
2049
2726
  h('span', { class: 'section-hint', title: '工作区 CRUD 属于 DSH 宿主;fang 不复制宿主职责' }, '宿主管理 · 只读')))
2050
2727
 
@@ -2058,18 +2735,112 @@ window.__ModuleLoader__.load({
2058
2735
  }
2059
2736
 
2060
2737
  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
2738
+ const defaultEssenceId = String(S.essenceList?.data?.defaultId ?? '')
2739
+ const staleCount = Number(S.essenceList?.data?.staleCount) || 0
2740
+ const essenceHead = h('div', { class: 'section-head', 'data-zone': 'essence-head' },
2741
+ h('span', { class: 'section-title', style: { cursor: 'default' } }, '元主'),
2742
+ h('span', { class: 'section-sub' }, `${essences.length} 个 · 默认 ${defaultEssenceId ? short(defaultEssenceId, 18) : '—'}${staleCount > 0 ? ` · ${staleCount} 待同步` : ''}`),
2743
+ h('span', { class: 'spacer' }),
2744
+ staleCount > 0
2745
+ ? button('全部同步', {
2746
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-02',
2747
+ title: '把所有待同步元主重放到新母体:只重建底层,用户插件配置与设置保持不变',
2748
+ onClick: () => void app.syncEssences(),
2749
+ })
2750
+ : null,
2751
+ button('导入', {
2752
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-11',
2753
+ title: '导入元主整包(自己或他人下载的 JSON):生成新元主文件夹并重算,可直接继续开发',
2754
+ onClick: () => void app.essenceImport(),
2755
+ }),
2756
+ button('从母体生成元主', {
2757
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-01',
2758
+ title: '克隆母体 profile 的可写层(插件补丁/依赖/设置)生成新元主;不复制凭据与会话',
2759
+ onClick: () => void app.captureEssence(),
2760
+ }))
2761
+ const essenceList = h('div', { class: 'essence-list', 'data-zone': 'essence-list', style: { display: 'flex', flexWrap: 'wrap', gap: '8px', padding: '4px 8px' } },
2762
+ essences.length === 0
2763
+ ? h('span', { class: 'hint' }, '还没有自定义元主;点上方「从母体生成元主」克隆当前母体配置。')
2764
+ : null,
2765
+ ...essences.map((essence) => h('div', { class: 'essence-row', 'data-essence-id': essence.id, style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
2766
+ essence.locked
2767
+ ? h('span', { class: 'hint' }, essence.name || essence.id)
2768
+ : editableText(S, app, { key: 'essence:' + essence.id, label: '元主', value: essence.name || essence.id }),
2769
+ essence.id === defaultEssenceId ? h('span', { class: 'chip' }, '默认') : null,
2770
+ essence.locked ? h('span', { class: 'chip' }, '锁定') : null,
2771
+ essence.stale ? h('span', { class: 'chip', title: '母体镜像已变化,此元主仍在旧镜像上' }, '🔼 待同步') : null,
2772
+ essence.stale && essence.locked !== true
2773
+ ? button('同步', {
2774
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-03',
2775
+ title: '重放该元主的插件/设置到新母体(配置不变)',
2776
+ onClick: () => void app.syncEssence(essence.id),
2777
+ })
2778
+ : null,
2779
+ essence.status === 'conflicted' ? h('span', { class: 'chip' }, '冲突') : null,
2780
+ essence.archived === true ? h('span', { class: 'chip', title: '已归档(冻结):只能还原或删除' }, '冻结') : null,
2781
+ h('span', { style: { display: 'inline-flex', gap: 4 } },
2782
+ essence.archived === true ? null : button('派生', {
2783
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-05',
2784
+ title: '派生:以该元主为模板创建分身(继承其插件&配置),可复制一个现有会话进分身沙箱',
2785
+ onClick: () => void app.deriveFromEssence(essence),
2786
+ }),
2787
+ essence.archived === true
2788
+ ? button('还原', {
2789
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-15',
2790
+ title: '解冻(恢复活跃态,可打开/设置/派生);不还原备份内容',
2791
+ onClick: () => void app.unfreezeEssence(essence),
2792
+ })
2793
+ : button(essence.runtime?.running === true ? '停止' : '打开', {
2794
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-06',
2795
+ title: essence.runtime?.running === true
2796
+ ? '停止该元主的运行实例(端口释放;会话/沙盒文件保留)'
2797
+ : '打开&设置:启动或打开该元主的隔离配置态实例(不写母体 sessions)',
2798
+ onClick: () => essence.runtime?.running === true ? void app.stopEssenceRuntime(essence) : void app.openEssence(essence.id),
2799
+ }),
2800
+ essence.runtime?.running === true && essence.archived !== true ? button('进入', {
2801
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-21',
2802
+ title: '在新标签打开运行中的实例(临时 token,不落盘)',
2803
+ onClick: () => void app.openEssence(essence.id),
2804
+ }) : null,
2805
+ essence.archived === true ? null : button('复制', {
2806
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-07',
2807
+ title: essence.actions?.copy?.reason || '深复制整份沙盒到新文件夹(不含凭据/运行态/备份)',
2808
+ disabled: essence.actions?.copy?.enabled === false,
2809
+ onClick: () => void app.copyEssence(essence),
2810
+ }),
2811
+ essence.archived === true ? null : button('归档', {
2812
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-08',
2813
+ title: essence.actions?.archive?.reason || '归档元主(冻结,只改元数据)',
2814
+ disabled: essence.actions?.archive?.enabled === false,
2815
+ onClick: () => void app.archiveEssence(essence),
2816
+ }),
2817
+ button('删除', {
2818
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-09',
2819
+ title: essence.actions?.delete?.reason || '永久删除 essences/<id>(须先归档;不删会话)',
2820
+ disabled: essence.actions?.delete?.enabled === false,
2821
+ onClick: () => void app.deleteEssence(essence),
2822
+ }),
2823
+ essence.archived === true ? null : button('备份', {
2824
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-12',
2825
+ title: '在 essences/<id>/Backup 存档(只保留一份,旧备份覆盖)',
2826
+ onClick: () => void app.essenceBackup(essence),
2827
+ }),
2828
+ essence.archived === true ? null : button('还原备份', {
2829
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-13',
2830
+ title: '用最新 Backup 覆盖当前 overlay/merged(需二次确认)',
2831
+ onClick: () => void app.essenceRestore(essence),
2832
+ }),
2833
+ essence.archived === true ? null : button('下载', {
2834
+ size: 'sm', variant: 'ghost', dataBtnId: 'E-10',
2835
+ title: essence.actions?.download?.reason || '下载元主整包 JSON(不含凭据)',
2836
+ disabled: essence.actions?.download?.enabled === false,
2837
+ onClick: () => void app.downloadEssence(essence),
2838
+ })))))
2069
2839
 
2070
2840
  return h('section', { class: 'panel', 'data-zone': 'mother', 'data-freshness': freshness, 'aria-labelledby': 'fang-mother-title' },
2071
2841
  head,
2072
2842
  h('div', { class: 'mother-slots' }, renderSlotStrip(projectCapacity(S.status.data, S.tasks.items))),
2843
+ essenceHead,
2073
2844
  essenceList,
2074
2845
  scroll)
2075
2846
  }
@@ -2346,7 +3117,8 @@ window.__ModuleLoader__.load({
2346
3117
  h('div', { class: 'fork-chips' },
2347
3118
  chip(health.tone, health.label, { state: health.phase, danger: health.tone === 'bad' && health.anomaly }),
2348
3119
  archived ? null : chip(health.adapterTone, health.adapterLabel, { health: health.adapter }),
2349
- task.importedSession ? chip('info', '已导入会话', { title: '派生时导入了母体会话历史/摘要' }) : null)),
3120
+ task.importedSession ? chip('info', '已导入会话', { title: '派生时导入了母体会话历史/摘要' }) : null,
3121
+ task.essenceDeleted ? chip('warn', '原身已删除(仅运行/归档)', { title: '来源原身已删除:不能再从该原身派生,但本分身可继续运行/归档/还原/删除' }) : null)),
2350
3122
  h('div', { class: 'fork-actions' },
2351
3123
  archived
2352
3124
  ? [button('还原', {
@@ -2365,8 +3137,13 @@ window.__ModuleLoader__.load({
2365
3137
  onClick: () => void app.openTask(task),
2366
3138
  fk: 'open:' + taskId,
2367
3139
  }),
2368
- textAction('提升插件', {
2369
- title: '把分身里验证过的插件目录提升到母体(需目录名)', dataBtnId: 'C-02',
3140
+ button('分支', {
3141
+ size: 'sm', variant: 'ghost', dataBtnId: 'C-06',
3142
+ title: '物理分支:在分身内 fork 当前会话,挂回同一分身(可多分支、可激活)',
3143
+ onClick: () => void app.openBranches(task),
3144
+ fk: 'branches:' + taskId,
3145
+ }),
3146
+ textAction('提升插件', { title: '把分身里验证过的插件目录提升到母体(需目录名)', dataBtnId: 'C-02',
2370
3147
  softDisabled: busyPromote, busy: busyPromote,
2371
3148
  onClick: () => app.promoteTask(task),
2372
3149
  }),
@@ -2490,6 +3267,8 @@ window.__ModuleLoader__.load({
2490
3267
  kv('官方最新', data.officialLatest == null ? '未配置官方源' : String(data.officialLatest)),
2491
3268
  kv('上次备份', meta.lastBackupAt ? fmtClock(meta.lastBackupAt) : '从未'),
2492
3269
  kv('下次备份', meta.nextBackupAt ? fmtClock(meta.nextBackupAt) : '未安排'),
3270
+ kv('上次同步', data.sync?.lastSyncAt ? fmtClock(data.sync.lastSyncAt) : '从未'),
3271
+ kv('自动同步', (() => { const v = String(data.preferences?.syncIntervalHours ?? 'off'); return v === 'off' ? '关闭' : `${v} 小时` })()),
2493
3272
  kv('磁盘占用', fmtBytes(Number(data.diskUsageBytes) || 0)),
2494
3273
  kv('自动备份', `${Number(meta.backupIntervalHours) || 24} 小时`)))
2495
3274
 
@@ -2511,6 +3290,22 @@ window.__ModuleLoader__.load({
2511
3290
  app.render(true)
2512
3291
  },
2513
3292
  }),
3293
+ button('克隆母体', {
3294
+ size: 'sm', variant: 'quiet', dataBtnId: 'M-07',
3295
+ title: '把本机母体 profile(package.json / cordis.patch.yml / settings)克隆到镜像 active/profile,先自动备份',
3296
+ onClick: () => void app.mirrorAction('clone', async () => (await api('/fang/api/mirror/clone-profile', { method: 'POST', body: '{}' })).body),
3297
+ }),
3298
+ button('空白母体', {
3299
+ size: 'sm', variant: 'quiet', dataBtnId: 'M-08',
3300
+ title: '重置为初始盘(清空 active/profile);会先自动备份,需重新克隆或升级',
3301
+ onClick: () => {
3302
+ S.modal.pending = {
3303
+ text: '把镜像重置为空白母体(初始盘)?会先自动备份;之后需要重新克隆或升级才能恢复基础配置。',
3304
+ run: () => app.mirrorAction('blank', async () => (await api('/fang/api/mirror/blank', { method: 'POST', body: '{}' })).body),
3305
+ }
3306
+ app.render(true)
3307
+ },
3308
+ }),
2514
3309
  button('打开母体门户', {
2515
3310
  size: 'sm', variant: 'quiet', icon: icon('globe', 13),
2516
3311
  title: '在新窗口打开 /fang/panel 独立门户(桌面壳使用真实 HTTP 源)',
@@ -2524,6 +3319,13 @@ window.__ModuleLoader__.load({
2524
3319
  onClick: () => void app.mirrorAction('interval:' + hours, async () => (await api('/fang/api/mirror/backup-interval', { method: 'POST', body: JSON.stringify({ hours }) })).body),
2525
3320
  })))))
2526
3321
 
3322
+ section.append(h('div', { class: 'glass-section-title', style: { marginTop: '4px' } }, '母体自动同步',
3323
+ ...(['off', '6', '12', '24'].map((value) => button(value === 'off' ? '关闭' : value + 'h', {
3324
+ size: 'sm', variant: String(data.preferences?.syncIntervalHours ?? 'off') === value ? 'config' : 'quiet',
3325
+ title: value === 'off' ? '关闭自动同步' : `每 ${value} 小时从本机母体 profile 同步到镜像(同步前自动备份)`,
3326
+ onClick: () => void app.mirrorAction('sync:' + value, async () => (await api('/fang/api/mirror/preferences/set', { method: 'POST', body: JSON.stringify({ syncIntervalHours: value }) })).body),
3327
+ })))))
3328
+
2527
3329
  if (pending) {
2528
3330
  section.append(h('div', { class: 'notice notice--warn', role: 'alertdialog', 'aria-label': '确认操作' },
2529
3331
  h('div', { class: 'notice-main' }, h('div', { class: 'notice-text' }, pending.text)),
@@ -2617,6 +3419,78 @@ window.__ModuleLoader__.load({
2617
3419
  return section
2618
3420
  }
2619
3421
 
3422
+ // 元主详情页(设置 / 插件 / 运行日志)
3423
+ function renderEssenceModal(S, app) {
3424
+ const modal = S.modal
3425
+ const detail = modal.detail
3426
+ const meta = detail?.meta ?? null
3427
+ const tabs = [['settings', '设置'], ['plugins', '插件'], ['logs', '运行日志']]
3428
+ const body = h('div', { class: 'glass-body' })
3429
+ if (modal.loading) {
3430
+ body.append(h('div', { class: 'loading-line' }, icon('spinner', 14), '读取元主详情…'))
3431
+ } else if (modal.error) {
3432
+ body.append(h('div', { class: 'notice notice--warn' }, h('div', { class: 'notice-main' },
3433
+ h('div', { class: 'notice-title' }, icon('alert', 14), '读取失败'),
3434
+ h('div', { class: 'notice-text' }, failureHint(modal.error) + ' · ' + modal.error))))
3435
+ } else if (detail) {
3436
+ if (modal.tab === 'settings') {
3437
+ const rows = [
3438
+ ['状态', String(meta.status ?? 'unknown')],
3439
+ ['等级', String(meta.tier ?? '—')],
3440
+ ['插件条目', String(detail.overlay?.patchEntries?.length ?? 0)],
3441
+ ['设置项', (detail.overlay?.settings || []).join(', ') || '—'],
3442
+ ['备份', detail.backup ? '有(Backup/,只保留一份)' : '无'],
3443
+ ['进行中会话', `${detail.sessions?.used ?? 0} / ${detail.sessions?.limit ?? 10}${detail.sessions?.over ? '(已满,归档后再开)' : ''}`],
3444
+ ['运行态', detail.runtime?.running ? `运行中 · :${detail.runtime.port ?? '—'} · pid ${detail.runtime.pid ?? '—'}` : '未运行'],
3445
+ ['镜像指纹', String(meta.lastMergedFingerprint ?? '—').slice(0, 16)],
3446
+ ['归档', meta.archived === true ? '已冻结(只能删除)' : '活跃'],
3447
+ ]
3448
+ body.append(h('div', { style: { display: 'grid', gap: 6, padding: '6px 2px' } },
3449
+ ...rows.map(([key, value]) => h('div', { style: { display: 'flex', gap: 12 } },
3450
+ h('span', { style: { width: 88, opacity: .65 } }, key),
3451
+ h('span', null, value)))))
3452
+ } else if (modal.tab === 'plugins') {
3453
+ const entries = detail.overlay?.patchEntries || []
3454
+ body.append(entries.length
3455
+ ? h('div', null, ...entries.map((entry) => h('div', {
3456
+ style: { display: 'flex', gap: 8, alignItems: 'center', padding: '5px 0', borderBottom: '1px solid rgba(127,127,127,.15)' },
3457
+ },
3458
+ h('b', { style: { fontFamily: 'var(--f-mono)' } }, entry.id),
3459
+ h('span', { class: 'hint' }, entry.name || ''),
3460
+ entry.disabled ? h('span', { class: 'chip' }, '禁用') : null)))
3461
+ : h('div', { class: 'hint' }, '该元主还没有插件补丁条目;在「打开」起的实例里安装插件后再同步。'))
3462
+ } else {
3463
+ body.append(h('pre', {
3464
+ style: { maxHeight: '46vh', overflow: 'auto', fontSize: 11, lineHeight: 1.5, whiteSpace: 'pre-wrap', margin: 0 },
3465
+ }, detail.logs || '(暂无运行日志;先点「打开」启动该元主的隔离实例)'))
3466
+ }
3467
+ }
3468
+ const tabBar = h('div', { class: 'panel-tools', style: { borderTop: 'none' } },
3469
+ ...tabs.map(([id, label]) => button(label, {
3470
+ size: 'sm', variant: modal.tab === id ? 'primary' : 'ghost',
3471
+ onClick: () => { if (!S.modal || S.modal.kind !== 'essence') return; S.modal.tab = id; render(true) },
3472
+ })))
3473
+ const closeBtn = button('关闭', { size: 'sm', variant: 'quiet', onClick: () => app.closeModal() })
3474
+ const id = modal.essenceId
3475
+ return h('div', {
3476
+ class: 'overlay', 'data-overlay': '1',
3477
+ onClick: (event) => { if (event.target === event.currentTarget) app.closeModal() },
3478
+ },
3479
+ h('div', { class: 'glass', role: 'dialog', 'aria-modal': 'true', style: { width: 'min(880px, 94vw)' } },
3480
+ h('div', { class: 'glass-head' },
3481
+ h('div', { class: 'glass-head-main' },
3482
+ h('div', { class: 'glass-title', id: 'fang-essence-title' }, icon('gate', 16), meta?.name || id),
3483
+ h('div', { class: 'glass-sub' }, `${id} · ${meta?.archived === true ? '冻结' : '活跃'}${meta?.locked === true ? ' · 官方锁定' : ''}`)),
3484
+ closeBtn),
3485
+ tabBar,
3486
+ body,
3487
+ h('div', { class: 'glass-foot' },
3488
+ button('打开', { size: 'sm', variant: 'ghost', onClick: () => { app.closeModal(); void app.openEssence(id) } }),
3489
+ button('同步', { size: 'sm', variant: 'ghost', onClick: () => { app.closeModal(); void app.syncEssence(id) } }),
3490
+ button('备份', { size: 'sm', variant: 'ghost', onClick: () => { const name = S.modal?.detail?.meta?.name; app.closeModal(); void app.essenceBackup({ id, name }) } }),
3491
+ button('下载', { size: 'sm', variant: 'ghost', onClick: () => { const name = S.modal?.detail?.meta?.name; app.closeModal(); void app.downloadEssence({ id, name }) } }))))
3492
+ }
3493
+
2620
3494
  function renderMotherModal(S, app) {
2621
3495
  const data = S.status.data
2622
3496
  const mirror = S.mirror.data
@@ -2668,10 +3542,17 @@ window.__ModuleLoader__.load({
2668
3542
  function renderConfirmModal(S, app) {
2669
3543
  const modal = S.modal
2670
3544
  const expected = String(modal.expected || '')
2671
- const matches = !modal.strong || String(modal.typed || '').trim() === expected
2672
- const level = modal.strong ? 'strong' : 'once'
2673
3545
  const inputId = 'fang-confirm-input'
2674
3546
  const reasonId = 'fang-confirm-reason'
3547
+ // 输入框是就地改 DOM 的,点击时必须以输入框当前值为准,
3548
+ // 否则首次渲染算出的 matches=false 会把「已输入正确名称」的点击吞掉。
3549
+ const inputValue = () => {
3550
+ if (!modal.strong) return ''
3551
+ const node = app.view.querySelector('#' + inputId)
3552
+ return String(node?.value ?? modal.typed ?? '').trim()
3553
+ }
3554
+ const confirmed = () => !modal.strong || inputValue() === expected
3555
+ const level = modal.strong ? 'strong' : 'once'
2675
3556
  return h('div', { class: 'overlay', 'data-overlay': '1', onClick: (event) => { if (event.target === event.currentTarget) app.closeModal() } },
2676
3557
  h('div', {
2677
3558
  class: 'glass glass--sm', role: 'alertdialog', 'aria-modal': 'true',
@@ -2722,10 +3603,15 @@ window.__ModuleLoader__.load({
2722
3603
  }),
2723
3604
  button(modal.confirmLabel || '确认', {
2724
3605
  size: 'sm', variant: modal.tone === 'info' ? 'info' : 'danger', fk: 'confirm-ok',
2725
- disabled: !matches,
3606
+ disabled: modal.strong,
2726
3607
  describedBy: modal.strong ? reasonId : undefined,
2727
3608
  onClick: () => {
2728
- if (!matches) return
3609
+ if (!confirmed()) {
3610
+ // 名称还没对上:把焦点送回输入框,别让点击静默丢失。
3611
+ const node = app.view.querySelector('#' + inputId)
3612
+ if (node) node.focus({ preventScroll: true })
3613
+ return
3614
+ }
2729
3615
  const run = modal.onConfirm
2730
3616
  app.closeModal()
2731
3617
  void run()
@@ -2736,6 +3622,48 @@ window.__ModuleLoader__.load({
2736
3622
  : null))
2737
3623
  }
2738
3624
 
3625
+ function renderBranchModal(S, app) {
3626
+ const modal = S.modal
3627
+ const branches = Array.isArray(modal.branches) ? modal.branches : []
3628
+ return h('div', { class: 'overlay', 'data-overlay': '1', onClick: (event) => { if (event.target === event.currentTarget) app.closeModal() } },
3629
+ h('div', { class: 'glass', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'fang-branch-title' },
3630
+ h('div', { class: 'glass-head' },
3631
+ h('div', { class: 'glass-head-main' },
3632
+ h('div', { class: 'glass-title', id: 'fang-branch-title' }, '分支 · ' + (modal.taskTitle || '')),
3633
+ h('div', { class: 'glass-sub' }, '会话 ' + (modal.sessionId || '—') + ' · 当前分支 ' + (modal.activeBranchId || '—'))),
3634
+ button('', { variant: 'quiet', size: 'sm', iconOnly: true, icon: icon('close', 15), ariaLabel: '关闭', onClick: () => app.closeModal() })),
3635
+ h('div', { class: 'glass-body' },
3636
+ modal.error ? h('div', { class: 'hint', style: { color: 'var(--f-red)' }, role: 'alert' }, modal.error) : null,
3637
+ h('div', { style: { display: 'flex', gap: 8, margin: '4px 0 12px' } },
3638
+ button('派生分支', { size: 'sm', variant: 'primary', dataBtnId: 'B-01', onClick: () => void app.forkBranch({ taskId: modal.taskId, title: modal.taskTitle }) }),
3639
+ button('刷新', { size: 'sm', variant: 'ghost', onClick: () => void app.openBranches({ taskId: modal.taskId, title: modal.taskTitle }) })),
3640
+ branches.length === 0
3641
+ ? h('p', { class: 'glass-sub' }, '还没有分支。派生分支会在分身内 fork 当前会话(物理分支,子会话挂回同一分身)。')
3642
+ : h('div', { style: { display: 'grid', gap: 6 } },
3643
+ 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 } },
3644
+ h('span', null,
3645
+ String(branch.branchId) + ' · ' + String(branch.status ?? '')
3646
+ + (branch.sessionId ? ' · ' + short(String(branch.sessionId), 8) : '')
3647
+ + (branch.branchId === modal.activeBranchId ? ' · 当前' : '')),
3648
+ branch.branchId !== modal.activeBranchId && branch.status === 'active'
3649
+ ? button('激活', { size: 'sm', variant: 'ghost', onClick: () => void app.activateBranch({ taskId: modal.taskId, title: modal.taskTitle }, branch.branchId) })
3650
+ : null,
3651
+ button('打开分身', {
3652
+ size: 'sm', variant: 'ghost', title: '打开分身 Web UI(DSH 暂不支持会话深链,子会话在左侧会话列表中)',
3653
+ onClick: () => void app.openTask({ taskId: modal.taskId, title: modal.taskTitle }),
3654
+ }),
3655
+ branch.sessionId ? button('复制会话 ID', {
3656
+ size: 'sm', variant: 'ghost', title: branch.sessionId,
3657
+ onClick: () => {
3658
+ const text = String(branch.sessionId || '')
3659
+ const done = () => setNotice({ tone: 'ok', title: '已复制会话 ID', message: short(text, 12) })
3660
+ try { void navigator.clipboard.writeText(text).then(done, done) } catch { done() }
3661
+ },
3662
+ }) : null)))),
3663
+ h('div', { class: 'glass-foot' },
3664
+ button('关闭', { size: 'sm', variant: 'ghost', onClick: () => app.closeModal() }))))
3665
+ }
3666
+
2739
3667
  function renderPromptModal(S, app) {
2740
3668
  const modal = S.modal
2741
3669
  const submit = () => {
@@ -2813,9 +3741,63 @@ window.__ModuleLoader__.load({
2813
3741
  for (const node of renderNotices(S, app)) frag.append(node)
2814
3742
 
2815
3743
  if (S.role.value === 'mother') {
2816
- frag.append(h('div', { class: 'fang-body', 'aria-busy': S.refreshing ? 'true' : undefined },
2817
- renderMotherPanel(S, app),
2818
- renderForkPanel(S, app)))
3744
+ const body = h('div', { class: 'fang-body', 'aria-busy': S.refreshing ? 'true' : undefined })
3745
+ body.append(renderMotherPanel(S, app), renderForkPanel(S, app))
3746
+ // 中间拖动手柄:默认 50:50,可拖动/键盘方向键调整,双击恢复 50:50(偏好存本机)。
3747
+ const handle = h('div', {
3748
+ class: 'fang-split-handle',
3749
+ role: 'separator',
3750
+ 'aria-orientation': 'vertical',
3751
+ 'aria-label': '调整元宝工作区与分身工作区比例',
3752
+ 'aria-valuemin': '25',
3753
+ 'aria-valuemax': '75',
3754
+ tabindex: '0',
3755
+ title: '拖动调整比例;双击恢复 50:50',
3756
+ })
3757
+ const applyRatio = (ratio, persist = false) => {
3758
+ const clamped = Math.min(0.75, Math.max(0.25, Number.isFinite(ratio) ? ratio : 0.5))
3759
+ S.splitRatio = clamped
3760
+ const left = (clamped * 100).toFixed(2)
3761
+ const right = ((1 - clamped) * 100).toFixed(2)
3762
+ // fr 会先扣除 gap 再按比例分配,避免 50% + gap 溢出。
3763
+ body.style.gridTemplateColumns = `minmax(320px, ${left}fr) minmax(0, ${right}fr)`
3764
+ handle.style.left = left + '%'
3765
+ handle.setAttribute('aria-valuenow', String(Math.round(clamped * 100)))
3766
+ if (persist) writeNumberPref('fang.panel.split', clamped)
3767
+ }
3768
+ applyRatio(S.splitRatio)
3769
+ const onMove = (event) => {
3770
+ const x = event.touches ? event.touches[0]?.clientX : event.clientX
3771
+ if (typeof x !== 'number') return
3772
+ const rect = body.getBoundingClientRect()
3773
+ if (rect.width > 0) applyRatio((x - rect.left) / rect.width)
3774
+ }
3775
+ const stop = () => {
3776
+ body.classList.remove('is-resizing')
3777
+ document.removeEventListener('mousemove', onMove)
3778
+ document.removeEventListener('touchmove', onMove)
3779
+ document.removeEventListener('mouseup', stop)
3780
+ document.removeEventListener('touchend', stop)
3781
+ writeNumberPref('fang.panel.split', S.splitRatio)
3782
+ }
3783
+ const start = (event) => {
3784
+ event.preventDefault()
3785
+ body.classList.add('is-resizing')
3786
+ document.addEventListener('mousemove', onMove)
3787
+ document.addEventListener('touchmove', onMove, { passive: false })
3788
+ document.addEventListener('mouseup', stop, { once: true })
3789
+ document.addEventListener('touchend', stop, { once: true })
3790
+ }
3791
+ handle.addEventListener('mousedown', start)
3792
+ handle.addEventListener('touchstart', start, { passive: false })
3793
+ handle.addEventListener('dblclick', () => applyRatio(0.5, true))
3794
+ handle.addEventListener('keydown', (event) => {
3795
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return
3796
+ event.preventDefault()
3797
+ applyRatio(S.splitRatio + (event.key === 'ArrowLeft' ? -0.02 : 0.02), true)
3798
+ })
3799
+ body.append(handle)
3800
+ frag.append(body)
2819
3801
  frag.append(renderFooter(S, app))
2820
3802
  } else if (S.role.value === 'fork') {
2821
3803
  frag.append(renderHostNotice(S, app))
@@ -2833,6 +3815,8 @@ window.__ModuleLoader__.load({
2833
3815
  }
2834
3816
  }
2835
3817
  if (S.modal.kind === 'mother') frag.append(renderMotherModal(S, app))
3818
+ else if (S.modal.kind === 'essence') frag.append(renderEssenceModal(S, app))
3819
+ else if (S.modal.kind === 'branches') frag.append(renderBranchModal(S, app))
2836
3820
  else if (S.modal.kind === 'confirm') frag.append(renderConfirmModal(S, app))
2837
3821
  else if (S.modal.kind === 'prompt') frag.append(renderPromptModal(S, app))
2838
3822
  }
@@ -2854,15 +3838,17 @@ window.__ModuleLoader__.load({
2854
3838
  return React.createElement('div', { ref, className: 'fang-mount', style: props.style || { display: 'block', minWidth: 0 } })
2855
3839
  }
2856
3840
 
2857
- function mountDiagnostics(app) {
2858
- const doc = document
3841
+ function mountDiagnostics(app, host) {
3842
+ const doc = host?.ownerDocument ?? document
3843
+ const parent = host ?? doc.body
3844
+ if (host) { host.style.position = host.style.position || 'relative' }
2859
3845
  const btn = doc.createElement('button')
2860
3846
  btn.id = 'fang-diag-btn'
2861
3847
  btn.setAttribute('data-btn-id', 'LOG-01')
2862
3848
  btn.type = 'button'
2863
3849
  btn.textContent = '日志'
2864
3850
  Object.assign(btn.style, {
2865
- position: 'fixed', right: '16px', bottom: '16px', zIndex: '9999',
3851
+ position: 'absolute', right: '16px', bottom: '16px', zIndex: '9999',
2866
3852
  height: '34px', padding: '0 12px', borderRadius: '10px',
2867
3853
  border: '1px solid rgba(127,127,127,.4)', background: '#fff', color: '#111',
2868
3854
  font: '600 13px/1 system-ui, sans-serif', cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,.18)',
@@ -2871,7 +3857,7 @@ window.__ModuleLoader__.load({
2871
3857
  overlay.id = 'fang-diag-panel'
2872
3858
  overlay.hidden = true
2873
3859
  Object.assign(overlay.style, {
2874
- position: 'fixed', right: '16px', bottom: '58px', zIndex: '9999',
3860
+ position: 'absolute', right: '16px', bottom: '58px', zIndex: '9999',
2875
3861
  width: 'min(520px, calc(100vw - 32px))', maxHeight: '60vh', overflow: 'auto',
2876
3862
  background: '#fff', color: '#111', border: '1px solid rgba(127,127,127,.35)',
2877
3863
  borderRadius: '12px', boxShadow: '0 12px 40px rgba(0,0,0,.25)', padding: '10px',
@@ -2945,7 +3931,7 @@ window.__ModuleLoader__.load({
2945
3931
  window.addEventListener('fang:diag', onDiag)
2946
3932
  window.addEventListener('error', onError)
2947
3933
  window.addEventListener('unhandledrejection', onRejection)
2948
- doc.body.append(btn, overlay)
3934
+ parent.append(btn, overlay)
2949
3935
  renderLogs()
2950
3936
  return () => {
2951
3937
  window.removeEventListener('fang:diag', onDiag)
@@ -2956,15 +3942,17 @@ window.__ModuleLoader__.load({
2956
3942
  }
2957
3943
  }
2958
3944
 
2959
- function mountConnectionInfo(app) {
2960
- const doc = document
3945
+ function mountConnectionInfo(app, host) {
3946
+ const doc = host?.ownerDocument ?? document
3947
+ const parent = host ?? doc.body
3948
+ if (host) { host.style.position = host.style.position || 'relative' }
2961
3949
  const trigger = doc.createElement('button')
2962
3950
  trigger.id = 'fang-conn-trigger'
2963
3951
  trigger.type = 'button'
2964
3952
  trigger.setAttribute('data-btn-id', 'CONN-00')
2965
3953
  trigger.textContent = '连接信息'
2966
3954
  Object.assign(trigger.style, {
2967
- position: 'fixed', left: '16px', bottom: '16px', zIndex: '9999',
3955
+ position: 'absolute', left: '16px', bottom: '16px', zIndex: '9999',
2968
3956
  height: '34px', padding: '0 12px', borderRadius: '10px',
2969
3957
  border: '1px solid rgba(127,127,127,.4)', background: '#fff', color: '#111',
2970
3958
  font: '600 13px/1 system-ui, sans-serif', cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,.18)',
@@ -2973,7 +3961,7 @@ window.__ModuleLoader__.load({
2973
3961
  popup.id = 'fang-conn-popup'
2974
3962
  popup.hidden = true
2975
3963
  Object.assign(popup.style, {
2976
- position: 'fixed', left: '16px', bottom: '58px', zIndex: '9999',
3964
+ position: 'absolute', left: '16px', bottom: '58px', zIndex: '9999',
2977
3965
  display: 'none', alignItems: 'center', gap: '6px', maxWidth: 'calc(100vw - 32px)',
2978
3966
  padding: '6px 8px', borderRadius: '10px', background: '#fff', color: '#111',
2979
3967
  border: '1px solid rgba(127,127,127,.35)', boxShadow: '0 4px 14px rgba(0,0,0,.14)',
@@ -2982,6 +3970,10 @@ window.__ModuleLoader__.load({
2982
3970
  const label = doc.createElement('span')
2983
3971
  label.id = 'fang-conn-url'
2984
3972
  label.style.cssText = 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:42vw'
3973
+ // Web 模式需要第二行显示安装 token;桌面模式保持原来的单行样子。
3974
+ const labelWrap = doc.createElement('div')
3975
+ labelWrap.style.cssText = 'display:flex;flex-direction:column;gap:2px;min-width:0'
3976
+ labelWrap.append(label)
2985
3977
  const eye = doc.createElement('button')
2986
3978
  eye.type = 'button'
2987
3979
  eye.setAttribute('data-btn-id', 'CONN-01')
@@ -2999,6 +3991,9 @@ window.__ModuleLoader__.load({
2999
3991
  }
3000
3992
  let full = ''
3001
3993
  let baseUrl = ''
3994
+ let tokenValue = ''
3995
+ let tokenLabel = null
3996
+ let copyToken = null
3002
3997
  let revealed = false
3003
3998
  let opened = false
3004
3999
  let loaded = false
@@ -3008,12 +4003,42 @@ window.__ModuleLoader__.load({
3008
4003
  return String(url).replace(/([?&]token=)[^&]*/, (_, prefix) => prefix + '•'.repeat(Math.min(16, token.length || 8)))
3009
4004
  } catch { return url }
3010
4005
  }
4006
+ // 桌面壳里 token 由主进程保管;纯 Web 里没有 fangShell,
4007
+ // 连接地址就是当前页面地址本身(同源打开,token 已在地址栏里)。
4008
+ const isDesktopShell = () => typeof window !== 'undefined' && typeof window.fangShell?.revealToken === 'function'
4009
+ const resolveFull = async () => {
4010
+ if (full) return full
4011
+ if (isDesktopShell()) {
4012
+ try {
4013
+ const info = await window.fangShell.revealToken()
4014
+ if (info?.token) { full = baseUrl + '/?token=' + encodeURIComponent(String(info.token)); return full }
4015
+ } catch { /* 主进程拒绝就退回页面地址 */ }
4016
+ }
4017
+ try {
4018
+ const result = await api('/fang/api/connection')
4019
+ const url = result?.body?.url
4020
+ if (typeof url === 'string' && url) { full = url; return full }
4021
+ } catch { /* 宿主没这个路由时继续兜底 */ }
4022
+ if (typeof location !== 'undefined' && location.href) full = String(location.href)
4023
+ return full
4024
+ }
4025
+ const maskedText = () => {
4026
+ if (full) return mask(full)
4027
+ if (baseUrl) return baseUrl + '/?token=••••••••'
4028
+ return '连接信息加载中…'
4029
+ }
3011
4030
  const render = () => {
3012
4031
  popup.hidden = !opened
3013
4032
  popup.style.display = opened ? 'flex' : 'none'
3014
- if (!opened) { label.textContent = ''; label.title = ''; return }
3015
- label.textContent = full && revealed ? full : (baseUrl ? baseUrl + '/?token=••••••••' : '连接信息加载中…')
4033
+ if (!opened) { label.textContent = ''; label.title = ''; if (tokenLabel) { tokenLabel.textContent = ''; tokenLabel.title = '' } return }
4034
+ label.textContent = full && revealed ? full : maskedText()
3016
4035
  label.title = revealed ? full : ''
4036
+ if (tokenLabel) {
4037
+ tokenLabel.textContent = tokenValue
4038
+ ? (revealed ? tokenValue : 'Token ' + '•'.repeat(Math.min(16, tokenValue.length)))
4039
+ : 'Token 未获取(宿主未就绪)'
4040
+ tokenLabel.title = revealed ? tokenValue : ''
4041
+ }
3017
4042
  eye.textContent = revealed ? '隐藏' : '显示'
3018
4043
  }
3019
4044
  const load = async () => {
@@ -3024,6 +4049,51 @@ window.__ModuleLoader__.load({
3024
4049
  if (info?.upstream) baseUrl = String(info.upstream).replace(/\/+$/, '')
3025
4050
  } catch { /* ignore */ }
3026
4051
  if (!baseUrl) baseUrl = String(location.origin || '')
4052
+ // 宿主侧 /fang/api/connection 给出带进程 token 的完整地址;
4053
+ // 拿不到就用当前页面地址兜底(同源,能用就能复制)。
4054
+ try {
4055
+ const result = await api('/fang/api/connection')
4056
+ const url = result?.body?.url
4057
+ if (typeof url === 'string' && url) full = url
4058
+ } catch { /* ignore */ }
4059
+ if (!isDesktopShell()) {
4060
+ // 纯 Web:宿主没有桌面壳桥,token 走同源的 /fang/api/auth-token。
4061
+ try {
4062
+ const result = await api('/fang/api/auth-token')
4063
+ const token = result?.body?.token
4064
+ if (typeof token === 'string' && token) tokenValue = token
4065
+ } catch { /* ignore */ }
4066
+ tokenLabel = doc.createElement('span')
4067
+ tokenLabel.id = 'fang-conn-token'
4068
+ tokenLabel.style.cssText = 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:42vw;color:#6E6E73'
4069
+ labelWrap.append(tokenLabel)
4070
+ copyToken = doc.createElement('button')
4071
+ copyToken.type = 'button'
4072
+ copyToken.setAttribute('data-btn-id', 'CONN-04')
4073
+ copyToken.textContent = '复制 Token'
4074
+ 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'
4075
+ copyToken.onclick = async () => {
4076
+ if (!tokenValue) { app.notify('warn', '还没拿到 Token:宿主可能未就绪'); return }
4077
+ const ok = await writeClipboard(tokenValue)
4078
+ app.notify(ok ? 'ok' : 'warn', ok ? '已复制 Token' : '复制失败:浏览器未授权剪贴板')
4079
+ }
4080
+ popup.insertBefore(copyToken, close)
4081
+ if (!full && typeof location !== 'undefined' && location.href) full = String(location.href)
4082
+ }
4083
+ }
4084
+ // 老 Electron / 无剪贴板权限时退回 execCommand。
4085
+ const writeClipboard = async (text) => {
4086
+ try { await navigator.clipboard.writeText(text); return true } catch { /* fall through */ }
4087
+ try {
4088
+ const area = doc.createElement('textarea')
4089
+ area.value = text
4090
+ area.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0'
4091
+ doc.body.appendChild(area)
4092
+ area.select()
4093
+ const ok = doc.execCommand('copy')
4094
+ area.remove()
4095
+ return Boolean(ok)
4096
+ } catch { return false }
3027
4097
  }
3028
4098
  trigger.onclick = async () => {
3029
4099
  opened = !opened
@@ -3033,25 +4103,35 @@ window.__ModuleLoader__.load({
3033
4103
  }
3034
4104
  eye.onclick = async () => {
3035
4105
  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 */ }
4106
+ const text = await resolveFull()
4107
+ if (!text) { app.notify('warn', '还没拿到连接地址:宿主可能未就绪'); return }
3040
4108
  }
3041
4109
  revealed = !revealed
3042
4110
  render()
3043
4111
  }
3044
4112
  copy.onclick = async () => {
3045
- try { await navigator.clipboard.writeText(full); app.notify('ok', '已复制连接地址') } catch { app.notify('warn', '复制失败:浏览器未授权剪贴板') }
4113
+ const text = await resolveFull()
4114
+ if (!text) { app.notify('warn', '还没拿到连接地址:宿主可能未就绪'); return }
4115
+ const ok = await writeClipboard(text)
4116
+ app.notify(ok ? 'ok' : 'warn', ok ? '已复制连接地址' : '复制失败:浏览器未授权剪贴板')
3046
4117
  }
3047
4118
  close.onclick = () => { opened = false; revealed = false; render() }
3048
- popup.append(label, eye, copy, close)
3049
- doc.body.append(trigger, popup)
4119
+ popup.append(labelWrap, eye, copy, close)
4120
+ parent.append(trigger, popup)
3050
4121
  render()
3051
4122
  return () => { trigger.remove(); popup.remove() }
3052
4123
  }
3053
4124
 
3054
4125
  function mountPanel(host) {
4126
+ // Electron: remember the real upstream origin so "打开母体 Web" does not
4127
+ // open the loopback proxy (which intentionally serves only /fang/api/*).
4128
+ try {
4129
+ window.fangShell?.desktopInfo?.().then((info) => {
4130
+ if (info && typeof info.upstream === 'string' && /^https?:\/\//i.test(info.upstream)) {
4131
+ window.__fangDesktopUpstream = info.upstream.replace(/\/+$/, '')
4132
+ }
4133
+ }).catch(() => {})
4134
+ } catch { /* web host: no shell bridge */ }
3055
4135
  // v3.0.7 UI 分析日志:记录面板挂载与所有按钮/链接点击,供自动冒烟/诊断读取
3056
4136
  try {
3057
4137
  const doc = host?.ownerDocument ?? document
@@ -3072,8 +4152,8 @@ window.__ModuleLoader__.load({
3072
4152
  window.__fangUiLog.push({ at: Date.now(), kind: 'panel-mount' })
3073
4153
  } catch { /* 宿主无 window 时忽略 */ }
3074
4154
  const app = createConsole(host)
3075
- const unmountDiagnostics = mountDiagnostics(app)
3076
- const unmountConnection = mountConnectionInfo(app)
4155
+ const unmountDiagnostics = mountDiagnostics(app, host)
4156
+ const unmountConnection = mountConnectionInfo(app, host)
3077
4157
  try { host.ownerDocument?.getElementById('fang-fallback')?.remove() } catch { /* ignore */ }
3078
4158
  return () => { unmountConnection(); unmountDiagnostics(); app.destroy() }
3079
4159
  }
@@ -3116,7 +4196,11 @@ window.__ModuleLoader__.load({
3116
4196
  const layout = ctx?.layout
3117
4197
  if (layout && typeof layout.selectPanel === 'function') { layout.selectPanel('fang'); return }
3118
4198
  } catch { /* fall through */ }
3119
- try { window.open('/fang/panel', '_blank', 'noopener') } catch { /* ignore */ }
4199
+ try {
4200
+ window.dispatchEvent(new CustomEvent('fang:notice', {
4201
+ detail: '瓮城面板未在当前视图打开;请从 DSH 左侧栏「瓮城」进入,或使用 PC 端。',
4202
+ }))
4203
+ } catch { /* ignore */ }
3120
4204
  }
3121
4205
  label.addEventListener('click', openPanel)
3122
4206
  label.addEventListener('dblclick', (event) => {
@@ -3189,12 +4273,310 @@ window.__ModuleLoader__.load({
3189
4273
  }
3190
4274
  }
3191
4275
 
4276
+ // ── 截图(内置客户端模块,不再作为独立子插件)──────────────────────────
4277
+ // 结果一律落在一个 body 级预览层里:看得见、能复制、说得清失败原因。
4278
+ // 面板未挂载时 fang:notice 没有监听者,所以失败提示不能只靠事件。
4279
+ const SHOT_NAME = () => `wengcheng-${Date.now()}.png`
4280
+ let shotOverlay = null
4281
+
4282
+ function closeShotOverlay() {
4283
+ if (!shotOverlay) return
4284
+ try { shotOverlay.off() } catch { /* ignore */ }
4285
+ try { shotOverlay.node.remove() } catch { /* ignore */ }
4286
+ try { URL.revokeObjectURL(shotOverlay.url) } catch { /* ignore */ }
4287
+ shotOverlay = null
4288
+ }
4289
+
4290
+ function showShotOverlay({ blob = null, message = '', hint = '', extraActions = [] } = {}) {
4291
+ closeShotOverlay()
4292
+ const doc = typeof document !== 'undefined' ? document : null
4293
+ if (!doc?.body) return
4294
+ const url = blob ? URL.createObjectURL(blob) : ''
4295
+ const status = h('div', {
4296
+ style: { fontSize: 13, lineHeight: 1.5, color: '#EFEFEF', whiteSpace: 'pre-wrap' },
4297
+ text: message,
4298
+ })
4299
+ const actions = h('div', { style: { display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' } })
4300
+ const mkBtn = (label, primary) => h('button', {
4301
+ type: 'button',
4302
+ style: {
4303
+ height: 30, padding: '0 12px', borderRadius: 8, cursor: 'pointer', fontSize: 12,
4304
+ border: primary ? '1px solid #17803D' : '1px solid rgba(255,255,255,.24)',
4305
+ background: primary ? '#17803D' : 'transparent', color: '#fff',
4306
+ },
4307
+ }, label)
4308
+ if (blob) {
4309
+ const copyBtn = mkBtn('复制到剪贴板', true)
4310
+ copyBtn.addEventListener('click', async () => {
4311
+ try {
4312
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
4313
+ copyBtn.textContent = '已复制 ✓'
4314
+ status.textContent = '已复制到剪贴板,在输入框里 Ctrl+V 即可粘贴图片。'
4315
+ } catch (error) {
4316
+ status.textContent = '复制失败:' + String(error?.message ?? error) + '\n可点「下载 PNG」,或右键预览图选「复制图片」。'
4317
+ }
4318
+ })
4319
+ const dlBtn = mkBtn('下载 PNG', false)
4320
+ dlBtn.addEventListener('click', () => {
4321
+ const link = h('a', { href: url, download: SHOT_NAME() })
4322
+ doc.body.appendChild(link)
4323
+ link.click()
4324
+ link.remove()
4325
+ status.textContent = '已下载 PNG,去浏览器的下载目录取文件。'
4326
+ })
4327
+ actions.append(copyBtn, dlBtn)
4328
+ }
4329
+ for (const extra of Array.isArray(extraActions) ? extraActions : []) {
4330
+ if (!extra || typeof extra.onClick !== 'function') continue
4331
+ const btn = mkBtn(String(extra.label ?? '操作'), extra.primary === true)
4332
+ btn.setAttribute('data-fang-shot-action', String(extra.label ?? 'action'))
4333
+ btn.addEventListener('click', () => { try { extra.onClick() } catch { /* ignore */ } })
4334
+ actions.append(btn)
4335
+ }
4336
+ const closeBtn = mkBtn('关闭', false)
4337
+ actions.append(closeBtn)
4338
+ const preview = blob ? h('img', {
4339
+ src: url,
4340
+ alt: '截图预览',
4341
+ style: { display: 'block', width: '100%', maxHeight: '58vh', objectFit: 'contain', borderRadius: 10, background: '#111', marginTop: 12 },
4342
+ }) : null
4343
+ const parts = [
4344
+ h('div', { style: { fontSize: 14, fontWeight: 600, color: '#fff', marginBottom: 8 } }, '瓮城截图'),
4345
+ status,
4346
+ ]
4347
+ if (preview) parts.push(preview)
4348
+ if (hint) parts.push(h('div', { style: { marginTop: 8, fontSize: 12, color: '#9A9AA0' }, text: hint }))
4349
+ parts.push(actions)
4350
+ const card = h('div', {
4351
+ role: 'dialog',
4352
+ 'aria-modal': 'true',
4353
+ 'aria-label': '瓮城截图',
4354
+ style: {
4355
+ width: 'min(760px, 92vw)', padding: 18, borderRadius: 14, background: '#1D1D1F',
4356
+ boxShadow: '0 24px 64px -12px rgba(0,0,0,.6)', pointerEvents: 'auto',
4357
+ },
4358
+ }, parts)
4359
+ const backdrop = h('div', {
4360
+ style: {
4361
+ position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
4362
+ alignItems: 'center', justifyContent: 'center', padding: 24,
4363
+ background: 'rgba(0,0,0,.55)', pointerEvents: 'auto',
4364
+ },
4365
+ }, card)
4366
+ backdrop.addEventListener('click', (event) => { if (event.target === backdrop) closeShotOverlay() })
4367
+ closeBtn.addEventListener('click', () => closeShotOverlay())
4368
+ const onKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); closeShotOverlay() } }
4369
+ doc.addEventListener('keydown', onKey, true)
4370
+ doc.body.appendChild(backdrop)
4371
+ shotOverlay = { node: backdrop, url, off: () => doc.removeEventListener('keydown', onKey, true) }
4372
+ }
4373
+
4374
+ // DSH 桌面端的渲染进程是 Electron:没有 setDisplayMediaRequestHandler 时
4375
+ // getDisplayMedia 会直接 reject,用户看到的就是「没有选择共享内容」。
4376
+ // 第一次 getDisplayMedia 被拒后记住:这个窗口没有共享选择器,之后直接走系统截图。
4377
+ let webCaptureBlocked = false
4378
+ const isEmbeddedDesktop = () => {
4379
+ try { return /Electron\//i.test(String(navigator?.userAgent ?? '')) } catch { return false }
4380
+ }
4381
+
4382
+ /** 调 Windows「屏幕截图」URI(与 Win+Shift+S 同一入口);被拦截时返回 false。 */
4383
+ function requestSystemSnip() {
4384
+ try {
4385
+ const link = h('a', { href: 'ms-screenclip:', rel: 'noopener', style: { display: 'none' } })
4386
+ document.body.appendChild(link)
4387
+ link.click()
4388
+ link.remove()
4389
+ return true
4390
+ } catch { return false }
4391
+ }
4392
+
4393
+ async function readClipboardImage() {
4394
+ try {
4395
+ if (!navigator.clipboard?.read) return { ok: false, error: '当前环境不支持读取剪贴板图片' }
4396
+ const items = await navigator.clipboard.read()
4397
+ for (const item of items) {
4398
+ const type = (item.types || []).find((candidate) => String(candidate).startsWith('image/'))
4399
+ if (type) return { ok: true, blob: await item.getType(type) }
4400
+ }
4401
+ return { ok: false, error: '剪贴板里还没有图片(先按 Win+Shift+S 截图)' }
4402
+ } catch (error) {
4403
+ return { ok: false, error: String(error?.message ?? error) }
4404
+ }
4405
+ }
4406
+
4407
+ async function readClipboardIntoOverlay() {
4408
+ const result = await readClipboardImage()
4409
+ if (!result.ok) {
4410
+ showShotOverlay({
4411
+ message: '读取剪贴板失败:' + result.error,
4412
+ hint: '先按 Win+Shift+S 拖选区域截图,再回来点「读取剪贴板」;也可以直接 Ctrl+V 粘贴。',
4413
+ })
4414
+ return
4415
+ }
4416
+ showShotOverlay({
4417
+ blob: result.blob,
4418
+ message: '已从剪贴板读到截图:直接 Ctrl+V 就能粘贴到输入框。',
4419
+ hint: '要换一张,再按一次 Win+Shift+S。',
4420
+ })
4421
+ }
4422
+
4423
+ function showSnipGuidance(reason) {
4424
+ showShotOverlay({
4425
+ message: reason || '这个窗口不提供网页屏幕共享选择器,浏览器抓屏不可用。',
4426
+ hint: '按 Win+Shift+S 拖选区域,截图会直接进剪贴板,然后 Ctrl+V 粘贴;也可以点下面的按钮。',
4427
+ extraActions: [
4428
+ {
4429
+ label: '打开系统截图', primary: true,
4430
+ onClick: () => {
4431
+ const ok = requestSystemSnip()
4432
+ showShotOverlay({
4433
+ message: ok ? '已请求打开 Windows 截图:拖选区域后点「读取剪贴板」。' : '系统截图没有打开:请直接按 Win+Shift+S。',
4434
+ hint: ok ? '截完图直接 Ctrl+V 粘贴;或点「读取剪贴板」先预览。' : '',
4435
+ extraActions: [{ label: '读取剪贴板', primary: true, onClick: () => void readClipboardIntoOverlay() }],
4436
+ })
4437
+ },
4438
+ },
4439
+ { label: '读取剪贴板', onClick: () => void readClipboardIntoOverlay() },
4440
+ ],
4441
+ })
4442
+ }
4443
+
4444
+ async function captureScreenshot() {
4445
+ if (typeof window.fangShell?.captureScreen === 'function') {
4446
+ try {
4447
+ const result = await window.fangShell.captureScreen()
4448
+ if (result?.ok) notifyScreenshot('已截图并复制到剪贴板,可直接 Ctrl+V 粘贴')
4449
+ else showShotOverlay({ message: '桌面端没有拿到屏幕图像。', hint: '可改用 Win+Shift+S 截图后粘贴。' })
4450
+ return Boolean(result?.ok)
4451
+ } catch (error) {
4452
+ showShotOverlay({ message: '截图失败:' + String(error?.message ?? error) })
4453
+ return false
4454
+ }
4455
+ }
4456
+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getDisplayMedia) {
4457
+ showSnipGuidance('当前页面不支持网页截屏。')
4458
+ return false
4459
+ }
4460
+ // Electron 宿主不会弹共享选择器:先走系统截图(Ctrl+X ≈ Win+Shift+S),别再让用户看失败框。
4461
+ if (isEmbeddedDesktop() || webCaptureBlocked) {
4462
+ const requested = requestSystemSnip()
4463
+ showShotOverlay({
4464
+ message: requested
4465
+ ? '已请求 Windows 系统截图(等同 Win+Shift+S):拖选区域后,直接 Ctrl+V 粘贴。'
4466
+ : '这个窗口不能网页抓屏。请按 Win+Shift+S 截图。',
4467
+ hint: 'DSH 桌面端不提供屏幕共享选择器,所以浏览器抓屏会直接失败;系统截图走的是 Windows 自己的剪贴板。',
4468
+ extraActions: requested
4469
+ ? [{ label: '读取剪贴板', primary: true, onClick: () => void readClipboardIntoOverlay() }]
4470
+ : [{ label: '打开系统截图', primary: true, onClick: () => { requestSystemSnip() } }, { label: '读取剪贴板', onClick: () => void readClipboardIntoOverlay() }],
4471
+ })
4472
+ return requested
4473
+ }
4474
+ let stream = null
4475
+ try {
4476
+ // 浏览器会弹一次「选择要共享的内容」,选当前标签页/窗口/屏幕均可。
4477
+ stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false })
4478
+ const video = document.createElement('video')
4479
+ video.srcObject = stream
4480
+ video.muted = true
4481
+ await video.play()
4482
+ await new Promise((resolve) => { if (video.videoWidth) resolve(); else video.onloadedmetadata = resolve })
4483
+ const canvas = document.createElement('canvas')
4484
+ canvas.width = video.videoWidth
4485
+ canvas.height = video.videoHeight
4486
+ canvas.getContext('2d').drawImage(video, 0, 0)
4487
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
4488
+ if (!blob) throw new Error('截图内容为空')
4489
+ webCaptureBlocked = false
4490
+ let copied = false
4491
+ try {
4492
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
4493
+ copied = true
4494
+ } catch { /* 预览层里还有手动复制按钮 */ }
4495
+ showShotOverlay({
4496
+ blob,
4497
+ message: copied
4498
+ ? '已截图并复制到剪贴板,在输入框里 Ctrl+V 即可粘贴。'
4499
+ : '已截到图,但浏览器拒绝了自动写入剪贴板,请点下面的「复制到剪贴板」。',
4500
+ hint: copied ? '' : '也可以点「下载 PNG」,或右键预览图选「复制图片」。',
4501
+ })
4502
+ return true
4503
+ } catch (error) {
4504
+ const name = String(error?.name ?? '')
4505
+ if (name === 'NotAllowedError') {
4506
+ webCaptureBlocked = true
4507
+ showSnipGuidance('浏览器拒绝了屏幕捕获:这个窗口没有共享选择器。')
4508
+ } else if (name === 'AbortError') {
4509
+ showShotOverlay({
4510
+ message: '截图已取消(没有选择共享内容)。',
4511
+ hint: '再按一次 Ctrl+X 重试,或改用 Win+Shift+S 截图后 Ctrl+V 粘贴。',
4512
+ })
4513
+ } else {
4514
+ showShotOverlay({ message: '截图失败:' + String(error?.message ?? error), hint: '可以改用 Win+Shift+S 截图后 Ctrl+V 粘贴。' })
4515
+ }
4516
+ return false
4517
+ } finally {
4518
+ for (const track of stream?.getTracks?.() ?? []) { try { track.stop() } catch { /* ignore */ } }
4519
+ }
4520
+ }
4521
+
4522
+ function notifyScreenshot(message) {
4523
+ try { window.dispatchEvent(new CustomEvent('fang:notice', { detail: message })) } catch { /* ignore */ }
4524
+ }
4525
+
4526
+ function isScreenshotShortcut(event) {
4527
+ const key = String(event?.key || '').toLowerCase()
4528
+ if (key !== 'x' || !event.ctrlKey || event.altKey || event.metaKey) return false
4529
+ return true
4530
+ }
4531
+
4532
+ // 插槽返回的必须是 React 元素;直接返回 DOM 节点会让宿主判为异常而关掉该项。
4533
+ function ScreenshotDock() {
4534
+ return React.createElement(DomMount, {
4535
+ style: { display: 'inline-flex', alignItems: 'center' },
4536
+ mount: (host) => {
4537
+ const btn = h('button', {
4538
+ type: 'button',
4539
+ 'data-fang-entry': 'screenshot',
4540
+ title: '截图并复制到剪贴板:Ctrl+X(桌面端走 Windows 系统截图,浏览器走屏幕共享)',
4541
+ style: {
4542
+ height: 26, padding: '0 8px', borderRadius: 7, cursor: 'pointer',
4543
+ border: '1px solid rgba(127,127,127,.35)', background: 'transparent', color: 'inherit', fontSize: 12,
4544
+ },
4545
+ }, '截图 Ctrl+X')
4546
+ btn.addEventListener('click', () => { void captureScreenshot() })
4547
+ host.replaceChildren(btn)
4548
+ return () => { host.replaceChildren() }
4549
+ },
4550
+ })
4551
+ }
4552
+
3192
4553
  // ── 插件入口 ──────────────────────────────────────────────────────────
3193
4554
  return {
3194
4555
  mountPanel,
3195
4556
  inject: ['slots'],
3196
4557
  apply(ctx) {
3197
4558
  const disposers = []
4559
+ // 母体 Web = DSH 主会话视图;Web 端直接切回 conversation 面板。
4560
+ const goMother = () => {
4561
+ try {
4562
+ if (ctx?.layout && typeof ctx.layout.selectPanel === 'function') ctx.layout.selectPanel('conversation')
4563
+ } catch { /* fall back to panel notice */ }
4564
+ }
4565
+ window.addEventListener('fang:mother-portal', goMother)
4566
+ disposers.push(() => window.removeEventListener('fang:mother-portal', goMother))
4567
+ const onScreenshotKey = (event) => {
4568
+ if (!isScreenshotShortcut(event)) return
4569
+ event.preventDefault()
4570
+ event.stopPropagation()
4571
+ void captureScreenshot()
4572
+ }
4573
+ window.addEventListener('keydown', onScreenshotKey, true)
4574
+ disposers.push(() => window.removeEventListener('keydown', onScreenshotKey, true))
4575
+ disposers.push(ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
4576
+ name: 'conversation.composer.dock',
4577
+ id: 'fang-screenshot-inline',
4578
+ order: 91,
4579
+ }, ScreenshotDock)))
3198
4580
  // 左侧导航「瓮城」:图标组件即登记项组件(外壳只给 {size, active})
3199
4581
  disposers.push(ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
3200
4582
  name: 'sidebar.panellist',