@twinsearth/dsh-fang 3.8.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -3657,7 +3657,15 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
3657
3657
  else notify('bad', '解除 Safe Mode 失败', out.body?.error || '')
3658
3658
  }, fk: 'safe-mode-reset',
3659
3659
  })
3660
- : null,
3660
+ : button('释放全部内存', {
3661
+ variant: 'danger-quiet', size: 'sm',
3662
+ title: '全局 Panic:关闭所有托管浏览器 → 停所有分身 → 清 PID/token → 全部隔离 → Safe Mode',
3663
+ onClick: async () => {
3664
+ const out = await api('/fang/api/panic', { method: 'POST', body: '{}' })
3665
+ if (out.status === 200) { notify('warn', '已触发全局 Panic', '浏览器与分身已关闭;当前处于 Safe Mode。'); void refresh() }
3666
+ else notify('bad', 'Panic 失败', out.body?.error || '')
3667
+ }, fk: 'host-panic',
3668
+ }),
3661
3669
  restart?.available && restart.redLineAutoAllowed
3662
3670
  ? chip('warn', '红灯自动放行', {
3663
3671
  title: 'strictRedLine=false:auto 授权模式下红灯可被策略自动放行。这只到决策层;execution.executed 恒为 false,真正重启仍由外部 supervisor 的 armed 清单决定。',
@@ -4563,6 +4571,8 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
4563
4571
  chip(health.tone, health.label, { state: health.phase, danger: health.tone === 'bad' && health.anomaly }),
4564
4572
  archived ? null : chip(health.adapterTone, health.adapterLabel, { health: health.adapter }),
4565
4573
  task.importedSession ? chip('info', '已导入会话', { title: '派生时导入了母体会话历史/摘要' }) : null,
4574
+ task.quarantined ? chip('bad', '已隔离', { title: `通信已断开(${task.quarantined.reason || 'guard'});只有重启该分身或 DSH 母体才能恢复` }) : null,
4575
+ task.memoryGuard ? chip('warn', '内存保护关闭', { title: `关闭原因:${task.memoryGuard.reason || 'guard'};PID ${task.memoryGuard.pid ?? '—'};会话 home 保留,可重新打开` }) : null,
4566
4576
  task.sessions?.violation ? chip('warn', `会话 ${task.sessions.count}/${task.sessions.max} 超限`, { title: '分身会话超过上限;打开/修复不会再自动搬移,需手动归档或 enforce' }) : null,
4567
4577
  task.essenceDeleted ? chip('warn', '原身已删除(仅运行/归档)', { title: '来源原身已删除:不能再从该原身派生,但本分身可继续运行/归档/还原/删除' }) : null)),
4568
4578
  h('div', { class: 'fork-actions' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.8.0",
3
+ "version": "3.8.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "dsh-Fang (瓮城) — mother/fork plugin development environment for DeepSeek Harness: one readonly mother, a disposable child dsh-Web per task.",
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@twinsearth/dsh-fang-node-compat": "^0.1.0",
61
- "@twinsearth/fang-dsh-plugin": "3.8.0"
61
+ "@twinsearth/fang-dsh-plugin": "3.8.1"
62
62
  },
63
63
  "repository": {
64
64
  "type": "git",
@@ -131,7 +131,7 @@ export const AUDIT = {
131
131
  RUNTIME_ERROR: 'runtime-error',
132
132
  }
133
133
 
134
- export const FANG_VERSION = '3.8.0'
134
+ export const FANG_VERSION = '3.8.1'
135
135
 
136
136
  /**
137
137
  * @typedef {object} ForkInfo
@@ -3,7 +3,7 @@
3
3
  // Why: the default browser is outside Fang's process tree, so it cannot be
4
4
  // measured, force-closed, or crash-dumped. This module launches a dedicated
5
5
  // profile and exposes CDP metrics for the memory guard.
6
- import { spawn } from 'node:child_process'
6
+ import { spawn, execFile } from 'node:child_process'
7
7
  import fs from 'node:fs'
8
8
  import net from 'node:net'
9
9
  import path from 'node:path'
@@ -17,6 +17,18 @@ const CHROME_CANDIDATES = [
17
17
  'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
18
18
  ]
19
19
 
20
+ export async function lowerProcessPriority(pid) {
21
+ const value = Number(pid)
22
+ if (process.platform !== 'win32' || !Number.isInteger(value) || value <= 0) return { ok: false, error: 'unsupported' }
23
+ return new Promise((resolve) => {
24
+ try {
25
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-Process -Id ${value} -ErrorAction Stop).PriorityClass = 'BelowNormal'`], { windowsHide: true, timeout: 5000 }, (error) => {
26
+ resolve(error ? { ok: false, error: String(error.message ?? error) } : { ok: true })
27
+ })
28
+ } catch (error) { resolve({ ok: false, error: String(error?.message ?? error) }) }
29
+ })
30
+ }
31
+
20
32
  export function findBrowserPath(configured = '') {
21
33
  const explicit = String(configured || '').trim()
22
34
  if (explicit && fs.existsSync(explicit)) return explicit
@@ -93,18 +105,23 @@ export async function launchManagedBrowser({ exe, url, profileDir, logDir, port,
93
105
  try { await closeManagedBrowser({ pid, port }) } catch { /* ignore */ }
94
106
  return { ok: false, error: 'browser-cdp-timeout', pid }
95
107
  }
