Skip to content

The agent that grows with you

fix(build): reuse cached desktop npm dependencies

ethernet6380a4e0ab5d
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.yml
index 7be775c28d4..240f25f201f 100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@ -402,8 +402,9 @@ jobs:
restore-keys: |
eb2-${{ runner.os }}-${{ runner.arch }}-
- - name: Cache node_modules
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ - name: Restore prepared desktop dependencies
+ id: node-modules-cache
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
node_modules
@@ -412,25 +413,27 @@ jobs:
ui-tui/packages/*/node_modules
web/node_modules
tests-js/node_modules
- key: node-modules-${{ matrix.target.label }}-node${{ steps.pm.outputs.node-version }}-npm${{ steps.pm.outputs.npm-version }}-${{ hashFiles('package-lock.json') }}
- # npm ci rm -rf's node_modules before installing, so a restore is
- # never shipped stale — but a restore-key hit still makes the
- # reinstall incremental (postinstall outputs like node-pty's
- # prebuilds/ and esbuild's platform binary survive in place).
- # The build-bundled install-stamp gate (lock sha + node + npm +
- # target) is the real guard against stale trees shipping.
- restore-keys: |
- node-modules-${{ matrix.target.label }}-node${{ steps.pm.outputs.node-version }}-npm${{ steps.pm.outputs.npm-version }}-
+ # No partial restore: npm ci deletes both the tree and native outputs.
+ key: desktop-node-deps-v1-${{ matrix.target.label }}-node${{ steps.pm.outputs.node-version }}-npm${{ steps.pm.outputs.npm-version }}-${{ hashFiles('package-lock.json', 'package.json', 'apps/*/package.json', 'ui-tui/package.json', 'ui-tui/packages/*/package.json', 'web/package.json', 'tests-js/package.json', '.npmrc', 'scripts/build/node-deps.mjs') }}
- - name: Cache node-pty prebuilds (postinstall output, emulated-gyp tax on arm64)
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ - name: Prepare desktop dependencies
+ shell: bash
+ run: node scripts/build/node-deps.mjs --source . --workspace apps/desktop --workspace ui-tui --workspace web --reuse
+
+ # Save before packaging: a later build/signing failure must not lose this work,
+ # and builder mutations must not become the next job's dependency input.
+ - name: Save prepared desktop dependencies
+ if: steps.node-modules-cache.outputs.cache-hit != 'true'
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
- node_modules/node-pty/prebuilds
- node_modules/node-pty/build
- key: node-pty-prebuilds-${{ matrix.target.label }}-${{ hashFiles('package-lock.json') }}
- restore-keys: |
- node-pty-prebuilds-${{ matrix.target.label }}-
+ node_modules
+ apps/*/node_modules
+ ui-tui/node_modules
+ ui-tui/packages/*/node_modules
+ web/node_modules
+ tests-js/node_modules
+ key: ${{ steps.node-modules-cache.outputs.cache-primary-key }}
- name: Azure login (OIDC)
if: vars.AZURE_CLIENT_ID != ''
@@ -663,8 +666,9 @@ jobs:
restore-keys: |
eb2-${{ runner.os }}-${{ runner.arch }}-
- - name: Cache node_modules
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ - name: Restore prepared desktop dependencies
+ id: node-modules-cache
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
node_modules
@@ -673,25 +677,27 @@ jobs:
ui-tui/packages/*/node_modules
web/node_modules
tests-js/node_modules
- key: node-modules-${{ matrix.target.label }}-node${{ steps.pm.outputs.node-version }}-npm${{ steps.pm.outputs.npm-version }}-${{ hashFiles('package-lock.json') }}
- # npm ci rm -rf's node_modules before installing, so a restore is
- # never shipped stale — but a restore-key hit still makes the
- # reinstall incremental (postinstall outputs like node-pty's
- # prebuilds/ and esbuild's platform binary survive in place).
- # The build-bundled install-stamp gate (lock sha + node + npm +
- # target) is the real guard against stale trees shipping.
- restore-keys: |
- node-modules-${{ matrix.target.label }}-node${{ steps.pm.outputs.node-version }}-npm${{ steps.pm.outputs.npm-version }}-
+ # No partial restore: npm ci deletes both the tree and native outputs.
+ key: desktop-node-deps-v1-${{ matrix.target.label }}-node${{ steps.pm.outputs.node-version }}-npm${{ steps.pm.outputs.npm-version }}-${{ hashFiles('package-lock.json', 'package.json', 'apps/*/package.json', 'ui-tui/package.json', 'ui-tui/packages/*/package.json', 'web/package.json', 'tests-js/package.json', '.npmrc', 'scripts/build/node-deps.mjs') }}
- - name: Cache node-pty prebuilds (postinstall output)
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ - name: Prepare desktop dependencies
+ shell: bash
+ run: node scripts/build/node-deps.mjs --source . --workspace apps/desktop --workspace ui-tui --workspace web --reuse
+
+ # Save before packaging: a later build/signing failure must not lose this work,
+ # and builder mutations must not become the next job's dependency input.
+ - name: Save prepared desktop dependencies
+ if: steps.node-modules-cache.outputs.cache-hit != 'true'
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
- node_modules/node-pty/prebuilds
- node_modules/node-pty/build
- key: node-pty-prebuilds-${{ matrix.target.label }}-${{ hashFiles('package-lock.json') }}
- restore-keys: |
- node-pty-prebuilds-${{ matrix.target.label }}-
+ node_modules
+ apps/*/node_modules
+ ui-tui/node_modules
+ ui-tui/packages/*/node_modules
+ web/node_modules
+ tests-js/node_modules
+ key: ${{ steps.node-modules-cache.outputs.cache-primary-key }}
# Commit artifacts are downloadable too. Require signing for them,
# candidates, and published tags before building any payload.
diff --git a/scripts/build/README.md b/scripts/build/README.md
index 6f667a97379..402d46f7b2d 100644
--- a/scripts/build/README.md
+++ b/scripts/build/README.md
@@ -46,9 +46,20 @@ The prepared source needs these inputs:
Request the complete workspace union once. A later, narrower `npm ci` can
remove dependencies that another product needs. This provider modifies the
-prepared workspace. It does not build a frontend or publish a completion stamp.
+prepared workspace. It does not build a frontend.
Nix supplies dependencies through `importNpmLock` instead of this command.
+`--reuse` opts into reusing a completed dependency install. Desktop bundles use
+this with CI's cached `node_modules` tree. The receipt lives inside that tree
+and matches the lockfile, local package manifests, project npm configuration,
+Node/npm versions, OS/architecture, and exact workspace union. It also checks
+npm's installed-tree lock and the presence of its recorded package directories.
+A missing or mismatched receipt runs a clean `npm ci`; failed installs cannot
+leave a reusable receipt. Omit `--reuse` to force a clean dependency install.
+The receipt does not validate arbitrary edits inside installed packages and
+never skips product compilation. CI saves the prepared tree before packaging
+can mutate it, and before unrelated build/signing failures can discard it.
+
## Frontend products
```sh
diff --git a/scripts/build/node-deps.mjs b/scripts/build/node-deps.mjs
index ad9be189369..3aa87eb3a44 100644
--- a/scripts/build/node-deps.mjs
+++ b/scripts/build/node-deps.mjs
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import { execFileSync } from 'node:child_process'
-import { existsSync, readFileSync, realpathSync } from 'node:fs'
+import { createHash } from 'node:crypto'
+import { existsSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { delimiter, dirname, join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
@@ -29,7 +30,7 @@ export function npmCommand({ env = process.env } = {}) {
}
/** Install the full requested workspace union in one strict, locked operation. */
-export function prepareNodeDependencies({ source, workspaces, env = process.env }) {
+export function prepareNodeDependencies({ source, workspaces, env = process.env, reuse = false }) {
source = resolve(source)
if (!Array.isArray(workspaces) || workspaces.length === 0) {
throw new Error('Select at least one workspace; implicit all-workspace installation is not allowed')
@@ -45,7 +46,7 @@ export function prepareNodeDependencies({ source, workspaces, env = process.env
throw new Error(`Unknown or missing locked workspace: ${workspace}`)
}
return path
- }))]
+ }))].sort()
const [node, npm] = npmCommand({ env })
const npmVersion = execFileSync(node, [npm, '--version'], { cwd: source, env, encoding: 'utf8' }).trim()
const { satisfies } = createRequire(npm)('semver')
@@ -53,17 +54,48 @@ export function prepareNodeDependencies({ source, workspaces, env = process.env
const range = manifest.engines?.[name]
if (range && !satisfies(version, range)) throw new Error(`${name} ${version} violates ${range}`)
}
- execFileSync(node, [npm, 'ci', '--no-audit', '--no-fund', '--engine-strict', '--include=dev',
+ const args = ['ci', '--no-audit', '--no-fund', '--engine-strict', '--include=dev',
'--include=optional', '--include-workspace-root=true',
...selected.flatMap(workspace => ['--workspace', workspace]),
- ], { cwd: source, env, stdio: 'inherit' })
+ ]
+ // This receipt certifies dependency preparation, never compiled product freshness.
+ // Keep it inside the cached tree so a clean npm ci also removes the receipt.
+ const receipt = join(source, 'node_modules/.hermes-node-deps')
+ const hiddenLock = join(source, 'node_modules/.package-lock.json')
+ const inputs = createHash('sha256').update(JSON.stringify({
+ node: process.versions.node, npm: npmVersion, platform: process.platform, arch: process.arch, args,
+ config: Object.entries(env).filter(([key]) => /^npm_config_/i.test(key) && !/^npm_config_(cache|offline|prefer_offline)$/i.test(key)).sort(),
+ }))
+ const files = ['package-lock.json', '.npmrc', ...Object.keys(lock.packages)
+ .filter(path => !path.split('/').includes('node_modules'))
+ .map(path => join(path, 'package.json'))].sort()
+ for (const file of files) {
+ inputs.update(file).update('\0').update(existsSync(join(source, file)) ? readFileSync(join(source, file)) : '<missing>').update('\0')
+ }
+ const key = inputs.digest('hex')
+ if (reuse && existsSync(receipt) && existsSync(hiddenLock)) {
+ const installed = readFileSync(hiddenLock)
+ const expected = `${key}\n${createHash('sha256').update(installed).digest('hex')}\n`
+ if (readFileSync(receipt, 'utf8') === expected && Object.keys(JSON.parse(installed).packages)
+ .every(path => existsSync(join(source, path)))) {
+ console.log(`node-deps: reusing completed install (${selected.join(', ')})`)
+ return { source, workspaces: selected }
+ }
+ }
+ // npm can fail during validation before deleting node_modules. Invalidate first.
+ rmSync(receipt, { force: true })
+ execFileSync(node, [npm, ...args], { cwd: source, env, stdio: 'inherit' })
+ if (reuse) {
+ writeFileSync(receipt, `${key}\n${createHash('sha256').update(readFileSync(hiddenLock)).digest('hex')}\n`)
+ }
return { source, workspaces: selected }
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
const { values } = parseArgs({ options: {
source: { type: 'string' }, workspace: { type: 'string', multiple: true },
+ reuse: { type: 'boolean', default: false },
} })
if (!values.source) throw new Error('--source is required')
- prepareNodeDependencies({ source: values.source, workspaces: values.workspace })
+ prepareNodeDependencies({ source: values.source, workspaces: values.workspace, reuse: values.reuse })
}
diff --git a/scripts/bundles/desktop.py b/scripts/bundles/desktop.py
index e3f760a741f..e5707e02fca 100644
--- a/scripts/bundles/desktop.py
+++ b/scripts/bundles/desktop.py
@@ -102,7 +102,7 @@ def build(repo: Path, tag: str | None, variant: str, builder_args: list[str],
env = prepare_windows_environment(source=repo, state=repo / "apps/desktop/build/.build-deps", env=env)
workspaces = ["apps/desktop"] + ([] if variant == "light" else ["ui-tui", "web"])
- run([node, "scripts/build/node-deps.mjs", "--source", str(repo),
+ run([node, "scripts/build/node-deps.mjs", "--source", str(repo), "--reuse",
*[arg for workspace in workspaces for arg in ("--workspace", workspace)]], cwd=repo, env=env)
payload = repo / "apps/desktop/build/agent-payload"
if variant == "light":
diff --git a/tests-js/node-deps.test.mjs b/tests-js/node-deps.test.mjs
index cd1f017de15..829da7a0c64 100644
--- a/tests-js/node-deps.test.mjs
+++ b/tests-js/node-deps.test.mjs
@@ -1,5 +1,5 @@
import { execFileSync } from 'node:child_process'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
@@ -63,3 +63,56 @@ test('web-only selection excludes siblings and rejects stale locks without rewri
expect(() => prepareNodeDependencies({ source, workspaces: [], env })).toThrow(/workspace/)
expect(() => prepareNodeDependencies({ source, workspaces: ['missing'], env })).toThrow(/workspace/)
}, 30000)
+
+test('a restored completed install retains postinstall outputs only for matching inputs', async () => {
+ const { prepareNodeDependencies } = await import('../scripts/build/node-deps.mjs')
+ const source = fixture()
+ const env = { ...process.env, npm_config_offline: 'true', npm_config_cache: join(source, '.npm-cache') }
+ prepareNodeDependencies({ source, workspaces: ['ui-tui', 'web'], env, reuse: true })
+ const artifact = 'node_modules/postinstall-output'
+ writeFileSync(join(source, artifact), 'built')
+ const restored = mkdtempSync(join(tmpdir(), 'restored node union-'))
+ roots.push(restored)
+ cpSync(source, restored, { recursive: true, verbatimSymlinks: true })
+ prepareNodeDependencies({ source: restored, workspaces: ['web', 'ui-tui'], env, reuse: true })
+ expect(readFileSync(join(restored, artifact), 'utf8')).toBe('built')
+ const cli = [join(repo, 'scripts/build/node-deps.mjs'), '--source', restored, '--workspace', 'web', '--workspace', 'ui-tui', '--reuse']
+ execFileSync(process.execPath, cli, { cwd: tmpdir(), env, stdio: 'pipe' })
+ expect(readFileSync(join(restored, artifact), 'utf8')).toBe('built')
+ expect(createRequire(join(restored, 'web/package.json'))('web-only')).toBe('web-only')
+
+ prepareNodeDependencies({ source: restored, workspaces: ['web'], env, reuse: true })
+ expect(existsSync(join(restored, artifact))).toBe(false)
+ expect(existsSync(join(restored, 'node_modules/tui-only'))).toBe(false)
+ writeFileSync(join(restored, artifact), 'built again')
+ // Even an invalid manifest must reach npm, not hide behind a warm lockfile cache.
+ json(join(restored, 'web/package.json'), { name: 'web', version: '1.0.0', dependencies: { 'web-only': '9.0.0' } })
+ expect(() => prepareNodeDependencies({ source: restored, workspaces: ['web'], env, reuse: true })).toThrow()
+ cpSync(join(source, 'web/package.json'), join(restored, 'web/package.json'))
+ prepareNodeDependencies({ source: restored, workspaces: ['web'], env, reuse: true })
+ expect(existsSync(join(restored, artifact))).toBe(false)
+}, 30000)
+
+test('reuse respects lifecycle configuration and repairs missing installed packages', async () => {
+ const { prepareNodeDependencies } = await import('../scripts/build/node-deps.mjs')
+ const source = fixture()
+ const manifest = JSON.parse(readFileSync(join(source, 'package.json'), 'utf8'))
+ manifest.scripts = { postinstall: `node -e "require('node:fs').writeFileSync('node_modules/postinstall-output', require('node:crypto').randomUUID())"` }
+ json(join(source, 'package.json'), manifest)
+ const env = { ...process.env, npm_config_offline: 'true', npm_config_cache: join(source, '.npm-cache') }
+ const options = { source, workspaces: ['web'], env, reuse: true }
+ const artifact = join(source, 'node_modules/postinstall-output')
+ prepareNodeDependencies({ ...options, env: { ...env, npm_config_ignore_scripts: 'true' } })
+ expect(existsSync(artifact)).toBe(false)
+ prepareNodeDependencies(options)
+ const first = readFileSync(artifact, 'utf8')
+ prepareNodeDependencies(options)
+ expect(readFileSync(artifact, 'utf8')).toBe(first)
+ rmSync(join(source, 'node_modules/web-only'), { recursive: true, force: true })
+ prepareNodeDependencies(options)
+ const repaired = readFileSync(artifact, 'utf8')
+ expect(repaired).not.toBe(first)
+ expect(createRequire(join(source, 'web/package.json'))('web-only')).toBe('web-only')
+ prepareNodeDependencies({ ...options, reuse: false })
+ expect(readFileSync(artifact, 'utf8')).not.toBe(repaired)
+}, 30000)