主进程的 watch 台账显示 0 个存活资源,channel 台账里却躺着 20 个孤儿;renderer 的 V8 堆在主进程里根本读不到。leakscope-electron 把这两套堆拆成显式生命周期记录、预热 2 轮加测量 5 轮的趋势判定,以及一份确定性报告。20 轮窗口往返在鸿蒙 2in1 模拟器上跑完,下面是设备上取回的读数,以及库为什么是现在这个结构。

仓库地址:https://atomgit.com/oh-tpc/leakscope-electron
版本地址:https://atomgit.com/CPF-Electron
三方库框架:https://atomgit.com/oh-tpc

0. 环境与实测设备

三方库适配信息:

三方库Electron 版本鸿蒙化版本仓库地址社区社区地址
leakscope-electron40+(peer)37.2.1(26)https://atomgit.com/oh-tpc/leakscope-electron(生态收录:https://atomgit.com/oh-tpc)CPF-Electron 鸿蒙社区https://atomgit.com/CPF-Electron

说明:库的 peer 是 electron >= 40.0.0,但它不 import electron、也不安装运行时;本次鸿蒙侧用的是社区 Electron for OpenHarmony v37.2.1(页面内 process.versions.electron 报 37.2.0)。demo 只用到标准 Node/JS 能力,实际能跑;37.2.1 是宿主版本,不是库的兼容下限。

实测环境:

项版本/型号
Electron桌面:v40+(peer,本库不安装);鸿蒙:Electron for OpenHarmony v37.2.1,Chromium 138.0.7204.45,Node 22.17.0,process.platform === "openharmony"
Node.js>= 20(库);鸿蒙宿主 22.17.0
DevEco Studio内置 SDK / hvigor / hdc(构建、签名、安装 HAP)
实测设备DevEco 模拟器 MateBook Pro(2in1,arm64),OpenHarmony 7.0.0.105,API 26,hdc 目标 127.0.0.1:5555
应用LeakScope · Electron demo,bundle com.rnsmartgrip.example,HAP 205,628,595 B(已签名)
测试Vitest 3.2.7,6 个文件 48 项;npm pack 44 个文件、67,385 B
端侧结果20 轮窗口往返:active channels 20 / orphans 20 / image entries 10 / liveBytes 10.0 MB / failures 0
桌面验证macOS arm64、Node 24.12.0、npm 11.12.1:typecheck / 48 tests / build / pack 通过;未安装 Electron 运行时

说明:这是社区 Electron for OpenHarmony 宿主,上游 Electron 没有官方鸿蒙发行版;设备是模拟器,HAP 复用本机调试 profile,bundleName 与设备 UDID 绑定;构建时裁掉了 6 个需要 system_basic / ACL 的宿主权限。详见 宿主接入说明。

1. 21:53,20 个孤儿和 0 个存活资源

模拟器日志里的 AppWindowAdapter#setTitle 每 3 秒左右出现一对:先是 leakscope-electron-ohos-demo,再是 LeakScope · Electron demo。20 轮窗口往返跑完,设备上的 leakscope-report.md 第一张表是:存活资源 0、存活字节 0.0 KB、已释放 20、泄漏候选 0、通道孤儿 20。

这组数放在一起有点别扭。窗口和 webContents 每一轮都关了,watch 台账干净;demo:ping 的 ipcMain listener 每轮注册一次,从没移除,20 轮之后 channel 台账里有 20 条 active,越过 3 秒阈值全变成 orphan。

设备上的主进程第一次跑完时,我先看的是 process.memoryUsage().heapUsed。这个数字每轮都在跳,按单点读数判断不了任何事。后来把 scope.channels.audit() 打出来,opened=20, closed=0, active.length=20,才回头去数 ipcMain 的注册次数。主进程的 heapUsed 看不出 listener 累积的那点增量,renderer 的 V8 堆更不在这个进程里。

Electron 的进程模型把内存分成两套:主进程是 Node 堆,每个 renderer 是独立的 Blink / V8 堆。它们不在同一个进程里,也没有一条 API 能让主进程直接读 renderer 的堆。主进程这边更难发现的是生命周期没有闭合:BrowserWindow 关了,webContents、窗口引用或页面回调还被闭包拿着;ipcMain.on 每开一个页面多注册一次;EventEmitter listener 只增不减;一张 nativeImage 的 RGBA buffer 按 宽 × 高 × 4 吃内存,没人把它记进预算。renderer 那边相反,单个对象通常不大,页面往返一次,V8 堆抬高一截,回不到基线。

鸿蒙这一侧还有一层现实约束:Electron 上游并不官方支持 OpenHarmony / HarmonyOS,鸿蒙化这条路目前由 CPF-Electron 鸿蒙社区承接。为了让观测库既能跑在标准 Electron 上,又能在社区宿主里跑,我把它限制成纯 TypeScript:不 import electron,所有 Electron 对象都用结构化接口接收,宿主传什么就观察什么。

题目的边界因此很窄:不猜 GC 可达性,只观察登记的资源的生命周期是否闭合。

2. 设备上跑出来的 20 轮

这张截图是整条链路的端到端实拍:HarmonyOS 2in1 模拟器上的 LeakScope · Electron demo,顶部 eyebrow 是运行时真实取值:

LEAKSCOPE / ELECTRON · ELECTRON 37.2.0 · CHROME 138.0.7204.45 · openharmony/arm64

LeakScope · Electron demo 在鸿蒙 2in1 模拟器上的运行截图

Demo 干的事很具体:每一轮打开一个隐藏的 BrowserWindow,登记窗口 / webContents,故意注册一个 demo:ping 的 ipcMain 监听器且从不移除;偶数轮再故意保留一张 512×512 的 RGBA 图片。窗口 / webContents 的句柄本身是正确关闭的,release 和 scopeClose 也都调用了。20 轮之后,顶部四张卡片是:

ACTIVE CHANNELSORPHANSIMAGE ENTRIESIMAGE BYTES
20201010.0 MB

报告本体如下:

## LeakScope 报告 · 打开/关闭窗口 20 次

| 指标 | 值 |
| --- | --- |
| 存活资源 | 0 |
| 存活字节 | 0.0 KB |
| 已释放 | 20 |
| 泄漏候选 | 0 |
| 复现结论 | 未运行 |
| 通道孤儿 | 20 |

存活资源 0、泄漏候选 0,不等于没有泄漏。 窗口对象每一轮都正确 release 了,所以 watch 台账干净、候选为空;泄漏在 channel 台账里:20 个 demo:ping 监听器仍然 active,越过 3 秒 orphan 阈值后全部变成孤儿。图片台账独立记着 10 条、10.0 MB(512×512×4 = 1,048,576 B,正好 1 MB/张,偶数轮保留)。报告的「复现结论」一行显示「未运行」,是因为这个 demo 只做生命周期审计,没有调用 runLeakRepro / runMemoryRepro;要看趋势判定,得在 scope.report({ repro }) 里传入复现结果。

