Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

👷 ci: add bundle size gate for web dist and desktop asar (#17970)

Inneidf629b17ee00
diff --git a/.github/scripts/bundle-size-gate.cjs b/.github/scripts/bundle-size-gate.cjs
new file mode 100644
index 00000000000..c6afac1e965
--- /dev/null
+++ b/.github/scripts/bundle-size-gate.cjs
@@ -0,0 +1,226 @@
+#!/usr/bin/env node
+/**
+ * Bundle size gate: measure build artifacts and compare PR sizes against a
+ * baseline artifact uploaded by canary branch builds.
+ *
+ * Usage:
+ * node bundle-size-gate.js measure --type <web|asar> --out <file.json>
+ * node bundle-size-gate.js check --current <file.json> --baseline <file.json> [--label <name>] [--report <file.md>]
+ *
+ * Thresholds (env):
+ * SIZE_GATE_PERCENT max allowed increase in percent (default 3)
+ * SIZE_GATE_FLOOR_BYTES min absolute increase before failing (default 512 KiB)
+ *
+ * An entry fails when: increase > max(baseline * percent / 100, floor).
+ * Missing baseline or missing current report degrades to a warning + exit 0,
+ * so the gate never blocks before the first baseline exists.
+ */
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+const WEB_TARGETS = ['dist/desktop', 'dist/auth', 'dist/workbench'];
+const ASAR_SEARCH_ROOT = 'apps/desktop/release';
+
+const die = (message) => {
+ console.error(`❌ ${message}`);
+ process.exit(1);
+};
+
+const parseArgs = (argv) => {
+ const args = { _: [] };
+ for (let i = 0; i < argv.length; i += 1) {
+ const arg = argv[i];
+ if (arg.startsWith('--')) {
+ args[arg.slice(2)] = argv[i + 1];
+ i += 1;
+ } else {
+ args._.push(arg);
+ }
+ }
+ return args;
+};
+
+const dirSize = (dir) => {
+ let total = 0;
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) total += dirSize(full);
+ else if (entry.isFile()) total += fs.statSync(full).size;
+ }
+ return total;
+};
+
+/** Normalize runner os/arch so matrix naming differences (macos-latest vs macos-15) don't matter. */
+const normalizedPlatform = () => {
+ const platform = os.platform();
+ const arch = os.arch();
+ if (platform === 'darwin') return arch === 'arm64' ? 'macos-arm64' : 'macos-x64';
+ if (platform === 'win32') return 'windows-x64';
+ return `linux-${arch}`;
+};
+
+/** Recursively find app.asar, skipping extracted `*.asar.unpacked` directories. */
+const findAsar = (root) => {
+ const stack = [root];
+ while (stack.length > 0) {
+ const current = stack.pop();
+ let entries;
+ try {
+ entries = fs.readdirSync(current, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ const full = path.join(current, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name.endsWith('.asar.unpacked')) continue;
+ stack.push(full);
+ } else if (entry.isFile() && entry.name === 'app.asar') {
+ return full;
+ }
+ }
+ }
+ return null;
+};
+
+const measure = (args) => {
+ const { type, out } = args;
+ if (!type || !out) die('measure requires --type <web|asar> and --out <file.json>');
+
+ let result;
+ if (type === 'web') {
+ const sizes = {};
+ for (const target of WEB_TARGETS) {
+ if (!fs.existsSync(target)) {
+ console.warn(`⚠️ ${target} not found, skipping`);
+ continue;
+ }
+ sizes[target] = dirSize(target);
+ }
+ if (Object.keys(sizes).length === 0) die('no dist targets found — did the build run?');
+ sizes.total = Object.values(sizes).reduce((sum, size) => sum + size, 0);
+ result = { sizes, type };
+ } else if (type === 'asar') {
+ const asarPath = findAsar(ASAR_SEARCH_ROOT);
+ if (!asarPath) die(`app.asar not found under ${ASAR_SEARCH_ROOT}`);
+ result = {
+ path: asarPath,
+ platform: normalizedPlatform(),
+ sizes: { 'app.asar': fs.statSync(asarPath).size },
+ type,
+ };
+ } else {
+ die(`unknown --type "${type}" (expected web|asar)`);
+ }
+
+ fs.mkdirSync(path.dirname(out), { recursive: true });
+ fs.writeFileSync(out, JSON.stringify(result, null, 2));
+ console.log(`📦 measured ${type} sizes -> ${out}`);
+ for (const [key, size] of Object.entries(result.sizes)) {
+ console.log(` ${key}: ${humanSize(size)}`);
+ }
+};
+
+const humanSize = (bytes) => {
+ if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
+ return `${(bytes / 1024).toFixed(1)} KB`;
+};
+
+const formatDelta = (delta, baseline) => {
+ const sign = delta > 0 ? '+' : delta < 0 ? '-' : '';
+ const percent = baseline > 0 ? ` (${sign}${((delta / baseline) * 100).toFixed(2)}%)` : '';
+ return `${sign}${humanSize(Math.abs(delta))}${percent}`;
+};
+
+const appendReport = (file, section) => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.appendFileSync(file, `${section}\n\n`);
+};
+
+const check = (args) => {
+ const { current, baseline, label = 'Bundle', report } = args;
+ if (!current) die('check requires --current <file.json>');
+
+ // Emit a visible "skipped" section so the PR comment / step summary explain
+ // why the gate passed instead of falling back to a misleading placeholder.
+ const skipWithNotice = (reason) => {
+ const section = `### ⚠️ ${label}\n\n${reason}\n\n> Gate skipped — no failure is reported.`;
+ console.warn(`\n${section}\n`);
+ if (report) appendReport(report, section);
+ if (process.env.GITHUB_STEP_SUMMARY) appendReport(process.env.GITHUB_STEP_SUMMARY, section);
+ };
+
+ if (!fs.existsSync(current)) {
+ skipWithNotice(
+ `Current size report \`${current}\` not found — the measure step did not produce it.`,
+ );
+ return;
+ }
+ const currentSizes = JSON.parse(fs.readFileSync(current, 'utf8')).sizes || {};
+
+ if (!baseline || !fs.existsSync(baseline)) {
+ skipWithNotice(
+ `No baseline found (\`${baseline || '(not provided)'}\`). This is expected on first rollout or after baseline artifacts expire — the gate activates once a canary build publishes a baseline.`,
+ );
+ return;
+ }
+ const baselineSizes = JSON.parse(fs.readFileSync(baseline, 'utf8')).sizes || {};
+
+ const percent = Number(process.env.SIZE_GATE_PERCENT || 3);
+ const floor = Number(process.env.SIZE_GATE_FLOOR_BYTES || 512 * 1024);
+
+ const keys = [...new Set([...Object.keys(baselineSizes), ...Object.keys(currentSizes)])];
+ const rows = [];
+ let failed = false;
+
+ for (const key of keys) {
+ const base = baselineSizes[key];
+ const cur = currentSizes[key];
+ if (base === undefined) {
+ rows.push(`| ${key} | — | ${humanSize(cur)} | 🆕 new | ✅ |`);
+ continue;
+ }
+ if (cur === undefined) {
+ rows.push(`| ${key} | ${humanSize(base)} | — | removed | ✅ |`);
+ continue;
+ }
+ const delta = cur - base;
+ const limit = Math.max((base * percent) / 100, floor);
+ const over = delta > limit;
+ if (over) failed = true;
+ rows.push(
+ `| ${key} | ${humanSize(base)} | ${humanSize(cur)} | ${formatDelta(delta, base)} | ${over ? '❌' : '✅'} |`,
+ );
+ }
+
+ const section = [
+ `### ${failed ? '❌' : '✅'} ${label}`,
+ '',
+ `| Entry | Baseline | Current | Δ | Result |`,
+ `| --- | --- | --- | --- | --- |`,
+ ...rows,
+ '',
+ `> Gate: fails when increase > max(${percent}% of baseline, ${humanSize(floor)}). Baseline: latest canary build.`,
+ ].join('\n');
+
+ console.log(`\n${section}\n`);
+
+ if (report) appendReport(report, section);
+ if (process.env.GITHUB_STEP_SUMMARY) appendReport(process.env.GITHUB_STEP_SUMMARY, section);
+
+ if (failed) {
+ console.error(
+ `❌ ${label} size increase exceeds the gate threshold (+${percent}% / +${humanSize(floor)}). ` +
+ 'Inspect the added dependencies or assets, or adjust SIZE_GATE_PERCENT / SIZE_GATE_FLOOR_BYTES if this is expected.',
+ );
+ process.exit(1);
+ }
+};
+
+const [command, ...rest] = process.argv.slice(2);
+const args = parseArgs(rest);
+
+if (command === 'measure') measure(args);
+else if (command === 'check') check(args);
+else die('usage: bundle-size-gate.js <measure|check> [--flags]');
diff --git a/.github/scripts/find-size-baseline.cjs b/.github/scripts/find-size-baseline.cjs
new file mode 100644
index 00000000000..db54699101d
--- /dev/null
+++ b/.github/scripts/find-size-baseline.cjs
@@ -0,0 +1,48 @@
+/**
+ * Find the most recent successful `canary` push run of a workflow that
+ * contains a given size-baseline artifact, and return its run id (or '' when
+ * none exists). Used with actions/download-artifact's `run-id` input:
+ *
+ * const finder = require('<workspace>/.github/scripts/find-size-baseline.js');
+ * return await finder({ github, context, workflowId: 'e2e.yml', artifactName: 'bundle-size-baseline-web' });
+ *
+ * The returned string becomes the step's `result` output (empty string = no
+ * baseline yet, callers should skip the download step and let the gate degrade
+ * to a warning).
+ */
+const findSizeBaseline = async ({ github, context, workflowId, artifactName, artifactPrefix }) => {
+ const { data } = await github.rest.actions.listWorkflowRuns({
+ branch: 'canary',
+ event: 'push',
+ owner: context.repo.owner,
+ per_page: 20,
+ repo: context.repo.repo,
+ status: 'success',
+ workflow_id: workflowId,
+ });
+
+ for (const run of data.workflow_runs) {
+ const { data: artifacts } = await github.rest.actions.listWorkflowRunArtifacts({
+ owner: context.repo.owner,
+ per_page: 100,
+ repo: context.repo.repo,
+ run_id: run.id,
+ });
+
+ const match = artifacts.artifacts.find((artifact) =>
+ artifactName ? artifact.name === artifactName : artifact.name.startsWith(artifactPrefix),
+ );
+
+ if (match) {
+ console.log(`Found baseline artifact "${match.name}" in run ${run.id} (${run.created_at})`);
+ return String(run.id);
+ }
+ }
+
+ console.warn(
+ `No baseline artifact found in recent canary runs of ${workflowId} — gate will skip.`,
+ );
+ return '';
+};
+
+module.exports = findSizeBaseline;
diff --git a/.github/scripts/size-gate-comment.cjs b/.github/scripts/size-gate-comment.cjs
new file mode 100644
index 00000000000..f328325d4e4
--- /dev/null
+++ b/.github/scripts/size-gate-comment.cjs
@@ -0,0 +1,54 @@
+/**
+ * Upsert a PR comment with the bundle size gate report.
+ * Follows the same identifier-based update-or-create pattern as pr-comment.js.
+ *
+ * Usage (inside actions/github-script):
+ * const comment = require('<workspace>/.github/scripts/size-gate-comment.cjs');
+ * await comment({ github, context, title: 'Web dist', report, failed, identifier: 'web' });
+ *
+ * `identifier` keeps one comment per gate: the web (e2e) and desktop (asar)
+ * workflows run independently on the same PR and must not overwrite each other.
+ */
+const sizeGateComment = async ({ github, context, title, report, failed, identifier }) => {
+ if (!identifier)
+ throw new Error('sizeGateComment requires an `identifier` (e.g. "web" | "asar")');
+ const commentIdentifier = `<!-- SIZE-GATE-COMMENT-${identifier} -->`;
+
+ const body = `${commentIdentifier}
+### ${failed ? '❌' : '✅'} Bundle Size Gate — ${title}
+
+${report}
+
+---
+*Baseline: latest \`canary\` build (workflow artifact). Thresholds configurable via \`SIZE_GATE_PERCENT\` / \`SIZE_GATE_FLOOR_BYTES\`.*`;
+
+ const { data: comments } = await github.rest.issues.listComments({
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ });
+
+ const existing = comments.find((comment) => comment.body.includes(commentIdentifier));
+
+ if (existing) {
+ await github.rest.issues.updateComment({
+ body,
+ comment_id: existing.id,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ });
+ console.log(`Updated existing comment ID: ${existing.id}`);
+ return { id: existing.id, updated: true };
+ }
+
+ const result = await github.rest.issues.createComment({
+ body,
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ });
+ console.log(`Created new comment ID: ${result.data.id}`);
+ return { id: result.data.id, updated: false };
+};
+
+module.exports = sizeGateComment;
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 208c490e3d6..a0247a04aea 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -5,6 +5,7 @@ on: [push, pull_request]
permissions:
actions: write
contents: read
+ pull-requests: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -91,6 +92,64 @@ jobs:
env:
SKIP_LINT: '1'
+ # ===== Bundle size gate (web dist) =====
+ # Baseline: artifact uploaded by the latest successful canary push run of this workflow.
+ - name: Find latest canary baseline run
+ if: github.event_name == 'pull_request'
+ id: baseline_run
+ uses: actions/github-script@v8
+ with:
+ # github-script JSON-encodes return values by default; we need the raw run id string
+ result-encoding: string
+ script: |
+ const finder = require('${{ github.workspace }}/.github/scripts/find-size-baseline.cjs');
+ return await finder({ github, context, workflowId: 'e2e.yml', artifactName: 'bundle-size-baseline-web' });
+
+ - name: Download web dist size baseline
+ if: github.event_name == 'pull_request' && steps.baseline_run.outputs.result != ''
+ uses: actions/download-artifact@v7
+ with:
+ name: bundle-size-baseline-web
+ path: .size-baseline/
+ run-id: ${{ steps.baseline_run.outputs.result }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Measure web dist size
+ run: node .github/scripts/bundle-size-gate.cjs measure --type web --out size-report/web.json
+
+ - name: Upload web dist size baseline (canary only)
+ if: github.event_name == 'push' && github.ref == 'refs/heads/canary'
+ uses: actions/upload-artifact@v6
+ with:
+ name: bundle-size-baseline-web
+ path: size-report/web.json
+ retention-days: 30
+
+ - name: Check web dist size against baseline
+ if: github.event_name == 'pull_request'
+ id: dist_size_check
+ run: node .github/scripts/bundle-size-gate.cjs check --current size-report/web.json --baseline .size-baseline/web.json --label "Web dist" --report size-report/report.md
+
+ - name: Comment bundle size report on PR
+ if: always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
+ uses: actions/github-script@v8
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ script: |
+ const fs = require('node:fs');
+ const report = fs.existsSync('size-report/report.md')
+ ? fs.readFileSync('size-report/report.md', 'utf8')
+ : 'Build did not reach the size gate step.';
+ const comment = require('${{ github.workspace }}/.github/scripts/size-gate-comment.cjs');
+ await comment({
+ github,
+ context,
+ title: 'Web dist',
+ report,
+ failed: ${{ steps.dist_size_check.outcome == 'failure' }},
+ identifier: 'web',
+ });
+
- name: Start E2E server
run: |
bunx next start -p 3006 > /tmp/lobehub-e2e-server.log 2>&1 &
diff --git a/.github/workflows/pr-build-desktop.yml b/.github/workflows/pr-build-desktop.yml
index b176b686766..9a05339af1b 100644
--- a/.github/workflows/pr-build-desktop.yml
+++ b/.github/workflows/pr-build-desktop.yml
@@ -11,6 +11,7 @@ concurrency:
# Add default permissions
permissions:
+ actions: read # 跨 run 下载 canary 基线 artifact 需要
contents: write
pull-requests: write
@@ -191,6 +192,22 @@ jobs:
ls -la latest*.yml || echo "No latest*.yml files found"
fi
+ # 测量 app.asar 大小,供 ASAR size gate 与 canary 基线对比
+ - name: Measure ASAR size
+ id: asar_size
+ shell: bash
+ run: |
+ node .github/scripts/bundle-size-gate.cjs measure --type asar --out size-report/asar.json
+ platform=$(node -p "require('./size-report/asar.json').platform")
+ mv size-report/asar.json "size-report/asar-${platform}.json"
+
+ - name: Upload ASAR size report
+ uses: actions/upload-artifact@v6
+ with:
+ name: asar-size-${{ matrix.os }}
+ path: size-report/
+ retention-days: 1
+
# 上传构建产物
- name: Upload artifact
uses: actions/upload-artifact@v6
@@ -208,6 +225,76 @@ jobs:
apps/desktop/release/*.tar.gz*
retention-days: 5
+ # ASAR 包体积门禁:与 canary 基线对比,超阈值 fail
+ asar-size-gate:
+ needs: [build]
+ name: ASAR Size Gate
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Download ASAR size reports
+ uses: actions/download-artifact@v7
+ with:
+ path: size-reports
+ pattern: asar-size-*
+ merge-multiple: true
+
+ # 基线:release-desktop-canary 最近一次成功 run 上传的 asar-size-baseline-* artifacts
+ - name: Find latest canary baseline run
+ id: baseline_run
+ uses: actions/github-script@v8
+ with:
+ # github-script JSON-encodes return values by default; we need the raw run id string
+ result-encoding: string
+ script: |
+ const finder = require('${{ github.workspace }}/.github/scripts/find-size-baseline.cjs');
+ return await finder({ github, context, workflowId: 'release-desktop-canary.yml', artifactPrefix: 'asar-size-baseline-' });
+
+ - name: Download ASAR size baselines
+ if: steps.baseline_run.outputs.result != ''
+ uses: actions/download-artifact@v7
+ with:
+ pattern: asar-size-baseline-*
+ merge-multiple: true
+ path: .size-baseline
+ run-id: ${{ steps.baseline_run.outputs.result }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Check ASAR sizes against baseline
+ id: asar_size_check
+ shell: bash
+ run: |
+ status=0
+ for platform in macos-arm64 macos-x64 windows-x64 linux-x64; do
+ node .github/scripts/bundle-size-gate.cjs check \
+ --current "size-reports/asar-${platform}.json" \
+ --baseline ".size-baseline/asar-size-baseline-${platform}.json" \
+ --label "ASAR (${platform})" \
+ --report size-reports/report.md || status=1
+ done
+ exit $status
+
+ - name: Comment ASAR size report on PR
+ if: always() && github.event.pull_request.head.repo.full_name == github.repository
+ uses: actions/github-script@v8
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ script: |
+ const fs = require('node:fs');
+ const report = fs.existsSync('size-reports/report.md')
+ ? fs.readFileSync('size-reports/report.md', 'utf8')
+ : 'Build did not reach the size gate step.';
+ const comment = require('${{ github.workspace }}/.github/scripts/size-gate-comment.cjs');
+ await comment({
+ github,
+ context,
+ title: 'Desktop ASAR',
+ report,
+ failed: ${{ steps.asar_size_check.outcome == 'failure' }},
+ identifier: 'asar',
+ });
+
# 合并 macOS 多架构 latest-mac.yml 文件
merge-mac-files:
needs: [build, version]
diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.yml
index 8a5cc7862a8..134ea5f551a 100644
--- a/.github/workflows/release-desktop-canary.yml
+++ b/.github/workflows/release-desktop-canary.yml
@@ -287,6 +287,23 @@ jobs:
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
+ # 测量 app.asar 大小并上传为基线 artifact(PR 的 ASAR size gate 用它做对比)
+ - name: Measure ASAR size
+ id: asar_size
+ shell: bash
+ run: |
+ node .github/scripts/bundle-size-gate.cjs measure --type asar --out size-report/asar.json
+ platform=$(node -p "require('./size-report/asar.json').platform")
+ mv size-report/asar.json "size-report/asar-size-baseline-${platform}.json"
+ echo "platform=${platform}" >> "$GITHUB_OUTPUT"
+
+ - name: Upload ASAR size baseline
+ uses: actions/upload-artifact@v6
+ with:
+ name: asar-size-baseline-${{ steps.asar_size.outputs.platform }}
+ path: size-report/asar-size-baseline-${{ steps.asar_size.outputs.platform }}.json
+ retention-days: 30
+
- name: Upload artifacts
uses: ./.github/actions/desktop-upload-artifacts
with: