From 3f579d45ebf93c2d477e73a413d594661f9d5cbd Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 3 Nov 2026 15:49:44 +0800 Subject: [PATCH] fix(release): bind helper builds to the Actions run commit --- .github/workflows/cua-helper-package.yml | 30 ++++--- .github/workflows/release-publish.yml | 2 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 4 +- .../cua-macos/native/README.zh.md | 4 +- scripts/cua-helper/build-inputs.spec.ts | 6 +- scripts/cua-helper/build-inputs.ts | 15 +++- scripts/cua-helper/select-artifact.ts | 13 ++- scripts/tests/ci-release-selfhosted.spec.ts | 79 +++++++++++++++++-- 9 files changed, 117 insertions(+), 40 deletions(-) diff --git a/.github/workflows/cua-helper-package.yml b/.github/workflows/cua-helper-package.yml index 3ed909a35b..c9f2547d5c 100644 --- a/.github/workflows/cua-helper-package.yml +++ b/.github/workflows/cua-helper-package.yml @@ -3,11 +3,6 @@ name: Package CUA helper · macOS on: workflow_dispatch: inputs: - source_ref: - description: '同仓库可信源码分支或 dsh-v* tag' - type: string - default: master - required: true preset: description: '机器上的签名配置' type: choice @@ -16,9 +11,9 @@ on: required: true workflow_call: inputs: - source_ref: - type: string - required: true + reuse: + type: boolean + default: false cua_run_id: type: string default: '' @@ -52,21 +47,19 @@ jobs: outputs: artifact-id: ${{ steps.retained.outputs.artifact-id || steps.upload.outputs.artifact-id }} run-id: ${{ steps.retained.outputs.run-id || github.run_id }} - build-key: ${{ steps.retained.outputs.build-key }} + build-key: ${{ steps.build-inputs.outputs.build-key }} env: DSH_PACKAGING_PRESET: ${{ inputs.preset }} DSH_TELEMETRY_DISABLED: '1' - PACKAGE_SOURCE_REF: ${{ inputs.source_ref }} steps: - uses: actions/checkout@v7.0.1 with: - ref: ${{ inputs.source_ref }} persist-credentials: false clean: true - - name: Validate source selection + - name: Validate run ref and preset run: | - node -e 'const fs=require("node:fs"); const ref=process.env.PACKAGE_SOURCE_REF; - if(ref.startsWith("refs/pull/") || /^[a-f0-9]{40}$/i.test(ref)) throw Error("Select a trusted repository branch or release tag"); + node -e 'const fs=require("node:fs"); const ref=process.env.GITHUB_REF; + if(!ref || (!ref.startsWith("refs/heads/") && !ref.startsWith("refs/tags/"))) throw Error("Select a trusted repository branch or release tag"); const tag=ref.replace(/^refs\/tags\//, ""); if(tag.startsWith("dsh-v") && tag!=="dsh-v"+JSON.parse(fs.readFileSync("package.json","utf8")).version) throw Error("Release tag must match product version"); if(!["test","production"].includes(process.env.DSH_PACKAGING_PRESET)) throw Error("Invalid preset");' @@ -74,11 +67,16 @@ jobs: with: node-version: '24' package-manager-cache: false + - name: Record CUA helper build inputs + id: build-inputs + run: node scripts/cua-helper/build-inputs.ts - name: Find reusable CUA helper + if: inputs.reuse id: retained env: GH_TOKEN: ${{ github.token }} CUA_RUN_ID: ${{ inputs.cua_run_id }} + CUA_BUILD_KEY: ${{ steps.build-inputs.outputs.build-key }} run: node scripts/cua-helper/select-artifact.ts - uses: pnpm/action-setup@v5.0.0 if: steps.retained.outputs.artifact-id == '' @@ -90,7 +88,7 @@ jobs: - name: Build and verify notarized applications if: steps.retained.outputs.artifact-id == '' env: - CUA_EXPECTED_BUILD_KEY: ${{ steps.retained.outputs.build-key }} + CUA_EXPECTED_BUILD_KEY: ${{ steps.build-inputs.outputs.build-key }} run: | mkdir -p dist pnpm exec tsx scripts/cua-helper/package.ts --out dist/cua-helper @@ -98,7 +96,7 @@ jobs: if: steps.retained.outputs.artifact-id == '' id: upload with: - name: cua-helper-${{ github.run_id }}-${{ github.run_attempt }}-${{ steps.retained.outputs.build-key }} + name: cua-helper-${{ github.run_id }}-${{ github.run_attempt }}-${{ steps.build-inputs.outputs.build-key }} path: dist/cua-helper/* if-no-files-found: error compression-level: 0 diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index a0254aa69c..27a5a52916 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -32,7 +32,7 @@ jobs: if: startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check uses: ./.github/workflows/cua-helper-package.yml with: - source_ref: ${{ github.ref }} + reuse: true preset: production cua_run_id: ${{ inputs.cua_run_id }} diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 3bd7e46d45..6714cbdad8 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -15,8 +15,8 @@ en: e8cbc43d38786c40 zh: 52b3ba85d98011b9 /dsh-cua-native-helper/build-and-service: - en: 0957d00ac9d9f06e - zh: 96d5871ba1bfea1c + en: fbe2a4a9bc5e4e37 + zh: 40d21b7872e46db0 /dsh-cua-native-helper/request-protocol: en: fc8043c425322cdd zh: cf1edb9a78fda301 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 44577c9014..45acd5e694 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -37,11 +37,11 @@ Certificate signatures include a signing time. Development builds record the gen Generations in `native/.build/prepared/` and `native/bin/darwin-` are retained without automatic garbage collection. Use a fresh `--output-directory` for release staging, or clean the packaging output before building while no client uses it, so old generations do not enter the tarball. Secure signing timestamps can create distinct generations for identical sources. -The manual **Package CUA helper · macOS** [workflow](../../../../.github/workflows/cua-helper-package.yml) builds both architectures on `dsh-mac-package-trial`. The runner needs GitHub CLI (`gh`) on `PATH` for artifact discovery. Select a trusted `source_ref` and machine `preset`; credentials use the existing [macOS packaging configuration](../../../../apps/desktop/packaging/README.md#macos-actions). Packaging does not require a macOS desktop login or Rosetta. `pnpm exec tsx scripts/cua-helper/package.ts --out ` runs the same preparation from the repository root. It signs, notarizes and staples each complete application before selecting its final content digest, then verifies architectures, signatures, tickets, Gatekeeper and file integrity from the extracted `cua-helper.tgz`. Packaging does not launch the helper. Run `python3 scripts/cua-helper/smoke.py ` separately in a logged-in desktop session to check capabilities, helper identity and cleanup; x64 execution on Apple Silicon requires Rosetta. The smoke does not request permissions or inspect applications. Failed or timed-out commands and unreadable startup replies report captured stdout and stderr; invalid encoding is replaced only in diagnostic text, while protocol parsing remains strict. A successful package build does not certify runtime behavior. Helper packaging retains its own [diagnostic record](../../../../apps/desktop/packaging/README.md#macos-release-signing), including failures before desktop installer startup. +The manual **Package CUA helper · macOS** [workflow](../../../../.github/workflows/cua-helper-package.yml) builds both architectures on `dsh-mac-package-trial`. For manual runs, choose a trusted branch or tag with **Use workflow from** and select the machine `preset`. Checkout uses the commit recorded for that Actions run; publication calls use the caller run's commit. Manual runs always build new artifacts. Publication reuse requires GitHub CLI (`gh`) on the runner's `PATH`; credentials use the existing [macOS packaging configuration](../../../../apps/desktop/packaging/README.md#macos-actions). Packaging does not require a macOS desktop login or Rosetta. `pnpm exec tsx scripts/cua-helper/package.ts --out ` runs the same preparation from the repository root. It signs, notarizes and staples each complete application before selecting its final content digest, then verifies architectures, signatures, tickets, Gatekeeper and file integrity from the extracted `cua-helper.tgz`. Packaging does not launch the helper. Run `python3 scripts/cua-helper/smoke.py ` separately in a logged-in desktop session to check capabilities, helper identity and cleanup; x64 execution on Apple Silicon requires Rosetta. The smoke does not request permissions or inspect applications. Failed or timed-out commands and unreadable startup replies report captured stdout and stderr; invalid encoding is replaced only in diagnostic text, while protocol parsing remains strict. A successful package build does not certify runtime behavior. Helper packaging retains its own [diagnostic record](../../../../apps/desktop/packaging/README.md#macos-release-signing), including failures before desktop installer startup. The workflow retains `cua-helper.tgz` and `cua-helper.json`. The manifest records the original build's product version, commit and Team ID, both application digests, the source digest and the build key. [Release publish](../../../../.github/workflows/release-publish.yml) always calls this workflow, then downloads its selected run ID and artifact ID before packing the provider for npm. Staging verifies the current helper source digest and selected build key, both architectures, application generations, file bytes and executable permissions. npm publication rechecks the exact provider tarball before any registry write. Reuse preserves the original manifest and signed bytes across unrelated commits or product versions. Ordinary PR release rehearsals have no signing credentials. -**Release publish (dsh)** accepts an optional `cua_run_id`: enter the numeric run ID after `/actions/runs/` in the producer's GitHub URL, not its job ID. It passes this selection through the helper's `workflow_call` input. Manual **Package CUA helper · macOS** runs only ask for `source_ref` and `preset`, and always discover artifacts automatically. Automatic discovery searches completed runs of these two workflows from the last 14 days for an unexpired matching artifact. Selection runs on the Mac before pnpm setup or dependency installation. A match skips installation, compilation, signing and notarization; an automatic miss rebuilds. An explicit run selects its latest attempt once and fails on unsuccessful helper packaging, missing or expired artifacts, or mismatched inputs. It never chooses an older attempt or another run. A later npm failure does not invalidate a successful helper job. GitHub API failures stop selection. The summary links the actual producer; a run that only reuses an artifact does not upload another copy, so use its linked producer run for manual selection. Artifacts are retained for 14 days. +**Release publish (dsh)** accepts an optional `cua_run_id`: enter the numeric run ID after `/actions/runs/` in the producer's GitHub URL, not its job ID. The publisher enables `reuse` and passes this selection through the helper's `workflow_call` inputs; neither reuse input appears on the manual helper form. Leave `cua_run_id` empty for automatic discovery, which searches completed runs of these two workflows from the last 14 days for an unexpired matching artifact. Selection runs on the Mac before pnpm setup or dependency installation. A match skips installation, compilation, signing and notarization; an automatic miss rebuilds. An explicit run selects its latest attempt once and fails on unsuccessful helper packaging, missing or expired artifacts, or mismatched inputs. It never chooses an older attempt or another run. A later npm failure does not invalidate a successful helper job. GitHub API failures stop selection. The summary links the actual producer; a run that only reuses an artifact does not upload another copy, so use its linked producer run for manual selection. Artifacts are retained for 14 days. The [source digest](../../../../scripts/cua-helper/build-inputs.ts) includes tracked file paths, raw bytes and executable bits under `native/`, `scripts/cua-helper/` and `apps/desktop/scripts/`, plus the helper workflow, lockfile, workspace configuration, root TypeScript configurations and package-manager version. Product version and unrelated package sources are excluded. The build key additionally includes the preset, Node/Swift/Clang/Python versions, macOS SDK build, signing identity, Team ID and certificate-container digest; passwords are excluded. Missing inputs or unreadable configuration fail. Artifacts without these records require a new build. Source comparison still requires a Mac runner and checkout; matching inputs establish reuse eligibility, while the consuming pack job validates the downloaded application bytes. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 8a5c9de58b..6518ea20f0 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -37,11 +37,11 @@ kind: "package-reference" `native/.build/prepared/` 和 `native/bin/darwin-` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。 -手动工作流 **Package CUA helper · macOS** 的[配置](../../../../.github/workflows/cua-helper-package.yml)在 `dsh-mac-package-trial` 构建两种架构。runner 的 `PATH` 中需要有 GitHub CLI(`gh`),用于查询历史产物。选择可信的 `source_ref` 和机器 `preset`;凭据沿用[macOS 打包配置](../../../../apps/desktop/packaging/README.zh.md#macos-actions)。打包无需 macOS 桌面登录或 Rosetta。在仓库根目录运行 `pnpm exec tsx scripts/cua-helper/package.ts --out ` 可执行相同准备。完整应用签名、公证和贴票后才确定最终内容摘要,再从解包后的 `cua-helper.tgz` 验证架构、签名、票据、Gatekeeper 和文件完整性。打包不启动 helper。在已登录的桌面会话中单独运行 `python3 scripts/cua-helper/smoke.py ` 检查能力、helper 身份和退出清理;Apple Silicon 上执行 x64 版本需要 Rosetta。该检查不申请权限或观察应用。命令失败、超时或启动回复无法解析时,会输出捕获的 stdout 和 stderr;无效编码只在诊断文本中替换,协议解析仍严格校验。打包成功不代表运行验收通过。 helper 打包保留独立的[诊断记录](../../../../apps/desktop/packaging/README.zh.md#macos-release-signing),包括桌面安装包开始构建前发生的失败。 +手动工作流 **Package CUA helper · macOS** 的[配置](../../../../.github/workflows/cua-helper-package.yml)在 `dsh-mac-package-trial` 构建两种架构。手动启动时,在 **Use workflow from** 中选择可信的分支或 tag,再选择机器 `preset`。checkout 使用本次 Actions 运行记录的提交;由发布工作流调用时使用调用方本次运行的提交。手动运行始终构建新产物。发布复用要求 runner 的 `PATH` 中有 GitHub CLI(`gh`);凭据沿用[macOS 打包配置](../../../../apps/desktop/packaging/README.zh.md#macos-actions)。打包无需 macOS 桌面登录或 Rosetta。在仓库根目录运行 `pnpm exec tsx scripts/cua-helper/package.ts --out ` 可执行相同准备。完整应用签名、公证和贴票后才确定最终内容摘要,再从解包后的 `cua-helper.tgz` 验证架构、签名、票据、Gatekeeper 和文件完整性。打包不启动 helper。在已登录的桌面会话中单独运行 `python3 scripts/cua-helper/smoke.py ` 检查能力、helper 身份和退出清理;Apple Silicon 上执行 x64 版本需要 Rosetta。该检查不申请权限或观察应用。命令失败、超时或启动回复无法解析时,会输出捕获的 stdout 和 stderr;无效编码只在诊断文本中替换,协议解析仍严格校验。打包成功不代表运行验收通过。 helper 打包保留独立的[诊断记录](../../../../apps/desktop/packaging/README.zh.md#macos-release-signing),包括桌面安装包开始构建前发生的失败。 工作流保留 `cua-helper.tgz` 和 `cua-helper.json`。清单记录原始构建的产品版本、commit、Team ID、两份应用摘要、源码摘要和构建摘要。[Release publish](../../../../.github/workflows/release-publish.yml)始终调用该工作流,再按返回的 run ID 和 artifact ID 下载所选产物,生成 provider 的 npm 包。准备步骤校验当前 helper 的源码摘要、选定的构建摘要、两种架构、应用目录、文件字节和执行权限。npm 发布在写入注册表前重新检查实际 provider tarball。无关 commit 或产品版本变化时,复用保留原始清单和已签名字节。普通 PR 发布检查不使用签名凭据。 -**Release publish (dsh)** 接受可选的 `cua_run_id`:填写构建运行页面 URL 中 `/actions/runs/` 后的数字,不填 job ID。发布工作流通过 helper 的 `workflow_call` 参数传入这个选择。手动启动 **Package CUA helper · macOS** 只填写 `source_ref` 和 `preset`,始终自动查找产物。自动查找会查询这两个工作流最近 14 天内已结束的运行,选择未过期的匹配产物。选择在 Mac 上执行,早于 pnpm 准备和依赖安装。命中时跳过安装、编译、签名和公证,自动查找未命中时重新构建。手动指定 run ID 时选定最新 attempt;helper 打包未成功、产物缺失或过期、输入不匹配时直接失败,不选择更早的 attempt 或其他运行。后续 npm 失败不影响成功的 helper job。GitHub API 读取失败会停止选择。运行摘要链接实际构建者;只复用产物的运行不重新上传副本,手动选择时填写摘要所链接的构建 run ID。产物保留 14 天。 +**Release publish (dsh)** 接受可选的 `cua_run_id`:填写构建运行页面 URL 中 `/actions/runs/` 后的数字,不填 job ID。发布工作流开启 `reuse`,并通过 helper 的 `workflow_call` 参数传入这个选择;这两个复用参数均不出现在 helper 的手动表单中。`cua_run_id` 留空时自动查找,查询这两个工作流最近 14 天内已结束的运行,选择未过期的匹配产物。选择在 Mac 上执行,早于 pnpm 准备和依赖安装。命中时跳过安装、编译、签名和公证,自动查找未命中时重新构建。手动指定 run ID 时选定最新 attempt;helper 打包未成功、产物缺失或过期、输入不匹配时直接失败,不选择更早的 attempt 或其他运行。后续 npm 失败不影响成功的 helper job。GitHub API 读取失败会停止选择。运行摘要链接实际构建者;只复用产物的运行不重新上传副本,手动选择时填写摘要所链接的构建 run ID。产物保留 14 天。 [源码摘要](../../../../scripts/cua-helper/build-inputs.ts)覆盖 `native/`、`scripts/cua-helper/`、`apps/desktop/scripts/` 下受 Git 跟踪文件的路径、原始字节和执行权限,以及 helper 工作流、锁文件、workspace 配置、根目录 TypeScript 配置和包管理器版本。产品版本及无关包的源码不参与比较。构建摘要还包含 preset、Node/Swift/Clang/Python 版本、macOS SDK build、签名身份、Team ID 和证书容器摘要,不包含密码。输入缺失或配置无法读取时失败。没有这些记录的旧产物需要重新构建。源码比较仍需等待 Mac runner 并检出代码;输入匹配确定可复用性,消费产物的 pack job 再校验下载的应用字节。 diff --git a/scripts/cua-helper/build-inputs.spec.ts b/scripts/cua-helper/build-inputs.spec.ts index 3d9c612545..8a28225c8b 100644 --- a/scripts/cua-helper/build-inputs.spec.ts +++ b/scripts/cua-helper/build-inputs.spec.ts @@ -109,7 +109,7 @@ it('resolves the configured signing file without installing desktop dependencies expect(() => readCuaSigningSettings({ ...environment, DSH_PACKAGING_CONFIG_DIR: 'relative' })).toThrow('CONFIG_DIR') }) -it('loads the selector under plain Node with no node_modules directory', () => { +it('loads fingerprinting and selection under plain Node with no node_modules directory', () => { const f = fixture() for (const file of ['scripts/cua-helper/build-inputs.ts', 'scripts/cua-helper/select-artifact.ts', 'apps/desktop/scripts/desktop-file-settings.mjs', 'apps/desktop/scripts/desktop-release-environment.mjs']) { @@ -117,7 +117,7 @@ it('loads the selector under plain Node with no node_modules directory', () => { copyFileSync(resolve(file), join(f.root, file)) } const output = execFileSync(process.execPath, ['--input-type=module', '-e', - "const { selectCuaHelperArtifact } = await import('./scripts/cua-helper/select-artifact.ts'); console.log(typeof selectCuaHelperArtifact)"], + "const a = await import('./scripts/cua-helper/select-artifact.ts'); const b = await import('./scripts/cua-helper/build-inputs.ts'); console.log(typeof a.selectCuaHelperArtifact, typeof b.cuaHelperSourceDigest)"], { cwd: f.root, encoding: 'utf8', timeout: 30_000, stdio: 'pipe' }) - expect(output.trim()).toBe('function') + expect(output.trim()).toBe('function function') }) diff --git a/scripts/cua-helper/build-inputs.ts b/scripts/cua-helper/build-inputs.ts index b063078c2a..ee18d079be 100644 --- a/scripts/cua-helper/build-inputs.ts +++ b/scripts/cua-helper/build-inputs.ts @@ -1,8 +1,8 @@ /** Content and machine identity for reusing a signed helper before installing dependencies. */ import { execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { lstatSync, readFileSync } from 'node:fs' -import { isAbsolute, join } from 'node:path' +import { appendFileSync, lstatSync, readFileSync } from 'node:fs' +import { isAbsolute, join, resolve } from 'node:path' import { readDesktopPackageSettings } from '../../apps/desktop/scripts/desktop-file-settings.mjs' import { resolveMacOSSigningEnvironment } from '../../apps/desktop/scripts/desktop-release-environment.mjs' @@ -78,3 +78,14 @@ export function cuaHelperBuildKey(source: string, environment: NodeJS.ProcessEnv } return createHash('sha256').update(JSON.stringify(configuration)).digest('hex') } + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { + const env = process.env + if (!env.GITHUB_OUTPUT || !env.GITHUB_STEP_SUMMARY) throw new Error('CUA build inputs: Actions context required') + const root = resolve(import.meta.dirname, '../..') + const sourceDigest = cuaHelperSourceDigest(root) + const buildKey = cuaHelperBuildKey(sourceDigest, readCuaSigningSettings(env)) + appendFileSync(env.GITHUB_OUTPUT, `source-digest=${sourceDigest}\nbuild-key=${buildKey}\n`) + appendFileSync(env.GITHUB_STEP_SUMMARY, `CUA helper 源码摘要:\`${sourceDigest}\`。\n\n`) + console.log(`CUA helper source digest: ${sourceDigest}`) +} diff --git a/scripts/cua-helper/select-artifact.ts b/scripts/cua-helper/select-artifact.ts index 57dc2fc448..15865c253c 100644 --- a/scripts/cua-helper/select-artifact.ts +++ b/scripts/cua-helper/select-artifact.ts @@ -3,7 +3,6 @@ import assert from 'node:assert/strict' import { execFileSync } from 'node:child_process' import { appendFileSync } from 'node:fs' import { resolve } from 'node:path' -import { cuaHelperBuildKey, cuaHelperSourceDigest, readCuaSigningSettings } from './build-inputs.ts' const workflows = ['cua-helper-package.yml', 'release-publish.yml'] as const @@ -97,17 +96,17 @@ export function selectCuaHelperArtifact(repository: string, runId: string, build if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { const env = process.env - if (!env.GITHUB_REPOSITORY || !env.GITHUB_OUTPUT || !env.GITHUB_STEP_SUMMARY) throw new Error('CUA reuse: Actions context required') - const root = resolve(import.meta.dirname, '../..') - const sourceDigest = cuaHelperSourceDigest(root) - const buildKey = cuaHelperBuildKey(sourceDigest, readCuaSigningSettings(env)) + if (!env.GITHUB_REPOSITORY || !env.GITHUB_OUTPUT || !env.GITHUB_STEP_SUMMARY || !env.CUA_BUILD_KEY) { + throw new Error('CUA reuse: Actions context and CUA_BUILD_KEY are required') + } + const buildKey = env.CUA_BUILD_KEY const selection = selectCuaHelperArtifact(env.GITHUB_REPOSITORY, env.CUA_RUN_ID ?? '', buildKey, (path, paginate) => JSON.parse(execFileSync('gh', ['api', ...(paginate ? ['--paginate', '--slurp'] : []), path], { encoding: 'utf8', timeout: 60_000, maxBuffer: 8 * 1024 * 1024 }))) - appendFileSync(env.GITHUB_OUTPUT, `source-digest=${sourceDigest}\nbuild-key=${buildKey}\nartifact-id=${selection?.artifactId ?? ''}\nrun-id=${selection?.runId ?? ''}\nattempt=${selection?.attempt ?? ''}\n`) + appendFileSync(env.GITHUB_OUTPUT, `artifact-id=${selection?.artifactId ?? ''}\nrun-id=${selection?.runId ?? ''}\nattempt=${selection?.attempt ?? ''}\n`) const summary = selection ? `复用 [CUA helper 构建](https://github.com/${env.GITHUB_REPOSITORY}/actions/runs/${selection.runId}/attempts/${selection.attempt}),run ID \`${selection.runId}\`,artifact ID \`${selection.artifactId}\`。跳过依赖安装、编译、签名和公证。` : '未找到源码逐字节一致且构建配置匹配的可用 CUA helper 产物,执行依赖安装和重新构建。' - appendFileSync(env.GITHUB_STEP_SUMMARY, `${summary}\n\n源码摘要:\`${sourceDigest}\`。\n`) + appendFileSync(env.GITHUB_STEP_SUMMARY, `${summary}\n`) console.log(summary) } diff --git a/scripts/tests/ci-release-selfhosted.spec.ts b/scripts/tests/ci-release-selfhosted.spec.ts index 9d4743cc3b..48403f79be 100644 --- a/scripts/tests/ci-release-selfhosted.spec.ts +++ b/scripts/tests/ci-release-selfhosted.spec.ts @@ -1,9 +1,11 @@ /** Release rehearsal routing and persistent-runner isolation, without executing release builds. */ -import { readFileSync } from 'node:fs' -import { resolve } from 'node:path' +import { spawnSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' import { runInNewContext } from 'node:vm' import { load } from 'js-yaml' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, onTestFinished } from 'vitest' const root = resolve(import.meta.dirname, '../..') const repository = 'deepseek-harness/deepseek-harness' @@ -32,6 +34,7 @@ interface Workflow { needs?: string permissions?: Record outputs?: Record + env?: Record }> } @@ -189,12 +192,15 @@ it('keeps DSH publication manual and delegates all helper selections to the Mac expect(helper).toEqual({ if: "startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check", uses: './.github/workflows/cua-helper-package.yml', - with: { source_ref: '${{ github.ref }}', preset: 'production', cua_run_id: '${{ inputs.cua_run_id }}' }, + with: { reuse: true, preset: 'production', cua_run_id: '${{ inputs.cua_run_id }}' }, }) for (const [name, job] of Object.entries(publish.jobs)) { if (name !== 'cua-helper') expect(job['runs-on']).toBe(hosted) } expect(JSON.stringify(publish)).not.toContain('cua_run_attempt') + expect(publish.on['workflow_dispatch']).toMatchObject({ inputs: { 'skip-tag-check': { + description: 'Skip release tag validation for the selected ref; other publication checks still apply.', + } } }) expect(publish.jobs['pack']!.needs).toBe('cua-helper') expect(publish.jobs['pack']!.if).toBeUndefined() }) @@ -214,6 +220,13 @@ it('skips installation and signing on a helper match and exports the original pr const job = helper.jobs['package']! const select = job.steps.find(step => step.name === 'Find reusable CUA helper')! expect(select.run).toBe('node scripts/cua-helper/select-artifact.ts') + expect(Boolean(evaluate(select.if!, {}))).toBe(false) + expect(evaluate(select.if!, { 'inputs.reuse': true })).toBe(true) + expect(select.env?.['CUA_BUILD_KEY']).toBe('${{ steps.build-inputs.outputs.build-key }}') + const inputs = job.steps.find(step => step.name === 'Record CUA helper build inputs')! + expect(inputs.run).toBe('node scripts/cua-helper/build-inputs.ts') + expect(inputs.if).toBeUndefined() + expect(job.steps.indexOf(inputs)).toBeLessThan(job.steps.indexOf(select)) const expensive = job.steps.filter(step => step.uses === 'pnpm/action-setup@v5.0.0' || step.name === 'Install locked dependencies' || step.name === 'Build and verify notarized applications' || step.uses === 'actions/upload-artifact@v7.0.1') @@ -226,7 +239,7 @@ it('skips installation and signing on a helper match and exports the original pr expect(job.outputs).toMatchObject({ 'artifact-id': '${{ steps.retained.outputs.artifact-id || steps.upload.outputs.artifact-id }}', 'run-id': '${{ steps.retained.outputs.run-id || github.run_id }}', - 'build-key': '${{ steps.retained.outputs.build-key }}', + 'build-key': '${{ steps.build-inputs.outputs.build-key }}', }) }) @@ -249,3 +262,59 @@ it('downloads the selected producer artifact and verifies its build key before p expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(download)) expect(pack.steps.indexOf(stage)).toBeLessThan(pack.steps.findIndex(step => step.name === 'Pack release tarballs')) }) + +it('checks out the Actions run commit and exposes only the preset on the manual helper form', () => { + const helper = workflow('cua-helper-package.yml') + const dispatch = helper.on['workflow_dispatch'] as { inputs: Record } + const called = helper.on['workflow_call'] as { inputs: Record } + expect(Object.keys(dispatch.inputs)).toEqual(['preset']) + expect(called.inputs).toEqual({ reuse: { type: 'boolean', default: false }, + cua_run_id: { type: 'string', default: '' }, preset: { type: 'string', default: 'production' } }) + const job = helper.jobs['package']! + const checkout = job.steps.find(step => step.uses === 'actions/checkout@v7.0.1')! + expect(checkout.with).toEqual({ 'persist-credentials': false, clean: true }) + expect(job.env).not.toHaveProperty('PACKAGE_SOURCE_REF') + expect(JSON.stringify(helper)).not.toContain('source_ref') + expect(workflow('release-publish.yml').jobs['cua-helper']!.with).not.toHaveProperty('source_ref') +}) + +it.each([ + ['refs/heads/release-candidate', 'test', true, ''], + ['refs/tags/dsh-v1.2.3', 'production', true, ''], + ['refs/tags/dsh-v1.2.4', 'production', false, 'Release tag must match product version'], + ['refs/heads/master', 'invalid', false, 'Invalid preset'], + ['refs/pull/42/merge', 'test', false, 'Select a trusted repository branch or release tag'], + ['', 'test', false, 'Select a trusted repository branch or release tag'], +] as const)('validates the run ref %s and preset %s before dependency installation', (ref, preset, accepted, diagnostic) => { + const directory = mkdtempSync(join(tmpdir(), 'cua-workflow-ref-')) + onTestFinished(() => { rmSync(directory, { recursive: true, force: true }) }) + writeFileSync(join(directory, 'package.json'), JSON.stringify({ version: '1.2.3' })) + const job = workflow('cua-helper-package.yml').jobs['package']! + const validation = job.steps.find(step => step.name === 'Validate run ref and preset')! + const source = /^node -e '([\s\S]+)'$/u.exec(validation.run!.trim())?.[1] + expect(source).toBeDefined() + const result = spawnSync(process.execPath, ['-e', source!], { + cwd: directory, encoding: 'utf8', timeout: 60_000, + env: { ...process.env, GITHUB_REF: ref, DSH_PACKAGING_PRESET: preset, PACKAGE_SOURCE_REF: 'refs/tags/dsh-v0.0.0' }, + }) + expect(result.error).toBeUndefined() + expect(result.signal).toBeNull() + expect(result.status, result.stderr).toBe(accepted ? 0 : 1) + if (!accepted) expect(result.stderr).toContain(diagnostic) + expect(job.steps.indexOf(validation)).toBeLessThan(job.steps.findIndex(step => step.name === 'Record CUA helper build inputs')) +}) + +it.each([ + [false, '', true], + [true, '', true], + [true, '456', false], +] as const)('builds for reuse=%s and selected artifact=%s only when required', (reuse, artifactId, build) => { + const steps = workflow('cua-helper-package.yml').jobs['package']!.steps + const selection = steps.find(step => step.name === 'Find reusable CUA helper')! + expect(Boolean(evaluate(selection.if!, reuse ? { 'inputs.reuse': true } : {}))).toBe(reuse) + for (const step of steps.filter(step => step.uses === 'pnpm/action-setup@v5.0.0' + || step.name === 'Install locked dependencies' || step.name === 'Build and verify notarized applications' + || step.uses === 'actions/upload-artifact@v7.0.1')) { + expect(evaluate(step.if!, { 'steps.retained.outputs.artifact-id': artifactId })).toBe(build) + } +})