报告里的 Top offenders 是空的(没有 live 资源),通道审计按 topN=5 只列前 5 条,完整的计数在设备端 leakscope-summary.json 里(channels: 20、orphans: 20);报告中的通道名从 demo:ping#1 到 demo:ping#5,owner 从 window-1 到 window-5,状态都是 orphan。这份报告写在 app.getPath('userData') 下(设备上是 /data/storage/el2/base/files/leakscope-report.md),再用 hdc file recv 取回;截图里的窗口是同一份证据的裁切。

取证命令就是下面三行,报告、摘要和整屏截图都从设备端拉回 harmony/evidence/:

hdc file recv /data/storage/el2/base/files/leakscope-report.md \
  harmony/evidence/leakscope-report.md
hdc file recv /data/storage/el2/base/files/leakscope-summary.json \
  harmony/evidence/leakscope-summary.json
hdc shell snapshot_display -f /data/local/tmp/shot.jpeg

设备端的摘要 JSON 同时记录了运行时:

{
  "env": { "platform": "openharmony", "arch": "arm64", "electron": "37.2.0",
    "chrome": "138.0.7204.45", "node": "22.17.0" },
  "summary": { "rounds": 20, "imageBytes": 1048576, "channels": 20, "orphans": 20,
    "images": 10, "liveBytes": 10485760, "failures": 0 }
}

设备日志里保留了窗口标题切换的四行,这里是原文:

11-12 21:53:12.698 14043 14043 I A00000/com.rnsmartgrip.example/[WebEngine]: tag: LogMethodCall --> AppWindowAdapter#setTitle(13,"leakscope-electron-ohos-demo") in
11-12 21:53:12.860 14043 14043 I A00000/com.rnsmartgrip.example/[WebEngine]: tag: LogMethodCall --> AppWindowAdapter#setTitle(13,"LeakScope · Electron demo") in
11-12 21:53:16.038 14043 14043 I A00000/com.rnsmartgrip.example/[WebEngine]: tag: LogMethodCall --> AppWindowAdapter#setTitle(14,"leakscope-electron-ohos-demo") in
11-12 21:53:16.213 14043 14043 I A00000/com.rnsmartgrip.example/[WebEngine]: tag: LogMethodCall --> AppWindowAdapter#setTitle(14,"LeakScope · Electron demo") in

第 13 个窗口到第 14 个窗口隔了约 3.34 秒,报告里最老的孤儿存活 67042 毫秒。宿主接入说明 记录的每轮约 3.2 秒和这个量级一致。20 轮全部成功,0 失败;这个耗时来自模拟器环境。整条链路没有改库的一行代码;harmony/ 只换了外壳和渲染参数。

3. 两套堆不能互读,API 只能显式接收

两套堆不能互相读。这句话听起来像背景知识,落到 API 上会排除很多看起来很自然的写法。

先看库的 import 列表。src/ 里没有任何 from 'electron',测试里也没有。Electron 对象全部在 adapters.ts 里写成结构化接口:BrowserWindowLike 的核心是 on / isDestroyed / destroy,IpcMainLike 的核心是 on,NativeImageLike 的核心是 getBitmap / getSize,其余方法都按可选处理。宿主传真实 Electron 对象,结构兼容就能用;测试传 fake 对象,不需要 Electron 运行时。

这条决定直接影响了版本策略:peerDependencies 写 electron >= 40.0.0,但仓库不安装、不 import。鸿蒙侧用的是社区 Electron for OpenHarmony v37.2.1(页面里 process.versions.electron 报 37.2.0),低于 peer 声明。它能跑,是因为库只用到 ipcMain.on、removeListener、webContents.destroy 这些稳定表面;这不代表 37.2.1 是兼容下限,也不代表上游 Electron 官方支持鸿蒙。

如果库 import 了 electron,会多出两个具体问题:npm test 要求装运行时;社区宿主和标准 Electron 的版本差异会变成模块解析错误。现在这两个问题都不存在,代价是接口只覆盖库实际用到的方法,宿主传一个不满足接口的对象时只能在运行时报错。

renderer 侧只发 JSON,原因更直接:主进程读不到 renderer 的 V8 堆,renderer 也拿不到主进程的 ledger。跨进程传的是结构化克隆的普通数据,这条链路只发 JSON 形状的指标。RendererMetrics 就长这样:{ round, heapUsed, images, channels, at?, owner? },没有 BrowserWindow,没有 webContents,没有函数。

createRendererReporter 是接收端,不是采集端。它不注入 performance.memory,不 patch renderer;每轮收到一张快照,跟上一轮做差:新出现的 image / channel 写进 ledger,消失的 release / close,heapUsed 存成样本。上报代码要宿主自己接,preload 只暴露一个 report(payload),底层 ipcRenderer.send,页面拿不到 ipcRenderer,contextIsolation: true 的边界没有被打破。

主进程只做汇总,因为只有它能跨轮持有记录;renderer 会随页面销毁,账本不能放在页面里。LeakScope 把 watch、image、channel 放在同一个进程、同一个注入时钟上;report() 一次取齐快照、候选、图片统计和 channel audit。renderer 的样本留在 reporter.samples(),不会自动进报告;要把两边关联起来,得由宿主把 renderer 样本和主进程的复现结果放在一起看。库没有提供「远程读 renderer」的 API,renderer 的堆只能由页面自己上报。

demo 的报告是 0 和 20,原因就在这里:watch 只记显式登记的资源,IPC listener 没进 watch,只在 channel ledger 里。三份记录各回答一个问题:

  • LeakWatch 回答「该释放的有没有释放」:watch 登记,release 销账,scopeClose(owner) 标记作用域结束。候选原因按强度排序:unreleased-after-scope > duplicate-key > stale。
  • ChannelLedger 回答「打开与关闭是否对称」:ipcMain / ipcRenderer / EventEmitter / window / webContents 都记成通道;dedupeKey 抓重复注册,orphanAfterMs 抓长期 active,lateClose 抓作用域结束之后才关闭。
  • ImageMemoryLedger 回答「解码字节有没有超预算」:bytesFor 按 ceil(宽 × dpr) × ceil(高 × dpr) × bpp 算,nativeImageBytes 优先读 getBitmap() 的真实 buffer,planImageDecode 在解码前按 2 的幂降采样,evictTo 做 LRU。

