Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(release): retry accepted macOS app stapling

vastsac31821c9de8a
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 59cac83d8..dbe82f648 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -289,6 +289,8 @@ jobs:
# watchdog (diagnostics + summary) inside the 60-minute job budget.
PI_SIGNING_TIMEOUT_SECONDS: "1800"
PI_SIGNING_STALL_SECONDS: "300"
+ PI_STAPLER_MAX_ATTEMPTS: "6"
+ PI_STAPLER_RETRY_DELAY_SECONDS: "10"
run: |
set -euo pipefail
# Artifact names are defined in apps/desktop/package.json: the mac
diff --git a/apps/desktop/test/ci-workflow.test.mjs b/apps/desktop/test/ci-workflow.test.mjs
index d9796c963..583dab236 100644
--- a/apps/desktop/test/ci-workflow.test.mjs
+++ b/apps/desktop/test/ci-workflow.test.mjs
@@ -320,6 +320,8 @@ test("macOS release signing is required on tag pushes", () => {
assert.doesNotMatch(signedBlock, /DEBUG: ".*electron-builder.*"/);
assert.match(signedBlock, /PI_SIGNING_TIMEOUT_SECONDS: "1800"/);
assert.match(signedBlock, /PI_SIGNING_STALL_SECONDS: "300"/);
+ assert.match(signedBlock, /PI_STAPLER_MAX_ATTEMPTS: "6"/);
+ assert.match(signedBlock, /PI_STAPLER_RETRY_DELAY_SECONDS: "10"/);
assert.match(
signedBlock,
/node scripts\/macos-signing-watchdog\.mjs \\\n\s+--label "dist:mac-\$\{\{ matrix\.arch \}\}" \\\n\s+-- pnpm --filter @pi-desktop\/desktop run dist:mac/,
diff --git a/apps/desktop/test/macos-release-lane.test.mjs b/apps/desktop/test/macos-release-lane.test.mjs
index f70b0eddb..3744c5d08 100644
--- a/apps/desktop/test/macos-release-lane.test.mjs
+++ b/apps/desktop/test/macos-release-lane.test.mjs
@@ -24,6 +24,7 @@ const LANE_SCRIPTS = [
"verify-macos-release.sh",
"macos-signing-watchdog.mjs",
"macos-codesign-shim.sh",
+ "macos-stapler-retry-shim.sh",
"macos-bundle-inventory.mjs",
];
const SIGNING_IDENTITY = "Developer ID Application: XingYu Liu (DUV63RKYTW)";
@@ -118,6 +119,11 @@ test(
assert.ok(builderCall, "the lane invokes electron-builder");
assert.match(builderCall, /--mac --(?:arm64|x64)/);
assert.match(builderCall, /--publish never/);
+ assert.match(
+ await readFile(join(repoRoot, "scripts", "release-macos.sh"), "utf8"),
+ /PI_STAPLER_MAX_ATTEMPTS="\$\{PI_STAPLER_MAX_ATTEMPTS:-6\}"/,
+ "the local signed lane enables the same bounded app stapling retries",
+ );
assert.match(builderCall, /-c\.mac\.identity=XingYu Liu \(DUV63RKYTW\)/);
assert.match(builderCall, /-c\.mac\.forceCodeSigning=true/);
assert.match(builderCall, /-c\.mac\.notarize=true/);
diff --git a/apps/desktop/test/macos-signing-watchdog.test.mjs b/apps/desktop/test/macos-signing-watchdog.test.mjs
index 443704afe..44823d571 100644
--- a/apps/desktop/test/macos-signing-watchdog.test.mjs
+++ b/apps/desktop/test/macos-signing-watchdog.test.mjs
@@ -36,6 +36,9 @@ function runWatchdog(args, { env = {}, cwd = repoRoot } = {}) {
PI_SIGNING_HEARTBEAT_SECONDS: "",
PI_CODESIGN_LOG: "",
PI_CODESIGN_REAL: "",
+ PI_STAPLER_MAX_ATTEMPTS: "",
+ PI_STAPLER_RETRY_DELAY_SECONDS: "",
+ PI_XCRUN_REAL: "",
GITHUB_STEP_SUMMARY: "",
...env,
},
@@ -337,6 +340,159 @@ test(
},
);
+test("the app stapler shim retries only stapler staple and preserves arguments", async (t) => {
+ const root = await makeTempDir(t);
+ const fakeBin = join(root, "fakebin");
+ const callLog = join(root, "xcrun-calls.log");
+ const invocationLog = join(root, "xcrun-invocations.log");
+ await mkdir(fakeBin, { recursive: true });
+ await writeFile(
+ join(fakeBin, "xcrun"),
+ `#!/bin/bash
+printf '<%s>\\n' "$@" >> "$PI_TEST_XCRUN_LOG"
+printf 'call\\n' >> "$PI_TEST_XCRUN_INVOCATIONS"
+if [[ "$1 $2" == "stapler staple" ]]; then
+ PI_TEST_CALLS="$(wc -l < "$PI_TEST_XCRUN_INVOCATIONS" | tr -d ' ')"
+ if (( PI_TEST_CALLS <= PI_TEST_XCRUN_FAILURES )); then
+ echo "The network connection was lost." >&2
+ exit 68
+ fi
+fi
+echo "fake xcrun completed"
+exit 0
+`,
+ );
+ await chmod(join(fakeBin, "xcrun"), 0o755);
+
+ const { status, stdout, stderr } = await runWatchdog(
+ [
+ "--label",
+ "stapler-retry",
+ "--no-codesign-shim",
+ "--",
+ "bash",
+ "-c",
+ 'xcrun "$@"',
+ "bash",
+ "stapler",
+ "staple",
+ "/tmp/PI Desktop.app",
+ ],
+ {
+ env: {
+ PATH: `${fakeBin}:${process.env.PATH}`,
+ PI_TEST_XCRUN_LOG: callLog,
+ PI_TEST_XCRUN_INVOCATIONS: invocationLog,
+ PI_TEST_XCRUN_FAILURES: "2",
+ PI_STAPLER_MAX_ATTEMPTS: "3",
+ PI_STAPLER_RETRY_DELAY_SECONDS: "0",
+ },
+ },
+ );
+
+ assert.equal(status, 0, `${stdout}\n${stderr}`);
+ assert.match(stdout, /stapler-shim=on/);
+ assert.match(stderr, /stapler staple attempt 1\/3 failed/);
+ assert.match(stderr, /stapler staple attempt 2\/3 failed/);
+ assert.equal(
+ (await readFile(callLog, "utf8")).split("\n").filter(Boolean).length,
+ 9,
+ "three attempts must each preserve the three xcrun arguments",
+ );
+ assert.equal(
+ (await readFile(invocationLog, "utf8")).trim().split("\n").length,
+ 3,
+ );
+ assert.ok(stdout.includes("[sign] fake xcrun completed"));
+});
+
+test("the app stapler shim fails after its configured bound", async (t) => {
+ const root = await makeTempDir(t);
+ const fakeBin = join(root, "fakebin");
+ const callLog = join(root, "xcrun-calls.log");
+ await mkdir(fakeBin, { recursive: true });
+ await writeFile(
+ join(fakeBin, "xcrun"),
+`#!/bin/bash
+printf 'call\\n' >> "$PI_TEST_XCRUN_INVOCATIONS"
+exit 68
+`,
+ );
+ await chmod(join(fakeBin, "xcrun"), 0o755);
+
+ const { status, stdout, stderr } = await runWatchdog(
+ [
+ "--label",
+ "stapler-exhausted",
+ "--no-codesign-shim",
+ "--",
+ "bash",
+ "-c",
+ "xcrun stapler staple /tmp/PI-Desktop.app",
+ ],
+ {
+ env: {
+ PATH: `${fakeBin}:${process.env.PATH}`,
+ PI_TEST_XCRUN_INVOCATIONS: callLog,
+ PI_STAPLER_MAX_ATTEMPTS: "3",
+ PI_STAPLER_RETRY_DELAY_SECONDS: "0",
+ },
+ },
+ );
+
+ assert.equal(status, 68, `${stdout}\n${stderr}`);
+ assert.match(stdout, /stapler-shim=on/);
+ assert.equal((await readFile(callLog, "utf8")).trim().split("\n").length, 3);
+ assert.equal((stderr.match(/stapler staple attempt .* failed/g) ?? []).length, 2);
+});
+
+test("the app stapler shim passes non-stapling xcrun commands through once", async (t) => {
+ const root = await makeTempDir(t);
+ const fakeBin = join(root, "fakebin");
+ const callLog = join(root, "xcrun-calls.log");
+ await mkdir(fakeBin, { recursive: true });
+ await writeFile(
+ join(fakeBin, "xcrun"),
+ `#!/bin/bash
+printf '<%s>\\n' "$@" >> "$PI_TEST_XCRUN_LOG"
+exit 0
+`,
+ );
+ await chmod(join(fakeBin, "xcrun"), 0o755);
+
+ const { status, stdout, stderr } = await runWatchdog(
+ [
+ "--label",
+ "notarytool-passthrough",
+ "--no-codesign-shim",
+ "--",
+ "bash",
+ "-c",
+ 'xcrun "$@"',
+ "bash",
+ "notarytool",
+ "submit",
+ "/tmp/PI Desktop.app",
+ ],
+ {
+ env: {
+ PATH: `${fakeBin}:${process.env.PATH}`,
+ PI_TEST_XCRUN_LOG: callLog,
+ PI_STAPLER_MAX_ATTEMPTS: "6",
+ PI_STAPLER_RETRY_DELAY_SECONDS: "0",
+ },
+ },
+ );
+
+ assert.equal(status, 0, `${stdout}\n${stderr}`);
+ assert.deepEqual((await readFile(callLog, "utf8")).trim().split("\n"), [
+ "<notarytool>",
+ "<submit>",
+ "</tmp/PI Desktop.app>",
+ ]);
+ assert.doesNotMatch(stderr, /stapler staple attempt/);
+});
+
test("--no-codesign-shim runs the command untouched and reports zero calls", async (t) => {
const root = await makeTempDir(t);
const codesignLog = join(root, "unused-codesign-timing.log");
diff --git a/docs/adr/0289-signed-macos-github-releases.md b/docs/adr/0289-signed-macos-github-releases.md
index 9f1664b7b..5b083eb6d 100644
--- a/docs/adr/0289-signed-macos-github-releases.md
+++ b/docs/adr/0289-signed-macos-github-releases.md
@@ -28,8 +28,11 @@ for the official `vastsa/PI-Desktop` release lane.
the final DMG is submitted separately (`xcrun notarytool submit --wait`) and
must return `status: Accepted` before `xcrun stapler staple` may run; the
run then verifies the app as `Notarized Developer ID` and both stapled
- tickets before upload. Stapler retries are bounded and only allowed after
- Apple accepts. Missing signing or notarization secrets fail the job;
+ tickets before upload. The app's exact `xcrun stapler staple` call is
+ retried at most six times with a 10-second delay by the signing watchdog;
+ all other `xcrun` calls pass through. The DMG stapler has the same bounded
+ retry policy. Retries only occur after Apple accepts the matching
+ notarization submission. Missing signing or notarization secrets fail the job;
unsigned macOS artifacts must not be published from a tag.
2. The signing certificate is
`Developer ID Application: XingYu Liu (DUV63RKYTW)`; Apple team id
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 9f476bff6..b540c3b40 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -940,8 +940,10 @@ identify the platform validation still needed.
`codesign --verify --deep --strict --verbose=2`,
`spctl --assess --type execute --verbose=4`, and `xcrun stapler validate`
against the app, including `Contents/Resources/bin/pi-desktop-host-core`.
- 4) Confirm the workflow's DMG step reported an Apple notary status of
- `Accepted` and then run `xcrun stapler validate` against the matching DMG.
+ 4) Confirm the app stapler shim retries only `xcrun stapler staple` up to six
+ total attempts after the app submission is accepted, then confirm the
+ workflow's DMG step reported an Apple notary status of `Accepted` and run
+ `xcrun stapler validate` against the matching DMG.
5) Download the DMG on a clean macOS profile, move the app to
`/Applications`, and open it without clearing `com.apple.quarantine`.
- **Expected**: Each macOS app passes signature integrity, Gatekeeper reports
diff --git a/docs/spec/06-delivery/06-release-runbook.md b/docs/spec/06-delivery/06-release-runbook.md
index 21e8e868f..b6be09c16 100644
--- a/docs/spec/06-delivery/06-release-runbook.md
+++ b/docs/spec/06-delivery/06-release-runbook.md
@@ -243,6 +243,15 @@ tickets before any artifact upload. The per-architecture `latest-mac.yml` files
are renamed before upload; the publish job merges them into one feed after
downloading both artifacts.
+For the app ticket, the signing watchdog injects a temporary `xcrun` shim when
+`PI_STAPLER_MAX_ATTEMPTS` is set. It retries only the exact `stapler staple`
+operation, at most six total attempts with a 10-second delay; `notarytool` and
+all other `xcrun` commands pass through unchanged. electron-notarize reaches
+that command only after Apple accepts the app submission. The DMG script has
+its own bounded retry after its separate submission is accepted. Both retry
+paths fail the job if their limit is exhausted, and artifact verification
+still requires valid stapled tickets on the app and DMG.
+
The shared electron-builder configuration applies the architecture-labelled
pattern at the macOS platform level for ZIPs and overrides it at the DMG target
level. Both public architectures are therefore explicit: the arm64 lane
@@ -343,6 +352,7 @@ hide in that gap, and the macOS lanes now expose all three:
| Per-file signing | `codesign --force --sign <identity> --timestamp --entitlements ... <file>` runs serially, deepest file first, the app bundle last | `DEBUG=electron-osx-sign*` prints `Signing... <file>` and `Executing... <file> codesign ...`; the codesign shim times every invocation. If a keychain ever refuses to hand the key to a wrapped `codesign`, `PI_SIGNING_NO_CODESIGN_SHIM=1` runs the phase without the shim |
| Silent retry | A failing pass is retried up to three more times with a 5s/10s/15s backoff and no log line | The watchdog's `codesign-calls` and `failures` lines expose repeated passes |
| App notarization | `@electron/notarize` zips the app, uploads it, and waits for Apple's queue (`mac.notarize=true`) | `DEBUG=electron-notarize*` prints `zipping application to`, `attempting to upload file to Apple`, `notarization success`, then electron-builder prints `notarization successful` |
+| App ticket stapling | `xcrun stapler staple` attaches the accepted app ticket; the watchdog retries only this exact command up to six attempts with a 10-second delay | `stapler-shim=on` appears in the watchdog header and each failed attempt is reported |
| DMG notarization | The DMG carries its own signature, so the next step submits it again with `xcrun notarytool submit --wait` | The same watchdog keeps that wait observable and bounded |
`scripts/macos-signing-watchdog.mjs` wraps both long phases. It forwards every
@@ -362,6 +372,8 @@ block. The knobs:
| `PI_SIGNING_TIMEOUT_SECONDS` | 2400 (CI: 1800 packaging, 1200 DMG) | Hard limit for the wrapped phase: diagnostics are dumped, the process group is killed, and the step exits 124 instead of hanging |
| `PI_SIGNING_STALL_SECONDS` | 300 | Silence with no codesign activity for this long triggers one diagnostics dump; the phase keeps running, because Apple's notarization queue is a legitimate wait |
| `PI_SIGNING_HEARTBEAT_SECONDS` | 60 | Heartbeat interval while the child produces no output |
+| `PI_STAPLER_MAX_ATTEMPTS` | unset (no stapler shim) | When set for signed app packaging, enables at most six attempts for `xcrun stapler staple` |
+| `PI_STAPLER_RETRY_DELAY_SECONDS` | 10 | Delay between failed app stapler attempts (maximum 60 seconds) |
| `DEBUG` | `electron-osx-sign*,electron-notarize*` | Namespaces that expose walking, per-file signing, and notarization progress |
`DEBUG` lists only the two namespaces that sanitize their own command lines,
@@ -412,7 +424,7 @@ artifact per submission and electron-builder only covers the app:
| Artifact | Submitted by | Ticket |
|---|---|---|
-| `PI-Desktop.app` (inside the ZIP) | electron-builder `-c.mac.notarize=true` | stapled by electron-builder |
+| `PI-Desktop.app` (inside the ZIP) | electron-builder `-c.mac.notarize=true` | stapled by electron-builder through the watchdog's bounded `xcrun stapler staple` retry shim |
| `PI-Desktop-<version>-<arch>.dmg` | `scripts/notarize-and-staple-macos-release-dmg.sh` (`notarytool submit --wait`) | stapled by the same script after `status: Accepted` |
A DMG that was never submitted has no ticket, so stapling it fails with
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index af6dd9566..a3dda6d9d 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -3951,7 +3951,7 @@ IPC 请求无法关闭。
#### E2E-196c:macOS 标签工件通过 Gatekeeper 且无需移除隔离属性
- **先决条件**:推送与 `apps/desktop/package.json` 匹配的 `vX.Y.Z` 标签,或手动运行 Release 工作流并保持 `sign_macos: true`(默认);GitHub Actions 已配置 `CSC_LINK`、`CSC_KEY_PASSWORD`、`APPLE_ID`、`APPLE_APP_SPECIFIC_PASSWORD` 和 `APPLE_TEAM_ID` 密钥;两个本机 macOS 运行器均可用。
-- **步骤**:1) 运行标签工作流。2) 对每个 macOS 架构检查解压后的应用,使用 `codesign -dv --verbose=4` 确认权限为 `Developer ID Application: XingYu Liu (DUV63RKYTW)`。3) 对应用运行 `codesign --verify --deep --strict --verbose=2`、`spctl --assess --type execute --verbose=4` 和 `xcrun stapler validate`,并检查 `Contents/Resources/bin/pi-desktop-host-core`。4) 确认工作流的 DMG 步骤报告 Apple 公证状态为 `Accepted`,然后对对应的 DMG 运行 `xcrun stapler validate`。5) 在干净的 macOS 配置文件中下载 DMG,将应用移到 `/Applications` 后不清除 `com.apple.quarantine` 直接打开。
+- **步骤**:1) 运行标签工作流。2) 对每个 macOS 架构检查解压后的应用,使用 `codesign -dv --verbose=4` 确认权限为 `Developer ID Application: XingYu Liu (DUV63RKYTW)`。3) 对应用运行 `codesign --verify --deep --strict --verbose=2`、`spctl --assess --type execute --verbose=4` 和 `xcrun stapler validate`,并检查 `Contents/Resources/bin/pi-desktop-host-core`。4) 确认 app stapler shim 只在 app 公证提交被接受后重试 `xcrun stapler staple`,最多六次;再确认工作流的 DMG 步骤报告 Apple 公证状态为 `Accepted`,并对对应的 DMG 运行 `xcrun stapler validate`。5) 在干净的 macOS 配置文件中下载 DMG,将应用移到 `/Applications` 后不清除 `com.apple.quarantine` 直接打开。
- **预期**:每个 macOS 应用通过签名完整性检查,Gatekeeper 报告 `source=Notarized Developer ID`,应用和 DMG 都包含有效的装订票据。DMG 有自己的提交:从未提交过的 DMG 没有票据,装订会以 error 65 失败,因此标签构建绝不能走到该状态。应用可正常打开,无需 `xattr` 命令或“安全性与隐私”覆盖。缺少密钥、提交被拒或装订重试耗尽都会让作业失败。
- **关联规格**:`06-delivery/06-release-runbook.md`、`05-security/01-security.md`、ADR 0289
- **验收**:质量、安全
diff --git a/docs/zh-CN/spec/06-delivery/06-release-runbook.md b/docs/zh-CN/spec/06-delivery/06-release-runbook.md
index 221dc50ff..85a849ba7 100644
--- a/docs/zh-CN/spec/06-delivery/06-release-runbook.md
+++ b/docs/zh-CN/spec/06-delivery/06-release-runbook.md
@@ -214,6 +214,8 @@ macOS ZIP 在安装包根目录包含 `PI-Desktop.app`。DMG 和 ZIP 都不附
标签构建和 `sign_macos: true`(手动运行的默认值)仅从 GitHub Actions 密钥接收 `CSC_LINK`、`CSC_KEY_PASSWORD`、`APPLE_ID`、`APPLE_APP_SPECIFIC_PASSWORD` 和 `APPLE_TEAM_ID`,通过 `CSC_NAME=XingYu Liu (DUV63RKYTW)`(裸通用名——electron-builder 拒绝 `Developer ID Application:` 前缀)固定证书,强制代码签名与 `notarytool` 公证 `PI-Desktop.app`。随后 DMG 会由 `scripts/notarize-and-staple-macos-release-dmg.sh` 单独提交到同一个服务,只有返回 `Accepted` 才允许装订票据。之后验证身份、代码签名完整性(含 `pi-desktop-host-core`)、Gatekeeper `Notarized Developer ID` 以及两份已装订票据,再进行任何工件上传。
+对于 app 票据,当设置 `PI_STAPLER_MAX_ATTEMPTS` 时,签名看门狗会注入临时 `xcrun` shim。它只重试确切的 `stapler staple` 操作,最多总计六次、间隔 10 秒;`notarytool` 和其他 `xcrun` 命令会原样透传。electron-notarize 仅会在 Apple 接受 app 提交后调用该命令。DMG 脚本会在其单独提交被接受后执行自己的有界重试。任一重试耗尽都会让作业失败;工件验证仍要求 app 和 DMG 都包含有效的装订票据。
+
DMG、ZIP、NSIS、AppImage、deb、rpm、块图和更新程序提要输出已
压缩或压缩不敏感。因此,工作流程会上传它们的
发布作业之前压缩级别为零的临时操作工件
@@ -282,6 +284,7 @@ identityName=...` —— 之后直到该阶段结束都没有任何输出。这
| 逐文件签名 | `codesign --force --sign <identity> --timestamp --entitlements ... <file>` 串行执行,最深的文件优先,应用包最后签 | `DEBUG=electron-osx-sign*` 打印 `Signing... <file>` 与 `Executing... <file> codesign ...`;codesign shim 记录每次调用的耗时。若钥匙串拒绝把私钥交给被包裹的 `codesign`,可设置 `PI_SIGNING_NO_CODESIGN_SHIM=1` 在不使用 shim 的情况下运行该阶段 |
| 静默重试 | 一轮签名失败后最多再重试三次,退避 5s/10s/15s,且没有任何日志行 | 看门狗汇总中的 `codesign-calls` 与 `failures` 行会暴露重复的整轮签名 |
| 应用公证 | `@electron/notarize` 打包 zip、上传并等待 Apple 队列(`mac.notarize=true`) | `DEBUG=electron-notarize*` 打印 `zipping application to`、`attempting to upload file to Apple`、`notarization success`,随后 electron-builder 打印 `notarization successful` |
+| 应用票据装订 | `xcrun stapler staple` 附加已接受的 app 票据;看门狗只对这一确切命令最多重试六次,间隔 10 秒 | 看门狗标题显示 `stapler-shim=on`,并报告每次失败 |
| DMG 公证 | DMG 有自己的签名,因此下一步会用 `xcrun notarytool submit --wait` 再提交一次 | 同一个看门狗让该等待过程可见并且有上限 |
`scripts/macos-signing-watchdog.mjs` 包裹这两个长时间阶段。它给子进程的每一行加上
@@ -297,6 +300,8 @@ codesign 耗时 —— 调用次数、总耗时、p50、p95、最大值以及最
| `PI_SIGNING_TIMEOUT_SECONDS` | 2400(CI:打包 1800,DMG 1200) | 被包裹阶段的硬上限:输出诊断、杀掉进程组,并以 124 退出而不是继续挂起 |
| `PI_SIGNING_STALL_SECONDS` | 300 | 无 codesign 活动的静默持续这么长时间就触发一次诊断输出;阶段继续运行,因为等待 Apple 公证队列是合法等待 |
| `PI_SIGNING_HEARTBEAT_SECONDS` | 60 | 子进程无输出时的心跳间隔 |
+| `PI_STAPLER_MAX_ATTEMPTS` | 未设置(不启用 stapler shim) | 为签名 app 打包设置后,`xcrun stapler staple` 最多执行六次 |
+| `PI_STAPLER_RETRY_DELAY_SECONDS` | 10 | app 装订失败后的间隔(最长 60 秒) |
| `DEBUG` | `electron-osx-sign*,electron-notarize*` | 暴露遍历、逐文件签名与公证进度的命名空间 |
`DEBUG` 只列出两个会自行清洗命令行的命名空间,因为 `electron-builder` 的命名空间在这里
@@ -333,7 +338,7 @@ override 作用于它。它的 `signApplication()` 对每个文件 `await` 一
| 工件 | 提交方 | 票据 |
|---|---|---|
-| `PI-Desktop.app`(ZIP 内) | electron-builder `-c.mac.notarize=true` | 由 electron-builder 装订 |
+| `PI-Desktop.app`(ZIP 内) | electron-builder `-c.mac.notarize=true` | electron-builder 通过看门狗的有界 `xcrun stapler staple` 重试 shim 装订 |
| `PI-Desktop-<version>-<arch>.dmg` | `scripts/notarize-and-staple-macos-release-dmg.sh`(`notarytool submit --wait`) | 同一脚本在 `status: Accepted` 后装订 |
从未提交过的 DMG 没有票据,因此装订会失败并报 `Could not find base64 encoded ticket ... Error 65`。只有在 Apple 返回 `Accepted` 之后才允许重试装订。
diff --git a/scripts/README.md b/scripts/README.md
index 5523822a4..098f2f283 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -23,10 +23,11 @@ disagrees, so a green `check:release-docs` is a precondition, not a substitute.
| Script | Alias | Purpose |
|---|---|---|
| `notarize-and-staple-macos-release-dmg.sh` | `scripts/notarize-and-staple-macos-release-dmg.sh [release-dir]` | Submit the single DMG a native macOS job produced to Apple's notary service (`xcrun notarytool submit --wait`), require `status: Accepted`, then attach and validate the ticket (`xcrun stapler staple` / `validate`); run by the Release workflow when `sign_macos` is set. electron-builder only notarizes the `.app`, so the DMG needs this separate submission |
+| `macos-stapler-retry-shim.sh` | injected by `macos-signing-watchdog.mjs` when `PI_STAPLER_MAX_ATTEMPTS` is set | Retry only `xcrun stapler staple` up to the configured bound; all other `xcrun` commands pass through unchanged |
| `verify-macos-release.sh` | `scripts/verify-macos-release.sh [release-dir]` | Fail unless the one `PI-Desktop.app` and DMG under the release directory are Developer ID-signed, notarized, and stapled; run by the Release workflow after stapling |
| `macos-signing-diagnostics.sh` | `scripts/macos-signing-diagnostics.sh [--require-identity]` | Print the non-secret signing baseline before packaging (system, `codesign`, keychain identities/list/default, Xcode notary tools, Apple timestamp reachability). Informational by default, because the Developer ID identity is imported from `CSC_LINK` during packaging; `--require-identity` makes a missing Developer ID fatal |
| `macos-bundle-inventory.mjs` | `node scripts/macos-bundle-inventory.mjs <app-or-release-dir>` | Count what the signing phase has to touch: entries, Mach-O binaries, `.dylib`/`.node`/frameworks/nested bundles, per-directory cost, and the largest binaries (`signing-candidates`). Informational; run after every macOS package build |
-| `macos-signing-watchdog.mjs` | `node scripts/macos-signing-watchdog.mjs [options] -- <command>` | Run a long silent phase (`electron-builder` signing, `notarytool submit --wait`) with a heartbeat, phase tracking, stall diagnostics (last file, `ps` state, codesign log tail), per-file codesign timings, and a hard timeout that fails instead of hanging; it forwards the child output and exit code unchanged and redacts `CSC_KEY_PASSWORD`/`APPLE_APP_SPECIFIC_PASSWORD`/`CSC_LINK` values plus `--password` arguments |
+| `macos-signing-watchdog.mjs` | `node scripts/macos-signing-watchdog.mjs [options] -- <command>` | Run a long silent phase (`electron-builder` signing, `notarytool submit --wait`) with a heartbeat, phase tracking, stall diagnostics (last file, `ps` state, codesign log tail), per-file codesign timings, optional bounded app stapler retries, and a hard timeout that fails instead of hanging; it forwards the child output and exit code unchanged and redacts `CSC_KEY_PASSWORD`/`APPLE_APP_SPECIFIC_PASSWORD`/`CSC_LINK` values plus `--password` arguments |
| `macos-codesign-shim.sh` | used by `macos-signing-watchdog.mjs` | PATH shim that timestamps every `codesign` invocation and then executes the real `codesign`; inert unless `PI_CODESIGN_LOG` is set |
| `export-linux-asar.mjs` | `node scripts/export-linux-asar.mjs` | Copy the Linux `linux-unpacked/resources/app.asar` into the versioned release asset used for system-Electron repackaging |
| `build-desktop-release.mjs` | called by the desktop `dist` / `dist:win` scripts | Build the native runner target without publishing; Windows runs separate NSIS and ZIP passes and stamps their updater distribution metadata |
diff --git a/scripts/macos-signing-watchdog.mjs b/scripts/macos-signing-watchdog.mjs
index 6abbf3080..439ab05fa 100644
--- a/scripts/macos-signing-watchdog.mjs
+++ b/scripts/macos-signing-watchdog.mjs
@@ -19,6 +19,8 @@
* - every child line is forwarded live with a `[sign] ` prefix (redacted),
* - `codesign` is wrapped by scripts/macos-codesign-shim.sh so each call is
* timed through $PI_CODESIGN_LOG (see --codesign-log),
+ * - when PI_STAPLER_MAX_ATTEMPTS is set, `xcrun stapler staple` is wrapped
+ * with bounded retries; every other xcrun invocation passes through,
* - a heartbeat reports phase/idle time/active codesign while output is
* silent, plus a bounded stall diagnostic dump,
* - a hard timeout terminates the whole process group and exits 124,
@@ -49,6 +51,9 @@ import { fileURLToPath } from "node:url";
const SHIM_SOURCE_PATH = fileURLToPath(
new URL("./macos-codesign-shim.sh", import.meta.url),
);
+const STAPLER_SHIM_SOURCE_PATH = fileURLToPath(
+ new URL("./macos-stapler-retry-shim.sh", import.meta.url),
+);
const DEFAULT_CODESIGN_LOG = join(
tmpdir(),
`pi-desktop-codesign-timing-${process.pid}.log`,
@@ -264,6 +269,26 @@ function resolveRealCodesign(pathValue) {
return "/usr/bin/codesign";
}
+function resolveRealXcrun(pathValue) {
+ try {
+ const result = spawnSync("bash", ["-c", "command -v xcrun"], {
+ encoding: "utf8",
+ env: { ...process.env, PATH: pathValue },
+ });
+ const candidates = (result.stdout ?? "")
+ .split("\n")
+ .map((line) => line.trim())
+ .filter(Boolean);
+ const candidate = candidates[candidates.length - 1];
+ if (typeof candidate === "string" && candidate.startsWith("/")) {
+ return candidate;
+ }
+ } catch {
+ // Fall through to the system default.
+ }
+ return "/usr/bin/xcrun";
+}
+
/**
* Line splitter that keeps partial lines buffered so a child killed mid-line
* still flushes its remainder on exit ('end' or an explicit flush()).
@@ -428,41 +453,74 @@ function run() {
};
const isDarwin = process.platform === "darwin";
- const useShim = options.codesignShim && isDarwin;
+ const useCodesignShim = options.codesignShim && isDarwin;
+ const useStaplerShim =
+ typeof process.env.PI_STAPLER_MAX_ATTEMPTS === "string" &&
+ process.env.PI_STAPLER_MAX_ATTEMPTS.trim() !== "";
+ const useShim = useCodesignShim || useStaplerShim;
let shimRoot = "";
let childEnv = { ...process.env };
- let shimActive = false;
+ let codesignShimActive = false;
+ let staplerShimActive = false;
if (useShim) {
try {
- const realCodesign = resolveRealCodesign(process.env.PATH ?? "");
shimRoot = mkdtempSync(join(tmpdir(), "pi-desktop-signing-watchdog-"));
const shimDir = join(shimRoot, "bin");
mkdirSync(shimDir, { recursive: true });
- const shimPath = join(shimDir, "codesign");
- writeFileSync(shimPath, readFileSync(SHIM_SOURCE_PATH));
- chmodSync(shimPath, 0o755);
- mkdirSync(dirname(options.codesignLog), { recursive: true });
- // Start from an empty log so a previous run cannot pollute the summary.
- writeFileSync(options.codesignLog, "");
+ if (useCodesignShim) {
+ const realCodesign = resolveRealCodesign(process.env.PATH ?? "");
+ const shimPath = join(shimDir, "codesign");
+ writeFileSync(shimPath, readFileSync(SHIM_SOURCE_PATH));
+ chmodSync(shimPath, 0o755);
+ mkdirSync(dirname(options.codesignLog), { recursive: true });
+ // Start from an empty log so a previous run cannot pollute the summary.
+ writeFileSync(options.codesignLog, "");
+ childEnv = {
+ ...childEnv,
+ PI_CODESIGN_LOG: options.codesignLog,
+ PI_CODESIGN_REAL: realCodesign,
+ };
+ codesignShimActive = true;
+ }
+ if (useStaplerShim) {
+ const realXcrun = resolveRealXcrun(process.env.PATH ?? "");
+ const shimPath = join(shimDir, "xcrun");
+ writeFileSync(shimPath, readFileSync(STAPLER_SHIM_SOURCE_PATH));
+ chmodSync(shimPath, 0o755);
+ childEnv = { ...childEnv, PI_XCRUN_REAL: realXcrun };
+ staplerShimActive = true;
+ }
childEnv = {
...childEnv,
PATH: `${shimDir}:${process.env.PATH ?? ""}`,
- PI_CODESIGN_LOG: options.codesignLog,
- PI_CODESIGN_REAL: realCodesign,
};
- shimActive = true;
} catch (error) {
- // Timing data is diagnostics: losing it must not fail the release.
+ if (shimRoot !== "") {
+ try {
+ rmSync(shimRoot, { recursive: true, force: true });
+ } catch {
+ // Best effort: a leftover temp directory is harmless.
+ }
+ }
shimRoot = "";
process.stderr.write(
- `[sign] warning: codesign timing shim disabled (${redact(error.message)})\n`,
+ `[sign] warning: signing command shims disabled (${redact(error.message)})\n`,
);
+ codesignShimActive = false;
+ staplerShimActive = false;
+ if (useStaplerShim) {
+ process.stderr.write(
+ "[sign] error: could not install the requested stapler retry shim.\n",
+ );
+ process.exitCode = 1;
+ return;
+ }
}
}
process.stdout.write(
- `[sign] watchdog label=${options.label} timeout=${options.timeoutSeconds}s stall=${options.stallSeconds}s heartbeat=${options.heartbeatSeconds}s codesign-shim=${shimActive ? "on" : "off"}\n`,
+ `[sign] watchdog label=${options.label} timeout=${options.timeoutSeconds}s stall=${options.stallSeconds}s heartbeat=${options.heartbeatSeconds}s codesign-shim=${codesignShimActive ? "on" : "off"} stapler-shim=${staplerShimActive ? "on" : "off"}\n`,
);
process.stdout.write(
`[sign] watchdog command: ${redact(options.command.map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(" "))}\n`,
@@ -485,7 +543,7 @@ function run() {
);
const heartbeatDueMs = Math.max(0, heartbeatIntervalMs - tickIntervalMs);
const readShimState = () =>
- useShim
+ useCodesignShim && codesignShimActive
? readCodesignLog(options.codesignLog)
: { calls: [], active: [], failures: 0 };
@@ -563,7 +621,7 @@ function run() {
}
function codesignLogTail() {
- if (!useShim) return [];
+ if (!useCodesignShim || !codesignShimActive) return [];
try {
const raw = readFileSync(options.codesignLog, "utf8");
return raw
diff --git a/scripts/macos-stapler-retry-shim.sh b/scripts/macos-stapler-retry-shim.sh
new file mode 100644
index 000000000..c4d9fe7a2
--- /dev/null
+++ b/scripts/macos-stapler-retry-shim.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+# Retry only the stapling operation after the caller has an accepted ticket.
+# electron-notarize invokes this command only after notarytool reports Accepted.
+
+set -u
+
+PI_STAPLER_REAL_XCRUN="${PI_XCRUN_REAL:-/usr/bin/xcrun}"
+
+if [[ "${1:-}" != "stapler" || "${2:-}" != "staple" || -z "${PI_STAPLER_MAX_ATTEMPTS:-}" ]]; then
+ exec "$PI_STAPLER_REAL_XCRUN" "$@"
+fi
+
+PI_STAPLER_ATTEMPTS="$PI_STAPLER_MAX_ATTEMPTS"
+PI_STAPLER_DELAY="${PI_STAPLER_RETRY_DELAY_SECONDS:-10}"
+
+if [[ ! "$PI_STAPLER_ATTEMPTS" =~ ^[1-6]$ ]]; then
+ echo "error: PI_STAPLER_MAX_ATTEMPTS must be between 1 and 6." >&2
+ exit 2
+fi
+
+if [[ ! "$PI_STAPLER_DELAY" =~ ^[0-9]+$ ]] || (( PI_STAPLER_DELAY > 60 )); then
+ echo "error: PI_STAPLER_RETRY_DELAY_SECONDS must be between 0 and 60." >&2
+ exit 2
+fi
+
+PI_STAPLER_STATUS=1
+for ((attempt = 1; attempt <= PI_STAPLER_ATTEMPTS; attempt += 1)); do
+ if "$PI_STAPLER_REAL_XCRUN" "$@"; then
+ exit 0
+ else
+ PI_STAPLER_STATUS=$?
+ fi
+
+ if (( attempt < PI_STAPLER_ATTEMPTS )); then
+ echo "warning: stapler staple attempt $attempt/$PI_STAPLER_ATTEMPTS failed; retrying in ${PI_STAPLER_DELAY}s." >&2
+ sleep "$PI_STAPLER_DELAY"
+ fi
+done
+
+exit "$PI_STAPLER_STATUS"
diff --git a/scripts/release-macos.sh b/scripts/release-macos.sh
index 26e4a8e34..455cca73b 100755
--- a/scripts/release-macos.sh
+++ b/scripts/release-macos.sh
@@ -90,6 +90,8 @@ echo "==> Packaging the desktop (Developer ID signed + notarized, $MAC_ARCH)"
# `executing` line prints every spawned command with only its own stem list
# redacted, which leaves `security set-key-partition-list -k <p12 password>`
# in clear text on a terminal or in a log file.
+PI_STAPLER_MAX_ATTEMPTS="${PI_STAPLER_MAX_ATTEMPTS:-6}" \
+PI_STAPLER_RETRY_DELAY_SECONDS="${PI_STAPLER_RETRY_DELAY_SECONDS:-10}" \
DEBUG="${DEBUG:-electron-osx-sign*,electron-notarize*}" \
node scripts/macos-signing-watchdog.mjs --label "release-macos-${MAC_ARCH}" -- \
pnpm --filter @pi-desktop/desktop exec electron-builder --mac "--${MAC_ARCH}" \