108
+ try { await lowerProcessPriority(pid) } catch { /* best effort */ }
96
109
  return { ok: true, pid, port, profileDir, logFile, crashDir, exe }
97
110
  }
98
111
 
99
- export async function closeManagedBrowser({ pid, port, timeoutMs = 3000 }) {
112
+ export async function closeManagedBrowser({ pid, port, graceMs = 3000, timeoutMs = 3000 }) {
100
113
  const value = Number(pid)
101
114
  if (Number.isInteger(value) && value > 0) {
102
- // Best-effort graceful close first; CDP Browser.close may be unavailable.
115
+ // 1) Ask the browser to close itself, giving the page a chance to flush.
116
+ let graceful = false
103
117
  if (port) {
104
- try {
105
- await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(800) })
106
- } catch { /* already gone */ }
118
+ try { graceful = await browserCloseCdp(port) } catch { graceful = false }
119
+ for (let i = 0; i < Math.ceil(Math.max(0, graceMs) / 100); i += 1) {
120
+ if (!isPidAlive(value)) return { ok: true, graceful: true }
121
+ await sleep(100)
122
+ }
107
123
  }
124
+ // 2) Force the whole tree only after the grace window.
108
125
  if (process.platform === 'win32') {
109
126
  try {
110
127
  await new Promise((resolve) => {
@@ -120,8 +137,9 @@ export async function closeManagedBrowser({ pid, port, timeoutMs = 3000 }) {
120
137
  if (!isPidAlive(value)) break
121
138
  await sleep(100)
122
139
  }
140
+ return { ok: !isPidAlive(value), graceful: false }
123
141
  }
124
- return { ok: !isPidAlive(value) }
142
+ return { ok: true, graceful: true }
125
143
  }
126
144
 
127
145
  async function cdpTargets(port) {
@@ -134,6 +152,10 @@ async function cdpTargets(port) {
134
152
  }
135
153
 
136
154
  function cdpEvaluate(wsUrl, expression, timeoutMs = 2500) {
155
+ return cdpCommand(wsUrl, 'Runtime.evaluate', { expression, returnByValue: true, awaitPromise: false }, timeoutMs).then((result) => result?.result?.value ?? null)
156
+ }
157
+
158
+ function cdpCommand(wsUrl, method, params = {}, timeoutMs = 2500) {
137
159
  return new Promise((resolve) => {
138
160
  let ws
139
161
  let timer
@@ -150,15 +172,13 @@ function cdpEvaluate(wsUrl, expression, timeoutMs = 2500) {
150
172
  }
151
173
  timer = setTimeout(() => done(null), timeoutMs)
152
174
  ws.addEventListener('open', () => {
153
- try {
154
- ws.send(JSON.stringify({ id: 1, method: 'Runtime.evaluate', params: { expression, returnByValue: true, awaitPromise: false } }))
155
- } catch { done(null) }
175
+ try { ws.send(JSON.stringify({ id: 1, method, params })) } catch { done(null) }
156
176
  })
157
177
  ws.addEventListener('message', (event) => {
158
178
  try {
159
179
  const message = JSON.parse(String(event.data))
160
180
  if (message.id !== 1) return
161
- done(message.result?.result?.value ?? null)
181
+ done(message.result ?? null)
162
182
  } catch { done(null) }
163
183
  })
164
184
  ws.addEventListener('error', () => done(null))
@@ -166,6 +186,18 @@ function cdpEvaluate(wsUrl, expression, timeoutMs = 2500) {
166
186
  })
167
187
  }
168
188
 
189
+ async function browserCloseCdp(port) {
190
+ try {
191
+ const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })
192
+ if (!response.ok) return false
193
+ const info = await response.json()
194
+ if (!info.webSocketDebuggerUrl) return false
195
+ await cdpCommand(info.webSocketDebuggerUrl, 'Browser.close', {}, 1500)
196
+ return true
197
+ } catch { return false }
198
+ }
199
+
200
+
169
201
  /** Read DOM/heap/visibility from the managed page. */
170
202
  /** Best-effort page flush before force-close; server-side session persistence is authoritative. */
171
203
  export async function flushManagedBrowser(port) {
@@ -184,12 +216,23 @@ export async function sampleManagedBrowser(port) {
184
216
  if (!targets.length) return { ok: false, error: 'browser-cdp-no-page' }
185
217
  const target = targets.find((item) => item.url?.startsWith('http://127.0.0.1:')) ?? targets[0]
186
218
  const value = await cdpEvaluate(target.webSocketDebuggerUrl, `(() => {
187
- const perf = performance;
188
- const heap = perf && perf.memory ? perf.memory.usedJSHeapSize : 0;
189
- const nodes = document.getElementsByTagName('*').length;
190
- const text = document.body && document.body.innerText ? document.body.innerText.length : 0;
191
- return { visibility: document.visibilityState, heapBytes: heap, nodes, textLength: text, url: location.href };
219
+ return { visibility: document.visibilityState, url: location.href };
192
220
  })()`)
193
221
  if (!value || typeof value !== 'object') return { ok: false, error: 'browser-cdp-evaluate-failed' }
194
- return { ok: true, ...value }
222
+ const perf = await cdpCommand(target.webSocketDebuggerUrl, 'Performance.getMetrics', {}, 2000)
223
+ const dom = await cdpCommand(target.webSocketDebuggerUrl, 'Memory.getDOMCounters', {}, 2000)
224
+ const heap = await cdpCommand(target.webSocketDebuggerUrl, 'Runtime.getHeapUsage', {}, 2000)
225
+ const metrics = Array.isArray(perf?.metrics)
226
+ ? Object.fromEntries(perf.metrics.map((item) => [item.name, item.value]))
227
+ : {}
228
+ return {
229
+ ok: true,
230
+ visibility: value.visibility,
231
+ url: value.url,
232
+ heapBytes: Number(metrics.JSHeapUsedSize || heap?.usedSize || dom?.jsHeapUsedSize || 0),
233
+ nodes: Number(perf?.nodes ?? metrics.Nodes ?? dom?.nodes ?? 0),
234
+ documents: Number(metrics.Documents ?? dom?.documents ?? 0),
235
+ listeners: Number(dom?.jsEventListeners ?? 0),
236
+ layoutCount: Number(metrics.LayoutCount ?? 0),
237
+ }
195
238
  }
@@ -28,7 +28,7 @@ import { ensureInstallSnapshot } from '../lib/install-snapshot.mjs'
28
28
  import { exportVault, importVault, readVault } from '../../vault/lib/vault.mjs'
29
29
  import { installGlobalRedline } from '../lib/global-redline.mjs'
30
30
  import { evaluateMemoryGuard, killProcessTree, memoryGuardDefaults, readProcessTable, readSystemMemory, selectProcessTree, sumProcessTree } from '../lib/memory-guard.mjs'
31
- import { closeManagedBrowser, findBrowserPath, flushManagedBrowser, freePort, isPidAlive, launchManagedBrowser, sampleManagedBrowser } from '../lib/browser-guard.mjs'
31
+ import { closeManagedBrowser, findBrowserPath, flushManagedBrowser, freePort, isPidAlive, launchManagedBrowser, lowerProcessPriority, sampleManagedBrowser } from '../lib/browser-guard.mjs'
32
32
  import { normalizeFetchDescriptor } from '../lib/node-compat.mjs'
33
33
  import { cleanupApprovalDrill, runApprovalDrill } from '../lib/approval-drill.mjs'
34
34
  import { negotiateProtocol } from '../lib/adapter-protocol.mjs'
@@ -192,7 +192,7 @@ export const Config = z.object({
192
192
  officialSourceToken: z.string().default('')
193
193
  .description('官方源 Bearer token(可选;不会写进日志/状态)'),
194
194
  maxForks: z.number().min(1).max(64).default(8)
195
- .description('同时存活的任务/分身上限'),
195
+ .description('同时存活的任务/分身上限;运行并发由 singleActiveFork 硬限制为 1'),
196
196
  memoryGuard: z.boolean().default(true)
197
197
  .description('创建/打开/还原分身前检查 Windows CommitFree 余量'),
198
198
  memoryMinFreeMB: z.number().min(0).max(1048576).default(6144)
@@ -205,7 +205,7 @@ export const Config = z.object({
205
205
  .description('宿主最低保留(MB);低于此值进入 Safe Mode 并隔离'),
206
206
  memoryWatchdog: z.boolean().default(true)
207
207
  .description('定时采样每个分身的 PID 树/Commit,异常增长时只杀该分身'),
208
- memoryWatchIntervalMs: z.number().min(5000).max(600000).default(30000)
208
+ memoryWatchIntervalMs: z.number().min(5000).max(600000).default(15000)
209
209
  .description('内存看门狗采样间隔(毫秒)'),
210
210
  memoryKillCommitMB: z.number().min(128).max(1048576).default(2048)
211
211
  .description('单个分身 PID 树 commit 超过该值(MB)时进入杀进程候选'),
@@ -221,6 +221,18 @@ export const Config = z.object({
221
221
  .description('同时存活的托管浏览器窗口上限'),
222
222
  browserMemoryLimitMB: z.number().min(256).max(1048576).default(2048)
223
223
  .description('单个托管浏览器 PID 树 Commit 上限(MB),超过即关闭'),
224
+ browserHeapLimitMB: z.number().min(128).max(1048576).default(1536)
225
+ .description('托管浏览器 JS heap 上限(MB),超过即关闭'),
226
+ gracefulBrowserCloseMs: z.number().min(0).max(30000).default(3000)
227
+ .description('CDP Browser.close 后等待优雅退出的时间;超时才 taskkill'),
228
+ idleCloseOnlyWhenIdle: z.boolean().default(true)
229
+ .description('只关闭确认空闲的 fork 页面;无法确认活跃状态时不自动关'),
230
+ orphanSweepMinutes: z.number().min(0).max(1440).default(5)
231
+ .description('孤儿 fork 进程清理间隔(分钟;0=仅启动时)'),
232
+ forkFlushPath: z.string().default('')
233
+ .description('关闭浏览器前调用的 fork 落盘路径(如 /api/session/flush;留空=显式 unsupported)'),
234
+ forkCommitShareLimit: z.number().min(0.05).max(1).default(0.4)
235
+ .description('fork+browser PID 树 commit 总和占系统 CommitLimit 的上限'),
224
236
  browserDomNodeLimit: z.number().min(1000).max(10000000).default(200000)
225
237
  .description('托管浏览器 DOM 节点上限,超过即关闭'),
226
238
  autoCloseIdleMinutes: z.number().min(0).max(1440).default(10)
@@ -529,15 +541,24 @@ export function apply(ctx, config) {
529
541
  // means the last run died; enter Safe Mode unless explicitly disabled.
530
542
  const safeModeFile = path.join(layout.dataDir, 'safe-mode.json')
531
543
  const hostStateFile = path.join(layout.dataDir, 'host-state.json')
544
+ const hostCrashFile = path.join(layout.dataDir, 'host-crashes.json')
532
545
  const readJsonFile = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null } }
533
546
  const previousHost = readJsonFile(hostStateFile)
534
547
  const previousSafeMode = readJsonFile(safeModeFile)
535
548
  const unclean = Boolean(previousHost && previousHost.clean !== true && Number(previousHost.pid) !== process.pid)
536
549
  let safeMode = Boolean(previousSafeMode?.safeMode)
537
550
  let safeModeReason = String(previousSafeMode?.reason ?? '')
538
- if (unclean && cfg.safeModeAfterCrash === true && !safeMode) {
539
- safeMode = true
540
- safeModeReason = 'unclean-shutdown'
551
+ if (unclean) {
552
+ const now = nowMs()
553
+ const prior = readJsonFile(hostCrashFile)?.crashes
554
+ const recent = (Array.isArray(prior) ? prior : []).filter((item) => now - Number(item.at) <= 10 * 60_000)
555
+ recent.push({ at: now, previousPid: previousHost?.pid ?? null, reason: 'unclean-shutdown' })
556
+ try { fs.writeFileSync(hostCrashFile, JSON.stringify({ crashes: recent }, null, 2)) } catch { /* best effort */ }
557
+ // Red line: one crash is context; two crashes within 10 minutes means a loop.
558
+ if (cfg.safeModeAfterCrash === true && !safeMode && recent.length >= 2) {
559
+ safeMode = true
560
+ safeModeReason = 'crash-loop-10m'
561
+ }
541
562
  }
542
563
  // A fresh host process is an explicit recovery boundary: clear per-task
543
564
  // quarantine latches, but keep tokens revoked so the old page cannot reconnect.
@@ -591,15 +612,29 @@ export function apply(ctx, config) {
591
612
  if (process.platform === 'win32' && process.env.DSH_FANG_DISABLE_SIDECAR !== '1' && !testLike && !sidecarAlready) {
592
613
  globalThis.__fangWatchdogSidecar = true
593
614
  try {
594
- const sidecar = fileURLToPath(new URL('../lib/watchdog-sidecar.mjs', import.meta.url))
595
- const child = spawn(process.execPath, [sidecar, watchdogFile], {
596
- detached: true,
597
- stdio: 'ignore',
598
- windowsHide: true,
599
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
600
- })
601
- child.on('error', () => {})
602
- child.unref()
615
+ // IMPORTANT: never spawn process.execPath here. In a packaged DSH host that
616
+ // is DeepSeek Harness.exe, and ELECTRON_RUN_AS_NODE may be fused off; it
617
+ // would boot a second host, corrupt the profile, and trigger the exact
618
+ // "Failed to load plugins" / handler-threw failure seen in v3.8.0.
619
+ const nodeCandidates = [
620
+ process.env.DSH_FANG_NODE_EXE,
621
+ path.join(path.dirname(process.execPath), 'resources', 'runtime', 'primary-runtime', 'dependencies', 'node', 'bin', 'node.exe'),
622
+ 'D:\\DSH\\resources\\runtime\\primary-runtime\\dependencies\\node\\bin\\node.exe',
623
+ ].filter(Boolean)
624
+ const nodeExe = nodeCandidates.find((candidate) => exists(candidate))
625
+ if (!nodeExe) {
626
+ audit('watchdog-sidecar-unavailable', { reason: 'bundled-node-not-found' })
627
+ } else {
628
+ const sidecar = fileURLToPath(new URL('../lib/watchdog-sidecar.mjs', import.meta.url))
629
+ const child = spawn(nodeExe, [sidecar, watchdogFile], {
630
+ detached: true,
631
+ stdio: 'ignore',
632
+ windowsHide: true,
633
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
634
+ })
635
+ child.on('error', () => {})
636
+ child.unref()
637
+ }
603
638
  } catch { /* sidecar is best effort; host watchdog remains */ }
604
639
  }
605
640
 
@@ -750,18 +785,42 @@ export function apply(ctx, config) {
750
785
 
751
786
  const memorySamples = new Map()
752
787
 
788
+ const flushForkSession = async (task) => {
789
+ const flushPath = String(cfg.forkFlushPath || '').trim()
790
+ if (!flushPath) return { ok: false, error: 'unsupported' }
791
+ const opened = forker()?.openUrl?.(task.taskId)
792
+ if (!opened?.url) return { ok: false, error: 'fork-url-unavailable' }
793
+ try {
794
+ const endpoint = new URL(flushPath, opened.url)
795
+ const response = await fetch(endpoint, { method: 'POST', signal: AbortSignal.timeout(3000) })
796
+ return { ok: response.ok, status: response.status, path: flushPath }
797
+ } catch (error) {
798
+ return { ok: false, error: String(error?.message ?? error), path: flushPath }
799
+ }
800
+ }
801
+
753
802
  const closeTaskBrowser = async (task, reason = 'guard') => {
754
803
  if (!task?.browser?.pid) return { ok: true, skipped: 'no-browser' }
755
804
  const browser = task.browser
805
+ const forkFlush = await flushForkSession(task)
756
806
  try { await flushManagedBrowser(browser.port) } catch { /* best effort */ }
757
- const result = await closeManagedBrowser({ pid: browser.pid, port: browser.port })
807
+ const result = await closeManagedBrowser({ pid: browser.pid, port: browser.port, graceMs: cfg.gracefulBrowserCloseMs })
758
808
  task.browser = null
759
- task.browserClosed = { at: nowMs(), reason, pid: browser.pid, ok: result.ok }
809
+ task.browserClosed = { at: nowMs(), reason, pid: browser.pid, ok: result.ok, graceful: result.graceful === true }
810
+ task.memoryGuard = {
811
+ reason,
812
+ at: nowMs(),
813
+ pid: browser.pid,
814
+ metrics: browser.last ?? null,
815
+ graceful: result.graceful === true,
816
+ forkFlush,
817
+ saved: result.graceful === true,
818
+ }
760
819
  writeWatchdog()
761
820
  try {
762
- fs.appendFileSync(path.join(layout.dataDir, 'browser-events.jsonl'), JSON.stringify({ taskId: task.taskId, at: nowMs(), event: 'closed', reason, pid: browser.pid, ok: result.ok }) + '\n')
821
+ fs.appendFileSync(path.join(layout.dataDir, 'browser-events.jsonl'), JSON.stringify({ taskId: task.taskId, at: nowMs(), event: 'closed', reason, pid: browser.pid, ok: result.ok, graceful: result.graceful === true, forkFlush, metrics: browser.last ?? null }) + '\n')
763
822
  } catch { /* diagnostics only */ }
764
- audit('fork-browser-closed', { taskId: task.taskId, reason, pid: browser.pid, ok: result.ok })
823
+ audit('fork-browser-closed', { taskId: task.taskId, reason, pid: browser.pid, ok: result.ok, graceful: result.graceful === true, forkFlush })
765
824
  persist()
766
825
  return result
767
826
  }
@@ -839,7 +898,8 @@ export function apply(ctx, config) {
839
898
  safeModeReason = `host-emergency:${reason}`
840
899
  persistSafeMode()
841
900
  }
842
- audit('host-emergency-guard', { reason, safe, tasks: tasks.size })
901
+ const self = process.memoryUsage()
902
+ audit('host-emergency-guard', { reason, safe, tasks: tasks.size, selfRssMB: Math.round(self.rss / 1048576), selfPrivateMB: Math.round((self.heapUsed + self.external) / 1048576) })
843
903
  return { ok: true, reason, safe }
844
904
  } finally {
845
905
  hostPanic = false
@@ -876,6 +936,14 @@ export function apply(ctx, config) {
876
936
  return tree
877
937
  }
878
938
 
939
+ const taskIdleForClose = (task) => {
940
+ const live = forker()?.status?.(task.taskId)
941
+ if (!live?.running) return true
942
+ if (task.adapter?.busy === true) return false
943
+ // Conservative: without an explicit idle signal, never auto-close a live fork page.
944
+ return task.adapter?.idle === true
945
+ }
946
+
879
947
  const browserWatchdogTick = async (table) => {
880
948
  if (cfg.managedBrowser !== true || process.platform !== 'win32') return
881
949
  for (const task of tasks.values()) {
@@ -892,22 +960,24 @@ export function apply(ctx, config) {
892
960
  const sample = await sampleManagedBrowser(browser.port)
893
961
  const nodes = Number(sample?.nodes) || 0
894
962
  const heapMB = Math.round((Number(sample?.heapBytes) || 0) / 1048576)
895
- browser.last = { at: nowMs(), ...tree, nodes, heapMB, visibility: sample?.visibility ?? 'unknown' }
963
+ browser.last = { at: nowMs(), ...tree, nodes, heapMB, visibility: sample?.visibility ?? 'unknown', documents: Number(sample?.documents) || 0, listeners: Number(sample?.listeners) || 0 }
896
964
  try {
897
965
  fs.appendFileSync(path.join(layout.dataDir, 'browser-samples.jsonl'), JSON.stringify({ taskId: task.taskId, ...browser.last }) + '\n')
898
966
  } catch { /* diagnostics only */ }
899
967
  const overMemory = Number(tree.commitMB) >= Number(cfg.browserMemoryLimitMB)
968
+ const overHeap = heapMB >= Number(cfg.browserHeapLimitMB)
900
969
  const overDom = nodes >= Number(cfg.browserDomNodeLimit)
901
- if (overMemory || overDom) {
902
- audit('fork-browser-memory-guard', { taskId: task.taskId, commitMB: tree.commitMB, nodes, heapMB, overMemory, overDom })
903
- await quarantineTask(task, overMemory ? 'browser-memory-limit' : 'browser-dom-limit')
970
+ if (overMemory || overHeap || overDom) {
971
+ const reason = overMemory ? 'browser-memory-limit' : overHeap ? 'browser-heap-limit' : 'browser-dom-limit'
972
+ audit('fork-browser-memory-guard', { taskId: task.taskId, commitMB: tree.commitMB, nodes, heapMB, overMemory, overHeap, overDom })
973
+ await quarantineTask(task, reason)
904
974
  continue
905
975
  }
906
976
  if (cfg.autoCloseIdleMinutes > 0) {
907
977
  if (sample?.ok === true && sample.visibility === 'hidden') {
908
978
  if (!browser.hiddenSince) browser.hiddenSince = nowMs()
909
979
  const idleMs = nowMs() - Number(browser.hiddenSince)
910
- if (idleMs >= Number(cfg.autoCloseIdleMinutes) * 60_000) {
980
+ if (idleMs >= Number(cfg.autoCloseIdleMinutes) * 60_000 && (!cfg.idleCloseOnlyWhenIdle || taskIdleForClose(task))) {
911
981
  await closeTaskBrowser(task, 'idle-hidden')
912
982
  continue
913
983
  }
@@ -930,6 +1000,23 @@ export function apply(ctx, config) {
930
1000
  if (rootPid > 0) await recordForkMemory(task, rootPid, table)
931
1001
  }
932
1002
  await browserWatchdogTick(table)
1003
+ // Red line: aggregate fork+browser commit must stay below the configured share.
1004
+ const memory = await readSystemMemory()
1005
+ if (memory.ok && Number(memory.commitLimitMB) > 0) {
1006
+ let total = 0
1007
+ for (const task of tasks.values()) {
1008
+ if (task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING) {
1009
+ total += sumProcessTree(selectProcessTree(table.rows, Number(forker()?.status?.(task.taskId)?.pid ?? task.pid))).commitMB
1010
+ }
1011
+ if (task.browser?.pid) total += sumProcessTree(selectProcessTree(table.rows, Number(task.browser.pid))).commitMB
1012
+ }
1013
+ const limit = Number(memory.commitLimitMB) * Number(cfg.forkCommitShareLimit)
1014
+ if (total > limit) {
1015
+ audit('fork-commit-share-exceeded', { totalMB: total, limitMB: Math.round(limit), share: cfg.forkCommitShareLimit })
1016
+ await hostEmergency('fork-commit-share', { safe: true })
1017
+ return
1018
+ }
1019
+ }
933
1020
  writeWatchdog()
934
1021
  }
935
1022
 
@@ -941,7 +1028,8 @@ export function apply(ctx, config) {
941
1028
  const free = Number(memory.commitFreeMB) || 0
942
1029
  if (free < Number(cfg.hostWarnFreeMB) && nowMs() - lastHostWarnAt > 60_000) {
943
1030
  lastHostWarnAt = nowMs()
944
- audit('host-memory-warning', { commitFreeMB: free, warnMB: cfg.hostWarnFreeMB })
1031
+ const self = process.memoryUsage()
1032
+ audit('host-memory-warning', { commitFreeMB: free, warnMB: cfg.hostWarnFreeMB, selfRssMB: Math.round(self.rss / 1048576), selfPrivateMB: Math.round((self.heapUsed + self.external) / 1048576) })
945
1033
  }
946
1034
  if (free < Number(cfg.hostCriticalFreeMB)) {
947
1035
  await hostEmergency('commit-free-critical', { safe: true })
@@ -1701,6 +1789,8 @@ export function apply(ctx, config) {
1701
1789
  task.url = started.url ?? null
1702
1790
  task.token = started.token ?? extractTokenSafe(task.url)
1703
1791
  persist()
1792
+ writeWatchdog()
1793
+ void lowerProcessPriority(task.pid)
1704
1794
  audit(AUDIT.FORK_STARTED, { taskId, pid: task.pid, port: task.port, profile })
1705
1795
  bus.emit('fang/task-created', { taskId, forkId: taskId, title, url: task.url, port: task.port })
1706
1796
 
@@ -2449,6 +2539,8 @@ export function apply(ctx, config) {
2449
2539
  task.token = started.token ?? extractTokenSafe(task.url)
2450
2540
  task.adapter = { ok: false, error: 'handshaking' }
2451
2541
  persist()
2542
+ writeWatchdog()
2543
+ void lowerProcessPriority(task.pid)
2452
2544
  audit(AUDIT.FORK_STARTED, { taskId: id, pid: task.pid, port: task.port, profile: task.profile, restored: true })
2453
2545
  const adapter = await handshake(task)
2454
2546
  task.status = adapter.ok ? TASK_STATUS.READY : TASK_STATUS.RUNNING
@@ -2826,6 +2918,11 @@ export function apply(ctx, config) {
2826
2918
  }
2827
2919
  // Startup: reclaim archived/failed fork processes whose recorded PID still lives.
2828
2920
  void cleanupOrphanForks()
2921
+ if (cfg.orphanSweepMinutes > 0) {
2922
+ const timer = setInterval(() => { void cleanupOrphanForks() }, Number(cfg.orphanSweepMinutes) * 60_000)
2923
+ timer.unref?.()
2924
+ try { ctx.effect(() => () => clearInterval(timer)) } catch { /* fake ctx */ }
2925
+ }
2829
2926
  // v3.3.8:启动后异步自愈默认元主;不阻塞 boot,不 unref 也不会阻止退出。
2830
2927
  {
2831
2928
  const timer = setTimeout(() => { void refreshStaleDefaultEssenceIfNeeded() }, 1500)
@@ -3974,6 +4071,7 @@ export function apply(ctx, config) {
3974
4071
  return closeTaskBrowser(task, reason)
3975
4072
  },
3976
4073
  safeModeStatus: () => ({ ok: true, safeMode, reason: safeModeReason }),
4074
+ panic: async () => hostEmergency('manual-panic', { safe: true }),
3977
4075
  resetSafeMode: () => {
3978
4076
  safeMode = false
3979
4077
  safeModeReason = ''
@@ -5108,9 +5206,14 @@ export function apply(ctx, config) {
5108
5206
  }
5109
5207
  let managed = { ok: true, managed: false }
5110
5208
  if (out.url) {
5111
- const browser = await service.openManagedBrowser(taskId, out.url)
5112
- if (browser?.ok === true) managed = browser
5113
- else managed = { ok: true, managed: false, browserError: browser?.error ?? 'browser-unavailable' }
5209
+ try {
5210
+ const browser = await service.openManagedBrowser(taskId, out.url)
5211
+ if (browser?.ok === true) managed = browser
5212
+ else managed = { ok: true, managed: false, browserError: browser?.error ?? 'browser-unavailable' }
5213
+ } catch (error) {
5214
+ managed = { ok: true, managed: false, browserError: String(error?.message ?? error) }
5215
+ audit('fork-browser-open-handler-failed', { taskId, error: String(error?.message ?? error) })
5216
+ }
5114
5217
  }
5115
5218
  return json(res, 200, { ...out, ...managed })
5116
5219
  })