两套堆不能互读,库只能接收第二套数据,不能去读它。这条边界决定了前面三个设计:不 import、JSON 上报、主进程汇总。它也有代价:宿主得自己接上报代码;renderer 的资源释放仍要在 renderer 里做,主进程只能记账。

一次趋势判定把「单点噪声」变成「可判定的量」。runLeakRepro 默认预热 2 轮、测量 5 轮;baseline 取最后一个预热轮,growth 是末轮减 baseline,slope 是测量轮的最小二乘斜率。判定顺序不能反:测量轮 < 2 → insufficient-data;growth <= budget + tolerance → stable;每轮增量都不低于 -tolerance → leak;否则 noisy。runMemoryRepro 换的是指标:每轮 process.memoryUsage().heapUsed,返回里额外带 heapGrowth / rssGrowth。

报告必须可回归。renderLeakReport 不写时间戳、不读 Date.now,所有集合先按显式键排序,空数据渲染空表;同一份输入在同一运行时渲染两次必须得到相同字节,才能进 CI 的 golden test。它和常见观测路径的差别可以列成一张表:

观测路径能回答什么代价 / 边界
DevTools Heap SnapshotRetainer path、Detached DOM、对象图人工分析、不能自动回归、跨进程不便
process.memoryUsage()主进程 Node 堆 / RSS 趋势单点噪声、看不到 renderer、没有归属
webContents.takeHeapSnapshotrenderer 的 V8 堆快照事后分析、体积大、不适合每轮跑
LeakScope(本库)显式台账 + 按轮趋势 + nativeImage/IPC 账本 + 确定性报告依赖宿主登记,不做 GC 可达性

能力边界一并列出:本库不覆盖 GPU 显存、原生堆和 ArkTS 侧的 TaskPool 内部状态;nativeImageBytes 只算 CPU 侧图片 buffer;unreleased-after-scope 是「没有调用 release」的事实,不直接等于「对象一定被 GC 回收」。这份报告只覆盖登记过的资源;没登记的对象、GPU 显存和 GC 时机,都不在它的证明范围里。

4. 一个 npm 包,两边各记各的账

仓库分三块:src/ 是纯 TS 库,demo/ 是手动 Electron 演示,harmony/ 是社区宿主的外壳。dist/ 是 tsc 产物,构建时同步到 harmony/app/dist:

leakscope-electron/
├─ src/
│  ├─ types.ts          # 数据模型、默认常量、MemorySample / RendererMetrics
│  ├─ watch.ts          # LeakWatch 生命周期台账
│  ├─ repro.ts          # runLeakRepro / runMemoryRepro
│  ├─ image-memory.ts   # bytesFor / nativeImageBytes / planImageDecode / LRU
│  ├─ channel.ts        # ChannelLedger + IPC / emitter / window / webContents
│  ├─ report.ts         # 确定性 markdown
│  ├─ scope.ts          # LeakScope 门面
│  ├─ adapters.ts       # Electron 结构化接口 + renderer 上报
│  └─ index.ts          # 公共导出
├─ __tests__/            # 6 个测试文件、48 个用例
├─ demo/                 # 手动 Electron 演示(20 次窗口往返)
├─ docs/                 # 泄漏分类、验证记录、包检查
├─ harmony/              # 社区 Electron for OpenHarmony 宿主包装
│  ├─ app/               # 应用外壳(dist 注入后与 main.js 同级)
│  ├─ scripts/           # build-run.sh / patch-host.mjs
│  ├─ signing/           # 签名模板(真实材料 gitignore)
│  └─ evidence/          # 设备截图、设备端报告、摘要 JSON
├─ dist/                 # tsc 产物
├─ README.md / README.OpenHarmony_CN.md
└─ CHANGELOG.md

leakscope-electron 的目录:src、demo、harmony

结构上还有两个决定影响接口形状:

库不做自动探针。它不 hook BrowserWindow 构造函数,也不 patch ipcMain。窗口、webContents、IPC、图片都需要宿主在生命周期里显式登记;这是「漏报」的来源,也是「可解释」的来源:报告里每一条都能对应到你写的那一行 watch / ipc / image。

三份记录共享同一个时钟。LeakScope 把 watch、image、channel 的 now 统一注入,report() 一次取齐快照、候选、图片统计和通道审计,避免报告内部时间不一致;dispose() 会真实关闭通道、重置图片账本,但保留 watch 记录,方便退出前再打一份 post-mortem 报告。

对使用方来说,主进程、preload、renderer 各一段就接完:

// main.ts
import { app, BrowserWindow, ipcMain } from 'electron';
import { LeakScope, createRendererReporter } from 'leakscope-electron';

const scope = new LeakScope({ staleAfterMs: 3000, orphanAfterMs: 3000 });
const reporter = createRendererReporter({
  owner: 'renderer',
  watch: scope.watcher,
  images: scope.images,
  channels: scope.channels,
});

function openFeed(id: number): BrowserWindow {
  const owner = `window-${id}`;
  const win = new BrowserWindow({ width: 1180, height: 760, show: false });
  scope.watch(`window:${id}`, { kind: 'object', owner, bytes: 8 * 1024 * 1024 });
  const windowHandle = scope.window(win, { owner });
  const contentsHandle = scope.webContents(win.webContents, { owner });
  const ipcHandle = scope.ipc(ipcMain, 'feed:refresh', () => undefined, { owner });

  win.on('closed', () => {
    contentsHandle.close();
    windowHandle.close();
    ipcHandle.close();          // 真实 removeListener
    scope.release(`window:${id}`);
    scope.scopeClose(owner);    // 先清理,再关作用域,避免 lateClose
  });
  return win;
}

scope.ipc(ipcMain, 'leakscope:report', (_event, payload) => reporter.report(payload), {
  owner: 'app',
});
app.on('before-quit', () => {
  console.log(scope.report({ title: 'before-quit' }));
  scope.dispose();
});

main 里只有两件事:创建窗口时登记 window / webContents / IPC,closed 时按逆序销账;退出前再取一份报告。登记和释放都写在生命周期回调里,报告才能逐条对上调用点。

// preload.js — 只转发 JSON,不暴露 ipcRenderer
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('leakscope', {
  report: (payload) => ipcRenderer.send('leakscope:report', payload),
});
// renderer.js — 每轮固定相位上报
let round = 0;
const used = performance.memory?.usedJSHeapSize ?? 0;
window.leakscope.report({ round: round++, heapUsed: used, images: [], channels: [] });

preload 只暴露一个 report,renderer 每轮按固定相位把图片、通道和 heapUsed 交出去;两边都不碰业务状态,主进程收到什么就记什么。

鸿蒙侧的外壳在 harmony/app/:它负责 require('./dist')(库被注入到应用根)、默认软件渲染(模拟器 GPU/EGL 路径无法满足 Chromium 合成)、清空应用菜单(鸿蒙 PC 自带菜单栏)、每轮窗口往返包 try/catch(宿主异常不丢整份账本),并把报告和摘要写到 userData 方便 hdc file recv。这些都在外壳里,库本体和 dist/ 一行未改;harmony/app/ 是 demo 的外壳副本。

5. 台账是怎么写出来的

下面按模块贴关键实现。代码来自仓库源码,函数体和缩进都保持原样;LeakWatch、ImageMemoryLedger 这类类是方法块,字段与构造器对照 src/ 看,runCore、trackIpcMain、renderLeakReport 是完整函数。

5.1 LeakWatch:窗口关了,引用还在

LeakWatch 不做 GC 可达性推断,它只记录业务声明的「我拥有什么」和「什么时候释放」。同一个 key 在 live 期间重复 watch 会累加 watchCount,成为 duplicate-key 候选;scopeClose(owner) 会给该 owner 下所有 live 记录打上 scopeClosedAt,之后它们就是 unreleased-after-scope。三个方法加起来不到 80 行,边界都在这里:

// src/watch.ts · LeakWatch 的三个方法
  watch(key: string, spec: ResourceSpec): ResourceRecord {
    if (typeof key !== 'string' || key.length === 0) {
      throw new TypeError('[leakscope] watch key must be a non-empty string');
    }
    const at = this.clock();
    const existing = this.records.get(key);
    if (existing && existing.releasedAt === undefined) {
      existing.watchCount += 1;
      existing.lastWatchedAt = at;
      if (spec.bytes !== undefined) {
        existing.bytes = numberOrZero(spec.bytes);
      }
      return copyRecord(existing);
    }

    if (existing && existing.releasedAt !== undefined) {
      this.releasedCount = Math.max(0, this.releasedCount - 1);
    }

    const scopeClosedAt = spec.owner === undefined ? undefined : this.closedScopes.get(spec.owner);
    const record: ResourceRecord = {
      key,
      kind: spec.kind,
      label: spec.label ?? key,
      owner: spec.owner,
      bytes: numberOrZero(spec.bytes),
      meta: spec.meta,
      watchedAt: at,
      lastWatchedAt: at,
      scopeClosedAt,
      watchCount: 1,
    };
    this.records.set(key, record);
    this.prune();
    return copyRecord(record);
  }

  release(key: string): boolean {
    const record = this.records.get(key);
    if (!record || record.releasedAt !== undefined) {
      return false;
    }
    record.releasedAt = this.clock();
    this.releasedCount += 1;
    this.prune();
    return true;
  }

  scopeClose(owner: string): number {
    if (!this.closedScopes.has(owner)) {
      this.closedScopes.set(owner, this.clock());
    }
    const closedAt = this.closedScopes.get(owner) ?? this.clock();
    let live = 0;
    for (const record of this.records.values()) {
      if (record.owner !== owner || record.releasedAt !== undefined) {
        continue;
      }
      live += 1;
      if (record.scopeClosedAt === undefined) {
        record.scopeClosedAt = closedAt;
      }
    }
    return live;
  }

maxRecords 超出时只淘汰最旧的已释放记录,live 记录永不丢弃;scopeClose 返回该 owner 仍 live 的数量,方便业务在关闭窗口时立刻打日志。stale 不是泄漏:一个长期缓存活过 3 秒是正常的,它只提示「这个资源没有 owner 作用域可判定,确认它是否该一直活着」。

demo 里 20 个窗口都先 release 再 scopeClose,所以 watch 候选是 0。如果先 scopeClose 再关通道,watch 的 release 仍然会成功,但 channel 那边会把 close 标成 lateClose;channel.test.ts 有一条用例专门把 close 放在 scopeClose 之后,断言 lateClose=1,另一条把 close 放在同一毫秒,断言 0。lateClose 本身不一定是泄漏,它先暴露的是清理顺序问题。

5.2 5 轮判定:baseline 取预热末轮

runLeakRepro 和 runMemoryRepro 共用 runCore:每轮 cycle → 可选 settle → 采样;baseline 取最后一个预热轮,测量轮逐轮算增量。完整实现如下:

// src/repro.ts
async function runCore<T>(options: CoreOptions<T>): Promise<CoreResult<T>> {
  if (typeof options.cycle !== 'function') {
    throw new TypeError('[leakscope] repro requires a cycle function');
  }
  const totalRounds = options.warmup + options.rounds;
  const samples: T[] = [];
  let preSample: T | undefined;
  let baselineSample: T | undefined;

  if (options.warmup === 0) {
    preSample = options.takeSample();
    baselineSample = preSample;
  }

  for (let index = 0; index < totalRounds; index += 1) {
    await options.cycle(index);
    if (options.settle) {
      await options.settle();
    }
    const sample = options.takeSample();
    samples.push(sample);
    if (index === options.warmup - 1) {
      baselineSample = sample;
    }
  }

  if (baselineSample === undefined) {
    baselineSample = samples[samples.length - 1] ?? options.takeSample();
  }
  const lastSample = samples[samples.length - 1] ?? baselineSample;
  const measuredSamples = options.warmup === 0 ? samples : samples.slice(options.warmup);
  const baselineMetric = options.metric(baselineSample);
  const budget = Math.max(0, finiteOr(options.budget, 0));
  const tolerance = Math.max(0, finiteOr(options.tolerance, 0));

  let previous = baselineMetric;
  const rounds: CoreRound<T>[] = measuredSamples.map((sample, index) => {
    const metric = options.metric(sample);
    const delta = metric - previous;
    previous = metric;
    const live = options.live(sample);
    return {
      index: index + 1,
      metric,
      delta,
      live: live.live,
      liveBytes: live.liveBytes,
      sample,
    };
  });

  const lastMetric = rounds.length > 0 ? (rounds[rounds.length - 1]?.metric ?? baselineMetric) : baselineMetric;
  const growth = lastMetric - baselineMetric;
  const slope = slopeOf(rounds.map((round) => round.metric));
  let verdict: ReproVerdict;
  if (rounds.length < 2) {
    verdict = 'insufficient-data';
  } else if (growth <= budget + tolerance) {
    verdict = 'stable';
  } else if (rounds.every((round) => round.delta >= -tolerance)) {
    verdict = 'leak';
  } else {
    verdict = 'noisy';
  }

  const attribution =
    options.attribute && (verdict === 'leak' || verdict === 'noisy')
      ? options.attribute(baselineSample, lastSample)
      : undefined;
  const perRound = rounds.length === 0 ? 0 : growth / rounds.length;

  return {
    verdict,
    metricName: options.metricName,
    baseline: baselineMetric,
    rounds,
    growth,
    perRound,
    slope,
    budget,
    suspiciousKind: attribution?.kind,
    suspiciousOwner: attribution?.owner,
    note: noteFor(verdict, growth, budget, tolerance, slope, rounds.length),
    samples,
    preSample,
    baselineSample,
    lastSample,
  };
}

几个细节单独说。warmup 为 0 时会在循环前先采一次 preSample,把第一次测量前的状态当 baseline;否则 baseline 是 index === warmup - 1 那一轮的样本。delta 只跟上一轮比(第一轮跟 baseline 比);相对 baseline 的累计值是 growth。slope 用最小二乘,x 从 1 开始,样本少于 2 个时直接返回 0。

判定顺序是有意排的:先看测量轮够不够,再看增长是否被 budget + tolerance 吸收,最后才看单调性。leak 要求每一轮 delta >= -tolerance,一次明显回落就降级成 noisy;noisy 只说明这组数据还判不了,不能当成没泄漏;先补 settle 再复测。

runLeakRepro 的默认指标是 snapshot.live,runMemoryRepro 的指标是 process.memoryUsage().heapUsed;两者在拿到 watch 台账时,都会在判定为 leak / noisy 时按 baseline 与末轮的 byKind / byOwner 增长最大者做归因。repro.test.ts 里的 leak 用例是真实断言:baseline=2,5 轮 metric 为 [3,4,5,6,7],growth=5,slope=1,suspiciousKind='object',suspiciousOwner='feed'。

settle 是宿主责任:setImmediate、requestAnimationFrame、await once(webContents, 'did-finish-load') 都行;异步清理没完成就采样,看到的是清理过程,还没到泄漏。

5.3 ImageMemoryLedger:按解码字节记账

nativeImage 的字节按解码尺寸算,磁盘上的 PNG/JPEG 大小不能直接拿来记账。bytesFor 先看显式 bytes,否则按 ceil(width × dpr) × ceil(height × dpr) × bpp 计算;nativeImageBytes 优先读 getBitmap() 的真实 buffer,toBitmap() 兜底,最后才回退到尺寸;planImageDecode 在解码前按 2 的幂降采样。落到账本上的是下面三个方法:

// src/image-memory.ts · ImageMemoryLedger 的三个方法
  retain(input: ImageRetainInput): ImageEntry {
    if (typeof input.key !== 'string' || input.key.length === 0) {
      throw new TypeError('[leakscope] image key must be a non-empty string');
    }
    const at = this.clock();
    const existing = this.entries.get(input.key);
    if (existing) {
      existing.refCount += 1;
      existing.lastUsed = at;
      this.duplicates += 1;
      return copyEntry(existing);
    }

    const bytes = bytesFor(input);
    const entry: ImageEntry = {
      key: input.key,
      width: numberOrZero(input.width),
      height: numberOrZero(input.height),
      format: formatOf(input.format),
      dpr: positiveDpr(input.dpr),
      bytes,
      owner: input.owner,
      refCount: 1,
      retainedAt: at,
      lastUsed: at,
    };
    this.entries.set(input.key, entry);
    this.liveBytes += bytes;
    this.peakBytes = Math.max(this.peakBytes, this.liveBytes);
    return copyEntry(entry);
  }

  release(key: string): boolean {
    const entry = this.entries.get(key);
    if (!entry) {
      return false;
    }
    entry.refCount -= 1;
    if (entry.refCount > 0) {
      return true;
    }
    this.entries.delete(key);
    this.liveBytes = Math.max(0, this.liveBytes - entry.bytes);
    return true;
  }

  evictTo(maxBytes: number): ImageEntry[] {
    const target = numberOrZero(maxBytes);
    const removed: ImageEntry[] = [];
    while (this.liveBytes > target && this.entries.size > 0) {
      const [oldestKey, oldest] = this.oldestEntry();
      this.entries.delete(oldestKey);
      this.liveBytes = Math.max(0, this.liveBytes - oldest.bytes);
      this.evictions += 1;
      removed.push(copyEntry(oldest));
    }
    return removed;
  }

retain 对同一个 key 做引用计数:第二次 retain 只把 refCount 加 1、duplicates 加 1,liveBytes 不重复计;release 减到 0 才移除条目;evictTo 按 lastUsed 做 LRU,淘汰时不管引用计数,整条移除并计入 evictions。LeakScope.image() 在 retain 之后检查预算,所以单张图本身就超过 imageBudget 时,它会在返回前被立刻淘汰。

demo 里的 512×512 RGBA 是 512 × 512 × 4 = 1,048,576 B,10 张就是 10.0 MB;如果换成 1600×900 的封面、dpr=2,全量是 3200 × 1800 × 4 = 23,040,000 B,约 22 MB;把 maxBytes 收到 16 MiB 再调 planImageDecode,它会按 2 的幂降到 1600 × 900,账本记 5,760,000 B。nativeImageBytes 读到 0 时不要硬算:已销毁或空的 NativeImage 可能让 getBitmap 抛错或返回 0 长度,此时看 watch 记录,别硬算字节。

5.4 ChannelLedger:每次 open 都要有 close

ipcMain.on、ipcMain.handle、EventEmitter.on、webContents / window 都是「打开有记录、关闭没记录」的同一个形状。ChannelLedger 用 dedupeKey 标记同一通道的重复注册,用 orphanAfterMs 标记长期 active,用 lateClose 标记作用域结束之后才关闭。IPC 和 EventEmitter 这两个 tracker 的完整实现:

// src/channel.ts
export function trackIpcMain(
  ipcMain: IpcMainLike,
  ledger: ChannelLedger,
  channel: string,
  listener: Listener,
  options: TrackIpcOptions = {},
): ChannelHandle {
  const mode = options.mode ?? 'on';
  const dedupeKey = `ipc-main:${mode}:${channel}`;
  const registerHandle = mode === 'handle' ? ipcMain.handle : undefined;
  if (mode === 'handle' && typeof registerHandle !== 'function') {
    throw new TypeError('[leakscope] ipcMain.handle is not available');
  }

  let registered = false;
  const release = () => {
    // A failed registration must not remove an existing handler/listener.
    if (!registered) {
      return;
    }
    if (mode === 'handle') {
      if (typeof ipcMain.removeHandler === 'function') {
        ipcMain.removeHandler(channel);
        return;
      }
      removeListenerOf(ipcMain, channel, listener);
      return;
    }
    removeListenerOf(ipcMain, channel, listener);
  };

  const handle = ledger.open({
    id: options.id ?? dedupeKey,
    kind: 'ipc-main',
    label: options.label ?? `ipcMain.${mode} ${channel}`,
    owner: options.owner,
    meta: { ...options.meta, channel, mode },
    dedupeKey,
    release,
  });

  try {
    if (registerHandle !== undefined) {
      registerHandle.call(ipcMain, channel, listener);
    } else {
      ipcMain.on(channel, listener);
    }
    registered = true;
  } catch (error) {
    // Record the failed/duplicate registration, then let Electron's error
    // propagate. Closing with `registered=false` is a no-op cleanup.
    ledger.close(handle.id);
    throw error;
  }
  return handle;
}

export function trackEmitter(
  emitter: EventEmitterLike,
  ledger: ChannelLedger,
  event: string,
  listener: Listener,
  options: TrackChannelOptions & { kind?: Extract<ChannelKind, 'event-emitter' | 'listener' | 'timer'> } = {},
): ChannelHandle {
  emitter.on(event, listener);
  return ledger.open({
    id: options.id,
    kind: options.kind ?? 'event-emitter',
    label: options.label ?? `emitter.on ${event}`,
    owner: options.owner,
    meta: { ...options.meta, event },
    release: () => removeListenerOf(emitter, event, listener),
  });
}

trackIpcMain 里有一个容易忽略的 registered 标志:底层注册抛错时,ledger.close(handle.id) 会执行,但 cleanup 看到 registered=false 就直接返回,不会误删已有的 handler/listener。handle 模式优先用 removeHandler(channel),因为 Electron 对同名 handler 的第二次注册会直接抛错,而 on 模式可以叠加。

trackEmitter 的 release 走 removeListenerOf:优先 off,其次 removeListener,都没有才退回 removeAllListeners(event)。demo 正好演示了最典型的累加:每轮 scope.ipc(ipcMain, 'demo:ping', () => undefined) 注册一个新监听器,owner 是 window-N;窗口 closed 时只关窗口 / webContents 句柄,不关这个 IPC 句柄。20 轮之后,channel 台账里有 20 条 active,越过 3 秒阈值后全部 orphan。修复只需要在 closed 里 ipcHandle.close(),或者 scope.channels.closeAll(owner);后者会真的调用 removeListener。

removeAllListeners 会把同一个 emitter 上别人的 listener 也一起删了,下一次事件可能直接没人接;所以这里宁可让每个注册都带一个 handle,也不把兜底清理当常规路径。

5.5 renderer 只发 JSON:差量写进主进程台账

renderer 侧不跑 LeakScope,只发每轮指标。createRendererReporter 做的是「差量同步」:新出现的图片 / 通道 retain / open,消失的 release / close,heapUsed 存成样本;同一个 round 重复上报会把 duplicateRound 置为 true。核心就是下面这个 report:

// src/adapters.ts · createRendererReporter 的 report 方法
report(metrics: RendererMetrics): RendererReportSummary {
  const owner = metrics.owner ?? options.owner ?? 'renderer';
  const at = metrics.at !== undefined && Number.isFinite(metrics.at) ? metrics.at : clock();
  const heapUsed = numberOrZero(metrics.heapUsed);
  const duplicateRound = lastRound !== undefined && metrics.round <= lastRound;
  const heapDelta = lastHeap === undefined ? 0 : heapUsed - lastHeap;

  // Images: retain only newly reported keys, drop keys that disappeared.
  const seenImages = new Set<string>();
  let imageBytes = 0;
  for (const image of metrics.images ?? []) {
    const metricKey = compositeKey(owner, image.key);
    const ledgerKey = imageLedgerKey(owner, image.key);
    seenImages.add(metricKey);
    imageBytes += bytesFor(image);
    if (!imageKeys.has(metricKey)) {
      options.images?.retain({
        key: ledgerKey,
        width: image.width,
        height: image.height,
        format: image.format,
        dpr: image.dpr,
        bytes: image.bytes,
        owner: image.owner ?? owner,
      });
      options.watch?.watch(ledgerKey, {
        kind: 'image',
        label: image.key,
        owner: image.owner ?? owner,
        bytes: bytesFor(image),
        meta: { renderer: owner, round: metrics.round },
      });
      imageKeys.set(metricKey, ledgerKey);
    } else {
      options.images?.touch(ledgerKey);
    }
  }
  for (const [metricKey, ledgerKey] of [...imageKeys]) {
    if (seenImages.has(metricKey)) {
      continue;
    }
    options.images?.release(ledgerKey);
    options.watch?.release(ledgerKey);
    imageKeys.delete(metricKey);
  }

  // Channels: open only new ids, close ids that disappeared this round.
  const seenChannels = new Set<string>();
  for (const [index, channel] of (metrics.channels ?? []).entries()) {
    const channelId = channel.id ?? `${channel.kind}:${channel.label ?? index}`;
    const metricKey = compositeKey(owner, channelId);
    const ledgerKey = channelLedgerKey(owner, channelId);
    seenChannels.add(metricKey);
    if (!channelKeys.has(metricKey)) {
      const handle = options.channels?.open({
        id: ledgerKey,
        kind: channel.kind as ChannelKind,
        label: channel.label ?? channelId,
        owner: channel.owner ?? owner,
        meta: { renderer: owner, round: metrics.round },
      });
      channelKeys.set(metricKey, handle?.id ?? ledgerKey);
    }
  }
  for (const [metricKey, ledgerId] of [...channelKeys]) {
    if (seenChannels.has(metricKey)) {
      continue;
    }
    options.channels?.close(ledgerId);
    channelKeys.delete(metricKey);
  }

  samples.push({ at, round: metrics.round, heapUsed });
  lastHeap = heapUsed;
  lastRound = metrics.round;

  return {
    round: metrics.round,
    at,
    owner,
    heapUsed,
    heapDelta,
    images: metrics.images?.length ?? 0,
    imageBytes,
    channels: metrics.channels?.length ?? 0,
    samples: samples.length,
    duplicateRound,
  };
}

图片和通道的 key 都带 owner 前缀(renderer:<owner>:image:<key> / renderer:<owner>:channel:<id>),compositeKey 再用 \u0000 把 owner 和 key 拼起来,避免两个 owner 下同名图片互相顶掉。新图片同时写 ImageMemoryLedger 和 LeakWatch,所以它既能算字节,也能进 watch 候选;消失的图片两边都释放。

通道这边只开记录,不注册 cleanup。原因很实际:主进程拿不到 renderer 的 ipcRenderer,没法替页面 removeListener。reporter 能做的是把「这一轮页面里还有哪些通道」记下来;off 必须在 renderer 卸载路径里执行。close 在这里只把主进程的账目关掉,两边要各自负责自己的那一半。

heapUsed 只存样本,不参与 runLeakRepro 的判定;runMemoryRepro 默认读的是主进程的 process.memoryUsage()。要把 renderer 的堆接进趋势,得由宿主把 reporter.samples() 转成自己的采样源,再决定用什么指标;库不替宿主做这个选择。

下面这条测试直接覆盖了「renderer 上报 → 主进程台账」的差量行为,包括第二轮资源消失后自动释放:

// __tests__/scope.test.ts
import { describe, expect, it } from 'vitest';
import { createRendererReporter } from '../src/adapters';
import { LeakScope } from '../src/scope';

function fakeClock(start = 0) {
  let current = start;
  return {
    now: () => current,
    advance: (ms: number) => {
      current += ms;
    },
  };
}

describe('LeakScope facade', () => {
  it('turns renderer round reports into ledger inputs and diffs removals', () => {
    const clock = fakeClock();
    const scope = new LeakScope({ now: clock.now });
    const reporter = createRendererReporter({
      owner: 'page-a',
      watch: scope.watcher,
      images: scope.images,
      channels: scope.channels,
      now: clock.now,
    });

    const first = reporter.report({
      round: 1,
      heapUsed: 1000,
      images: [{ key: 'cover', width: 100, height: 100, format: 'rgba8888' }],
      channels: [{ id: 'sub', kind: 'event-emitter', label: 'feed-sub' }],
    });
    expect(first).toMatchObject({
      round: 1,
      owner: 'page-a',
      heapUsed: 1000,
      heapDelta: 0,
      images: 1,
      imageBytes: 40000,
      channels: 1,
      samples: 1,
      duplicateRound: false,
    });
    expect(scope.images.stats().entries).toBe(1);
    expect(scope.watcher.snapshot().live).toBe(1);
    expect(scope.channels.audit().active).toHaveLength(1);

    clock.advance(100);
    const second = reporter.report({ round: 2, heapUsed: 1500 });
    expect(second).toMatchObject({
      heapDelta: 500,
      images: 0,
      channels: 0,
      samples: 2,
      duplicateRound: false,
    });
    expect(scope.images.stats().entries).toBe(0);
    expect(scope.watcher.snapshot().live).toBe(0);
    expect(scope.channels.audit().active).toEqual([]);
    expect(reporter.latest()).toEqual({ at: 100, round: 2, heapUsed: 1500 });

    const duplicate = reporter.report({ round: 2, heapUsed: 1500 });
    expect(duplicate.duplicateRound).toBe(true);
    expect(reporter.samples()).toHaveLength(3);
  });
});

三轮上报串起来看:第一轮上报 100×100 的 rgba8888 图片,imageBytes 是 40000;第二轮只报 heapUsed,图片和通道都从 payload 里消失,scope.images.stats().entries、scope.watcher.snapshot().live、scope.channels.audit().active 全部归零;第三轮重复 round: 2,duplicateRound 变成 true,样本数继续增加。没有 Electron 对象跨进程,测试也不需要 Electron 运行时。

5.6 报告:同样输入,同样字节

renderLeakReport 的目标是可归档、可比较、可进 golden test。所有集合先排序再输出,缺省数据渲染空表,建议最多 4 条:

// src/report.ts
export function renderLeakReport(input: LeakReportInput): string {
  const topN = Math.max(1, Math.floor(input.topN ?? 5));
  const snapshot = input.snapshot;
  const candidates = input.candidates ?? [];
  const images: ImageMemoryStats = input.images ?? {
    entries: 0,
    liveBytes: 0,
    peakBytes: 0,
    duplicates: 0,
    evictions: 0,
    byFormat: {},
  };
  const audit = input.audit;
  const offenders = offendersOf(input)
    .sort((a, b) => b.bytes - a.bytes || b.liveMs - a.liveMs || a.key.localeCompare(b.key))
    .slice(0, topN);

  const lines: string[] = [
    `## LeakScope 报告 · ${input.title}`,
    '',
    ...table(
      ['指标', '值'],
      [
        ['存活资源', `${snapshot.live}`],
        ['存活字节', formatBytes(snapshot.liveBytes)],
        ['已释放', `${snapshot.released}`],
        ['泄漏候选', `${candidates.length}`],
        ['复现结论', reproSummary(input.repro)],
        ['通道孤儿', `${audit?.orphans.length ?? 0}`],
      ],
    ),
    '',
    '### Top offenders',
    '',
    ...table(
      ['资源', '类型', 'owner', '存活(ms)', '字节'],
      offenders.map((offender) => [
        offender.key,
        offender.kind,
        ownerOf(offender.owner),
        `${offender.liveMs}`,
        formatBytes(offender.bytes),
      ]),
    ),
    '',
    '### 复现明细',
    '',
  ];

  if (input.repro) {
    const repro = input.repro;
    lines.push(
      ...table(
        ['轮次', '指标', '增量'],
        repro.rounds.map((round) => [
          `${round.index}`,
          formatMetric(round.metric, repro.metricName),
          formatSigned(round.delta, repro.metricName),
        ]),
      ),
    );
  } else {
    lines.push('未运行 `runLeakRepro`。');
  }

  lines.push(
    '',
    '### 图片内存',
    '',
    ...table(
      ['指标', '值'],
      [
        ['条目', `${images.entries}`],
        ['存活', formatBytes(images.liveBytes)],
        ['峰值', formatBytes(images.peakBytes)],
        ['重复引用', `${images.duplicates}`],
        ['淘汰', `${images.evictions}`],
      ],
    ),
    '',
    '### 通道审计',
    '',
    ...table(
      ['通道', '类型', 'owner', '状态', '存活(ms)'],
      channelRows(audit, snapshot.at, topN),
    ),
    '',
    '### 建议',
    '',
    ...recommendations(input).map((item, index) => `${index + 1}. ${item}`),
  );

  return `${lines.join('\n')}\n`;
}

topN 只截断 Top offenders 和通道审计,不截断计数;formatBytes 按 < 1 MiB → KB、< 1 GiB → MB、否则 GB,保留 1 位小数;Top offenders 按字节、存活时间、key 排序;通道按「orphan 优先、存活时间降序、id 升序」排序;建议按「作用域未释放 → 重复 key → 通道 orphan / lateClose → 复现结论 → 图片重复引用 → stale」生成,最多 4 条。

报告里唯一的“时间”来自输入里的 snapshot.at,渲染函数本身不读 Date.now,也不写生成时间。report.test.ts 的确定性用例把同一份输入渲染两次,直接用 toBe 比较两个完整字符串;同一文件还锁了空场景、topN 和 formatBytes 的边界。相同输入得到字节相同的 markdown,这也是它能直接进 CI 的原因。

6. 开发与取证时遇到的几件事

最初只看主进程的 process.memoryUsage().heapUsed,20 轮窗口往返的曲线来回跳,给不出可判定的信号。renderer 的 V8 堆在主进程里读不到,只能让 renderer 每轮把 JSON 发上来,主进程用 createRendererReporter 存成样本,再和 channel 台账对齐。单次采样也不够:V8 的 scavenge、页面缓存、图片解码都会让数字上下跳,预热 2 轮、测量 5 轮,看净增长、单调性和斜率;一次回落就降级 noisy。settle 要等页面清理完成,异步清理没做完就采样,看到的是清理过程,还没到泄漏。

窗口和 webContents 是另一条线。BrowserWindow 的 closed 只销毁原生窗口,JS 对象还可能被闭包、监听器或模块级变量拿着。窗口创建时同时登记 window 和 webContents,closed 里依次 contentsHandle.close()、windowHandle.close()、release、scopeClose。顺序反过来,channel 会记成 lateClose。trackWebContents 故意不自动销账,因为它不知道宿主还要不要 destroy(),遗漏的生命周期调用应该暴露成 orphan。

ipcMain 的 listener 是 demo 里故意留下的泄漏,也是真实项目最常见的形态:每轮 scope.ipc(ipcMain, 'demo:ping', () => undefined) 注册一个新监听器,从不移除,20 轮之后 demo:ping 的 listenerCount 就是 20。ChannelLedger 用 dedupeKey = ipc-main:on:demo:ping 把重复注册标成 duplicate,audit().orphans 再列出“窗口关了但监听器还活着”。修法是窗口级 IPC 保存 ChannelHandle,closed 里 close(),或者 closeAll(owner) 一次收口;removeAllListeners 只是掩盖,下一次注册照样从头开始。

图片按解码字节记账,磁盘上的 PNG/JPEG 大小不能直接拿来用。512×512 的 RGBA 是 512 × 512 × 4 = 1,048,576 B,10 张就是 10 MB;一个 200 KB 的 PNG 解码后可能是 22 MB。nativeImageBytes 先读 getBitmap() 的真实 buffer,toBitmap() 兜底;已销毁或空的 NativeImage 可能让 getBitmap 抛错或返回 0 长度,这时看 watch 记录,别硬算。planImageDecode 在解码前降采样,ImageMemoryLedger 管引用计数和 LRU,窗口关闭时 releaseImage。

模拟器还有两类宿主问题。2in1 模拟器里 Electron-OH 的硬件渲染撑不起 Chromium 合成,Chromium 内容可能不显示或黑屏;harmony/app/main.js 默认 disableHardwareAcceleration() + --use-gl=swiftshader + --disable-gpu-compositing,LEAKSCOPE_GPU=1 可以关掉这组开关。HAP 安装报 9568289 是 ACL 缺失:社区宿主的 web_engine 声明了 6 个需要 system_basic / ACL 的权限,本机调试 profile 没有 ACL;harmony/scripts/patch-host.mjs 会在注入后裁掉这 6 个权限,并同步修改 bundleName 和应用名。社区宿主 37.2.1 低于 peer 的 40,能跑是因为库不 import electron、demo 只用标准 Node/JS 能力;37.2.1 只是这次宿主版本,标准 Electron 的 peer 仍按 40+ 声明。

7. 安装、构建与设备取证

工程是「npm 库 + 鸿蒙宿主包装」双形态交付(npm 包名 leakscope-electron,版本 1.0.0,Apache-2.0)。安装与自检:

npm install leakscope-electron
npm run verify      # typecheck + 48 个测试 + build
npm pack --json     # 67,385 B / 44 files

verify 最近一次的真实输出是 6 个测试文件全过:

 ✓ __tests__/report.test.ts (5 tests) 2ms
 ✓ __tests__/image-memory.test.ts (9 tests) 3ms
 ✓ __tests__/watch.test.ts (9 tests) 2ms
 ✓ __tests__/repro.test.ts (8 tests) 3ms
 ✓ __tests__/channel.test.ts (12 tests) 7ms
 ✓ __tests__/scope.test.ts (5 tests) 9ms

 Test Files  6 passed (6)
      Tests  48 passed (48)

electron 是 optional peer,由宿主应用提供;本仓库不安装运行时。桌面 demo 需要先自己装 Electron:

npm i -D electron
npm run demo        # 20 次窗口往返,输出报告与 [leakscope demo] summary

鸿蒙 2in1 的构建、签名、安装与启动由 harmony/scripts/build-run.sh 串起来:

# 前置:模拟器已启动;hdc list targets 能看到 127.0.0.1:5555
cp harmony/signing/authorized-signing.example.json \
   harmony/signing/authorized-signing.local.json   # 填真实值

./harmony/scripts/build-run.sh --launch

# 取证:报告写在 userData(HarmonyOS 上是 /data/storage/el2/base/files/)
hdc file recv /data/storage/el2/base/files/leakscope-report.md \
  harmony/evidence/leakscope-report.md

本次端到端结果:HAP 205,628,595 B(已签名),20 轮窗口往返,active channels 20 / orphans 20 / image entries 10 / liveBytes 10.0 MB / failures 0,设备端通道审计给出了同一组数字;模拟器上每轮约 3.2 秒。设备日志里能看到 AppWindowAdapter#setTitle 一轮一轮地切换 leakscope-electron-ohos-demo 与 LeakScope · Electron demo——这就是 20 个隐藏窗口的往返轨迹。

更完整的 API、阈值与误报说明、ArkWeb / ArkTS 宿主的接入边界在仓库文档里:

  • 仓库说明:完整 API、快速开始、报告格式、阈值与误报;
  • OpenHarmony 接入说明:OpenHarmony 接入边界、ArkTS 上报示例、不能声称的事;
  • 泄漏分类文档:七类 Electron 泄漏的症状 / 定位 / 修复;
  • 验证与包检查记录:构建、测试、npm pack 的结果;
  • 2in1 宿主说明:构建、签名、权限裁剪与取证步骤。

边界也要写清楚:本库只记录登记过的生命周期,不做 GC 可达性证明,不覆盖 GPU 显存和原生堆;createRendererReporter 只接收上报,采集要宿主自己做;trackWindow / trackIpcMain 依赖 Electron 等价对象,ArkWeb-only 宿主不能直接套用。

这次验证停在模拟器:真机、Windows、Linux、ArkWeb-only 宿主都还没跑。库能确定的是登记过的生命周期,和同一份输入渲染出的同一份报告;不能确定的是没登记的对象、GPU 显存,以及 GC 什么时候回收。20 个孤儿留在设备报告里,是这轮跑完留下的一条实测记录。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