Merge master and fix CI on shared menu branch

- 合并最新 master,无冲突。
- 清理 `no-unknown-casts` 基线中已失效的 `session-log-export` 测试条目。
- 会话行 ⋯ 改为共享 `contextMenu.button` 后会显示 tooltip;它在气泡尺寸
  测量完成后才可见,原用例在假时钟下立即记录,结果取决于渲染时机。用例
  改为等待该 tooltip 可见,快照 `more-hover` 阶段记录该 tooltip。
- 删除子菜单几何用例中对父卡片施加 `transform` 的步骤。它验证的是已删除
  的逐帧移动跟踪;产品中的菜单卡片不带 transform,CSS 锚点对 transform
  的跟随由浏览器决定,WebKit 在负载下不稳定。行外边距、字号、父列表滚动
  与视口缩窄的真实布局验证保留。
This commit is contained in:
zhc
2026-11-04 13:56:23 +08:00
169 changed files with 2004 additions and 338 deletions
+1 -1
View File
@@ -6,4 +6,4 @@ The manual [Windows packaging workflow](workflows/windows-package.yml) uses the
The merge checks run from three workflows named `Policy`, which run on `pull_request_target` and cover pull requests into master or a `release/dsh-x.y.z` branch, so their definitions come from the base branch, and call the `deepseek-harness-check` action directly: `pr-check-on-head-branch.yml` on pull-request updates gives `Policy / Master Change` and `Policy / Pre-Merge Check`, `pr-check-after-approve.yml` on pull-request updates and submitted or dismissed reviews gives `Policy / Approve Check`, which also publishes the review verdict as the check run `Policy / Reviewer Check`, and `pr-check-on-base-branch.yml` on pushes to master or a release branch re-runs the head-branch checks as `Policy / Recheck`. Branch rules require those check names, so keep the job names and the workflow name. Each job reads its mode from a repository variable: `MERGE_POLICY_MASTER_DIFF`, `MERGE_POLICY_PRE_MERGE`, and `MERGE_POLICY_HEAD_DIFF`, each `off` (skip), `report` (run without failing the job), or `block` (fail the job); a missing value or an unknown one counts as `report`. `MERGE_POLICY_HEAD_DIFF` decides whether `Policy / Approve Check` runs and fails; while it runs, `Policy / Reviewer Check` is published whatever that mode says, with `success` when every file that needs review has one and `action_required` with the reviewers to ask otherwise. `Policy / Pre-Merge Check` merges the commit `Policy / Master Change` reports, so it runs only after that job and stays off while `MERGE_POLICY_MASTER_DIFF` is `off`; a merge it cannot do and a build that fails both follow its own mode, so `report` warns and skips the build while `block` fails the job. `Policy / Pre-Merge Check` runs `scripts/pre-merge-check.ts` under plain Node and knows nothing else about the merged tree: that script checks the released manifests against the root version, installs, and builds the Host and Client contracts, so change it in one pull request together with the build it orchestrates.
The manual Desktop publication workflow selects a successful package run and attempt, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job.
The manual Desktop publication workflow selects the original successful `package` job attempt independently of `upload-artifact` archival status, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job.
+100
View File
@@ -9,6 +9,11 @@ on:
description: '打包运行 ID:填写成功的 Package Desktop run ID;发布环境和 release ID 沿用原包'
type: string
required: true
upload_website:
description: '同时上传官网安装包并刷新缓存(仅 production);取消后仅执行版本与自动更新发布'
type: boolean
default: true
required: true
package_run_attempt:
description: '打包尝试次数:留空选择最新一次,且必须成功;失败时不会回退到旧包'
type: string
@@ -57,9 +62,13 @@ jobs:
route: ${{ steps.local.outputs.route }}
preset: ${{ steps.local.outputs.preset }}
approval: ${{ steps.check.outputs.approval }}
website-approval: ${{ steps.check.outputs.website-approval }}
website-destination: ${{ steps.check.outputs.website-destination }}
label: ${{ steps.check.outputs.label }}
env:
DESKTOP_PACKAGE_SELECTION: ${{ needs.route.outputs.selection }}
DESKTOP_UPLOAD_WEBSITE: ${{ inputs.upload_website }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
DSH_TELEMETRY_DISABLED: '1'
steps:
- uses: actions/checkout@v7.0.1
@@ -151,6 +160,7 @@ jobs:
DESKTOP_TAG_TOKEN: ${{ steps.app.outputs.token }}
run: node --import tsx apps/desktop/scripts/publish-desktop-ci.ts --publish
- name: Retain publication audit
continue-on-error: true
if: always() && steps.publish.outputs.record != ''
uses: actions/upload-artifact@v7.0.1
with:
@@ -158,3 +168,93 @@ jobs:
path: ${{ steps.publish.outputs.record }}/
if-no-files-found: error
retention-days: 30
upload-website-installer:
needs: [route, prepare, publish]
if: inputs.upload_website && needs.prepare.outputs.preset != 'test'
runs-on: [self-hosted, '${{ needs.route.outputs.runner }}']
environment: desktop-production
timeout-minutes: 60
concurrency:
group: desktop-website-upload-${{ needs.prepare.outputs.website-destination }}
cancel-in-progress: false
env:
DESKTOP_PUBLISH_ROUTE: ${{ needs.prepare.outputs.route }}
DESKTOP_WEBSITE_APPROVAL: ${{ needs.prepare.outputs.website-approval }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
clean: false
path: website-publisher
- uses: pnpm/action-setup@v5.0.0
with:
package_json_file: website-publisher/package.json
dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: '24'
- name: Check local publication configuration
working-directory: website-publisher
run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs
- run: pnpm install --frozen-lockfile
working-directory: website-publisher
- name: Upload website installer
id: website
working-directory: website-publisher
run: node --import tsx apps/desktop/scripts/publish-website-ci.ts upload
- name: Archive website publication diagnostics
if: always() && steps.website.outputs.record != ''
continue-on-error: true
uses: actions/upload-artifact@v7.0.1
with:
name: website-upload-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ steps.website.outputs.record }}/
if-no-files-found: warn
retention-days: 30
purge-website-installer:
needs: [route, prepare, upload-website-installer]
if: inputs.upload_website && needs.prepare.outputs.preset != 'test'
runs-on: [self-hosted, '${{ needs.route.outputs.runner }}']
environment: desktop-production
timeout-minutes: 60
concurrency:
group: desktop-website-purge-${{ needs.prepare.outputs.website-destination }}
cancel-in-progress: false
env:
DESKTOP_PUBLISH_ROUTE: ${{ needs.prepare.outputs.route }}
DESKTOP_WEBSITE_APPROVAL: ${{ needs.prepare.outputs.website-approval }}
DOWNLOAD_PROD_EO_ZONE_ID: ${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
clean: false
path: website-publisher
- uses: pnpm/action-setup@v5.0.0
with:
package_json_file: website-publisher/package.json
dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: '24'
- name: Check local publication configuration
working-directory: website-publisher
run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs
- run: pnpm install --frozen-lockfile
working-directory: website-publisher
- name: Recover and observe website cache purge
id: website
working-directory: website-publisher
run: node --import tsx apps/desktop/scripts/publish-website-ci.ts purge
- name: Archive website publication diagnostics
if: always() && steps.website.outputs.record != ''
continue-on-error: true
uses: actions/upload-artifact@v7.0.1
with:
name: website-purge-${{ github.run_id }}-${{ github.run_attempt }}
path: ${{ steps.website.outputs.record }}/
if-no-files-found: warn
retention-days: 30
+49 -2
View File
@@ -57,6 +57,13 @@ concurrency:
jobs:
package:
outputs:
directory: ${{ steps.retained.outputs.directory }}
runner: ${{ steps.retained.outputs.runner }}
runner-name: ${{ steps.retained.outputs.runner-name }}
attempt: ${{ steps.retained.outputs.attempt }}
version: ${{ steps.settings.outputs.version }}
mode: ${{ steps.settings.outputs.mode }}
runs-on: [self-hosted, macOS, ARM64, dsh-mac-package-trial]
timeout-minutes: 180
defaults:
@@ -98,6 +105,7 @@ jobs:
if(branch==='HEAD' || branch!==ref || ref.startsWith('refs/')) throw Error('Select a branch in this repository, not a SHA or PR ref');
}
if(!fs.readFileSync('apps/desktop/scripts/prepare-macos-ci.mjs','utf8').includes('resolveDesktopBuildTarget')) throw Error('Source lacks Intel macOS CI support; select a newer source');
if(!fs.readFileSync('apps/desktop/scripts/retain-desktop-ci.ts','utf8').includes('--check-runner')) throw Error('Source lacks independent Desktop artifact archival support; select a newer source');
if(!fs.readFileSync('apps/desktop/scripts/desktop-ci-version.mjs','utf8').includes('PACKAGE_VERSION_MODE')) throw Error('Source lacks Desktop channel/version CI support; select a newer release');"
- uses: pnpm/action-setup@v5.0.0
with:
@@ -115,6 +123,10 @@ jobs:
run: arch -x86_64 /usr/bin/true
- name: Install locked dependencies
run: pnpm install --frozen-lockfile
- name: Check original machine archival route
env:
DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }}
run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts --check-runner
- name: Validate preset and resolve build version
id: settings
env:
@@ -154,10 +166,12 @@ jobs:
- name: Retain complete package outside the checkout
id: retained
env:
DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }}
PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }}
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts
- name: Retain packaging diagnostics
continue-on-error: true
if: always() && steps.checkout.outcome == 'success'
uses: actions/upload-artifact@v7.0.1
with:
@@ -166,13 +180,46 @@ jobs:
path: apps/desktop/.desktop-build/packaging-runs/
if-no-files-found: warn
retention-days: 14
upload-artifact:
needs: package
runs-on: [self-hosted, '${{ needs.package.outputs.runner }}']
timeout-minutes: 30
env:
DESKTOP_RETAINED_DIRECTORY: ${{ needs.package.outputs.directory }}
DESKTOP_PACKAGE_ATTEMPT: ${{ needs.package.outputs.attempt }}
DESKTOP_PACKAGE_RUNNER: ${{ needs.package.outputs.runner-name }}
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
path: artifact-archiver
- uses: pnpm/action-setup@v5.0.0
with:
package_json_file: artifact-archiver/package.json
dest: ${{ runner.temp }}/archive-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: '24'
- name: Configure persistent package caches
env:
DSH_DESKTOP_PACKAGE_CACHE_DIR: ${{ runner.tool_cache }}/dsh-desktop-package-cache
run: |
echo "DSH_DESKTOP_PACKAGE_CACHE_DIR=$DSH_DESKTOP_PACKAGE_CACHE_DIR" >> "$GITHUB_ENV"
echo "PNPM_CONFIG_STORE_DIR=$DSH_DESKTOP_PACKAGE_CACHE_DIR/workspace-pnpm-store" >> "$GITHUB_ENV"
- run: pnpm install --frozen-lockfile
working-directory: artifact-archiver
- name: Verify original retained build before GitHub archival
working-directory: artifact-archiver
run: node --import tsx apps/desktop/scripts/archive-desktop-ci.ts
- name: Retain installers for the selected mode
if: success()
uses: actions/upload-artifact@v7.0.1
with:
name: macos-x64-${{ steps.settings.outputs.mode }}-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }}
name: macos-x64-${{ needs.package.outputs.mode }}-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}
include-hidden-files: true
path: ${{ steps.retained.outputs.directory }}/*
path: ${{ needs.package.outputs.directory }}/*
compression-level: 0
if-no-files-found: error
retention-days: 14
overwrite: true
+49 -2
View File
@@ -57,6 +57,13 @@ concurrency:
jobs:
package:
outputs:
directory: ${{ steps.retained.outputs.directory }}
runner: ${{ steps.retained.outputs.runner }}
runner-name: ${{ steps.retained.outputs.runner-name }}
attempt: ${{ steps.retained.outputs.attempt }}
version: ${{ steps.settings.outputs.version }}
mode: ${{ steps.settings.outputs.mode }}
runs-on: [self-hosted, macOS, ARM64, dsh-mac-package-trial]
timeout-minutes: 180
defaults:
@@ -97,6 +104,7 @@ jobs:
const branch=cp.execFileSync('git',['rev-parse','--abbrev-ref','HEAD'],{encoding:'utf8'}).trim();
if(branch==='HEAD' || branch!==ref || ref.startsWith('refs/')) throw Error('Select a branch in this repository, not a SHA or PR ref');
}
if(!fs.readFileSync('apps/desktop/scripts/retain-desktop-ci.ts','utf8').includes('--check-runner')) throw Error('Source lacks independent Desktop artifact archival support; select a newer source');
if(!fs.readFileSync('apps/desktop/scripts/desktop-ci-version.mjs','utf8').includes('PACKAGE_VERSION_MODE')) throw Error('Source lacks Desktop channel/version CI support; select a newer release');"
- uses: pnpm/action-setup@v5.0.0
with:
@@ -112,6 +120,10 @@ jobs:
echo "PNPM_CONFIG_STORE_DIR=$DSH_DESKTOP_PACKAGE_CACHE_DIR/workspace-pnpm-store" >> "$GITHUB_ENV"
- name: Install locked dependencies
run: pnpm install --frozen-lockfile
- name: Check original machine archival route
env:
DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }}
run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts --check-runner
- name: Validate preset and resolve build version
id: settings
env:
@@ -151,10 +163,12 @@ jobs:
- name: Retain complete package outside the checkout
id: retained
env:
DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }}
PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }}
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts
- name: Retain packaging diagnostics
continue-on-error: true
if: always() && steps.checkout.outcome == 'success'
uses: actions/upload-artifact@v7.0.1
with:
@@ -163,13 +177,46 @@ jobs:
path: apps/desktop/.desktop-build/packaging-runs/
if-no-files-found: warn
retention-days: 14
upload-artifact:
needs: package
runs-on: [self-hosted, '${{ needs.package.outputs.runner }}']
timeout-minutes: 30
env:
DESKTOP_RETAINED_DIRECTORY: ${{ needs.package.outputs.directory }}
DESKTOP_PACKAGE_ATTEMPT: ${{ needs.package.outputs.attempt }}
DESKTOP_PACKAGE_RUNNER: ${{ needs.package.outputs.runner-name }}
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
path: artifact-archiver
- uses: pnpm/action-setup@v5.0.0
with:
package_json_file: artifact-archiver/package.json
dest: ${{ runner.temp }}/archive-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: '24'
- name: Configure persistent package caches
env:
DSH_DESKTOP_PACKAGE_CACHE_DIR: ${{ runner.tool_cache }}/dsh-desktop-package-cache
run: |
echo "DSH_DESKTOP_PACKAGE_CACHE_DIR=$DSH_DESKTOP_PACKAGE_CACHE_DIR" >> "$GITHUB_ENV"
echo "PNPM_CONFIG_STORE_DIR=$DSH_DESKTOP_PACKAGE_CACHE_DIR/workspace-pnpm-store" >> "$GITHUB_ENV"
- run: pnpm install --frozen-lockfile
working-directory: artifact-archiver
- name: Verify original retained build before GitHub archival
working-directory: artifact-archiver
run: node --import tsx apps/desktop/scripts/archive-desktop-ci.ts
- name: Retain installers for the selected mode
if: success()
uses: actions/upload-artifact@v7.0.1
with:
name: macos-arm64-${{ steps.settings.outputs.mode }}-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }}
name: macos-arm64-${{ needs.package.outputs.mode }}-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}
include-hidden-files: true
path: ${{ steps.retained.outputs.directory }}/*
path: ${{ needs.package.outputs.directory }}/*
compression-level: 0
if-no-files-found: error
retention-days: 14
overwrite: true
+65 -4
View File
@@ -63,6 +63,13 @@ concurrency:
jobs:
package:
outputs:
directory: ${{ steps.retained.outputs.directory }}
runner: ${{ steps.retained.outputs.runner }}
runner-name: ${{ steps.retained.outputs.runner-name }}
attempt: ${{ steps.retained.outputs.attempt }}
version: ${{ steps.settings.outputs.version }}
mode: ${{ steps.settings.outputs.mode }}
runs-on: dsh-win-package-trial
timeout-minutes: 120
defaults:
@@ -127,6 +134,7 @@ jobs:
const branch=cp.execFileSync('git',['rev-parse','--abbrev-ref','HEAD'],{encoding:'utf8'}).trim();
if(branch==='HEAD' || branch!==ref || ref.startsWith('refs/')) throw Error('Select a branch in this repository, not a SHA or PR ref');
}
if(!fs.readFileSync('apps/desktop/scripts/retain-desktop-ci.ts','utf8').includes('--check-runner')) throw Error('Source lacks independent Desktop artifact archival support; select a newer source');
if(!fs.readFileSync('apps/desktop/scripts/desktop-ci-version.mjs','utf8').includes('PACKAGE_VERSION_MODE')) throw Error('Source lacks Desktop channel/version CI support; select a newer release');"
- uses: pnpm/action-setup@v5.0.0
with:
@@ -158,6 +166,10 @@ jobs:
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
pnpm install --frozen-lockfile
exit $LASTEXITCODE
- name: Check original machine archival route
env:
DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }}
run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts --check-runner
- name: Validate preset and resolve build version
id: settings
env:
@@ -183,10 +195,12 @@ jobs:
- name: Retain complete package outside the checkout
id: retained
env:
DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }}
PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }}
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
run: node --import tsx apps/desktop/scripts/retain-desktop-ci.ts
- name: Retain packaging diagnostics
continue-on-error: true
if: always() && steps.checkout.outcome == 'success'
uses: actions/upload-artifact@v7.0.1
with:
@@ -195,23 +209,70 @@ jobs:
path: ${{ github.workspace }}/apps/desktop/.desktop-build/packaging-runs/
if-no-files-found: warn
retention-days: 14
upload-artifact:
defaults:
run:
shell: pwsh
needs: package
runs-on: [self-hosted, '${{ needs.package.outputs.runner }}']
timeout-minutes: 30
env:
PACKAGE_CACHE_NAMESPACE: ${{ inputs.cache_namespace }}
DESKTOP_RETAINED_DIRECTORY: ${{ needs.package.outputs.directory }}
DESKTOP_PACKAGE_ATTEMPT: ${{ needs.package.outputs.attempt }}
DESKTOP_PACKAGE_RUNNER: ${{ needs.package.outputs.runner-name }}
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
path: artifact-archiver
- uses: pnpm/action-setup@v5.0.0
with:
package_json_file: artifact-archiver/package.json
dest: ${{ runner.temp }}/archive-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
- uses: actions/setup-node@v7.0.0
with:
node-version: '24'
- name: Configure persistent pnpm store
# PNPM_HOME belongs to this run; keep downloaded packages outside its temporary directory.
env:
DSH_DESKTOP_PACKAGE_CACHE_DIR: ${{ runner.tool_cache }}/dsh-desktop-package-cache
run: |
$storeRoot = Join-Path ([IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE)) '.pnpm-store'
$namespace = $env:PACKAGE_CACHE_NAMESPACE
if ($namespace) {
if ($namespace -cnotmatch '^[a-z0-9][a-z0-9-]{0,63}\z') { throw 'Cache namespace must contain 1-64 lowercase letters, digits or hyphens' }
if ($namespace -match '^(con|prn|aux|nul|com[1-9]|lpt[1-9])$') { throw 'Cache namespace cannot be a Windows device name' }
$storeRoot = Join-Path $storeRoot $namespace
$env:DSH_DESKTOP_PACKAGE_CACHE_DIR = Join-Path $env:DSH_DESKTOP_PACKAGE_CACHE_DIR $namespace
}
"DSH_DESKTOP_PACKAGE_CACHE_DIR=$env:DSH_DESKTOP_PACKAGE_CACHE_DIR" >> $env:GITHUB_ENV
"PNPM_CONFIG_STORE_DIR=$storeRoot" >> $env:GITHUB_ENV
- run: pnpm install --frozen-lockfile
working-directory: artifact-archiver
- name: Verify original retained build before GitHub archival
working-directory: artifact-archiver
run: node --import tsx apps/desktop/scripts/archive-desktop-ci.ts
- name: Retain verified unsigned installer
if: success() && inputs.signing == 'unsigned'
uses: actions/upload-artifact@v7.0.1
with:
name: windows-x64-unsigned-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }}
name: windows-x64-unsigned-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}
compression-level: 0
include-hidden-files: true
path: ${{ steps.retained.outputs.directory }}/*
path: ${{ needs.package.outputs.directory }}/*
if-no-files-found: error
retention-days: 14
overwrite: true
- name: Retain verified signed installer
if: success() && inputs.signing == 'signed'
uses: actions/upload-artifact@v7.0.1
with:
name: windows-x64-signed-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }}
name: windows-x64-signed-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}
compression-level: 0
include-hidden-files: true
path: ${{ steps.retained.outputs.directory }}/*
path: ${{ needs.package.outputs.directory }}/*
if-no-files-found: error
retention-days: 14
overwrite: true
+4 -4
View File
@@ -24,11 +24,11 @@
en: 5b4f0f80a117f202
zh: ff05be196c181087
/desktop-packaging/windows-actions-packaging:
en: 253e17998951931c
zh: b582b377391d2ec2
en: e0a852fdda949c40
zh: b96c613022f6189e
/desktop-packaging/macos-self-hosted-packaging:
en: b7e03e2e9807a62c
zh: e5b0c43910e085d8
en: 239d5ab433020745
zh: e8916ba0f4682ae1
/desktop-packaging/unsigned-windows-test-installer:
en: f429bc0c280e2dfa
zh: 4adbcc9e906bdf80
+5 -1
View File
@@ -113,7 +113,9 @@ The `Package Desktop · Windows · x64` [manual workflow](../../../.github/workf
Select the workflow in Actions, choose the source branch, preset, signing mode and version, then click Run workflow. Before merging input changes, test the pushed branch with `gh workflow run windows-package.yml --ref <branch> -f preset=test -f signing=unsigned -f build_version=auto`; verify the web form after merging. There is no push or PR trigger. Logs and successful EXEs are retained for 14 days. Inspect the retained logs and installer before relying on packaging; installation is separate. Before checkout, Node removes the runner-owned source directory without following dependency junctions; the workflow validates its location and rejects linked ancestors. Never point it at a development checkout. Runs share one concurrency group without cancelling an active build; only one run remains pending, and a newer dispatch replaces it. Diagnostics upload requires a successful clean checkout. Machine settings stay outside the checkout and are never uploaded as artifacts.
Open the completed run in Actions and download its Artifacts. `windows-x64-signed-<version>-<run_id>-<run_attempt>` and `windows-x64-unsigned-<version>-<run_id>-<run_attempt>` contain the corresponding EXE; `windows-package-logs-<run_id>-<run_attempt>` contains packaging diagnostics. The upload steps are `Retain verified signed installer`, `Retain verified unsigned installer`, and `Retain packaging diagnostics`; their step durations and timestamped logs show upload time. These artifacts are not a Release or download-site publication.
All Windows packaging modes, including test and unsigned, require the repository variable `DESKTOP_PUBLISH_RUNNERS`; configure the [original-machine route](../publishing/ci/README.md#machine-setup) before dispatch.
Open the completed run in Actions and download its Artifacts from the independent `upload-artifact` job. Installer names use the original `package_run_attempt`; diagnostic names use the current `run_attempt`. If archival fails after packaging succeeds, rerun only `upload-artifact` to reuse the retained installers. `windows-x64-signed-<version>-<run_id>-<package_run_attempt>` and `windows-x64-unsigned-<version>-<run_id>-<package_run_attempt>` contain the corresponding EXE; `windows-package-logs-<run_id>-<run_attempt>` contains packaging diagnostics. The upload steps are `Retain verified signed installer`, `Retain verified unsigned installer`, and `Retain packaging diagnostics`; their step durations and timestamped logs show upload time. These artifacts are not a Release or download-site publication.
For cache measurements, `cache_namespace` selects a retained subdirectory for both dependency stores and upstream downloads; leave it empty for normal shared caches. Use a new name for a cold sample and repeat that name for warm samples. Names contain 1–64 lowercase letters, digits or hyphens, start with a letter or digit, and cannot be Windows device names. This does not reset the separate signature cache or OS file cache; report those states and Job start-to-completion time alongside phase timings and artifact size. Before dependency installation, the workflow records the Node version, available CPU parallelism, logical CPU count, and total/free memory.
@@ -127,6 +129,8 @@ Installer uploads store the already-compressed release files without ZIP recompr
The [Apple Silicon workflow](../../../.github/workflows/macos-package.yml) and [Intel workflow](../../../.github/workflows/macos-intel-package.yml) produce separate arm64 and x64 packages on the Apple Silicon runner labeled `dsh-mac-package-trial`. Both share one concurrency group. The Intel workflow checks Rosetta execution before dependency installation; its selected source must include the target-aware macOS CI adapter. Both select `test` or `production` and use the existing signing, notarization and packaged-runtime checks. When the selected source's dsh ships the Computer Use bundle, each workflow builds, notarizes and stages the helper for both architectures with `scripts/cua-helper/package.ts` and `stage.ts` after the configuration check, the steps npm publication uses; `skip_notarization` does not skip the helper's notarization. A source that predates helper packaging only emits a warning, and Computer Use cannot prepare its helper in that package. Successful DMG/ZIP files and diagnostic logs are retained for 14 days without publishing a release. Installer uploads disable redundant ZIP compression. The operator must verify a complete Actions run and installation on the target architecture before release qualification. The `compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only ZIP and automatic-update downloads, not DMG.
Both macOS workflows require the repository variable `DESKTOP_PUBLISH_RUNNERS`, including test and unnotarized modes. Their independent `upload-artifact` job retains installer names with the original build attempt; if archival fails after packaging succeeds, rerun only that job. See [original-machine routing and recovery](../publishing/ci/README.md#recovery-and-records).
All three platform forms put source, environment, update channel, version mode, manual version, test release ID and compression level first, with matching defaults. macOS notarization and Windows signing and cache measurement options follow these common fields.
Run `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` to prepare private `runner/`, `packaging/{presets,secrets,certificates}` and `cache/macos-signatures` directories without overwriting existing files; append `--check` to inspect them. Fill the [preset](../config/macos-packaging/test.env.example) and [signing](../config/macos-packaging/macos-signing.env.example) templates outside the checkout. Set secret and certificate files to mode `0600`. `DSH_PACKAGING_CONFIG_DIR` selects the absolute `packaging` directory and `DSH_PACKAGING_PRESET` selects its preset; missing files fail without falling back to `.env.macos`. Signed and preparation-only Mac builds read `secrets/macos-signing.env`; relative credential paths resolve beside that file. Public presets reject signing credentials, and signing files cannot override public settings. Local unsigned Mac builds retain their configuration-free behavior.
+5 -1
View File
@@ -113,7 +113,9 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s
在 Actions 选择工作流、源码分支、preset、签名模式和版本,再点击 Run workflow。输入变更合并前,用 `gh workflow run windows-package.yml --ref <branch> -f preset=test -f signing=unsigned -f build_version=auto` 测试已推送分支;合并后验证网页表单。它不监听 push 或 PR。日志和成功生成的 EXE 保留 14 天。依赖打包流程前检查日志和安装包;安装是独立操作。检出前,Node 删除 runner 专用源码目录,不跟随依赖 junction;工作流校验目标位置并拒绝链接祖先目录。不得指向日常开发目录。运行共享一个并发组,不取消正在进行的构建;最多保留一个待运行任务,新触发会替换它。仅在成功完成干净检出后上传诊断。机器配置位于 checkout 之外,不作为产物上传。
在 Actions 打开完成的运行并下载 Artifacts。`windows-x64-signed-<version>-<run_id>-<run_attempt>` 与 `windows-x64-unsigned-<version>-<run_id>-<run_attempt>` 包含对应 EXE;`windows-package-logs-<run_id>-<run_attempt>` 包含打包诊断。上传步骤名为 `Retain verified signed installer`、`Retain verified unsigned installer` 和 `Retain packaging diagnostics`;步骤耗时与带时间戳的日志显示上传用时。这些产物不等于发布 Release 或下载站内容。
所有 Windows 打包模式(含 test 和 unsigned)都要求仓库变量 `DESKTOP_PUBLISH_RUNNERS`;触发前配置[原机器路由](../publishing/ci/README.zh.md#machine-setup)。
在 Actions 打开完成的运行,下载独立 `upload-artifact` job 生成的 Artifacts。安装包名称使用原构建的 `package_run_attempt`,诊断名称使用当前 `run_attempt`。打包成功但归档失败时,仅重跑 `upload-artifact` 以复用保留的安装包。`windows-x64-signed-<version>-<run_id>-<package_run_attempt>` 与 `windows-x64-unsigned-<version>-<run_id>-<package_run_attempt>` 包含对应 EXE;`windows-package-logs-<run_id>-<run_attempt>` 包含打包诊断。上传步骤名为 `Retain verified signed installer`、`Retain verified unsigned installer` 和 `Retain packaging diagnostics`;步骤耗时与带时间戳的日志显示上传用时。这些产物不等于发布 Release 或下载站内容。
测量缓存时,`cache_namespace` 为两个依赖 store 和上游下载选择保留的子目录;留空使用正常共享缓存。新名称用于冷缓存采样,再次使用同名用于热缓存采样。名称由 1–64 个小写字母、数字或连字符组成,以字母或数字开头,且不能为 Windows 设备名。这不会重置独立的签名缓存或操作系统文件缓存;应将其状态、Job 开始至完成的总耗时与阶段耗时和产物体积一并报告。workflow 在依赖安装前记录 Node 版本、可用 CPU 并行数、逻辑 CPU 数及总内存和空闲内存。
@@ -127,6 +129,8 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s
[Apple Silicon 工作流](../../../.github/workflows/macos-package.yml)与 [Intel 工作流](../../../.github/workflows/macos-intel-package.yml)在带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner 上分别生成 arm64 和 x64 安装包,两者共用一个并发组。Intel 工作流在安装依赖前检查 Rosetta 能否执行;所选源码必须包含按目标架构校验的 macOS CI 适配脚本。两者均选择 `test` 或 `production`,并复用现有签名、公证和打包运行时检查。所选源码的 dsh 随附 Computer Use 组合包时,两者都在配置检查之后用 `scripts/cua-helper/package.ts` 和 `stage.ts` 构建、公证并放入两种架构的 helper,与 npm 发布的步骤相同;`skip_notarization` 不会跳过 helper 的公证。源码早于 helper 打包支持时只输出警告,该安装包中的 Computer Use 无法准备 helper。成功的 DMG/ZIP 与诊断日志保留 14 天,不发布 release;安装包上传关闭重复 ZIP 压缩。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。
两个 macOS 工作流都要求仓库变量 `DESKTOP_PUBLISH_RUNNERS`,包括 test 和未公证模式。独立 `upload-artifact` job 的安装包名称保留原构建 attempt;打包成功但归档失败时,仅重跑该 job。参见[原机器路由与恢复](../publishing/ci/README.zh.md#recovery-and-records)。
三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量选项位于公共字段之后。
运行 `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` 创建私有 `runner/`、`packaging/{presets,secrets,certificates}` 和 `cache/macos-signatures` 目录,不覆盖已有文件;追加 `--check` 仅检查。在 checkout 外填写 [preset](../config/macos-packaging/test.env.example) 和[签名](../config/macos-packaging/macos-signing.env.example)模板,将秘密和证书文件权限设为 `0600`。`DSH_PACKAGING_CONFIG_DIR` 指定 `packaging` 的绝对目录,`DSH_PACKAGING_PRESET` 选择其中的 preset;缺少文件立即失败,不回退到 `.env.macos`。Mac 签名和仅准备构建读取 `secrets/macos-signing.env`,相对凭据路径以该文件所在目录为基准。公开 preset 拒绝签名凭据,签名文件不能覆盖公开配置。本地未签名 Mac 构建保留无需配置的行为。
+2 -2
View File
@@ -24,8 +24,8 @@
en: 4723059d6f16b25b
zh: 54e5afad8fff8eb6
/desktop-publication/fixed-installer-downloads:
en: ce8296f8f1ee881e
zh: 749ab63bd6ed4248
en: ed4dcced7bd4e7ba
zh: a9e7f5da9e39454f
/desktop-publication/upload-credentials:
en: 47442fb912fa4d5d
zh: a21a0d67cd01724b
+3 -1
View File
@@ -69,11 +69,13 @@ Windows NSIS uploads require the generated, nonempty `.exe.blockmap` beside the
## Fixed installer downloads
Uploads set `Content-Disposition: attachment` with the verified installer basename as `filename`, preserving the complete version, platform and architecture. The fixed `dsh-latest-*` URL remains independent of nightly/stable update channels; no additional naming suffix is added. Verify CDN header forwarding and the browser save name after publication.
Fixed installer downloads use `pnpm run upload:latest:mac:arm64`, `pnpm run upload:latest:mac:x64`, or `pnpm run upload:latest:win:x64` from the repository root. They upload the completed target's DMG or EXE to `desktop/dsh-latest-macos-arm64.dmg`, `desktop/dsh-latest-macos-x64.dmg`, or `desktop/dsh-latest-windows-x64.exe`. Production URLs start with `https://download.deepseek.com/`; test URLs use `DOWNLOAD_TEST_ORIGIN`. Both deployments reuse the target dotenv's deployment, bucket, and credentials, all normal release validation, and the upload audit below. Each command replaces one fixed object without publishing feeds, blockmaps, or release tags. Test fixed downloads are shared across release IDs in the test bucket; the packaged update URL still requires its original release ID. Publication is explicit, including prerelease versions. Production commands then submit one EdgeOne URL purge and report its task ID; they do not query or wait for cache completion. Test uploads retain deployment-managed cache policy. Local loopback tests cover the upload; release operators own real COS and CDN acceptance.
Production fixed downloads require `DOWNLOAD_PROD_EO_ZONE_ID` in the target dotenv and `teo:CreatePurgeTask` permission for that zone on the existing `DOWNLOAD_PROD_COS_SECRET_ID` / `DOWNLOAD_PROD_COS_SECRET_KEY` identity. The release operator must confirm that permission before use; no additional CI Secret is required. Required settings are resolved before uploading. The submission has a 30-second request timeout and is never retried automatically.
The command reports submission acceptance, not completed cache invalidation. EO results go to the console without separate purge record files; the existing upload audit records only COS writes. A rejected or unconfirmed submission exits unsuccessfully; the uploaded installer stays published. Check EO task history before submitting again after a connection loss or missing response. To submit a purge without uploading, use `pnpm run purge:latest <target>` with production settings and credentials; no local installer is needed. DPAPI users reuse the original credential launcher and add `-PurgeOnly` to their `-Upload -Latest` invocation. Serialize uploads and cache-only submissions per target. The CI publisher does not publish fixed downloads or run this refresh.
The command reports submission acceptance, not completed cache invalidation. EO results go to the console without separate purge record files; the existing upload audit records only COS writes. A rejected or unconfirmed submission exits unsuccessfully; the uploaded installer stays published. Check EO task history before submitting again after a connection loss or missing response. To submit a purge without uploading, use `pnpm run purge:latest <target>` with production settings and credentials; no local installer is needed. DPAPI users reuse the original credential launcher and add `-PurgeOnly` to their `-Upload -Latest` invocation. Serialize uploads and cache-only submissions per target. The [CI publication workflow](ci/README.md#recovery-and-records) has separate website upload and observed-purge jobs.
<a id="credentials"></a>
+3 -1
View File
@@ -69,11 +69,13 @@ Windows NSIS 上传要求安装包旁存在生成的非空 `.exe.blockmap`。blo
## 固定安装包下载
上传设置 `Content-Disposition: attachment`,`filename` 沿用经校验安装包的 basename,保留完整版本、平台和架构。固定 `dsh-latest-*` URL 与 nightly/stable 升级通道独立,不另加命名后缀。发布后需验证 CDN 响应头透传及浏览器保存文件名。
固定安装包下载在仓库根目录使用 `pnpm run upload:latest:mac:arm64`、`pnpm run upload:latest:mac:x64` 或 `pnpm run upload:latest:win:x64`。它们把已完成目标的 DMG 或 EXE 上传到 `desktop/dsh-latest-macos-arm64.dmg`、`desktop/dsh-latest-macos-x64.dmg` 或 `desktop/dsh-latest-windows-x64.exe`。生产 URL 以 `https://download.deepseek.com/` 开头;测试 URL 使用 `DOWNLOAD_TEST_ORIGIN`。两个部署环境均复用目标 dotenv 中的部署、bucket 和凭据、全部常规发布校验以及下述上传审计。每个命令覆盖一个固定对象,不发布更新清单、blockmap 或发布标签。测试固定下载在测试 bucket 中跨发布 ID 共享;包内更新 URL 仍要求原有发布 ID。发布由操作人员显式执行,也允许预发布版本。生产命令随后提交一次 EdgeOne URL 缓存清除任务并报告任务 ID,不查询或等待缓存清除完成。测试上传仍由部署基础设施管理缓存策略。本地回环测试覆盖上传行为;真实 COS 和 CDN 验收由发布操作人员负责。
生产固定下载要求在目标 dotenv 中配置 `DOWNLOAD_PROD_EO_ZONE_ID`,且既有 `DOWNLOAD_PROD_COS_SECRET_ID` / `DOWNLOAD_PROD_COS_SECRET_KEY` 身份具备对应站点的 `teo:CreatePurgeTask` 权限。发布操作人员须在使用前确认该权限;无需新增 CI Secret。上传前解析必需配置。提交请求超时为 30 秒,不自动重试。
命令报告提交已接受,不代表缓存清除已完成。EO 结果输出到控制台,不另建刷新记录文件;既有上传审计仅记录 COS 写入。提交被拒绝或未确认时,命令以失败状态退出,已上传安装包保持发布。连接中断或未收到响应时,先检查 EO 任务历史再重新提交。使用 `pnpm run purge:latest <target>` 可只提交刷新,无需上传;需要生产配置和凭据,无需本地安装包。DPAPI 用户复用原凭据启动器,在 `-Upload -Latest` 命令上添加 `-PurgeOnly`。按目标串行执行上传和单独刷新。CI 发布器不发布固定下载,也不执行此刷新。
命令报告提交已接受,不代表缓存清除已完成。EO 结果输出到控制台,不另建刷新记录文件;既有上传审计仅记录 COS 写入。提交被拒绝或未确认时,命令以失败状态退出,已上传安装包保持发布。连接中断或未收到响应时,先检查 EO 任务历史再重新提交。使用 `pnpm run purge:latest <target>` 可只提交刷新,无需上传;需要生产配置和凭据,无需本地安装包。DPAPI 用户复用原凭据启动器,在 `-Upload -Latest` 命令上添加 `-PurgeOnly`。按目标串行执行上传和单独刷新。[CI 发布工作流](ci/README.zh.md#recovery-and-records)使用独立的官网上传和刷新观察 job。
<a id="credentials"></a>
+4 -4
View File
@@ -24,11 +24,11 @@
en: 0f43f2e193e95043
zh: 1c1efb062c06f7b8
/desktop-ci-publication/package-and-publish:
en: ee8d79ac75482502
zh: 1d986a76860ed262
en: 3f58698708671202
zh: be0ba215a67168d6
/desktop-ci-publication/recovery-and-records:
en: 4ff6f0673d057ca8
zh: 7171d060dd86db9a
en: 266afba2adeeadef
zh: 063114103585dae8
/desktop-ci-publication/restore-a-channel:
en: d82e2ccf70cce397
zh: d93dcb77cc4b463e
+13 -3
View File
@@ -68,11 +68,11 @@ Environment approval gates this workflow, not arbitrary code running under the s
## Package and publish
For publication to either test or production, choose Windows `signing=signed` or leave macOS **Skip notarization** unchecked. Unsigned and unnotarized packages are only for internal debugging; they cannot publish or provide automatic updates. Before installing dependencies, the hosted routing job rejects debugging artifacts identified by the selected run and attempt. Missing artifact metadata does not establish eligibility: the original machine still validates its retained manifest and signatures. A debugging-package rejection requires a new signed/notarized package and its run ID / attempt; retrying publication cannot qualify the existing bytes.
For publication to either test or production, choose Windows `signing=signed` or leave macOS **Skip notarization** unchecked. Unsigned and unnotarized packages are only for internal debugging; they cannot publish or provide automatic updates. Before installing dependencies, the hosted routing job rejects debugging artifacts identified by the selected run and attempt. An archive-only rerun retains the original build attempt in artifact names, so this early check can miss it; local manifest qualification still rejects debugging builds before publication. Missing artifact metadata does not establish eligibility: the original machine still validates its retained manifest and signatures. A debugging-package rejection requires a new signed/notarized package and its run ID / attempt; retrying publication cannot qualify the existing bytes.
Select the platform's `Package Desktop` workflow, preset, source, channel and version mode. `source_ref` accepts repository branch names (for example `feature/desktop-update`) or `dsh-v*` tags for test; production accepts only `master` or `dsh-v*` tags. Names matching `dsh-v` followed by a digit and letters, digits, dots or hyphens are treated as tags, even if a branch has that name. Tags must match the selected product version. We recommend dispatching the packaging workflow from `master` and enter the source separately; raw commit SHAs, PR refs and fork repositories are not supported. The selected source must contain the CI adapters, so older sources fail before dependency installation. Only select trusted branches: their build code runs on the signing machine. This is an operating convention, not enforced workflow-origin or credential isolation. Publication uses the recorded commit and requires it to remain in the selected branch history; normal branch advances are allowed, deletion or a diverging force-push rejects. Tag publication requires the tag to still resolve to the recorded commit. Dispatch the publisher from `master`; its hosted routing job rejects other refs before scheduling the original machine. The packaged source commit is recorded separately. `version_mode=default` selects product for production and auto for test; product preserves the selected checkout version, auto appends date/run/attempt, and manual requires `build_version`. A stable-channel package requires a stable version, so test/stable needs product or a stable manual version. The optional `test_release_id` is the test URL prefix: blank retains the machine default, successive upgrade tests on that platform need the same value, and defaults should be rotated periodically. It is not a GitHub run ID. See [packaging configuration](../../packaging/README.md#configuration-and-local-builds) for its validation and rotation limits.
Packaging only retains files. After success, open **Publish Desktop · COS → Run workflow** on `master`, enter `package_run_id` from the packaging run URL, and optionally enter `package_run_attempt`. Blank selects the latest attempt, which must have succeeded; it never falls back to an older success. An explicit attempt selects that exact successful build. Windows must be signed; macOS must finish notarization and stapling. GitHub job evidence selects the original runner; its local manifest supplies the preset, version, source and channel before approval. No installer or request artifact is downloaded. Retained packages with the old `publishRequested=false` flag remain eligible; missing or changed local files stop publication.
Packaging only retains files. After success, open **Publish Desktop · COS → Run workflow** on `master`, enter `package_run_id` from the packaging run URL, and optionally enter `package_run_attempt`. Blank selects the latest attempt and its successful package job. An archival-only retry retains the original build attempt; a failed newer package job never falls back to an older success. An explicit attempt selects that build even when its separate GitHub archival failed. Windows must be signed; macOS must finish notarization and stapling. GitHub job evidence selects the original runner; its local manifest supplies the preset, version, source and channel before approval. No installer or request artifact is downloaded. Retained packages with the old `publishRequested=false` flag remain eligible; missing or changed local files stop publication.
Before installing dependencies on the original runner, preparation and the approved publish job check that the selected `publishing/<preset>.json` is readable JSON. Missing configuration reports its path; restore it and retry publication with the same package. Full configuration and signature validation still run afterward. Before uploading, the publisher hashes all retained files, checks version and destination metadata, and rechecks the platform signatures. macOS verifies the DMG and extracts the ZIP to verify the app's ticket; Windows checks Authenticode, the configured signer thumbprint and the timestamp. Preparation writes a Chinese approval summary with separate version, channel, platform and deployment fields, the retained test release ID, full installer/feed URLs, a link to the original packaging attempt, source ref/SHA, platform verification results and proposed tag. Folded details include the COS bucket and file sizes/SHA-256 of the upload bytes, including rewritten YAML. Public-repository summaries expose the test prefix and download URLs; the prefix is not authentication. Both publishing jobs wait for **Review deployments → Approve and deploy**, then recheck the approved manifest and upload plan digest. Changed bytes or destinations reject. Approval cannot edit a version; reject and rebuild instead. Both deployments upload missing binaries, verify remote bytes, then update YAML. There is no files-only mode in this workflow. Production finally creates `desktop-v<version>` at the recorded packaging commit; an existing tag must name the same commit.
@@ -80,7 +80,17 @@ Before installing dependencies on the original runner, preparation and the appro
## Recovery and records
After resolving a failure, re-run the failed publishing job to keep its prepared package attempt, or start a new publication with the explicit original package run and attempt. Re-running all jobs with a blank attempt resolves the latest package attempt again and requires a new approval. Do not rebuild solely to retry an upload. Missing objects are uploaded, identical objects are skipped, and conflicting same-name bytes stop the operation. Unknown write outcomes are reconciled by reading remote bytes. A newer channel version prevents a stale upload from replacing it. Each package updates only its embedded channel: nightly writes `nightly.yml` / `nightly-mac.yml`, stable writes `stable.yml` / `stable-mac.yml`. Stable-channel binaries use a `stable/` subdirectory under the target binary prefix, separate from existing nightly objects. Publishing the same source/version to both channels requires two packages; an existing release tag is reused only for the same source commit.
The packaging workflows separate `package` from `upload-artifact` (GitHub artifact archival). All packaging modes, including test and unsigned builds, require `DESKTOP_PUBLISH_RUNNERS` before packaging; it routes archival to the original machine. Rerun only `upload-artifact` after an archival failure; it verifies the original manifest and hashes without rebuilding, signing or notarizing. Packaging diagnostics are best effort and do not change package success. If an archival retry stays queued without a runner, inspect the resolved runner label and upstream package outputs before treating the runner as offline. Missing outputs require operator recovery of the original retained directory and manifest; rerunning the whole workflow rebuilds the package and is not archival-only recovery. Verify output reuse in the Actions acceptance test.
Production COS publication enables website installer upload and cache refresh by default (`upload_website=true`). Clear it to publish only versioned resources and automatic-update feeds; test publication never changes the production website. `upload-website-installer` uploads the fixed installer and `purge-website-installer` refreshes its URL. The website installer validator needs only the final DMG/EXE and retained manifest. It matches production qualification, build identity and target, hashes the installer once and uploads through the same open file handle. Both production nightly and stable packages can replace the fixed website installer. Operators select the intended version; the fixed object has no downgrade protection, so rerunning an older publication can replace a newer installer. The pre-approval summary names the fixed website URL, selected version and lack of downgrade protection when website upload is selected. The existing version/update publication retains its own checks.
Set the repository variable `DOWNLOAD_PROD_EO_ZONE_ID` to the production EdgeOne zone. The production COS credential pair also needs `teo:CreatePurgeTask` and `teo:DescribePurgeTasks`. Website uploads serialize by bucket/target in Actions and by bucket/object on the original machine. Cache observation runs separately. Version publication, website upload and cache refresh each use the production approval Environment; later jobs and reruns may require another approval. GitHub concurrency retains at most one pending job per group, so a newer pending job can cancel an older pending job; inspect canceled jobs before rerunning them.
Website state lives in `upload-records/website-<publication run ID>-<target>/state.json`, beside the retained releases root. macOS and Windows use the same record format on separate local disks. Website URLs and download filenames follow the [fixed-download rules](../README.md#fixed-downloads). Upload retries reconcile both bytes and `Content-Disposition`; identical bytes with a missing or different header receive one upload and readback. A completed journal with different remote bytes stops recovery and requires a newly approved publication. Completion evidence survives failed metadata repairs. Each new upload intent clears the previous purge record, so repaired metadata requires a new cache refresh; inspect EdgeOne history for the previous task ID and diagnostics. Unknown writes are read before any retry; CDN header forwarding requires real-environment validation. Rerun only the purge job to inspect its saved task when the original routing and preparation outputs remain available. With website upload enabled, website jobs skip only an explicitly selected test deployment. Each job requires its injected `route` or `selection` output for local preflight. Missing or changed website approval fails before upload or purge submission. Missing `website-destination` broadens both website concurrency groups. Missing `runner` output can prevent scheduling before preflight. Stop partial retries when outputs are missing; the workflow does not reconstruct them. Before restarting the publication workflow, inspect current remote state and obtain approval for its upload scope; this is not cache-only recovery. Do not rerun packaging to recover publication outputs. A manually rerun purge may submit once after confirming the previous task failed. A lost submission response queries matching history instead of resubmitting. An unknown result with a task ID means submission was confirmed; without an ID it may never have been submitted. Inspect EdgeOne history before manual recovery, and a fresh publication run is one recovery option. Operators may instead use the documented [fixed-download purge command](../README.md#fixed-downloads); Windows operators use the existing DPAPI credential launcher described there. This submits only a fixed-URL purge: it does not observe completion or update this Actions run’s journal. Inspect the returned task in EdgeOne before considering recovery complete.
Purge observation waits up to five minutes at ten-second intervals, with one additional query after an unknown result or observation deadline. Confirmed failed, timeout or canceled tasks fail the job. An unresolved result exits successfully with an Actions warning and a prominent summary; its durable state remains unknown, not completed. Diagnostic artifact archival is best effort; local records remain the recovery source. Simulated-provider tests cover these paths; release operators must verify production COS/EdgeOne permissions, job-id filtering, time-range queries, task type and timestamp formats, cross-attempt Actions recovery, and actual CDN behavior before relying on recovery in production.
After resolving a failure, re-run the failed publishing job only when the upstream outputs required above remain available, keeping its prepared package attempt; otherwise stop partial retries. A new publication can explicitly select the original package run and attempt. Re-running all jobs with a blank attempt resolves the latest package attempt again and requires a new approval. Do not rebuild solely to retry an upload. Missing objects are uploaded, identical objects are skipped, and conflicting same-name bytes stop the operation. Unknown write outcomes are reconciled by reading remote bytes. A newer channel version prevents a stale upload from replacing it. Each package updates only its embedded channel: nightly writes `nightly.yml` / `nightly-mac.yml`, stable writes `stable.yml` / `stable-mac.yml`. Stable-channel binaries use a `stable/` subdirectory under the target binary prefix, separate from existing nightly objects. Publishing the same source/version to both channels requires two packages; an existing release tag is reused only for the same source commit.
The sibling `upload-records/` directory retains an operation identity, newline-delimited events and terminal result. Feed-write intents retain both previous and requested YAML. Failures record their stage, safe error classification and diagnostic; COS failures also identify `GetObject` or `PutObject`, plus a validated HTTP status and request ID when available. Access-denied reports name the permission to inspect. Raw provider responses and credentials are excluded. Audit initialization becomes visible only after its files are complete; abandoned `.initializing-*` directories are not scanned for completed publication. Writes and readback are recorded before proceeding; missing terminal results mean interruption, not success. Actions also keeps its operation record as a diagnostic artifact for 30 days. These local records are not tamper-proof. COS readback verifies storage bytes, not public CDN behavior; public download acceptance is separate.
+13 -3
View File
@@ -68,11 +68,11 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任
## 打包与发布
发布到 test 或 production 都必须在 Windows 选择 `signing=signed`,或在 macOS 不勾选**跳过公证**。无签名、无公证的包仅限内部调试,不能发布或用于自动更新。托管路由 job 会在安装依赖前,依据所选 run 和 attempt 对应的 artifact 名称拒绝已标明的调试包。缺少 artifact 元数据不代表允许发布:原机器仍会验证留存清单和签名。遇到调试包拒绝提示时,需重新完成签名或公证,再使用新包的 run ID / attempt 发布;重跑发布不能使现有产物获得发布资格。
发布到 test 或 production 都必须在 Windows 选择 `signing=signed`,或在 macOS 不勾选**跳过公证**。无签名、无公证的包仅限内部调试,不能发布或用于自动更新。托管路由 job 会在安装依赖前,依据所选 run 和 attempt 对应的 artifact 名称拒绝已标明的调试包。仅重跑归档时,artifact 名称保留原构建 attempt,早期检查可能未识别该包;本地清单资格校验仍会在发布前拒绝调试包。缺少 artifact 元数据不代表允许发布:原机器仍会验证留存清单和签名。遇到调试包拒绝提示时,需重新完成签名或公证,再使用新包的 run ID / attempt 发布;重跑发布不能使现有产物获得发布资格。
选择对应平台的 `Package Desktop` 工作流、preset、源码、通道和版本模式。test 的 `source_ref` 接受仓库内分支名(如 `feature/desktop-update`)或 `dsh-v*` tag;production 仅接受 `master` 或 `dsh-v*` tag。符合 `dsh-v` 后接数字、其余为字母、数字、点或连字符的名称按 tag 处理,即使存在同名分支。tag 必须与所选产品版本一致。建议从 `master` 启动打包工作流,再单独填写打包源码;不支持直接填写 commit SHA、PR ref 或 fork 仓库。源码必须包含 CI 适配脚本,旧源码会在安装依赖前失败。仅选择可信分支:其构建代码将在签名机器上执行。这是操作约定,不提供工作流来源强制限制或凭据隔离。发布使用记录的 commit,并要求该提交仍在所选分支历史中;正常追加提交不影响发布,删除分支或导致历史分叉的强推会拒绝。tag 发布要求 tag 仍指向记录的提交。从 `master` 发起发布;托管路由 job 会在派发到原机器前拒绝其他 ref。实际打包源码提交单独记录。`version_mode=default` 对 production 选择 product,对 test 选择 auto;product 保留所选源码版本,auto 追加日期/run/attempt,manual 要求填写 `build_version`。stable 包要求稳定版本,因此 test/stable 需选择 product 或稳定的手填版本。可选 `test_release_id` 是测试 URL 前缀:留空沿用机器默认值,同一平台连续升级测试需保持相同值,并应定期轮换默认值。它不是 GitHub run ID。格式校验和轮换限制见[打包配置](../../packaging/README.zh.md#configuration-and-local-builds)。
打包只保留文件。成功后,在 `master` 上打开 **Publish Desktop · COS → Run workflow**,填写打包运行 URL 中的 `package_run_id`,并可填写 `package_run_attempt`。留空选择最新尝试,且该尝试必须成功,不会回退到较早的成功尝试;显式填写则选择对应的成功构建。Windows 必须完成签名,macOS 必须完成公证和 stapling。GitHub job 证据确定原 runner,本机清单在审批前提供 preset、版本、源码和通道。不会下载安装包或请求 artifact。旧清单的 `publishRequested=false` 不影响发布资格;本机文件缺失或变化会停止发布。
打包只保留文件。成功后,在 `master` 上打开 **Publish Desktop · COS → Run workflow**,填写打包运行 URL 中的 `package_run_id`,并可填写 `package_run_attempt`。留空选择最新尝试及其成功的 package job;归档重跑继续使用原始构建 attempt,新的构建失败时不回退到较早成功构建。显式填写则选择对应构建,独立的 GitHub 归档失败不取消其资格。Windows 必须完成签名,macOS 必须完成公证和 stapling。GitHub job 证据确定原 runner,本机清单在审批前提供 preset、版本、源码和通道。不会下载安装包或请求 artifact。旧清单的 `publishRequested=false` 不影响发布资格;本机文件缺失或变化会停止发布。
在原 runner 安装依赖前,准备阶段和审批后的发布 job 都会检查所选 `publishing/<preset>.json` 是否为可读取的 JSON。配置缺失时会报告路径;补齐后可使用同一个包重试发布。之后仍会执行完整配置与签名校验。上传前,发布器校验全部留存文件的哈希、版本及目标信息,再复核平台签名。macOS 校验 DMG,并解压 ZIP 校验 app 票据;Windows 校验 Authenticode、配置的签名证书指纹及时间戳。准备阶段生成中文审批摘要,分别展示版本、通道、平台和环境,以及留存的 test release ID、安装包与升级 YAML 的完整 URL、原打包尝试链接、源码 ref/SHA、平台校验结果及拟创建的 tag。折叠详情包含 COS 存储桶,以及实际上传字节的大小和 SHA-256(包括改写后的 YAML)。公开仓库的摘要会公开测试前缀和下载 URL;前缀不提供访问鉴权。两种发布 job 均等待 **Review deployments → Approve and deploy**,随后重新核对已批准的 manifest 与上传计划摘要。文件或目标变化会被拒绝。审批不能修改版本;应拒绝并重新打包。两种环境都上传缺失文件、校验远端字节,再更新 YAML。此工作流没有只上传文件的模式。production 最后为记录的打包提交创建 `desktop-v<version>`;已有 tag 必须指向同一提交。
@@ -80,7 +80,17 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任
## 恢复与记录
解决故障后重跑失败的发布 job,以保持准备阶段选定的打包尝试;也可显式填写原打包运行和尝试,发起新的发布。尝试留空时重跑所有 job 会重新解析最新打包尝试,并需要重新审批。不要仅为重试上传而重新打包。缺失对象会上传,相同对象跳过,同名但字节不同的对象会停止操作。写入结果不明时通过读取远端字节核对。频道已有更高版本时,旧上传不能替换它。每个包只更新自身内置通道:nightly 写入 `nightly.yml` / `nightly-mac.yml`,stable 写入 `stable.yml` / `stable-mac.yml`。stable 二进制位于目标二进制前缀下的 `stable/` 子目录,与已有 nightly 对象分离。同一源码和版本发布到两个通道需要分别打包;已有发布 tag 仅在源码提交相同时复用。
打包 workflow 将 `package` 与 `upload-artifact`(GitHub 产物归档)分开。所有打包模式(包括 test 和 unsigned)都要求在打包前配置 `DESKTOP_PUBLISH_RUNNERS`,用于将归档路由到原机器。归档失败后仅重跑 `upload-artifact`;它校验原始 manifest 和 hash,不重新构建、签名或公证。打包诊断归档尽力执行,不改变构建成功状态。归档重跑若一直排队且未分配 runner,应先检查解析出的 runner 标签和上游 package 输出,不能直接认定机器离线。输出缺失时需由操作者从原留存目录和 manifest 恢复文件;重跑整个 workflow 会重新构建,不属于仅归档恢复。Actions 验收须验证输出复用。
生产 COS 发布默认启用官网安装包上传和缓存刷新(`upload_website=true`)。取消后仅发布版本化资源及自动更新清单;test 发布不修改生产官网。`upload-website-installer` 上传固定安装包,`purge-website-installer` 刷新该 URL。官网安装包校验器只需要最终 DMG/EXE 和保留的 manifest,匹配生产资格、构建身份及平台,只计算一次安装包 hash,并通过同一打开的文件句柄上传。production nightly 和 stable 包都可以替换官网固定安装包。操作者负责选择预期版本;固定对象没有防降级保护,重跑旧发布可能覆盖新安装包。勾选官网上传时,审批前摘要展示固定官网 URL、选定版本和无防降级保护的说明。原有版本与自动更新发布保留自身校验。
将仓库变量 `DOWNLOAD_PROD_EO_ZONE_ID` 配置为生产 EdgeOne 站点。生产 COS 凭据还需要 `teo:CreatePurgeTask` 和 `teo:DescribePurgeTasks` 权限。官网上传在 Actions 中按 bucket/平台互斥,在原机器上按 bucket/对象互斥;缓存观察单独运行。版本发布、官网上传和缓存刷新分别使用生产审批 Environment,后续 job 和重跑可能需要再次审批。GitHub 每个并发组最多保留一个排队 job,新排队 job 可能取消旧排队 job;重跑前应检查取消记录。
官网状态保存在 releases 根目录同级的 `upload-records/website-<发布 run ID>-<target>/state.json`。macOS 和 Windows 在各自本地磁盘使用相同记录格式。官网 URL 和保存文件名遵循[固定下载规则](../README.zh.md#fixed-downloads)。上传重跑同时核对字节和 `Content-Disposition`;字节相同但响应头缺失或错误时,上传一次并读回验证。记录已完成但远端字节改变时停止恢复,需要重新审批发布。完成标记在元数据修复失败后仍保留。每次新的上传意图清除旧刷新记录,因此修复元数据后需重新刷新缓存;上一次任务 ID 和诊断需查 EdgeOne 历史。未知写入先读取再决定重试;CDN 响应头透传仍需实测。原机器路由和准备阶段输出完整时,仅重跑刷新 job 即可查询已保存任务。启用官网上传时,官网 job 仅跳过明确选择的 test 环境。各 job 的本地预检要求其注入的 `route` 或 `selection` 输出存在。官网审批缺失或变化时,在上传或提交刷新任务前失败。`website-destination` 缺失会扩大两个官网并发组的互斥范围。`runner` 输出缺失可能导致无法调度,尚未进入预检。输出缺失时停止局部重试,workflow 不重建这些输出。重新启动发布 workflow 前,先检查当前远端状态并确认上传范围的审批;这不属于仅缓存恢复。不要为恢复发布输出重跑打包。人工重跑确认旧任务失败后可提交一次。提交响应丢失时查询匹配的历史记录,不重新提交。unknown 带任务 ID 表示提交已确认;没有 ID 则可能从未提交。人工恢复前应检查 EdgeOne 历史,重新发起发布运行是恢复方式之一。操作者也可使用已有的[固定下载刷新命令](../README.zh.md#fixed-downloads);Windows 操作者使用该处说明的 DPAPI 凭据启动器。该命令只提交固定 URL 刷新,不观察完成状态,也不更新本次 Actions 运行的 journal。确认恢复完成前应在 EdgeOne 检查返回的任务。
刷新观察每十秒查询一次,最长五分钟;结果未知或观察超时后额外查询一次。明确的 failed、timeout、canceled 结果使 job 失败。仍无法确认时成功退出,并输出 Actions warning 和醒目摘要;持久化状态保持 unknown,不标为完成。诊断 artifact 尽力归档,本地记录仍是恢复依据。模拟服务测试覆盖这些路径;发布操作者必须在生产依赖恢复能力前验证 COS/EdgeOne 权限、job-id 筛选、时间范围查询、任务类型和时间戳格式、Actions 跨 attempt 恢复及实际 CDN 行为。
解决故障后,仅在上文要求的上游输出完整时重跑失败的发布 job,以保持准备阶段选定的打包尝试;否则停止局部重试。新发布可显式选择原打包运行和尝试。尝试留空时重跑所有 job 会重新解析最新打包尝试,并需要重新审批。不要仅为重试上传而重新打包。缺失对象会上传,相同对象跳过,同名但字节不同的对象会停止操作。写入结果不明时通过读取远端字节核对。频道已有更高版本时,旧上传不能替换它。每个包只更新自身内置通道:nightly 写入 `nightly.yml` / `nightly-mac.yml`,stable 写入 `stable.yml` / `stable-mac.yml`。stable 二进制位于目标二进制前缀下的 `stable/` 子目录,与已有 nightly 对象分离。同一源码和版本发布到两个通道需要分别打包;已有发布 tag 仅在源码提交相同时复用。
同级 `upload-records/` 目录保留操作标识、逐行事件和最终结果。频道写入意图同时记录先前和目标 YAML。失败记录阶段、安全错误分类与诊断;COS 失败还标明 `GetObject` 或 `PutObject`,并在可用时记录经过校验的 HTTP 状态码和 request ID。访问拒绝提示会指出需检查的权限。不保存原始服务响应或凭据。审计初始化在文件完整后才可见;遗留的 `.initializing-*` 目录不参与已完成发布的扫描。写入和回读在继续操作前落盘;没有最终结果代表中断,不代表成功。Actions 还将操作记录保存为诊断 artifact,保留 30 天。这些本地记录不防篡改。COS 回读验证存储字节,不代表公开 CDN 行为;公开下载需单独验收。
@@ -0,0 +1,31 @@
/** Validate the original machine and immutable inventory before GitHub artifact archival. */
import { resolve } from 'node:path'
import { desktopPublicationFailure } from './desktop-publication-failure.ts'
import { desktopReleasesRoot } from './retain-desktop-ci.ts'
import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts'
/**
* Verify an original build without interpreting the archive job's attempt as a new build.
* @param env Original build outputs and current Actions machine identity.
* @returns Resolves after the retained inventory passes all digest checks.
*/
export async function verifyDesktopArchive(env: NodeJS.ProcessEnv): Promise<void> {
if (!env.RUNNER_NAME || env.RUNNER_NAME !== env.DESKTOP_PACKAGE_RUNNER) throw new Error('desktop archival: wrong original machine')
const root = desktopReleasesRoot(env)
const runId = env.GITHUB_RUN_ID || ''
const attempt = env.DESKTOP_PACKAGE_ATTEMPT || ''
const expected = retainedDesktopPath(root, runId, attempt)
if (env.DESKTOP_RETAINED_DIRECTORY !== expected) throw new Error('desktop archival: retained directory differs from original build')
const manifest = await verifyRetainedDesktopRelease(root, runId, attempt)
if (manifest.source.repository !== env.GITHUB_REPOSITORY || manifest.source.runnerName !== env.RUNNER_NAME) {
throw new Error('desktop archival: retained source does not match repository or machine')
}
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
try { await verifyDesktopArchive(process.env) }
catch (error) {
process.stderr.write(`${JSON.stringify(desktopPublicationFailure(error, 'artifact archival'))}\n`)
process.exitCode = 1
}
}
@@ -14,6 +14,13 @@ export type DesktopAutoUpdateTarget = 'mac-arm64' | 'mac-x64' | 'win-x64'
*/
export function desktopLatestInstallerFilename(target: DesktopAutoUpdateTarget): string
/**
* Resolve the production website installer URL shared by approval, upload and purge.
* @param target Supported Desktop target.
* @returns Fixed production download URL.
*/
export function desktopWebsiteInstallerUrl(target: DesktopAutoUpdateTarget): string
/** Public updater URL and object prefixes for one release target. */
export interface DesktopAutoUpdateConfig {
readonly environment: DesktopAutoUpdateEnvironment
@@ -46,6 +46,15 @@ export function desktopLatestInstallerFilename(target) {
return `dsh-latest-${windows ? 'windows' : 'macos'}-${target === 'mac-arm64' ? 'arm64' : 'x64'}.${windows ? 'exe' : 'dmg'}`
}
/**
* Resolve the production website installer URL shared by approval, upload and purge.
* @param {'mac-arm64' | 'mac-x64' | 'win-x64'} target Supported Desktop target.
* @returns {string} Fixed production download URL.
*/
export function desktopWebsiteInstallerUrl(target) {
return `${UPDATE_ENVIRONMENTS.production.fixedOrigin}/desktop/${desktopLatestInstallerFilename(target)}`
}
/**
* Resolve the update deployment, defaulting local release work to test.
* @param {NodeJS.ProcessEnv} env - Packaging or upload environment.
@@ -1,5 +1,6 @@
/** Safe failure details shared by publication diagnostics and durable journals. */
import { ZodError } from 'zod'
import { DesktopPurgeExecutionError } from './desktop-purge-recovery.ts'
import { DesktopPublishError } from './desktop-publish.ts'
const publicCodes = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'BadDigest', 'SignatureDoesNotMatch',
@@ -39,12 +40,15 @@ export function desktopPublicationFailure(error: unknown, phase: string): {
...(typeof requestId === 'string' && /^[\w+/=.-]{1,256}$/u.test(requestId) ? { requestId } : {}),
...(typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599 ? { httpStatus: status } : {}) }
}
if (error instanceof DesktopPurgeExecutionError) return { phase, code: `purge-${error.status}`, message: error.message }
if (error instanceof DesktopPublishError) return { phase, code: error.code, message: error.message }
if (error instanceof ZodError) return { phase, code: 'invalid-data',
message: `Invalid fields: ${error.issues.map(issue => `${issue.path.join('.') || '(root)'} (${issue.code})`).join(', ')}` }
if (error instanceof SyntaxError) return { phase, code: 'invalid-json', message: 'Invalid JSON; check the configuration or retained record for this stage.' }
const ownedMessage = /^(desktop (?:publish|release store|retention|rollback|tag|upload|auto-update|macOS signing|build)[^\n]*:|Usage:)/u
if (error instanceof Error && ownedMessage.test(error.message)) {
const ownedMessage =
/^(desktop (?:publish|archival|release store|retention|rollback|tag|upload|auto-update|macOS signing|build)[^\n]*:|Usage:)/u
const websiteMessage = /^website (?:publication|installer|cache purge):/u
if (error instanceof Error && (ownedMessage.test(error.message) || websiteMessage.test(error.message))) {
return { phase, code: 'validation', message: error.message }
}
const record = typeof error === 'object' && error !== null ? error : {}
@@ -1,6 +1,7 @@
/** Render the verified publication plan for GitHub's native deployment reviewers. */
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import { desktopWebsiteInstallerUrl } from './desktop-auto-update-environment.mjs'
import type { DesktopRetainedSource } from './desktop-release-store.ts'
import type { DesktopUploadPlan } from './desktop-upload-plan.ts'
@@ -18,10 +19,11 @@ function link(url: string, label = url): string { return `<a href="${text(url)}"
* @param plan Validated upload plan; YAML contents are the bytes that will be uploaded.
* @param approval Digest bound to the approved manifest and upload plan.
* File SHA-256 hex supports `shasum -a 256` on downloads; upload reconciliation separately uses SHA-512 base64.
* @param uploadWebsite Whether the selected operation also replaces the production website installer.
* @returns GitHub-flavored Markdown with final URLs and upload-byte fingerprints, without credentials or local paths.
*/
export async function desktopPublicationSummary(
source: DesktopRetainedSource, plan: DesktopUploadPlan, approval: string,
source: DesktopRetainedSource, plan: DesktopUploadPlan, approval: string, uploadWebsite: boolean,
): Promise<string> {
const origin = new URL(plan.publicUrl).origin
const url = (key: string) => `${origin}/${key.split('/').map(encodeURIComponent).join('/')}`
@@ -52,6 +54,8 @@ export async function desktopPublicationSummary(
row('升级 YAML', `${feeds.map(file => link(url(file.key))).join('<br>')}<br>本次发布将更新此文件;审批前可能不存在或仍指向旧版本。`),
row('打包来源', `${link(runUrl, `查看打包运行 #${source.runId} · 第 ${source.attempt} 次尝试`)}<br>源码:${code(`${source.sourceRef} @ ${source.commit}`)}<br>打包机器:${code(source.runnerName)}`),
row('签名与公证', plan.target === 'win-x64' ? 'EXE 签名校验通过' : 'DMG 校验通过<br>ZIP 内应用校验通过'),
...(uploadWebsite && plan.environment === 'production' ? [row('官网固定安装包',
`${link(desktopWebsiteInstallerUrl(plan.target))}<br>替换为版本 ${code(plan.version)};已有安装包会被替换,无防降级保护;官网上传与刷新在后续 job 中执行,可能需另行审批。`)] : []),
row('Git tag', tag), '', '### 批准后将执行', '',
'1. 重新校验产物与发布目标;若与审批摘要不一致则停止。',
'2. 上传缺少的文件,跳过内容一致的已有文件;发现内容冲突则停止。',
+5 -3
View File
@@ -49,8 +49,9 @@ export function desktopPublishCos(
})
try {
const cos = client()
await cosOperation(cos, 900_000, () => cos.getObject({ ...address, Output: output }))
return { size, sha512: sha512.digest('base64'), ...(channel ? { contents: Buffer.concat(chunks).toString('utf8') } : {}) }
const response = await cosOperation(cos, 900_000, () => cos.getObject({ ...address, Output: output }))
return { size, sha512: sha512.digest('base64'),
...(typeof response.headers?.['content-disposition'] === 'string' ? { contentDisposition: response.headers['content-disposition'] } : {}), ...(channel ? { contents: Buffer.concat(chunks).toString('utf8') } : {}) }
} catch (error) {
if (missing(error)) return null
throw new DesktopCosOperationError('GetObject', error)
@@ -71,7 +72,8 @@ export function desktopPublishCos(
try {
await cosOperation(cos, 900_000, () => cos.putObject({
...address, Body: body, ContentLength: digest.size, ContentType: artifact.contentType,
Headers: { 'Content-MD5': md5.digest('base64'), ...(forbidOverwrite ? { 'x-cos-forbid-overwrite': 'true' } : {}) },
Headers: { 'Content-MD5': md5.digest('base64'),
...(artifact.contentDisposition ? { 'Content-Disposition': artifact.contentDisposition } : {}), ...(forbidOverwrite ? { 'x-cos-forbid-overwrite': 'true' } : {}) },
}))
} catch (error) {
throw new DesktopCosOperationError('PutObject', error)
@@ -1,4 +1,4 @@
/** Validate a completed packaging attempt and route publication back to its original runner. */
/** Validate package-job success and route publication; attempt selection enforces run completion. */
import { z } from 'zod'
import { desktopPublishRunnersSchema, desktopPackageWorkflows } from './desktop-publish-targets.ts'
import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs'
@@ -6,7 +6,7 @@ import { desktopPublishQualificationError } from './desktop-publish-qualificatio
const positive = z.number().int().positive()
const runSchema = z.object({
id: positive, run_attempt: positive, head_sha: z.string().regex(/^[a-f0-9]{40}$/u),
path: z.string(), conclusion: z.literal('success'), event: z.literal('workflow_dispatch'),
path: z.string(), event: z.literal('workflow_dispatch'),
repository: z.object({ full_name: z.string() }),
})
const requestSchema = z.object({ source: z.object({
+2 -2
View File
@@ -8,8 +8,8 @@ import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-
/** File identity computed from bytes, never inferred from COS ETags. */
export interface DesktopObjectDigest { readonly size: number; readonly sha512: string }
/** Remote object observation; channel objects additionally carry their exact YAML. */
export interface DesktopRemoteObject extends DesktopObjectDigest { readonly contents?: string }
/** Remote bytes, optional download filename header, and exact YAML for channel objects. */
export interface DesktopRemoteObject extends DesktopObjectDigest { readonly contents?: string; readonly contentDisposition?: string }
/** Transport owned by the caller holding the destination channel lock. */
export interface DesktopPublishTransport {
/** Read and hash remote bytes; only a confirmed missing object returns null. */
@@ -0,0 +1,149 @@
/** Resume a fixed-URL purge without repeating ambiguous submissions. */
import type { teo } from 'tencentcloud-sdk-nodejs-teo'
import type { DesktopPurgeConfig } from './desktop-edgeone.ts'
/** Non-secret evidence saved before submission and after every observation. */
export interface DesktopPurgeRecord {
readonly zoneId: string
readonly publicUrl: string
readonly submittedAt: string
readonly jobId?: string | undefined
readonly status: 'pending' | 'processing' | 'success' | 'failed' | 'timeout' | 'canceled' | 'unknown'
readonly observedAt?: string | undefined
readonly diagnostic?: string | undefined
}
/** SDK requests used by the recovery owner. */
export type DesktopPurgeRecoveryClient = Pick<InstanceType<typeof teo.v20220901.Client>, 'CreatePurgeTask' | 'DescribePurgeTasks'>
/** Explicit bounded observation policy; writes are never automatically retried. */
export interface DesktopPurgeRecoveryOptions {
readonly intervalMs: number
readonly waitMs: number
readonly allowResubmit: boolean
readonly now: () => number
readonly sleep: (milliseconds: number) => Promise<void>
readonly save: (record: DesktopPurgeRecord) => Promise<void>
}
/** A confirmed remote failure, distinct from an unconfirmed observation. */
export class DesktopPurgeExecutionError extends Error {
constructor(readonly status: 'failed' | 'timeout' | 'canceled') {
super(`website cache purge: ${status}; inspect the task before manually rerunning`)
}
}
function failed(status: DesktopPurgeRecord['status']): status is 'failed' | 'timeout' | 'canceled' {
return status === 'failed' || status === 'timeout' || status === 'canceled'
}
async function observe(record: DesktopPurgeRecord, client: DesktopPurgeRecoveryClient,
now: number, config: DesktopPurgeConfig): Promise<DesktopPurgeRecord> {
const observedAt = new Date(now).toISOString()
const unknown = (diagnostic: string): DesktopPurgeRecord => ({ ...record, status: 'unknown', observedAt, diagnostic })
const matches = []
try {
let offset = 0
do {
const response = await client.DescribePurgeTasks({
ZoneId: record.zoneId, Limit: 1000, Offset: offset,
...(record.jobId ? { Filters: [{ Name: 'job-id', Values: [record.jobId] }] } : {
StartTime: record.submittedAt,
EndTime: new Date(Math.min(now, Date.parse(record.submittedAt) + 120_000)).toISOString(),
}),
})
if (!Array.isArray(response.Tasks) || typeof response.TotalCount !== 'number') return unknown('invalid query response')
for (const task of response.Tasks) {
if (task.Target !== record.publicUrl || task.Type !== 'purge_url') continue
if (record.jobId ? task.JobId !== record.jobId
: !task.CreateTime || !Number.isFinite(Date.parse(task.CreateTime))
|| Date.parse(task.CreateTime) < Date.parse(record.submittedAt)
|| Date.parse(task.CreateTime) > Date.parse(record.submittedAt) + 120_000) continue
matches.push(task)
}
offset += response.Tasks.length
if (offset >= response.TotalCount) break
if (response.Tasks.length === 0 || offset >= 10_000) return unknown('task history could not be fully inspected')
} while (true)
} catch (error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') }
if (matches.length === 0) return unknown(record.jobId
? 'accepted task not found in query history; execution result unconfirmed'
: 'no matching submission found; purge may not have been submitted; inspect EdgeOne history before manual recovery')
if (matches.length !== 1) return unknown('multiple matching submissions found; cannot identify this submission')
const task = matches[0]!
if (!task.JobId || !/^[\w.-]{1,128}$/u.test(task.JobId)
|| task.JobId.includes(config.secretId) || task.JobId.includes(config.secretKey)) return unknown('query returned no usable task ID')
const status = task.Status
if (status !== 'processing' && status !== 'success' && status !== 'failed' && status !== 'timeout' && status !== 'canceled') {
return unknown('query returned an unknown task status')
}
return { zoneId: record.zoneId, publicUrl: record.publicUrl, submittedAt: record.submittedAt,
jobId: task.JobId, status, observedAt }
}
/**
* Submit at most once, or reconcile an earlier submission, then observe bounded completion.
* Unknown results receive one additional query and return unknown for warning-only Actions completion.
* @param config Validated destination and credentials; credentials never enter records.
* @param previous Durable record, or undefined for a new publication.
* @param client SDK client with bounded requests and no submission retry policy.
* @param options Clock, persistence, timing and explicit manual-resubmission authorization.
* @returns Successful or unconfirmed result; confirmed failures throw after durable recording.
*/
export async function recoverDesktopPurge(config: DesktopPurgeConfig, previous: DesktopPurgeRecord | undefined,
client: DesktopPurgeRecoveryClient, options: DesktopPurgeRecoveryOptions): Promise<DesktopPurgeRecord> {
if (options.intervalMs <= 0 || options.waitMs < 0) throw new Error('website cache purge: invalid observation budget')
if (previous && (previous.zoneId !== config.zoneId || previous.publicUrl !== config.publicUrl)) {
throw new Error('website cache purge: saved destination differs from selected publication')
}
let record = previous
let observedPrevious = false
if (record) {
record = await observe(record, client, options.now(), config)
observedPrevious = true
await options.save(record)
if (record.status === 'success') return record
if (failed(record.status)) {
if (!options.allowResubmit) throw new DesktopPurgeExecutionError(record.status)
record = undefined
observedPrevious = false
}
}
if (!record) {
record = { zoneId: config.zoneId, publicUrl: config.publicUrl,
submittedAt: new Date(Math.floor(options.now() / 1000) * 1000).toISOString(), status: 'pending' }
await options.save(record)
let response: Awaited<ReturnType<DesktopPurgeRecoveryClient['CreatePurgeTask']>> | undefined
try { response = await client.CreatePurgeTask({ ZoneId: config.zoneId, Type: 'purge_url', Targets: [config.publicUrl] }) }
catch (error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ }
const jobId = response?.JobId
if (response?.FailedList?.length) {
record = { ...record, status: 'failed' }
} else if (typeof jobId === 'string' && /^[\w.-]{1,128}$/u.test(jobId)
&& !jobId.includes(config.secretId) && !jobId.includes(config.secretKey)) {
record = { ...record, status: 'processing', jobId }
} else {
record = { ...record, status: 'unknown', diagnostic: 'submission acceptance unconfirmed; checking task history' }
}
await options.save(record)
if (failed(record.status)) throw new DesktopPurgeExecutionError(record.status)
}
let current: DesktopPurgeRecord = record
const deadline = options.now() + options.waitMs
let extraQuery = false
while (true) {
const observed: DesktopPurgeRecord = observedPrevious ? current : await observe(current, client, options.now(), config)
observedPrevious = false
current = observed
await options.save(current)
if (current.status === 'success') return current
if (failed(current.status)) throw new DesktopPurgeExecutionError(current.status)
if (extraQuery) {
current = { ...current, status: 'unknown', diagnostic: current.diagnostic ?? (options.now() >= deadline ? 'observation deadline exceeded' : 'task still processing after an additional query') }
await options.save(current)
return current
}
if (current.status === 'unknown' || options.now() >= deadline) extraQuery = true
await options.sleep(options.intervalMs)
}
}
+16 -3
View File
@@ -121,13 +121,13 @@ export async function retainDesktopRelease(root: string, source: DesktopRetained
}
/**
* Read an attempt and rehash every retained file before a consumer uses it.
* Read and validate manifest identity without requiring unrelated retained files.
* @param root Persistent releases root.
* @param runId Expected source run ID.
* @param attempt Expected source attempt.
* @returns Parsed inventory; missing, linked, changed or mismatched files reject.
* @returns Parsed inventory; consumers must verify the files they use against their recorded digests.
*/
export async function verifyRetainedDesktopRelease(root: string, runId: string, attempt: string): Promise<DesktopRetainedManifest> {
export async function readRetainedDesktopManifest(root: string, runId: string, attempt: string): Promise<DesktopRetainedManifest> {
const path = retainedDesktopPath(root, runId, attempt)
await directory(root)
await directory(join(root, runId))
@@ -137,6 +137,19 @@ export async function verifyRetainedDesktopRelease(root: string, runId: string,
const manifest = manifestSchema.parse(JSON.parse(await readFile(manifestPath, 'utf8')))
if (manifest.source.runId !== runId || manifest.source.attempt !== attempt) throw new Error('desktop release store: attempt identity mismatch')
if (new Set(manifest.files.map(file => file.name)).size !== manifest.files.length) throw new Error('desktop release store: duplicate file inventory')
return manifest
}
/**
* Verify every retained file against its immutable build manifest.
* @param root Persistent releases directory.
* @param runId Original packaging run.
* @param attempt Original packaging attempt, unchanged by archival reruns.
* @returns Manifest after all retained files pass size and hash verification.
*/
export async function verifyRetainedDesktopRelease(root: string, runId: string, attempt: string): Promise<DesktopRetainedManifest> {
const manifest = await readRetainedDesktopManifest(root, runId, attempt)
const path = retainedDesktopPath(root, runId, attempt)
for (const file of manifest.files) {
const current = await fingerprint(join(path, file.name))
if (current.size !== file.size || current.sha512 !== file.sha512) throw new Error(`desktop release store: changed file ${file.name}`)
+4 -1
View File
@@ -33,6 +33,8 @@ export interface DesktopUploadArtifact {
readonly filename: string
readonly key: string
readonly contentType: string
/** Browser save name for fixed website downloads, preserving the validated installer basename. */
readonly contentDisposition?: string
readonly channelMetadata: boolean
/** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */
readonly contents?: string
@@ -288,7 +290,8 @@ export async function createDesktopUploadPlan(
bucket: update.bucket,
secretIdEnvName: update.secretIdEnvName,
secretKeyEnvName: update.secretKeyEnvName,
artifacts: options.latest ? [{ ...installerArtifact, filename: latestFilename, key: latestKey }] : artifacts,
artifacts: options.latest ? [{ ...installerArtifact, filename: latestFilename, key: latestKey,
contentDisposition: `attachment; filename="${installerArtifact.filename}"` }] : artifacts,
...typeof buildRecord.commit === 'string' ? { commit: buildRecord.commit } : {},
...typeof buildRecord.dirty === 'boolean' ? { dirty: buildRecord.dirty } : {},
}
+1 -1
View File
@@ -101,7 +101,7 @@ export async function uploadDesktopRelease(plan: DesktopUploadPlan, cos: COS, re
try {
const response = await cos.putObject({ Bucket: plan.bucket, Region: DESKTOP_COS_REGION, Key: key,
Body: body, ContentLength: artifact.size, ContentType: artifact.contentType,
Headers: { 'Content-MD5': artifact.md5 } })
Headers: { 'Content-MD5': artifact.md5, ...(artifact.contentDisposition ? { 'Content-Disposition': artifact.contentDisposition } : {}) } })
confirmedPuts++
stage = 'record-response'
recordPackagingEvent(directory, { type: 'put-confirmed', key, attempts: 1, ...receipt(response) })
@@ -0,0 +1,116 @@
/** Validate one production installer and hold its file handle through COS publication. */
import { createHash } from 'node:crypto'
import { open, lstat, type FileHandle } from 'node:fs/promises'
import { join } from 'node:path'
import type { DesktopRetainedManifest } from './desktop-release-store.ts'
import type { DesktopPublishRoute } from './desktop-publish-route.ts'
import { desktopLatestInstallerFilename, desktopWebsiteInstallerUrl } from './desktop-auto-update-environment.mjs'
import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from './desktop-cos.ts'
import { cosOperation } from './cos-operation.ts'
import type { DesktopObjectDigest, DesktopPublishTransport } from './desktop-publish.ts'
import { DesktopCosOperationError } from './desktop-publication-failure.ts'
import type { DesktopUploadPlan } from './desktop-upload-plan.ts'
/** Verified file and destination; the caller closes the handle after publication. */
export interface DesktopWebsiteInstaller {
readonly plan: DesktopUploadPlan
readonly digest: DesktopObjectDigest
readonly md5: string
readonly contentDisposition: string
readonly handle: FileHandle
}
/**
* Check production build identity and hash only the selected installer once.
* @param directory Retained build directory on the original runner.
* @param manifest Trusted retained build inventory matched against GitHub evidence.
* @param route Pinned build identity from the credential-free routing job.
* @param repository Repository expected by the workflow.
* @param bucket Approved production COS bucket.
* @returns An open verified installer; callers must close its handle in finally.
*/
export async function prepareWebsiteInstaller(directory: string, manifest: DesktopRetainedManifest,
route: DesktopPublishRoute, repository: string, bucket: string): Promise<DesktopWebsiteInstaller> {
const source = manifest.source
if (route.preset !== 'production' || source.preset !== 'production'
|| source.repository !== repository || source.runId !== route.runId || source.attempt !== route.attempt
|| source.commit !== route.commit || source.runnerName !== route.runnerName || source.target !== route.target
|| source.sourceRef !== route.sourceRef || source.channel !== route.channel
|| source.qualification !== (route.target === 'win-x64' ? 'signed' : 'notarized')
|| !/^(?:master|dsh-v[0-9][0-9A-Za-z.-]*)$/u.test(source.sourceRef)) {
throw new Error('website installer: build identity or production qualification mismatch')
}
const windows = route.target === 'win-x64'
const filename = `deepseek-harness-${source.version}-${route.target}.${windows ? 'exe' : 'dmg'}`
const file = manifest.files.find(item => item.name === filename)
if (!file) throw new Error('website installer: selected installer is absent from build manifest')
const path = join(directory, file.name)
const info = await lstat(path)
if (!info.isFile() || info.isSymbolicLink()) throw new Error('website installer: expected a regular installer file')
const handle = await open(path, 'r')
try {
const sha512 = createHash('sha512')
const md5 = createHash('md5')
let size = 0
for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 })) {
size += bytes.length
sha512.update(bytes)
md5.update(bytes)
}
const digest = { size, sha512: sha512.digest('base64') }
if (size !== file.size || digest.sha512 !== file.sha512) throw new Error('website installer: SHA-512 or size differs from build manifest')
const key = `desktop/${desktopLatestInstallerFilename(route.target)}`
const contentDisposition = `attachment; filename="${file.name}"`
return { handle, digest, contentDisposition, md5: md5.digest('base64'), plan: {
environment: 'production', target: route.target, version: source.version, commit: source.commit, dirty: false,
bucket, publicUrl: desktopWebsiteInstallerUrl(route.target),
secretIdEnvName: 'DOWNLOAD_PROD_COS_SECRET_ID', secretKeyEnvName: 'DOWNLOAD_PROD_COS_SECRET_KEY',
artifacts: [{ path, filename: file.name, key, channelMetadata: false,
contentDisposition,
contentType: windows ? 'application/vnd.microsoft.portable-executable' : 'application/x-apple-diskimage' }],
} }
} catch (error) {
await handle.close()
throw error
}
}
/**
* Reconcile an earlier upload or replace the fixed object once using the already verified handle.
* @param installer Open installer verified against the selected build.
* @param credentials Production upload credentials, never logged.
* @param transport Read-only reconciliation adapter using the same destination.
* @param record Durable event writer; intent must persist before the remote write.
* @param options Optional COS factory and durable completion evidence; completed uploads cannot replace different remote bytes.
* @returns Whether bytes were uploaded or an existing identical object was reused.
*/
export async function uploadWebsiteInstaller(installer: DesktopWebsiteInstaller, credentials: DesktopCosCredentials,
transport: Pick<DesktopPublishTransport, 'read'>,
record: (event: 'upload-intent' | 'uploaded') => Promise<void>,
options: { createClient?: typeof createDesktopCos; previouslyUploaded?: boolean } = {},
): Promise<'uploaded' | 'present'> {
const artifact = installer.plan.artifacts[0]!
const matches = (remote: DesktopObjectDigest | null) =>
remote?.size === installer.digest.size && remote.sha512 === installer.digest.sha512
const remote = await transport.read(artifact.key, false)
if (options.previouslyUploaded && !matches(remote)) throw new Error(`website installer: recorded upload no longer matches remote bytes (${remote === null ? 'object missing' : 'bytes changed'}); select and approve a new publication`)
if (matches(remote) && remote?.contentDisposition === installer.contentDisposition) {
await record('uploaded')
return 'present'
}
await record('upload-intent')
const body = installer.handle.createReadStream({ autoClose: false, start: 0 })
const cos = (options.createClient ?? createDesktopCos)(credentials)
try {
await cosOperation(cos, 900_000, () => cos.putObject({ Bucket: installer.plan.bucket, Region: DESKTOP_COS_REGION,
Key: artifact.key, Body: body, ContentLength: installer.digest.size, ContentType: artifact.contentType,
Headers: { 'Content-MD5': installer.md5, 'Content-Disposition': installer.contentDisposition },
}))
} catch (error) { throw new DesktopCosOperationError('PutObject', error) }
finally { body.destroy() }
const confirmed = await transport.read(artifact.key, false)
if (!matches(confirmed)) throw new Error(`website installer: remote bytes unconfirmed; expected ${JSON.stringify(installer.digest)}, observed ${JSON.stringify(confirmed)}; reconcile before retrying`)
if (confirmed?.contentDisposition !== installer.contentDisposition) throw new Error(`website installer: remote download filename unconfirmed; expected ${JSON.stringify(installer.contentDisposition)}, observed ${JSON.stringify(confirmed?.contentDisposition ?? null)}; inspect COS metadata before retrying`)
await record('uploaded')
return 'uploaded'
}
+7 -2
View File
@@ -14,6 +14,7 @@ import { publishDesktopRelease } from './desktop-publish.ts'
import { desktopPublicationFailure } from './desktop-publication-failure.ts'
import { desktopPublicationSummary } from './desktop-publication-summary.ts'
import { publishDesktopTag } from './desktop-publish-tag.ts'
import { websiteApproval } from './publish-website-ci.ts'
import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs'
const routeSchema = z.object({ runId: z.string(), attempt: z.string(), commit: z.string(), runnerName: z.string(),
@@ -63,10 +64,14 @@ if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.fi
const env = process.env
const { route, manifest, config, plan, root, approval } = await prepareDesktopPublication(env)
if (mode === '--publish' && !env.DESKTOP_APPROVED_PACKAGE) throw new Error('desktop publish: approved package digest is required')
if (env.DESKTOP_UPLOAD_WEBSITE === 'true' && route.preset === 'production'
&& !/^zone-[a-z0-9]+$/u.test(env.DOWNLOAD_PROD_EO_ZONE_ID || '')) {
throw new Error('desktop publish: configure DOWNLOAD_PROD_EO_ZONE_ID before approving website upload')
}
if (mode === '--check') {
if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `approval=${approval}\nlabel=${plan.version} → ${manifest.source.channel} / ${plan.target} / ${plan.environment}\n`)
if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `website-destination=${createHash('sha256').update(`${config.bucket}/${plan.target}`).digest('hex')}\nwebsite-approval=${websiteApproval(manifest, config.bucket)}\napproval=${approval}\nlabel=${plan.version} → ${manifest.source.channel} / ${plan.target} / ${plan.environment}\n`)
if (env.GITHUB_STEP_SUMMARY && !env.DESKTOP_APPROVED_PACKAGE) await appendFile(env.GITHUB_STEP_SUMMARY,
await desktopPublicationSummary(manifest.source, plan, approval))
await desktopPublicationSummary(manifest.source, plan, approval, env.DESKTOP_UPLOAD_WEBSITE === 'true'))
if (env.GITHUB_OUTPUT && config.githubApp) await appendFile(env.GITHUB_OUTPUT,
`app-client-id=${config.githubApp.clientId}\napp-key-file=${config.githubApp.privateKeyFile}\n`)
process.stdout.write(`desktop publish: verified ${plan.target} ${plan.version}; no credentials read or COS requests made\n`)
+130
View File
@@ -0,0 +1,130 @@
/** Actions entrypoint for independently recoverable website upload and cache purge jobs. */
import { createHash, randomUUID } from 'node:crypto'
import { appendFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { z } from 'zod'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts'
import { desktopReleasesRoot } from './retain-desktop-ci.ts'
import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts'
import { prepareWebsiteInstaller, uploadWebsiteInstaller } from './desktop-website-installer.ts'
import { desktopPublishCos } from './desktop-publish-cos.ts'
import { withDesktopChannelLock } from './desktop-publish-record.ts'
import { recoverDesktopPurge, type DesktopPurgeRecord } from './desktop-purge-recovery.ts'
import { desktopPublicationFailure } from './desktop-publication-failure.ts'
const routeSchema = z.object({ runId: z.string().regex(/^[1-9]\d*$/u), attempt: z.string().regex(/^[1-9]\d*$/u),
commit: z.string().regex(/^[a-f0-9]{40}$/u), runnerName: z.string(), runnerLabel: z.string(), sourceRef: z.string(),
channel: z.enum(['nightly', 'stable']), target: z.enum(['mac-arm64', 'mac-x64', 'win-x64']), preset: z.literal('production') })
const purgeSchema = z.object({ zoneId: z.string(), publicUrl: z.url(), submittedAt: z.iso.datetime(),
jobId: z.string().regex(/^[\w.-]{1,128}$/u).optional(),
status: z.enum(['pending', 'processing', 'success', 'failed', 'timeout', 'canceled', 'unknown']),
observedAt: z.iso.datetime().optional(), diagnostic: z.string().optional() })
const stateSchema = z.object({ approval: z.string(), upload: z.enum(['pending', 'upload-intent', 'uploaded']),
uploadConfirmed: z.boolean().optional(), purge: purgeSchema.optional(), purgeAttempt: z.string().optional() })
/**
* Bind website approval to the retained manifest and exact production bucket.
* @param manifest Retained build metadata already matched to GitHub evidence.
* @param bucket Production COS destination.
* @returns Non-secret digest passed through the production approval job.
*/
export function websiteApproval(manifest: unknown, bucket: string): string {
return createHash('sha256').update(JSON.stringify({ manifest, bucket })).digest('hex')
}
/**
* Upload a fixed installer or recover its cache purge, using a publication-run-owned journal.
* @param mode Explicit website operation; purge never opens or uploads installer bytes.
* @param env Actions identity, approved build and machine configuration.
* @returns Resolves on success or a prominently reported unknown purge result.
*/
export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.ProcessEnv): Promise<void> {
const route = routeSchema.parse(JSON.parse(env.DESKTOP_PUBLISH_ROUTE || '{}'))
if (env.RUNNER_NAME !== route.runnerName || !/^[1-9]\d*$/u.test(env.GITHUB_RUN_ID || '')
|| !/^[1-9]\d*$/u.test(env.GITHUB_RUN_ATTEMPT || '')) throw new Error('website publication: invalid Actions identity or original machine')
const root = desktopReleasesRoot(env)
const manifest = await readRetainedDesktopManifest(root, route.runId, route.attempt)
const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, 'production')
const approval = websiteApproval(manifest, config.bucket)
if (!env.DESKTOP_WEBSITE_APPROVAL || env.DESKTOP_WEBSITE_APPROVAL !== approval) throw new Error('website publication: approved build or destination changed')
const zoneId = env.DOWNLOAD_PROD_EO_ZONE_ID
if (!zoneId || !/^zone-[a-z0-9]+$/u.test(zoneId)) throw new Error('website publication: configure DOWNLOAD_PROD_EO_ZONE_ID before uploading')
const directory = join(dirname(root), 'upload-records', `website-${env.GITHUB_RUN_ID}-${route.target}`)
await mkdir(directory, { recursive: true, mode: 0o700 })
const stateFile = join(directory, 'state.json')
let state: z.infer<typeof stateSchema> = { approval, upload: 'pending' }
try { state = stateSchema.parse(JSON.parse(await readFile(stateFile, 'utf8'))) }
catch (error) { if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error }
if (state.approval !== approval) throw new Error('website publication: journal belongs to another approved build')
const save = async () => {
const temporary = join(directory, `.state-${randomUUID()}.json`)
await writeFile(temporary, `${JSON.stringify(state)}\n`, { flag: 'wx', mode: 0o600, flush: true })
await rename(temporary, stateFile)
}
if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `record=${directory}\n`)
const credentials = await readDesktopUploadCredentials(config)
if (mode === 'upload') {
const installer = await prepareWebsiteInstaller(retainedDesktopPath(root, route.runId, route.attempt), manifest, route,
env.GITHUB_REPOSITORY || '', config.bucket)
try {
const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0]!.key}`, async () => {
const previouslyUploaded = state.uploadConfirmed === true || state.upload === 'uploaded'
return uploadWebsiteInstaller(installer, credentials, desktopPublishCos(installer.plan, credentials), async (event) => {
state = event === 'upload-intent'
? { approval: state.approval, upload: event, uploadConfirmed: previouslyUploaded }
: { ...state, upload: event, uploadConfirmed: true }
await save()
}, { previouslyUploaded })
})
const disposition = outcome === 'present' ? 'identical remote bytes and download filename confirmed; skipped' : 'uploaded'
const text = `Website installer ${disposition}: ${installer.plan.publicUrl}; version ${installer.plan.version}\n`
process.stdout.write(text)
if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY, text)
} finally { await installer.handle.close() }
return
}
if (state.upload !== 'uploaded') throw new Error('website publication: upload completion is not confirmed; recover the upload job first')
const { desktopWebsiteInstallerUrl } = await import('./desktop-auto-update-environment.mjs')
const publicUrl = desktopWebsiteInstallerUrl(route.target)
const { teo } = await import('tencentcloud-sdk-nodejs-teo')
const client = new teo.v20220901.Client({ credential: credentials, region: '',
profile: { httpProfile: { endpoint: 'teo.tencentcloudapi.com', reqTimeout: 30 } } })
const previousAttempt = state.purgeAttempt
const result = await recoverDesktopPurge({ ...credentials, zoneId, publicUrl }, state.purge, client, {
intervalMs: 10_000, waitMs: 300_000,
allowResubmit: previousAttempt !== undefined && previousAttempt !== env.GITHUB_RUN_ATTEMPT,
now: Date.now, sleep,
save: async (purge: DesktopPurgeRecord) => {
const accepted = purge.jobId && purge.jobId !== state.purge?.jobId
state = { ...state, purge, purgeAttempt: env.GITHUB_RUN_ATTEMPT }
await save()
if (accepted) process.stdout.write(`Website cache purge accepted: ${publicUrl}; task ${purge.jobId}\n`)
},
})
const details = `${publicUrl}\nTask: ${result.jobId ?? 'unknown'}\nObserved: ${result.observedAt}\n${result.diagnostic ?? ''}\n`
if (result.status === 'unknown') {
const acceptance = result.jobId ? '刷新已提交,执行结果未确认' : '刷新提交未确认,可能尚未提交'
process.stdout.write(`::warning title=官网缓存刷新结果未确认::官网资源已上传;${acceptance}。请核对 EdgeOne 任务记录后人工恢复。\n${details}`)
if (env.GITHUB_STEP_SUMMARY) {
let existing = ''
try { existing = await readFile(env.GITHUB_STEP_SUMMARY, 'utf8') }
catch (error) { if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error }
await writeFile(env.GITHUB_STEP_SUMMARY, `# ⚠ 官网资源已上传,缓存刷新结果未确认\n\n${acceptance}\n\n${details}${existing ? `\n${existing}` : ''}`)
}
} else {
process.stdout.write(`Website cache purge completed\n${details}`)
if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY, `Website cache purge completed\n\n${details}`)
}
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
try {
const mode = process.argv[2]
if (process.argv.length !== 3 || (mode !== 'upload' && mode !== 'purge')) throw new Error('Usage: publish-website-ci.ts upload|purge')
await publishWebsiteCi(mode, process.env)
} catch (error) {
process.stderr.write(`${JSON.stringify(desktopPublicationFailure(error, 'website publication'))}\n`)
process.exitCode = 1
}
}
@@ -8,11 +8,11 @@ import { desktopPublishRunnersSchema, desktopPackageWorkflows } from './desktop-
const positiveId = z.string().regex(/^[1-9]\d*$/u)
const inputsSchema = z.object({ package_run_id: positiveId, package_run_attempt: z.union([positiveId, z.literal('')]).optional() })
const runSchema = z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive(),
head_sha: z.string().regex(/^[a-f0-9]{40}$/u), status: z.literal('completed'), conclusion: z.literal('success'),
head_sha: z.string().regex(/^[a-f0-9]{40}$/u), status: z.literal('completed'), conclusion: z.string(),
event: z.literal('workflow_dispatch'), path: z.enum(Object.values(desktopPackageWorkflows)),
repository: z.object({ full_name: z.string() }) })
const jobsSchema = z.object({ jobs: z.array(z.object({
name: z.string(), runner_name: z.string().nullable(), conclusion: z.string().nullable(),
name: z.string(), run_attempt: z.number().int().positive(), runner_name: z.string().nullable(), conclusion: z.string().nullable(),
})) })
/**
@@ -29,12 +29,29 @@ export function selectDesktopPackage(repository: string, inputsValue: unknown, r
const inputs = inputsSchema.parse(inputsValue)
const base = `repos/${repository}/actions/runs/${inputs.package_run_id}`
const attempt = inputs.package_run_attempt || String(z.object({ run_attempt: z.number().int().positive() }).parse(api(base)).run_attempt)
const run = runSchema.parse(api(`${base}/attempts/${attempt}`))
let run = runSchema.parse(api(`${base}/attempts/${attempt}`))
if (String(run.id) !== inputs.package_run_id || String(run.run_attempt) !== attempt || run.repository.full_name !== repository) {
throw new Error('desktop publish: selected run or attempt does not match GitHub evidence')
}
const jobs = z.array(jobsSchema).parse(api(`${base}/attempts/${attempt}/jobs?per_page=100`, true)).flatMap(page => page.jobs)
const packages = jobs.filter(job => job.name === 'package' && job.conclusion === 'success' && job.runner_name)
let jobs = z.array(jobsSchema).parse(api(`${base}/attempts/${attempt}/jobs?per_page=100`, true)).flatMap(page => page.jobs)
let packages = jobs.filter(job => job.name === 'package')
if (packages.length === 0 || packages.every(job => job.run_attempt < Number(attempt))) {
// An archival-only attempt owns no new build; select the latest actual package job, never a prior success over a failed build.
const history = z.array(jobsSchema).parse(api(`${base}/jobs?filter=all&per_page=100`, true)).flatMap(page => page.jobs)
.filter(job => job.name === 'package' && job.run_attempt <= Number(attempt))
.sort((left, right) => right.run_attempt - left.run_attempt)
const original = history[0]
if (!original || original.conclusion !== 'success') throw new Error('desktop publish: latest original package job was not successful')
const selected = run
run = runSchema.parse(api(`${base}/attempts/${original.run_attempt}`))
if (String(run.id) !== inputs.package_run_id || run.run_attempt !== original.run_attempt || run.repository.full_name !== repository
|| run.head_sha !== selected.head_sha || run.path !== selected.path) {
throw new Error('desktop publish: original build identity differs from GitHub evidence')
}
jobs = z.array(jobsSchema).parse(api(`${base}/attempts/${original.run_attempt}/jobs?per_page=100`, true)).flatMap(page => page.jobs)
packages = jobs.filter(job => job.name === 'package')
}
packages = packages.filter(job => job.run_attempt === run.run_attempt && job.conclusion === 'success' && job.runner_name)
if (packages.length !== 1) throw new Error('desktop publish: expected one successful package job')
const runnerName = packages[0]!.runner_name!
const routes = desktopPublishRunnersSchema.parse(routesValue)
+22 -2
View File
@@ -6,6 +6,7 @@ import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDeskt
import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs'
import { retainDesktopRelease, type DesktopRetainedSource } from './desktop-release-store.ts'
import { validateDesktopBuildVersion } from './desktop-build-version.mjs'
import { desktopPublishRunnersSchema } from './desktop-publish-targets.ts'
import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs'
function required(env: NodeJS.ProcessEnv, name: string): string {
@@ -26,6 +27,22 @@ export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string {
return root
}
/**
* Resolve the original machine's unique label before expensive packaging work.
* @param env Machine identity, target and administrator-owned runner mapping.
* @returns The exact label used by the later GitHub archival job.
*/
export function resolveDesktopRetentionRunner(env: NodeJS.ProcessEnv): string {
const target = resolveDesktopBuildTarget(env)
const routes = desktopPublishRunnersSchema.parse(JSON.parse(required(env, 'DESKTOP_PUBLISH_RUNNERS')))
const route = routes[required(env, 'RUNNER_NAME')]
if (!route || !route.target.includes(target)
|| new Set(Object.values(routes).map(item => item.label)).size !== Object.keys(routes).length) {
throw new Error('desktop retention: original machine requires a unique artifact routing label')
}
return route.label
}
/**
* Save the complete installer inventory for a successful package job, without reading signing secrets.
* @param env Actions identity, resolved package version and machine preset selection.
@@ -34,6 +51,7 @@ export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string {
*/
export async function retainDesktopCi(env: NodeJS.ProcessEnv, appRoot = resolve(import.meta.dirname, '..')): Promise<string> {
const target = resolveDesktopBuildTarget(env)
const runnerLabel = resolveDesktopRetentionRunner(env)
const windows = target === 'win-x64'
const platform = windows ? 'win32' : 'darwin'
const settings = loadDesktopPackageEnvironment(platform, env, appRoot, { unsigned: true })
@@ -66,7 +84,7 @@ export async function retainDesktopCi(env: NodeJS.ProcessEnv, appRoot = resolve(
names.push(`${base}.${windows ? 'exe' : 'zip'}.blockmap`, desktopBuildRecordFilename(target), desktopUpdateMetadataFilename(version, platform, source.channel))
}
const retained = await retainDesktopRelease(desktopReleasesRoot(env), source, names.map(name => join(artifacts, name)))
if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `directory=${retained}\n`)
if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT, `directory=${retained}\nrunner=${runnerLabel}\nrunner-name=${source.runnerName}\nattempt=${source.attempt}\n`)
const nextStep = desktopPublishQualificationError(qualification)
?? `Publish separately with package_run_id=${env.GITHUB_RUN_ID} and package_run_attempt=${env.GITHUB_RUN_ATTEMPT}`
if (env.GITHUB_STEP_SUMMARY) await appendFile(env.GITHUB_STEP_SUMMARY,
@@ -75,5 +93,7 @@ export async function retainDesktopCi(env: NodeJS.ProcessEnv, appRoot = resolve(
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
await retainDesktopCi(process.env)
if (process.argv[2] === '--check-runner' && process.argv.length === 3) resolveDesktopRetentionRunner(process.env)
else if (process.argv.length === 2) await retainDesktopCi(process.env)
else throw new Error('Usage: retain-desktop-ci.ts [--check-runner]')
}
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
desktopBuildRecordFilename,
desktopWebsiteInstallerUrl,
desktopUpdateMetadataFilename,
resolveDesktopAutoUpdateConfig,
resolveDesktopAutoUpdateEnvironment,
@@ -120,6 +121,13 @@ describe('desktop auto-update environment', () => {
})
})
it.each([
['mac-arm64', 'dsh-latest-macos-arm64.dmg'],
['mac-x64', 'dsh-latest-macos-x64.dmg'],
['win-x64', 'dsh-latest-windows-x64.exe'],
] as const)('uses the production origin for website target %s', (target, filename) => {
expect(desktopWebsiteInstallerUrl(target)).toBe(`https://download.deepseek.com/desktop/${filename}`)
})
it.each([['darwin', 'arm64', 'mac-arm64', 'stable-mac.yml'], ['darwin', 'x64', 'mac-x64', 'stable-mac.yml'], ['win32', 'x64', 'win-x64', 'stable.yml']] as const)
('routes stable metadata and binaries separately for %s %s', (platform, arch, target, filename) => {
@@ -9,7 +9,7 @@ import { retainDesktopRelease, verifyRetainedDesktopRelease } from '../scripts/d
function fixture() {
const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), status: 'completed', conclusion: 'success',
event: 'workflow_dispatch', path: '.github/workflows/macos-package.yml', repository: { full_name: 'owner/repo' } }
const jobs = [{ name: 'package', runner_name: 'mini', conclusion: 'success' }]
const jobs = [{ name: 'package', run_attempt: 2, runner_name: 'mini', conclusion: 'success' }]
const routes = { mini: { label: 'dsh-mini', target: 'mac-arm64' } }
const calls: string[] = []
const api = (path: string, paginate?: boolean) => {
@@ -39,6 +39,7 @@ it('routes a Windows package through its own configured machine target', () => {
it('selects an explicit old attempt without consulting the latest attempt', () => {
const f = fixture()
f.run.run_attempt = 1
f.jobs[0]!.run_attempt = 1
selectDesktopPackage('owner/repo', { package_run_id: '42', package_run_attempt: '1' }, f.routes, f.api)
expect(f.calls).not.toContain('repos/owner/repo/actions/runs/42')
expect(f.calls).toContain('repos/owner/repo/actions/runs/42/attempts/1')
@@ -47,8 +48,8 @@ it('selects an explicit old attempt without consulting the latest attempt', () =
it.each(['failed', 'cancelled', 'running', 'workflow', 'repository', 'attempt', 'run', 'job', 'ambiguous', 'route', 'label'])(
'rejects %s evidence without falling back to a different attempt', (kind) => {
const f = fixture()
if (kind === 'failed') f.run.conclusion = 'failure'
if (kind === 'cancelled') f.run.conclusion = 'cancelled'
if (kind === 'failed') { f.run.conclusion = 'failure'; f.jobs[0]!.conclusion = 'failure' }
if (kind === 'cancelled') { f.run.conclusion = 'cancelled'; f.jobs[0]!.conclusion = 'cancelled' }
if (kind === 'running') f.run.status = 'in_progress'
if (kind === 'workflow') f.run.path = '.github/workflows/ci.yml'
if (kind === 'repository') f.run.repository.full_name = 'other/repo'
@@ -135,3 +136,24 @@ it('routes both Mac architectures to one machine without authorizing an unlisted
expect(() => selectDesktopPackage('owner/repo', { package_run_id: '42' }, { mini: { label: 'dsh-mini', target } }, f.api)).toThrow()
}
})
it.each([false, true])('keeps original build after archival retry with reused job listed: %s', (includesReused) => {
const f = fixture()
const selected = selectDesktopPackage('owner/repo', { package_run_id: '42' }, f.routes, (path) => {
if (path.endsWith('/42')) return { run_attempt: 3 }
if (path.endsWith('/attempts/3')) return { ...f.run, run_attempt: 3 }
if (path.endsWith('/attempts/3/jobs?per_page=100')) return [{ jobs: [{ name: 'upload-artifact', run_attempt: 3, runner_name: 'mini', conclusion: 'success' }, ...(includesReused ? f.jobs : [])] }]
if (path.includes('filter=all')) return [{ jobs: [{ ...f.jobs[0], run_attempt: 2 }] }]
if (path.endsWith('/attempts/2')) return { ...f.run, conclusion: 'failure' }
return [{ jobs: f.jobs }]
})
expect(selected.run.run_attempt).toBe(2)
expect(selected.runnerName).toBe('mini')
})
it('accepts a successful package when only archival failed', () => {
const f = fixture()
f.run.conclusion = 'failure'
f.jobs.push({ name: 'upload-artifact', run_attempt: 3, runner_name: 'mini', conclusion: 'failure' })
expect(selectDesktopPackage('owner/repo', { package_run_id: '42' }, f.routes, f.api).run.run_attempt).toBe(2)
})
@@ -44,3 +44,15 @@ it('omits malformed provider receipt fields and never copies raw errors into COS
expect(failure).not.toHaveProperty('httpStatus')
expect(JSON.stringify(failure)).not.toContain('fixture-secret')
})
it('prints structured archival failure through the real CLI', () => {
const result = spawnSync(process.execPath, ['--import', 'tsx/esm',
fileURLToPath(new URL('../scripts/archive-desktop-ci.ts', import.meta.url))], {
encoding: 'utf8', timeout: 30_000, env: { ...process.env, RUNNER_NAME: '', DESKTOP_PACKAGE_RUNNER: '' },
})
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(result.status).toBe(1)
expect(JSON.parse(result.stderr)).toEqual({ phase: 'artifact archival', code: 'validation',
message: 'desktop archival: wrong original machine' })
})
@@ -39,6 +39,7 @@ it.each(['mac-arm64', 'win-x64'] as const)('preflights a complete retained %s bu
}))
const env = {
DSH_PACKAGING_CONFIG_DIR: configRoot, DSH_PACKAGING_PRESET: 'test',
DESKTOP_PUBLISH_RUNNERS: JSON.stringify({ 'fixture-runner': { label: 'dsh-fixture', target: [target] } }),
DSH_DESKTOP_TARGET_PLATFORM: target === 'win-x64' ? 'win32' : 'darwin', DSH_DESKTOP_TARGET_ARCH: target === 'win-x64' ? 'x64' : 'arm64',
PACKAGE_SOURCE_REF: 'master', PACKAGE_SOURCE_SHA: 'b'.repeat(40), PACKAGE_VERSION: '1.0.0', PACKAGE_SIGNING: 'signed', PACKAGE_SKIP_NOTARIZATION: 'false',
GITHUB_RUN_ID: '10', GITHUB_RUN_ATTEMPT: '2', GITHUB_REPOSITORY: 'owner/repo', GITHUB_SHA: commit, RUNNER_NAME: 'fixture-runner',
@@ -52,7 +53,7 @@ it.each(['mac-arm64', 'win-x64'] as const)('preflights a complete retained %s bu
expect(prepared.plan.version).toBe('1.0.0')
expect(prepared.plan.artifacts.every(file => file.path.startsWith(retained))).toBe(true)
expect(signatureChecks).toBe(1)
const summary = await desktopPublicationSummary(prepared.manifest.source, prepared.plan, 'c'.repeat(64))
const summary = await desktopPublicationSummary(prepared.manifest.source, prepared.plan, 'c'.repeat(64), false)
await expect(summary).toMatchFileSnapshot(`./expected/publication-${target}.md`)
const feed = prepared.plan.artifacts.find(file => file.channelMetadata)!
expect(summary).toContain(createHash('sha256').update(feed.contents!).digest('hex'))
@@ -21,7 +21,7 @@ const plan: DesktopUploadPlan = {
}
it('shows production destinations and tag after approval with upload-byte fingerprints', async () => {
const summary = await desktopPublicationSummary(source, plan, 'c'.repeat(64))
const summary = await desktopPublicationSummary(source, plan, 'c'.repeat(64), false)
await expect(summary).toMatchFileSnapshot('./expected/publication-production.md')
expect(summary).toContain('/stable/deepseek-harness-1.0.0-win-x64.exe')
expect(summary).toContain('https&#58;//download.example.com/dsh-desk/feeds/win-x64/stable.yml')
@@ -32,7 +32,7 @@ it('shows production destinations and tag after approval with upload-byte finger
})
it('escapes runner display text without adding Markdown rows or HTML elements', async () => {
const summary = await desktopPublicationSummary({ ...source, runnerName: 'runner|\n<script>`&"__win__![x](https://example.com/x.png)' }, plan, 'c'.repeat(64))
const summary = await desktopPublicationSummary({ ...source, runnerName: 'runner|\n<script>`&"__win__![x](https://example.com/x.png)' }, plan, 'c'.repeat(64), false)
expect(summary).toContain('runner&#124;&#10;&#60;script&#62;&#96;&#38;&#34;')
expect(summary).not.toContain('<script>')
expect(summary).toContain('&#95;&#95;win&#95;&#95;&#33;&#91;x&#93;&#40;https&#58;//example.com/x.png&#41;')
@@ -42,5 +42,15 @@ it('fails instead of rendering success when an upload file cannot be read', asyn
await expect(desktopPublicationSummary(source, { ...plan,
artifacts: [{ path: '/missing-desktop-summary-artifact/installer.exe', filename: 'installer.exe',
key: 'installer.exe', contentType: 'application/octet-stream', channelMetadata: false }],
}, 'c'.repeat(64))).rejects.toThrow()
}, 'c'.repeat(64), false)).rejects.toThrow()
})
it('shows the fixed website replacement before production approval only when selected', async () => {
const summary = await desktopPublicationSummary(source, plan, 'c'.repeat(64), true)
await expect(summary).toMatchFileSnapshot('./expected/publication-production-website.md')
expect(summary).toContain('download.deepseek.com/desktop/dsh-latest-windows-x64.exe')
expect(summary).toContain('无防降级保护')
expect(await desktopPublicationSummary(source, plan, 'c'.repeat(64), false)).not.toContain('官网固定安装包')
expect(await desktopPublicationSummary({ ...source, preset: 'test', testReleaseId: 'a'.repeat(32) },
{ ...plan, environment: 'test' }, 'c'.repeat(64), true)).not.toContain('官网固定安装包')
})
@@ -6,12 +6,13 @@ import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts'
import { answer, cosError, startCosLoopback } from './cos-loopback.ts'
import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts'
it('uses overwrite prevention, streams verified bytes, and hashes remote readback through the SDK', async () => {
it.each([true, false])('preserves download headers and verified bytes with overwrite prevention %s', async (forbidOverwrite) => {
const objects = new Map<string, Buffer>()
const server = await startCosLoopback((request, response) => {
if (request.path.includes('versioning')) { answer(response, 403, cosError('AccessDenied')); return }
if (request.method === 'PUT') {
expect(request.headers['x-cos-forbid-overwrite']).toBe('true')
expect(request.headers['x-cos-forbid-overwrite']).toBe(forbidOverwrite ? 'true' : undefined)
expect(request.headers['content-disposition']).toBe('attachment; filename="file.exe"')
objects.set(request.path, request.body)
answer(response)
} else {
@@ -21,7 +22,7 @@ it('uses overwrite prevention, streams verified bytes, and hashes remote readbac
}
})
try {
const artifact = { path: '', filename: 'file.exe', key: 'bin/file.exe', contents: 'fixture bytes', contentType: 'application/octet-stream', channelMetadata: false }
const artifact = { path: '', filename: 'file.exe', key: 'bin/file.exe', contents: 'fixture bytes', contentType: 'application/octet-stream', channelMetadata: !forbidOverwrite, contentDisposition: 'attachment; filename="file.exe"' }
const plan: DesktopUploadPlan = {
environment: 'test', target: 'win-x64', version: '1.0.0', bucket: 'fixture-1250000000', publicUrl: 'https://example.com/',
secretIdEnvName: 'ID', secretKeyEnvName: 'KEY', artifacts: [artifact],
@@ -31,10 +32,10 @@ it('uses overwrite prevention, streams verified bytes, and hashes remote readbac
server.redirect(client)
return client
})
expect(await transport.read(artifact.key, false)).toBeNull()
expect(await transport.read(artifact.key, !forbidOverwrite)).toBeNull()
const digest = await desktopArtifactDigest(artifact)
await transport.put(artifact, digest, true)
expect(await transport.read(artifact.key, false)).toEqual(digest)
await transport.put(artifact, digest, forbidOverwrite)
expect(await transport.read(artifact.key, !forbidOverwrite)).toEqual({ ...digest, ...(!forbidOverwrite ? { contents: 'fixture bytes' } : {}) })
await expect(transport.read('elsewhere/file.exe', false)).rejects.toThrow(/outside/u)
expect(server.requests.filter(request => request.method === 'PUT')).toHaveLength(1)
expect(server.requests.map(request => request.method)).toEqual(['GET', 'PUT', 'GET'])
@@ -43,3 +43,8 @@ it('runs the local preflight before dependency installation in both self-hosted
expect(section.indexOf('node apps/desktop/scripts/preflight-desktop-publish-local.mjs')).toBeLessThan(section.indexOf('pnpm install --frozen-lockfile'))
}
})
it('rejects missing website preparation outputs before reading local configuration', async () => {
await expect(preflightDesktopPublishLocal({ DSH_PACKAGING_CONFIG_DIR: tmpdir(), DESKTOP_PUBLISH_ROUTE: '' }))
.rejects.toThrow('selected package must identify a positive run ID and attempt')
})
@@ -46,7 +46,6 @@ it('fails closed when a publishing route or its unique label is missing', () =>
expect(() => resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, duplicates)).toThrow(/unique runner label/u)
})
it('keeps the packaged source separate from the workflow commit', () => {
const f = fixture()
f.source.commit = 'b'.repeat(40)
@@ -88,3 +87,21 @@ it('matches Intel artifacts to the Intel workflow on a machine serving both arch
f.source.target = 'mac-arm64'
expect(() => resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, routes)).toThrow(/does not match/u)
})
it('accepts a successful package when the attempt failed during archival', () => {
const f = fixture()
f.run.conclusion = 'failure'
f.jobs.push({ ...f.jobs[0]!, name: 'upload-artifact', conclusion: 'failure' })
expect(resolveDesktopPublishRoute('owner/repo', f.run, { source: f.source }, f.jobs, f.routes))
.toMatchObject({ runId: '42', attempt: '2' })
})
it.each([null, undefined])('routes from successful package evidence without a run conclusion (%s)', (conclusion) => {
const f = fixture()
const run = { ...f.run, conclusion }
expect(resolveDesktopPublishRoute('owner/repo', run, { source: f.source }, f.jobs, f.routes))
.toMatchObject({ runId: '42', attempt: '2', runnerLabel: 'dsh-mini' })
f.jobs[0]!.conclusion = 'failure'
expect(() => resolveDesktopPublishRoute('owner/repo', run, { source: f.source }, f.jobs, f.routes))
.toThrow('single successful packaging runner')
})
@@ -0,0 +1,123 @@
import { describe, expect, it, vi } from 'vitest'
import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts'
import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '../scripts/desktop-purge-recovery.ts'
const config = { zoneId: 'zone-test', publicUrl: 'https://download.deepseek.com/desktop/test.dmg', secretId: 'secret-id', secretKey: 'secret-key' }
const submittedAt = '2026-10-30T00:00:00.000Z'
function fixture() {
let clock = Date.parse(submittedAt)
const records: DesktopPurgeRecord[] = []
const options: DesktopPurgeRecoveryOptions = {
intervalMs: 10, waitMs: 20, allowResubmit: false, now: () => clock,
sleep: async (ms) => { clock += ms }, save: async (record) => { records.push(record) },
}
const task = (status: string, jobId = 'job-1') => ({ TotalCount: 1, Tasks: [{ JobId: jobId, Status: status,
Target: config.publicUrl, Type: 'purge_url', CreateTime: submittedAt }] })
const client = { CreatePurgeTask: vi.fn(async () => ({ JobId: 'job-1' })), DescribePurgeTasks: vi.fn(async () => task('success')) }
return { options, records, task, client }
}
describe('website purge recovery', () => {
it('saves intent before submitting once and confirms completion', async () => {
const f = fixture()
f.client.CreatePurgeTask.mockImplementation(async () => {
expect(f.records.at(-1)?.status).toBe('pending')
return { JobId: 'job-1' }
})
expect((await recoverDesktopPurge(config, undefined, f.client, f.options)).status).toBe('success')
expect(f.client.CreatePurgeTask).toHaveBeenCalledOnce()
expect(f.records.map(r => r.status)).toEqual(['pending', 'processing', 'success'])
})
it('queries an existing successful task without submitting again', async () => {
const f = fixture()
const previous: DesktopPurgeRecord = { ...config, submittedAt, jobId: 'job-1', status: 'unknown' }
expect((await recoverDesktopPurge(config, previous, f.client, f.options)).status).toBe('success')
expect(f.client.CreatePurgeTask).not.toHaveBeenCalled()
})
it('reconciles a lost submission response using exact history', async () => {
const f = fixture()
f.client.CreatePurgeTask.mockRejectedValue(new Error(config.secretKey))
expect((await recoverDesktopPurge(config, undefined, f.client, f.options)).jobId).toBe('job-1')
expect(f.client.CreatePurgeTask).toHaveBeenCalledOnce()
expect(f.client.DescribePurgeTasks.mock.calls[0]).toBeDefined()
expect(JSON.stringify(f.records)).not.toContain(config.secretKey)
})
it('queries once more after uncertainty and preserves an unknown result', async () => {
const f = fixture()
f.client.DescribePurgeTasks.mockRejectedValue(new Error(config.secretKey))
const result = await recoverDesktopPurge(config, undefined, f.client, f.options)
expect(result.status).toBe('unknown')
expect(f.client.DescribePurgeTasks).toHaveBeenCalledTimes(2)
expect(f.client.CreatePurgeTask).toHaveBeenCalledOnce()
expect(JSON.stringify(f.records)).not.toContain(config.secretKey)
})
it('does not claim deadline expiry when the extra query resumes processing', async () => {
const f = fixture()
f.client.DescribePurgeTasks.mockRejectedValueOnce(new Error('transient')).mockResolvedValue(f.task('processing'))
const result = await recoverDesktopPurge(config, undefined, f.client, f.options)
expect(result.diagnostic).toBe('task still processing after an additional query')
expect(result.status).toBe('unknown')
expect(f.client.DescribePurgeTasks).toHaveBeenCalledTimes(2)
expect(f.options.now()).toBeLessThan(Date.parse(submittedAt) + f.options.waitMs)
})
it('bounds processing observations and makes one final query', async () => {
const f = fixture()
f.client.DescribePurgeTasks.mockResolvedValue(f.task('processing'))
expect((await recoverDesktopPurge(config, undefined, f.client, f.options)).status).toBe('unknown')
expect(f.client.DescribePurgeTasks).toHaveBeenCalledTimes(4)
})
it.each(['failed', 'timeout', 'canceled'])('fails for confirmed %s without retrying submission', async (status) => {
const f = fixture()
f.client.DescribePurgeTasks.mockResolvedValue(f.task(status))
await expect(recoverDesktopPurge(config, undefined, f.client, f.options)).rejects.toThrow(status)
expect(f.client.CreatePurgeTask).toHaveBeenCalledOnce()
expect(f.records.at(-1)?.status).toBe(status)
const saved = f.records.at(-1)!
await recoverDesktopPurge(config, saved, f.client, f.options).catch((error: unknown) => {
expect(desktopPublicationFailure(error, 'purge')).toMatchObject({ code: `purge-${status}` })
})
})
it('allows one replacement only after a manual rerun confirms previous failure', async () => {
const f = fixture()
f.client.DescribePurgeTasks.mockResolvedValueOnce(f.task('failed')).mockResolvedValue(f.task('success'))
const previous: DesktopPurgeRecord = { zoneId: config.zoneId, publicUrl: config.publicUrl, submittedAt, jobId: 'old-job', status: 'failed' }
f.client.DescribePurgeTasks.mockReset().mockResolvedValueOnce(f.task('failed', 'old-job')).mockResolvedValue(f.task('success'))
expect((await recoverDesktopPurge(config, previous, f.client, { ...f.options, allowResubmit: true })).status).toBe('success')
expect(f.client.CreatePurgeTask).toHaveBeenCalledOnce()
})
it('does not submit when intent persistence fails', async () => {
const f = fixture()
await expect(recoverDesktopPurge(config, undefined, f.client, { ...f.options,
save: async () => { throw new Error('disk full') },
})).rejects.toThrow('disk full')
expect(f.client.CreatePurgeTask).not.toHaveBeenCalled()
})
it('reports a possibly absent submission without resubmitting it', async () => {
const f = fixture()
f.client.CreatePurgeTask.mockRejectedValue(new Error('lost response'))
f.client.DescribePurgeTasks.mockResolvedValue({ TotalCount: 0, Tasks: [] })
const result = await recoverDesktopPurge(config, undefined, f.client, f.options)
expect(result.status).toBe('unknown')
expect(result.diagnostic).toContain('may not have been submitted')
expect(result.jobId).toBeUndefined()
expect(f.client.CreatePurgeTask).toHaveBeenCalledOnce()
expect(f.client.DescribePurgeTasks).toHaveBeenCalledTimes(2)
})
it('does not mistake multiple matching tasks for confirmed completion', async () => {
const f = fixture()
f.client.CreatePurgeTask.mockRejectedValue(new Error('lost response'))
f.client.DescribePurgeTasks.mockResolvedValue({ TotalCount: 2, Tasks: [...f.task('success').Tasks, ...f.task('success', 'job-2').Tasks] })
expect((await recoverDesktopPurge(config, undefined, f.client, f.options)).status).toBe('unknown')
expect(f.client.CreatePurgeTask).toHaveBeenCalledOnce()
})
})
@@ -135,6 +135,7 @@ describe('desktop upload plan', () => {
expect(request.method).toBe('PUT')
expect(request.path).toBe(`/${artifact.key}`)
expect(request.body).toEqual(await readFile(artifact.path))
expect(request.headers['content-disposition']).toBe(`attachment; filename="deepseek-harness-1.2.3-${target}.${target === 'win-x64' ? 'exe' : 'dmg'}"`)
expect(JSON.parse(await readFile(join(directory, 'result.json'), 'utf8'))).toMatchObject({
success: true, confirmedPuts: 1, publicReadback: 'not-performed',
})
@@ -157,6 +158,7 @@ describe('desktop upload plan', () => {
expect(plan.artifacts[0]).toMatchObject({
path: join(paths.artifactsRoot, 'deepseek-harness-1.2.3-alpha.4-win-x64.exe'),
key: 'desktop/dsh-latest-windows-x64.exe', channelMetadata: false,
contentDisposition: 'attachment; filename="deepseek-harness-1.2.3-alpha.4-win-x64.exe"',
})
})
@@ -192,3 +192,13 @@ describe('release upload audit with the real COS SDK and an isolated loopback or
expect(await readFile(join(first, 'result.json'), 'utf8')).toBe(before)
})
})
it('sends the fixed-download save filename through the real COS SDK', async () => {
const f = await fixture('production')
const contentDisposition = 'attachment; filename="deepseek-harness-1.2.3-rc.5-win-x64.exe"'
const plan = { ...f.plan, artifacts: [{ ...f.plan.artifacts[0]!, key: 'desktop/dsh-latest-windows-x64.exe', contentDisposition }] }
const { cos, loopback } = await transport()
await uploadDesktopRelease(plan, cos, f.records)
expect(loopback.requests).toHaveLength(1)
expect(loopback.requests[0]!.headers['content-disposition']).toBe(contentDisposition)
})
@@ -0,0 +1,120 @@
import { createHash } from 'node:crypto'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
import { createDesktopCos } from '../scripts/desktop-cos.ts'
import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts'
import { answer, cosError, startCosLoopback } from './cos-loopback.ts'
import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '../scripts/desktop-website-installer.ts'
import type { DesktopRetainedManifest } from '../scripts/desktop-release-store.ts'
import type { DesktopPublishRoute } from '../scripts/desktop-publish-route.ts'
const roots: string[] = []
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) })
async function fixture(target: DesktopPublishRoute['target'] = 'mac-arm64') {
const directory = await mkdtemp(join(tmpdir(), 'website-installer-'))
roots.push(directory)
const bytes = Buffer.from('final installer bytes')
const route: DesktopPublishRoute = { runId: '12', attempt: '1', commit: 'a'.repeat(40), sourceRef: 'master',
channel: 'nightly', runnerName: 'mini', runnerLabel: 'dsh-mini', target, preset: 'production' }
const filename = `deepseek-harness-0.2.1-rc.5-${target}.${target === 'win-x64' ? 'exe' : 'dmg'}`
await writeFile(join(directory, filename), bytes)
const manifest: DesktopRetainedManifest = { schemaVersion: 1, source: {
runId: route.runId, attempt: route.attempt, commit: route.commit, sourceRef: route.sourceRef,
channel: route.channel, runnerName: route.runnerName, target: route.target, preset: route.preset, repository: 'owner/repo', workflowCommit: route.commit, productVersion: '0.2.1', version: '0.2.1-rc.5',
testReleaseId: null, qualification: target === 'win-x64' ? 'signed' : 'notarized',
}, files: [{ name: filename, size: bytes.length, sha512: createHash('sha512').update(bytes).digest('base64') }] }
return { directory, bytes, route, manifest }
}
it.each(['mac-arm64', 'mac-x64', 'win-x64'] as const)('accepts only the final %s installer without any update files or current checkout version', async (target) => {
const f = await fixture(target)
f.manifest = { ...f.manifest, files: [...f.manifest.files,
{ name: 'missing-update.zip', size: 1, sha512: 'unused' }, { name: 'nightly.yml', size: 1, sha512: 'unused' }] }
const installer = await prepareWebsiteInstaller(f.directory, f.manifest, f.route, 'owner/repo', 'production-123')
try {
expect(installer.plan.version).toBe('0.2.1-rc.5')
expect(installer.plan.artifacts).toHaveLength(1)
expect(installer.digest).toEqual({ size: f.bytes.length, sha512: f.manifest.files[0]!.sha512 })
} finally { await installer.handle.close() }
})
it('rejects changed installer bytes', async () => {
const f = await fixture()
await writeFile(join(f.directory, f.manifest.files[0]!.name), 'wrong bytes')
await expect(prepareWebsiteInstaller(f.directory, f.manifest, f.route, 'owner/repo', 'production-123')).rejects.toThrow('differs from build manifest')
})
it.each(['preset', 'qualification', 'attempt', 'commit', 'target', 'repository', 'runId', 'runnerName', 'sourceRef', 'channel'] as const)('rejects mismatched %s even when file bytes match', async (field) => {
const f = await fixture()
const source = { ...f.manifest.source }
if (field === 'preset') source.preset = 'test'
if (field === 'qualification') source.qualification = 'unnotarized'
if (field === 'attempt') source.attempt = '2'
if (field === 'commit') source.commit = 'b'.repeat(40)
if (field === 'target') source.target = 'mac-x64'
if (field === 'repository') source.repository = 'other/repo'
if (field === 'runId') source.runId = '13'
if (field === 'runnerName') source.runnerName = 'other'
if (field === 'sourceRef') source.sourceRef = 'dsh-v0.2.1'
if (field === 'channel') source.channel = 'stable'
await expect(prepareWebsiteInstaller(f.directory, { ...f.manifest, source }, f.route, 'owner/repo', 'production-123')).rejects.toThrow('identity or production qualification mismatch')
})
it.each(['absent', 'missing-header', 'wrong-header', 'header-not-retained'] as const)('reconciles %s after audit failure without repeating the fixed-object PUT', async (initial) => {
const f = await fixture()
const installer = await prepareWebsiteInstaller(f.directory, f.manifest, f.route, 'owner/repo', 'production-123')
let stored: Buffer | undefined = initial === 'absent' ? undefined : f.bytes
const disposition = `attachment; filename="${f.manifest.files[0]!.name}"`
let storedDisposition = initial === 'wrong-header' ? 'attachment; filename="old.dmg"' : undefined
const server = await startCosLoopback((request, response) => {
if (request.method === 'PUT') {
expect(request.headers['x-cos-forbid-overwrite']).toBeUndefined()
expect(request.headers['content-md5']).toBe(createHash('md5').update(f.bytes).digest('base64'))
expect(request.headers['content-disposition']).toBe(disposition)
storedDisposition = disposition
stored = request.body
answer(response)
} else if (stored) answer(response, 200, stored, storedDisposition && initial !== 'header-not-retained' ? { 'content-disposition': storedDisposition } : {})
else answer(response, 404, cosError('NoSuchKey'))
})
try {
const credentials = { secretId: 'fixture-id', secretKey: 'fixture-key' }
const createClient: typeof createDesktopCos = (credentials) => {
const client = createDesktopCos(credentials)
server.redirect(client)
return client
}
const transport = desktopPublishCos(installer.plan, credentials, createClient)
await expect(uploadWebsiteInstaller(installer, credentials, transport, async (event) => {
if (event === 'uploaded') throw new Error('audit unavailable')
}, { createClient })).rejects.toThrow(initial === 'header-not-retained' ? 'remote download filename unconfirmed' : 'audit unavailable')
if (initial === 'header-not-retained') {
expect(server.requests.filter(request => request.method === 'PUT')).toHaveLength(1)
return
}
const events: string[] = []
expect(await uploadWebsiteInstaller(installer, credentials, transport, async (event) => { events.push(event) }, { createClient })).toBe('present')
expect(events).toEqual(['uploaded'])
expect(stored).toEqual(f.bytes)
expect(server.requests.filter(request => request.method === 'PUT')).toHaveLength(1)
} finally { await installer.handle.close(); await server.close() }
})
it('does not replace changed bytes when recovering an already completed publication', async () => {
const f = await fixture()
const installer = await prepareWebsiteInstaller(f.directory, f.manifest, f.route, 'owner/repo', 'production-123')
try {
await expect(uploadWebsiteInstaller(installer, { secretId: 'fixture-id', secretKey: 'fixture-key' },
{ read: async () => ({ size: 1, sha512: 'different' }) }, async () => { throw new Error('unexpected write intent') },
{ createClient: () => { throw new Error('unexpected PUT') }, previouslyUploaded: true })).rejects.toThrow('recorded upload no longer matches')
} finally { await installer.handle.close() }
})
it('rejects an unsupported source ref even when route and manifest agree', async () => {
const f = await fixture()
const route = { ...f.route, sourceRef: 'feature/unapproved' }
const manifest = { ...f.manifest, source: { ...f.manifest.source, sourceRef: route.sourceRef } }
await expect(prepareWebsiteInstaller(f.directory, manifest, route, 'owner/repo', 'production-123')).rejects.toThrow('identity or production qualification mismatch')
})
@@ -0,0 +1,42 @@
## 发布前确认
核对以下信息后,点击 **Review deployments**,选择 <code>desktop-production</code> 并点击 **Approve and deploy**;信息有误请点击 **Reject**。
| 项目 | 发布信息 |
| --- | --- |
| 发布环境 | <code>production</code> |
| 版本号 | <code>1.0.0</code> |
| 升级通道 | <code>stable</code> |
| 平台 | <code>win-x64</code> |
| 下载地址预览 | <a href="https&#58;//download.example.com/dsh-desk/bin/win-x64/stable/deepseek-harness-1.0.0-win-x64.exe">https&#58;//download.example.com/dsh-desk/bin/win-x64/stable/deepseek-harness-1.0.0-win-x64.exe</a><br>发布后的目标地址,审批前不保证可下载。 |
| 升级 YAML | <a href="https&#58;//download.example.com/dsh-desk/feeds/win-x64/stable.yml">https&#58;//download.example.com/dsh-desk/feeds/win-x64/stable.yml</a><br>本次发布将更新此文件;审批前可能不存在或仍指向旧版本。 |
| 打包来源 | <a href="https&#58;//github.com/owner/repo/actions/runs/20/attempts/3">查看打包运行 #20 · 第 3 次尝试</a><br>源码:<code>dsh-v1.0.0 @ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</code><br>打包机器:<code>windows-publisher</code> |
| 签名与公证 | EXE 签名校验通过 |
| 官网固定安装包 | <a href="https&#58;//download.deepseek.com/desktop/dsh-latest-windows-x64.exe">https&#58;//download.deepseek.com/desktop/dsh-latest-windows-x64.exe</a><br>替换为版本 <code>1.0.0</code>;已有安装包会被替换,无防降级保护;官网上传与刷新在后续 job 中执行,可能需另行审批。 |
| Git tag | <code>desktop-v1.0.0</code> |
### 批准后将执行
1. 重新校验产物与发布目标;若与审批摘要不一致则停止。
2. 上传缺少的文件,跳过内容一致的已有文件;发现内容冲突则停止。
3. 更新上述升级 YAML,并保存发布记录。
4. 为实际打包提交创建上述 Git tag;若 tag 创建失败,记录“已发布,待补 tag”。
<details>
<summary>技术详情与文件清单</summary>
COS 存储桶:<code>production-1234567890</code>
审批摘要 SHA-256:<code>cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc</code>
共 2 个文件;大小及 SHA-256 对应实际上传字节,包括更新后的 YAML 内容。
| 文件 | 大小 | SHA-256 |
| --- | --- | --- |
| <a href="https&#58;//download.example.com/dsh-desk/bin/win-x64/stable/deepseek-harness-1.0.0-win-x64.exe">deepseek-harness-1.0.0-win-x64.exe</a> | 15 字节 | <code>e34210a6de4f653edf588301431c3d69a633638cbf587345cc50a7fed9f38f4c</code> |
| <a href="https&#58;//download.example.com/dsh-desk/feeds/win-x64/stable.yml">stable.yml</a> | 15 字节 | <code>8850e6075dda0080c526269a4de29848c32c2a65e3d81f4a64ed8ce53d4b47c1</code> |
</details>
若仓库为公开仓库,此摘要中的下载路径及 test 发布的 release ID 也会公开。随机前缀不能替代访问鉴权。
@@ -0,0 +1,8 @@
# ⚠ 官网资源已上传,缓存刷新结果未确认
刷新已提交,执行结果未确认
https://download.deepseek.com/desktop/dsh-latest-macos-arm64.dmg
Task: job-1
Observed: 2026-10-30T00:00:00.000Z
task query failed; check EdgeOne history and DescribePurgeTasks permission
@@ -0,0 +1,8 @@
# ⚠ 官网资源已上传,缓存刷新结果未确认
刷新提交未确认,可能尚未提交
https://download.deepseek.com/desktop/dsh-latest-macos-arm64.dmg
Task: unknown
Observed: 2026-10-30T00:00:00.000Z
task query failed; check EdgeOne history and DescribePurgeTasks permission
@@ -0,0 +1,122 @@
import { createHash } from 'node:crypto'
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import * as desktopCos from '../scripts/desktop-cos.ts'
import { answer, cosError, startCosLoopback } from './cos-loopback.ts'
import { teo } from 'tencentcloud-sdk-nodejs-teo'
import { publishWebsiteCi, websiteApproval } from '../scripts/publish-website-ci.ts'
vi.mock('node:timers/promises', () => ({ setTimeout: async () => {} }))
afterEach(() => vi.restoreAllMocks())
it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'put', 'uploaded', 'metadata', 'metadata-retry', 'stable', 'approval'] as const)('preserves publication recovery for %s', async (scenario) => {
const root = await mkdtemp(join(tmpdir(), 'website-ci-'))
try {
const config = join(root, 'packaging')
const records = join(root, 'upload-records', 'website-99-mac-arm64')
await mkdir(join(config, 'publishing'), { recursive: true })
await mkdir(join(root, 'releases', '12', '1'), { recursive: true })
await mkdir(records, { recursive: true })
const credentialsFile = join(root, 'credentials.json')
await writeFile(credentialsFile, JSON.stringify({ secretId: 'fixture-id', secretKey: 'fixture-key' }))
await writeFile(join(config, 'publishing', 'production.json'), JSON.stringify({
bucket: 'production-123', origin: 'https://download.deepseek.com', credentialsFile,
githubApp: { clientId: 'app', privateKeyFile: join(root, 'app.pem') },
}))
const route = { runId: '12', attempt: '1', commit: 'a'.repeat(40), sourceRef: 'master', channel: scenario === 'stable' ? 'stable' : 'nightly',
runnerName: 'mini', runnerLabel: 'dsh-mini', target: 'mac-arm64', preset: 'production' }
const manifest = { schemaVersion: 1, source: { repository: 'owner/repo', runId: '12', attempt: '1', commit: route.commit,
workflowCommit: route.commit, sourceRef: 'master', channel: route.channel, runnerName: 'mini', target: 'mac-arm64',
preset: 'production', productVersion: '1.0.0', version: '1.0.0', testReleaseId: null, qualification: 'notarized' },
files: [{ name: 'deepseek-harness-1.0.0-mac-arm64.dmg', size: 1, sha512: createHash('sha512').update('x').digest('base64') }] }
await writeFile(join(root, 'releases', '12', '1', 'manifest.json'), JSON.stringify(manifest))
const approval = websiteApproval(manifest, 'production-123')
await writeFile(join(records, 'state.json'), JSON.stringify({ approval, upload: 'uploaded' }))
if (scenario === 'metadata') await writeFile(join(records, 'state.json'), JSON.stringify({ approval, upload: 'uploaded', purgeAttempt: '1', purge: { zoneId: 'zone-fixture', publicUrl: 'https://download.deepseek.com/desktop/dsh-latest-macos-arm64.dmg', submittedAt: '2026-10-30T00:00:00.000Z', jobId: 'old-job', status: 'success' } }))
if (scenario === 'metadata-retry') await writeFile(join(records, 'state.json'), JSON.stringify({ approval, upload: 'upload-intent', uploadConfirmed: true }))
const env = { RUNNER_NAME: 'mini', GITHUB_REPOSITORY: 'owner/repo', GITHUB_RUN_ID: '99',
GITHUB_RUN_ATTEMPT: '1', DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify(route),
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-fixture', GITHUB_OUTPUT: join(root, 'output') }
if (scenario === 'upload' || scenario === 'put' || scenario === 'uploaded' || scenario === 'metadata' || scenario === 'metadata-retry' || scenario === 'stable' || scenario === 'approval') {
await writeFile(join(root, 'releases', '12', '1', manifest.files[0]!.name), 'x')
if (scenario === 'upload' || scenario === 'put') await rm(join(records, 'state.json'))
let stored = scenario !== 'put'
let headerStored = scenario !== 'metadata'
const server = await startCosLoopback(async (request, response) => {
if (request.method === 'PUT') {
expect(request.body.toString()).toBe('x')
if (scenario === 'metadata') {
const state: unknown = JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))
expect(state).toMatchObject({ upload: 'upload-intent', uploadConfirmed: true })
expect(state).not.toHaveProperty('purge')
expect(state).not.toHaveProperty('purgeAttempt')
}
expect(request.headers['content-disposition']).toBe(`attachment; filename="${manifest.files[0]!.name}"`)
stored = true
headerStored = true
answer(response)
return
}
if (!stored) answer(response, 404, cosError('NoSuchKey'))
else answer(response, 200, scenario === 'metadata-retry' ? 'y' : 'x', headerStored ? { 'content-disposition': `attachment; filename="${manifest.files[0]!.name}"` } : {})
})
const original = desktopCos.createDesktopCos
vi.spyOn(desktopCos, 'createDesktopCos').mockImplementation((credentials) => {
const client = original(credentials)
server.redirect(client)
return client
})
try {
if (scenario === 'metadata-retry') {
await expect(publishWebsiteCi('upload', env)).rejects.toThrow('recorded upload no longer matches')
expect(server.requests.map(request => request.method)).toEqual(['GET'])
} else if (scenario === 'approval') {
await expect(publishWebsiteCi('upload', { ...env, DESKTOP_WEBSITE_APPROVAL: 'changed' })).rejects.toThrow('approved build or destination changed')
expect(server.requests).toHaveLength(0)
} else {
const output = vi.spyOn(process.stdout, 'write').mockReturnValue(true)
await publishWebsiteCi('upload', env)
expect(output.mock.calls.map(call => String(call[0])).join('')).toContain((scenario === 'put' || scenario === 'metadata')
? 'Website installer uploaded:' : 'identical remote bytes and download filename confirmed; skipped')
if (scenario === 'upload') expect(server.requests[0]!.path).toBe('/desktop/dsh-latest-macos-arm64.dmg')
expect(server.requests.map(request => request.method)).toEqual((scenario === 'put' || scenario === 'metadata') ? ['GET', 'PUT', 'GET'] : ['GET'])
expect(JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))).toMatchObject({ approval, upload: 'uploaded' })
expect(await readFile(env.GITHUB_OUTPUT, 'utf8')).toContain(`record=${records}`)
if (scenario === 'metadata') {
const submit = vi.spyOn(teo.v20220901.Client.prototype, 'CreatePurgeTask').mockResolvedValue({ JobId: 'new-job' })
vi.spyOn(teo.v20220901.Client.prototype, 'DescribePurgeTasks').mockRejectedValue(new Error('unavailable'))
await publishWebsiteCi('purge', env)
expect(submit).toHaveBeenCalledOnce()
expect(JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))).toMatchObject({ purge: { jobId: 'new-job' } })
}
}
} finally { await server.close() }
return
}
const submit = vi.spyOn(teo.v20220901.Client.prototype, 'CreatePurgeTask').mockResolvedValue({ JobId: 'job-1' })
if (scenario === 'incomplete' || scenario === 'wrong-journal') {
await writeFile(join(records, 'state.json'), JSON.stringify({ approval: scenario === 'wrong-journal' ? 'other' : approval, upload: 'upload-intent' }))
const query = vi.spyOn(teo.v20220901.Client.prototype, 'DescribePurgeTasks')
await expect(publishWebsiteCi('purge', env)).rejects.toThrow(scenario === 'incomplete' ? 'upload completion is not confirmed' : 'journal belongs to another approved build')
expect(submit).not.toHaveBeenCalled()
expect(query).not.toHaveBeenCalled()
return
}
const query = vi.spyOn(teo.v20220901.Client.prototype, 'DescribePurgeTasks').mockRejectedValue(new Error('fixture-key'))
if (scenario === 'unconfirmed') submit.mockRejectedValue(new Error('lost response'))
const output = vi.spyOn(process.stdout, 'write').mockReturnValue(true)
vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-10-30T00:00:00.000Z'))
const summary = join(root, 'summary.md')
await publishWebsiteCi('purge', { RUNNER_NAME: 'mini', GITHUB_REPOSITORY: 'owner/repo', GITHUB_RUN_ID: '99',
GITHUB_RUN_ATTEMPT: '1', DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify(route),
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-fixture', GITHUB_STEP_SUMMARY: summary })
expect(submit).toHaveBeenCalledOnce()
expect(query).toHaveBeenCalledTimes(2)
expect(output.mock.calls.map(call => String(call[0])).join('')).toContain('::warning title=官网缓存刷新结果未确认::')
expect(JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))).toMatchObject({ upload: 'uploaded', purge: { status: 'unknown' } })
await expect(await readFile(summary, 'utf8')).toMatchFileSnapshot(`./expected/website-purge-${scenario}.md`)
expect(await readFile(summary, 'utf8')).not.toContain('fixture-key')
} finally { await rm(root, { recursive: true, force: true }) }
})
+17 -2
View File
@@ -2,8 +2,9 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
import { desktopReleasesRoot, retainDesktopCi } from '../scripts/retain-desktop-ci.ts'
import { desktopReleasesRoot, retainDesktopCi, resolveDesktopRetentionRunner } from '../scripts/retain-desktop-ci.ts'
import { verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts'
import { verifyDesktopArchive } from '../scripts/archive-desktop-ci.ts'
import { prepareDesktopPublication } from '../scripts/publish-desktop-ci.ts'
const roots: string[] = []
@@ -32,9 +33,15 @@ it.each([
DSH_DESKTOP_TARGET_ARCH: target === 'mac-arm64' ? 'arm64' : 'x64', PACKAGE_SOURCE_REF: 'master', PACKAGE_SOURCE_SHA: 'b'.repeat(40), PACKAGE_VERSION: '1.0.0',
PACKAGE_SIGNING: qualification === 'unsigned' ? 'unsigned' : 'signed', PACKAGE_SKIP_NOTARIZATION: qualification === 'unnotarized' ? 'true' : 'false', GITHUB_RUN_ID: '123', GITHUB_RUN_ATTEMPT: '2',
GITHUB_STEP_SUMMARY: join(root, 'summary.md'),
DESKTOP_PUBLISH_RUNNERS: JSON.stringify({ dedicated: { label: 'dsh-dedicated', target: [target] } }),
GITHUB_REPOSITORY: 'owner/repository', GITHUB_SHA: 'b'.repeat(40), RUNNER_NAME: 'dedicated',
}
await retainDesktopCi(env, appRoot)
const directory = await retainDesktopCi(env, appRoot)
const archiveEnv = { ...env, GITHUB_RUN_ATTEMPT: '3', DESKTOP_RETAINED_DIRECTORY: directory,
DESKTOP_PACKAGE_ATTEMPT: '2', DESKTOP_PACKAGE_RUNNER: env.RUNNER_NAME }
await verifyDesktopArchive(archiveEnv)
await expect(verifyDesktopArchive({ ...archiveEnv, RUNNER_NAME: 'other' })).rejects.toThrow('wrong original machine')
await expect(verifyDesktopArchive({ ...archiveEnv, DESKTOP_PACKAGE_ATTEMPT: '3' })).rejects.toThrow('original build')
const manifest = await verifyRetainedDesktopRelease(desktopReleasesRoot(env), '123', '2')
expect(manifest.files.map(file => file.name)).toEqual(names)
expect(manifest.source).toMatchObject({ target, qualification })
@@ -49,3 +56,11 @@ it.each([
await expect(summary).toMatchFileSnapshot(`./expected/retained-${qualification}.md`)
} else expect(summary).toContain('Publish separately with package_run_id=123 and package_run_attempt=2')
})
it('rejects missing or ambiguous archival routing before packaging starts', () => {
const env = { RUNNER_NAME: 'dedicated', DSH_DESKTOP_TARGET_PLATFORM: 'darwin', DSH_DESKTOP_TARGET_ARCH: 'arm64' }
expect(() => resolveDesktopRetentionRunner(env)).toThrow('DESKTOP_PUBLISH_RUNNERS is required')
expect(() => resolveDesktopRetentionRunner({ ...env, DESKTOP_PUBLISH_RUNNERS: JSON.stringify({
dedicated: { label: 'dsh-shared', target: 'mac-arm64' }, other: { label: 'dsh-shared', target: 'mac-arm64' },
}) })).toThrow('unique artifact routing label')
})
@@ -7,7 +7,9 @@
{
"stage": "more-hover",
"details": true,
"tooltips": []
"tooltips": [
"Session actions for Use the read tool twice"
]
},
{
"stage": "archive-before-dwell",
-2
View File
@@ -260,8 +260,6 @@ describe('Open in Session menus', () => {
await expect.poll(alignment).toBeLessThanOrEqual(1)
// Browser layout changes are real; no observer callback or rectangle is mocked.
await rootElement.evaluate((node) => { node.style.transform = 'translate(-80px, 20px)' })
await expect.poll(alignment).toBeLessThanOrEqual(1)
await parent.evaluate((node) => { node.style.marginTop = '24px' })
await expect.poll(alignment).toBeLessThanOrEqual(1)
const before = await child.boundingBox()
@@ -587,6 +587,8 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo
await observe('details')
await row.getByRole('button', { name: /^Session actions for / }).hover()
await hoverPage.clock.runFor(1000)
// The shared menu button's tooltip appears once its bubble has been measured.
await tooltip.filter({ hasText: /^Session actions for / }).waitFor()
expect(await card.count()).toBe(1)
await observe('more-hover')
+2 -2
View File
@@ -129,8 +129,8 @@
en: 07d595ce1f1a5184
zh: 07d595ce1f1a5184
/tool-schema-catalog/deepseek-ai-dsh-tool-fs/apply-patch:
en: 882f2fa9fac236d6
zh: e8320796a5cb038f
en: 50b4939c9a1d96ac
zh: e733cc1156e2853c
/tool-schema-catalog/deepseek-ai-dsh-tool-fs/edit:
en: 5b6a252adde51af6
zh: 7aa172a5d8b9cbd2
+2 -2
View File
@@ -1045,7 +1045,7 @@ Standalone view/create/unique literal replace/line insert tool over the filesyst
### `apply_patch`
Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.
Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.
```json
{
@@ -1053,7 +1053,7 @@ Create, update, delete, or move UTF-8 text files with one Codex-style patch; pre
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
}
},
"required": [
+2 -2
View File
@@ -1051,7 +1051,7 @@ pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费
### `apply_patch`
用一个 Codex 风格补丁新增、更新、删除或移动 UTF-8 文本文件;变更跨越多个文件或分离区域时,优先于多次 edit 调用。
用一个补丁新增、更新、删除或移动 UTF-8 文本文件;变更跨越多个文件或分离区域时,优先于多次 edit 调用。
```json
{
@@ -1059,7 +1059,7 @@ pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
}
},
"required": [
+1 -1
View File
@@ -82,7 +82,7 @@ function styleInjectionModule(
* Everything else under @deepseek-ai/* is either a module-table entry
* (external) or a leak the purity gate rejects.
*/
export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/
export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/
/**
* Vendored framework libraries: rescoped into @deepseek-ai, so the gate below
@@ -330,7 +330,7 @@ export const zh = {
'tool.title.bash': '运行命令',
'tool.title.write': '写入',
'tool.title.edit': '编辑',
'tool.title.applyPatch': '应用补丁',
'tool.title.applyPatch': '编辑',
'tool.title.code': '代码',
'tool.title.generic': '工具调用',
'tool.title.inspect': '查询 Cordis 环境',
@@ -722,7 +722,7 @@ export const en = {
'tool.title.bash': 'Bash',
'tool.title.write': 'Write',
'tool.title.edit': 'Edit',
'tool.title.applyPatch': 'Apply patch',
'tool.title.applyPatch': 'Edit',
'tool.title.code': 'Code',
'tool.title.generic': 'Tool call',
'tool.title.inspect': 'Query Cordis environment',
@@ -1113,7 +1113,7 @@ export const ja = {
'tool.title.bash': 'Bash',
'tool.title.write': '書き込み',
'tool.title.edit': '編集',
'tool.title.applyPatch': 'パッチを適用',
'tool.title.applyPatch': '編集',
'tool.title.code': 'コード',
'tool.title.generic': 'ツール呼び出し',
'tool.title.inspect': 'Cordis 環境を照会',
@@ -1497,7 +1497,7 @@ export const es = {
'tool.title.bash': 'golpe',
'tool.title.write': 'escribir',
'tool.title.edit': 'Editar',
'tool.title.applyPatch': 'Aplicar parche',
'tool.title.applyPatch': 'Editar',
'tool.title.code': 'Código',
'tool.title.generic': 'llamada de herramienta',
'tool.title.inspect': 'Consulta entorno Cordis',
@@ -1888,7 +1888,7 @@ export const fr = {
'tool.title.bash': 'Frapper',
'tool.title.write': 'Écrire',
'tool.title.edit': 'Modifier',
'tool.title.applyPatch': 'Appliquer le patch',
'tool.title.applyPatch': 'Modifier',
'tool.title.code': 'Coder',
'tool.title.generic': "Appel d'outil",
'tool.title.inspect': "Interroger l'environnement Cordis",
@@ -2279,7 +2279,7 @@ export const de = {
'tool.title.bash': 'Bash',
'tool.title.write': 'Schreiben',
'tool.title.edit': 'Bearbeiten',
'tool.title.applyPatch': 'Patch anwenden',
'tool.title.applyPatch': 'Bearbeiten',
'tool.title.code': 'Code',
'tool.title.generic': 'Werkzeugaufruf',
'tool.title.inspect': 'Fragen Sie die Cordis-Umgebung ab',
@@ -2670,7 +2670,7 @@ export const ru = {
'tool.title.bash': 'Баш',
'tool.title.write': 'Написать',
'tool.title.edit': 'Редактировать',
'tool.title.applyPatch': 'Применить патч',
'tool.title.applyPatch': 'Редактировать',
'tool.title.code': 'Код',
'tool.title.generic': 'Вызов инструмента',
'tool.title.inspect': 'Запрос среды Cordis',
@@ -3061,7 +3061,7 @@ export const pt = {
'tool.title.bash': 'Bash',
'tool.title.write': 'Escreva',
'tool.title.edit': 'Editar',
'tool.title.applyPatch': 'Aplicar patch',
'tool.title.applyPatch': 'Editar',
'tool.title.code': 'Código',
'tool.title.generic': 'Chamada de ferramenta',
'tool.title.inspect': 'Consultar ambiente Cordis',
+4 -4
View File
@@ -15,14 +15,14 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-tool/use-this-package:
en: 2419beff9bcd8139
zh: 5aafe9b168e571a5
en: 813b9f2e3438eed2
zh: ac7616097d45991a
/deepseek-ai-dsh-client-ui-tool/use-this-package/registering-a-business-tool-view:
en: e458aff61e634190
zh: 650e417f450b3edf
/deepseek-ai-dsh-client-ui-tool/use-this-package/built-in-views:
en: 153498fd97c03524
zh: 210731b119db29a5
en: 4f141937224a0390
zh: b3b8a22df4936742
/deepseek-ai-dsh-client-ui-tool/understand-the-implementation:
en: 00bc7b0c84edc603
zh: 1cfcf5b435248a91
+2 -2
View File
@@ -33,7 +33,7 @@ Before dispatch, a named model call appears as one non-expandable row with its t
`subagent` and `subagent_fork` creation rows stream the first line of `description`, retaining it during execution, after creation, and when expanded. After preparation, calls without a description fall back to the first nonempty `prompt` line; missing arguments leave only the tool title. Both tools and `list_subagent_models` use the existing Users icon; `subagent_fork` uses the distinct title “Fork subagent”. Creation receipts show the started state, the full `description` as the agent task description, the recorded agent Session id, and complete task instructions. Current receipts read `kind: activation` and `subagentId` from result metadata; only historical results without metadata use text parsing. Malformed metadata keeps the generic result view. Synchronous agent responses remain in the result body; errors retain their failure summary.
File and URL toolview Slots obtain `useContextMenu` directly and supply bound `fileContextMenuProps` or `urlContextMenuProps` to `ToolRow`. File registrations inject a gesture-time path resolver for the originating Session’s working directory, falling back to its workspace root. `ToolCallTree` supplies an explicit file adapter to its plain `GenericToolCard` fallback, including nested calls. No Markdown provider is required. Mouse and keyboard gestures retain the captured path, line, URL, and Session without expanding the row or opening the file.
File and URL toolview Slots obtain `useContextMenu` directly and supply bound `fileContextMenuProps` or `urlContextMenuProps` to `ToolRow`; file rows also supply `fileTargetContextMenuProps` for each per-file patch link. File registrations inject a gesture-time path resolver for the originating Session’s working directory, falling back to its workspace root. `ToolCallTree` supplies an explicit file adapter to its plain `GenericToolCard` fallback, including nested calls. No Markdown provider is required. Mouse and keyboard gestures retain the captured path, line, URL, and Session without expanding the row or opening the file.
### Registering a business tool view
@@ -55,7 +55,7 @@ Every registered view receives the explicit `preparing`, `start`, and `result` p
File-tool rows prefer a complete `file_path`; other generic rows, including search and unregistered tools, prefer a non-empty `description` before their variant-specific argument fallback. Read `args` during rendering or view construction: a preparing reader grows in place, and only previously observed answer changes trigger subsequent block publication.
This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, `apply_patch`, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and PTC dispatch presentations. The `apply_patch` row shares the write/edit component: it shows its title without a single-file summary, derives no diff while running, shows the applied hunks from settled `meta.diffs`, and a result whose metadata is marked stopped renders as an error with its failure text beside the known diffs. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running atomic rows share one left-to-right highlight across their titles, separators, summaries, and suffixes, while settled rows stay static. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in PTC dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable. Valid explicit background `bash`/`pwsh` calls use the terminal Start presentation; a successful launch acknowledgement retains the command and cwd in a static command-only card without output or execution status. Launch failures retain generic arguments and errors, while background `terminal_send` stays generic. Inspect preserves the original arguments and acknowledgement; later job output is not attached to this card ([decision](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md)). Expanded terminal commands and background inputs wrap to the available width while preserving authored line breaks and selectable text; terminal output keeps its column-preserving layout. Only horizontal overflow adds a named keyboard focus target. Inspect is available when provided. The acknowledgement does not report the job's exit status. A native or PTC dispatch failure carrying `AUTO_REVIEW_DENIED` shows the Auto review verdict in its collapsed row and one normalized not-executed reason when expanded; a missing or whitespace-only reason uses localized fallback text. `ui-skill` demonstrates a business-owned registration for `skill`.
This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, `apply_patch`, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and PTC dispatch presentations. The `apply_patch` row shares the write/edit component and the Edit title. Once `input` completes, its summary lists the files that `dsh-fs-patch` `parsePatch` reads from the patch, with a move as `source → destination`; a malformed patch has no summary. A lone added or updated file is one openable path. After a successful result, several files or a move render one link per added, updated, or moved-to file, while move sources and deleted files stay plain text; running and failed rows show the plain list. The row derives no diff while running, shows the applied hunks from settled `meta.diffs`, and a result whose metadata is marked stopped renders as an error with its failure text beside the known diffs. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running atomic rows share one left-to-right highlight across their titles, separators, summaries, and suffixes, while settled rows stay static. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in PTC dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable. Valid explicit background `bash`/`pwsh` calls use the terminal Start presentation; a successful launch acknowledgement retains the command and cwd in a static command-only card without output or execution status. Launch failures retain generic arguments and errors, while background `terminal_send` stays generic. Inspect preserves the original arguments and acknowledgement; later job output is not attached to this card ([decision](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md)). Expanded terminal commands and background inputs wrap to the available width while preserving authored line breaks and selectable text; terminal output keeps its column-preserving layout. Only horizontal overflow adds a named keyboard focus target. Inspect is available when provided. The acknowledgement does not report the job's exit status. A native or PTC dispatch failure carrying `AUTO_REVIEW_DENIED` shows the Auto review verdict in its collapsed row and one normalized not-executed reason when expanded; a missing or whitespace-only reason uses localized fallback text. `ui-skill` demonstrates a business-owned registration for `skill`.
Question rows pair answers with questions by id, using the tool result or the `userQuestions` projection for late replies. An answerable call has a button to reopen its panel. Once a late reply is in the agent Inbox, the row shows its submitted answers; “View answers” expands its read-only transcript while admission is pending. A settled call with answers opens the panel read-only. Closed calls without answers and invalid records offer no button. Cancelled and interrupted rows show their verdict without inventing answers. If no panel provider accepts the button action, it expands the row. Unsupported or ambiguous input falls back to flattened Tool text.
+2 -2
View File
@@ -33,7 +33,7 @@ kind: "package-reference"
`subagent` 与 `subagent_fork` 的创建行逐步显示 `description` 的首行,执行中、创建完成后和展开时均保留。准备阶段结束后,缺少描述的调用回退到 `prompt` 的首个非空行;参数不可用时仅显示工具标题。两个工具与 `list_subagent_models` 均使用现有的 Users 图标;`subagent_fork` 使用独立标题“派生子智能体”。创建回执显示已启动状态、作为智能体任务描述的完整 `description`、记录的智能体 Session id,以及完整任务指令。当前回执从结果 metadata 读取 `kind: activation` 与 `subagentId`;仅缺少 metadata 的历史结果使用文本解析。metadata 无效时保留通用结果视图。同步返回的 agent 回复仍放在结果正文中;失败时保留错误摘要。
文件和 URL 工具视图 Slot 直接获取 `useContextMenu`,向 `ToolRow` 提供已绑定的 `fileContextMenuProps` 或 `urlContextMenuProps`。文件注册注入在触发时读取原始 Session 工作目录的路径解析器,工作目录缺失时使用工作区根目录。`ToolCallTree` 向普通 `GenericToolCard` fallback 显式提供文件适配函数,包含嵌套调用。无需 Markdown Provider。鼠标和键盘手势保留捕获的路径、行号、URL 与 Session,不会展开工具行或打开文件。
文件和 URL 工具视图 Slot 直接获取 `useContextMenu`,向 `ToolRow` 提供已绑定的 `fileContextMenuProps` 或 `urlContextMenuProps`;文件行还为补丁的每个文件链接提供 `fileTargetContextMenuProps`。文件注册注入在触发时读取原始 Session 工作目录的路径解析器,工作目录缺失时使用工作区根目录。`ToolCallTree` 向普通 `GenericToolCard` fallback 显式提供文件适配函数,包含嵌套调用。无需 Markdown Provider。鼠标和键盘手势保留捕获的路径、行号、URL 与 Session,不会展开工具行或打开文件。
### 注册业务工具视图
@@ -55,7 +55,7 @@ owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、`phase` 判别字
文件工具行优先使用完整的 `file_path`;其他通用行(包括搜索和未注册的工具)优先使用非空 `description`,再回退到各自类别的参数摘要。应在渲染或构造视图时读取 `args`:准备态读器原地增长,后续仅在已观察答案变化时重新发布块。
本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、`apply_patch`、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 PTC dispatch 的内置展示。`apply_patch` 行复用 write/edit 组件:显示工具标题而不给出单文件摘要,运行态不推导 diff,完成态展示 `meta.diffs` 中已应用的 hunk,元数据标记为停止的结果按错误呈现,并在已知 diff 旁保留失败文本。结构化卡片直接从第一方原始 event 字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中的原子工具行以同一道高光从左到右扫过标题、分隔符、摘要与后缀;已完成行保持静态。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 PTC dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开。合法的主动后台 `bash`/`pwsh` 调用使用 terminal Start 展示;成功启动回执后,静态仅命令卡片保留 command 和 cwd,不显示输出或执行状态。启动失败保留通用参数与错误展示,后台 `terminal_send` 仍为 generic。Inspect 保留原始参数及回执,后续 job 输出不接回此卡片([决定](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.zh.md))。展开的终端命令与后台输入按可用宽度自动折行,保留原有换行和可选文本;终端输出保持按列对齐的排版。仅横向溢出时添加具名的键盘聚焦目标。提供 Inspect 时也可使用。回执不表示后台任务的退出状态。带有 `AUTO_REVIEW_DENIED` 的原生或 PTC dispatch 失败会在折叠行显示 Auto review 裁决,展开时显示一行归一化后的“未执行”原因;原因缺失或只有空白时使用本地化 fallback 文案。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。
本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、`apply_patch`、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 PTC dispatch 的内置展示。`apply_patch` 行复用 write/edit 组件与“编辑”标题。`input` 完整到达后,摘要列出 `dsh-fs-patch` 的 `parsePatch` 从补丁读出的文件,移动显示为 `源 → 目标`;格式不合法的补丁没有摘要。单个新增或修改的文件是一个可打开路径。成功结果中有多个文件或含移动时,每个新增、修改或移动目标文件各是一个链接,移动源与被删除文件保持纯文本;运行中与失败的行显示纯文本列表。该行运行态不推导 diff,完成态展示 `meta.diffs` 中已应用的 hunk,元数据标记为停止的结果按错误呈现,并在已知 diff 旁保留失败文本。结构化卡片直接从第一方原始 event 字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中的原子工具行以同一道高光从左到右扫过标题、分隔符、摘要与后缀;已完成行保持静态。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 PTC dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开。合法的主动后台 `bash`/`pwsh` 调用使用 terminal Start 展示;成功启动回执后,静态仅命令卡片保留 command 和 cwd,不显示输出或执行状态。启动失败保留通用参数与错误展示,后台 `terminal_send` 仍为 generic。Inspect 保留原始参数及回执,后续 job 输出不接回此卡片([决定](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.zh.md))。展开的终端命令与后台输入按可用宽度自动折行,保留原有换行和可选文本;终端输出保持按列对齐的排版。仅横向溢出时添加具名的键盘聚焦目标。提供 Inspect 时也可使用。回执不表示后台任务的退出状态。带有 `AUTO_REVIEW_DENIED` 的原生或 PTC dispatch 失败会在折叠行显示 Auto review 裁决,展开时显示一行归一化后的“未执行”原因;原因缺失或只有空白时使用本地化 fallback 文案。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。
问题行按 id 配对问题与答案;答案来自工具结果,迟到回答则来自 `userQuestions` 投影。可回答的调用提供按钮以重新打开面板。迟到回复进入 agent Inbox 后,问题行显示已提交的答案;等待准入期间,「查看回答」展开只读的行内记录。带有答案的已结算调用则以只读方式打开面板。没有答案的已关闭调用和无效记录不提供按钮。已取消和已中断的行显示裁决,不虚构答案。若面板提供方不接受按钮操作,点击会展开该行。不受支持或含糊的输入回退为压平的工具文本。
+1
View File
@@ -48,6 +48,7 @@
},
"devDependencies": {
"@deepseek-ai/dsh-spill-policy": "workspace:*",
"@deepseek-ai/dsh-fs-patch": "workspace:*",
"@deepseek-ai/dsh-agent": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
@@ -108,6 +108,36 @@
font-size: var(--dsh-content-font-size-secondary, 13px);
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
color: inherit;
}
/* Multi-file patch summary: one ellipsized line of plain separators and per-file
links. Shrink-to-fit like .fileLink, so the row's empty remainder stays the
expand/collapse toggle. */
.fileLinks {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--dsh-content-font-size-secondary, 13px);
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
}
/* One file inside .fileLinks: .fileLink's affordance without its own box, so the
line keeps flowing and the parent's ellipsis applies. */
.fileTargetLink {
display: inline;
margin: 0;
padding: 0;
border: none;
background: none;
font: inherit;
color: inherit;
}
/* Path link affordance shared by the whole-summary and per-file links. */
.fileLink,
.fileTargetLink {
text-decoration: underline dotted;
text-decoration-color: currentColor;
text-decoration-thickness: 1px;
@@ -115,6 +145,23 @@
cursor: pointer;
}
/* Pointing at one file of a multi-file patch brightens that file alone: the
row keeps its idle color and diff totals instead of the whole-row hover. */
@media (hover: hover) {
.row:has(.fileTargetLink:hover) {
color: var(--dsw-alias-label-tertiary);
}
.row:not([aria-expanded='true']):has(.fileTargetLink:hover) .diffAdded,
.row:not([aria-expanded='true']):has(.fileTargetLink:hover) .diffRemoved {
color: inherit;
}
.fileTargetLink:hover {
color: var(--dsw-alias-label-secondary);
}
}
/* Error row's collapsed summary: the failure's first line in the error color. */
.errorSummary {
color: var(--dsw-alias-state-error-primary);
@@ -1,4 +1,4 @@
import { memo, useCallback, useMemo, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react'
import { Fragment, memo, useCallback, useMemo, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react'
import clsx from 'clsx'
import {
CodeBlock, DiffBlock, DisclosureRow, IconInspectOutlineRegular, ReadBlock, SearchBlock,
@@ -21,7 +21,7 @@ import {
} from '../models/primitive-labels.ts'
import type { AskQuestionCardModel } from '../models/ask-question-card-model.ts'
import {
formatToolBody, type ToolRowState, type ToolRowVariant,
FILE_TARGET_MOVE, FILE_TARGET_SEPARATOR, formatToolBody, type ToolRowFileTarget, type ToolRowState, type ToolRowVariant,
} from '../models/tool-call-model.ts'
import type { WebCardModelProps } from '../models/web-card-model.ts'
import { AskQuestionCard } from './AskQuestionCard.tsx'
@@ -93,6 +93,14 @@ export interface ToolRowProps {
onOpenFile?: ((path: string, options?: OpenFileOptions) => void) | undefined
/** File gesture bindings supplied by the owning tool view. */
fileContextMenuProps?: ContextMenuTriggerProps | undefined
/**
* Files a patch row names. When onOpenFile is set, the row state is `ok`, and
* at least one target has a `filePath`, each such target renders as its own
* link in place of the summary text; otherwise the row shows `summary`.
*/
fileTargets?: readonly ToolRowFileTarget[] | undefined
/** File gesture bindings for one `fileTargets` path, supplied by the owning tool view. */
fileTargetContextMenuProps?: ((path: string) => ContextMenuTriggerProps) | undefined
/** URL gesture bindings supplied by the owning tool view. */
urlContextMenuProps?: ContextMenuTriggerProps | undefined
/** Safe http(s) URL from tool args; when set, the summary renders as a link that opens it in a new tab. */
@@ -109,6 +117,35 @@ function stopLinkClick(event: MouseEvent<HTMLAnchorElement>): void {
event.stopPropagation()
}
interface FileTargetLinkProps {
label: string
path: string
onOpenFile: (path: string, options?: OpenFileOptions) => void
contextMenuProps: ContextMenuTriggerProps | undefined
onLinkKeyDown: (event: KeyboardEvent<HTMLElement>) => void
}
/** One openable file inside a multi-file summary; activating it never toggles the row. */
function FileTargetLink({ label, path, onOpenFile, contextMenuProps, onLinkKeyDown }: FileTargetLinkProps) {
return (
<button
type="button"
className={css.fileTargetLink}
{...contextMenuProps}
onClick={(event) => {
event.stopPropagation()
onOpenFile(path)
}}
onKeyDown={(event) => {
onLinkKeyDown(event)
contextMenuProps?.onKeyDown?.(event)
}}
>
{label}
</button>
)
}
/** Visually hidden run-state label for color-only running and settlement cues. */
function stateStatus(state: ToolRowState, t: TranslateNS<'conversation'>): string | null {
switch (state) {
@@ -151,7 +188,7 @@ export const ToolRow = memo(function ToolRow({
filePath,
filePathLine,
onOpenFile,
fileContextMenuProps, urlContextMenuProps,
fileContextMenuProps, urlContextMenuProps, fileTargets, fileTargetContextMenuProps,
href,
inspect,
useDisclosure,
@@ -203,6 +240,10 @@ export const ToolRow = memo(function ToolRow({
}
: undefined, [filePath, filePathLine, onOpenFile, settledWithCue])
const linkHref = settledWithCue ? undefined : href
// Per-file links appear only on a successful result: TextShimmer accepts no
// buttons, so running and failed rows keep the plain summary text.
const openTarget = state === 'ok' && fileTargets?.some(target => target.filePath !== undefined) === true
? onOpenFile : undefined
// Keep Enter/Space on the focused path or URL link from bubbling to the row's
// keydown handler, which would preventDefault() the key and toggle expand
// instead of activating the link — the keyboard analogue of the click
@@ -219,7 +260,25 @@ export const ToolRow = memo(function ToolRow({
its title shows no trailing dot). */
<>
<span className={css.sep} data-shimmer-decoration aria-hidden />
{exitLabel === null && openFile !== undefined ? (
{exitLabel === null && fileTargets !== undefined && openTarget !== undefined ? (
<span className={css.fileLinks}>
{fileTargets.map((target, index) => (
<Fragment key={target.id}>
{index > 0 && FILE_TARGET_SEPARATOR}
{target.from !== undefined && `${target.from}${FILE_TARGET_MOVE}`}
{target.filePath === undefined ? target.label : (
<FileTargetLink
label={target.label}
path={target.filePath}
onOpenFile={openTarget}
contextMenuProps={fileTargetContextMenuProps?.(target.filePath)}
onLinkKeyDown={summaryLinkKeyDown}
/>
)}
</Fragment>
))}
</span>
) : exitLabel === null && openFile !== undefined ? (
<button
type="button"
className={css.fileLink}
@@ -268,7 +327,8 @@ export const ToolRow = memo(function ToolRow({
</TextShimmer>
)}
</>
), [summaryLinkKeyDown, fileContextMenuProps, urlContextMenuProps, linkHref, openFile, state, suffix, totals, summaryText, exitLabel])
), [summaryLinkKeyDown, fileContextMenuProps, urlContextMenuProps, linkHref, openFile, fileTargets, openTarget,
fileTargetContextMenuProps, state, suffix, totals, summaryText, exitLabel])
const expandedContent = useMemo(() => open ? (
<div className={clsx(css.bodyWrap, detailsBody !== null && css.detailsBodyWrap)}>
{askQuestionBody !== null
@@ -7,6 +7,7 @@
*/
import type { ToolArgs, ToolCallBlock, ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client'
import type { LocaleKeysOf } from '@deepseek-ai/dsh-client-ui-slots'
import { parsePatch, PatchParseError, type PatchOperation } from '@deepseek-ai/dsh-fs-patch'
import { abbreviateHomePath, isAbsoluteWorkspacePath, relativizeToCwd } from '@deepseek-ai/dsh-util-workspace-path'
import { recordedAbsolutePath } from './recorded-path.ts'
@@ -144,6 +145,24 @@ export function toolTitleKey(toolName: string): ToolTitleKey {
return TOOL_TITLE_KEYS[toolName] ?? VARIANT_TITLE_KEYS[classifyTool(toolName)]
}
/** Text between two files a patch row names. */
export const FILE_TARGET_SEPARATOR = ', '
/** Text between a moved file's source and destination. */
export const FILE_TARGET_MOVE = ' → '
/** One file a patch row names, rendered as its own link when `filePath` is set. */
export interface ToolRowFileTarget {
/** One-based patch line of the file header; identifies the file operation within its call. */
readonly id: number
/** Display path of a moved file's source; the source no longer exists once the move completes. */
readonly from?: string | undefined
/** Display path of the file, or of a move's destination. */
readonly label: string
/** Path to open; absent for a deletion or while the row cannot open argument paths. */
readonly filePath: string | undefined
}
/** Everything ToolRow needs, derived once from the frozen slice. */
export interface ToolRowModel {
variant: ToolRowVariant
@@ -156,6 +175,11 @@ export interface ToolRowModel {
* stay unavailable until their result identifies the target.
*/
filePath: string | undefined
/**
* Per-file links for a patch naming several files or a move; undefined for
* every other row, which uses `filePath` for the whole summary.
*/
fileTargets: readonly ToolRowFileTarget[] | undefined
/** Original argument JSON retained for expansion-time body formatting. */
bodyRaw: string | null
/** Flattened result text ({@link resultText}); null while running or when the result carries no text. */
@@ -269,6 +293,47 @@ function argumentSummary(
return { summary: description === undefined ? '' : firstLine(description), filePath: undefined }
}
/** Summary material read from patch file headers; `targets` keep each file's raw openable path. */
interface PatchSummary {
summary: string
filePath: string | undefined
targets: readonly ToolRowFileTarget[]
}
/**
* Summary material for `apply_patch`: the files a complete `input` names, parsed
* by the same `parsePatch` the executor uses. A move reads `source → destination`,
* and only its destination is openable; a deletion is not. Only a lone added or
* updated file without a move sets `filePath`. Incomplete or malformed patch text
* yields an empty summary.
*/
function patchSummary(args: ToolArgs, cwd?: string, home?: string): PatchSummary {
const patch = args.complete('input') ? args.text('input') : undefined
let operations: PatchOperation[] = []
if (patch !== undefined) {
try {
operations = parsePatch(patch)
} catch (error) {
// PatchParseError: the executor rejects this patch before changing any file, so no file is named.
if (!(error instanceof PatchParseError)) throw error
}
}
const display = (path: string) => abbreviateHomePath(relativizeToCwd(path, cwd), home)
const targets = operations.map((operation): ToolRowFileTarget => {
const moveTo = operation.kind === 'update' ? operation.moveTo : undefined
return moveTo === undefined
? { id: operation.lineNumber, label: display(operation.path), filePath: operation.kind === 'delete' ? undefined : operation.path }
: { id: operation.lineNumber, from: display(operation.path), label: display(moveTo), filePath: moveTo }
})
const summary = targets.map(target => target.from === undefined ? target.label
: `${target.from}${FILE_TARGET_MOVE}${target.label}`).join(FILE_TARGET_SEPARATOR)
const only = operations.length === 1 ? operations[0] : undefined
return {
summary, targets,
filePath: only?.kind === 'add' || only?.kind === 'update' && only.moveTo === undefined ? only.path : undefined,
}
}
function deriveFilePath(variant: ToolRowVariant, argsRaw: string): string | undefined {
if (!FILE_PATH_VARIANTS.has(variant)) return undefined
const parsed = parseArgs(argsRaw)
@@ -312,18 +377,26 @@ export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: strin
// Result metadata marks a settled call that did not finish every requested effect.
const stopped = done && typeof block.meta === 'object' && block.meta !== null
&& !Array.isArray(block.meta) && (block.meta as Record<string, unknown>).stopped === true
const primary = argumentSummary(variant, block.args, cwd, home)
const patch = toolName === 'apply_patch' ? patchSummary(block.args, cwd, home) : undefined
const primary = patch ?? argumentSummary(variant, block.args, cwd, home)
const argumentPath = primary.filePath ?? (argsRaw === null ? undefined : deriveFilePath(variant, argsRaw))
const recordedPath = done ? recordedAbsolutePath(block.meta, 'path') : undefined
const canUseArgumentPath = argumentPath !== undefined
&& (isAbsoluteWorkspacePath(argumentPath) || done && !block.isError && block.parentCallId === undefined)
const usableArgumentPath = (path: string) => isAbsoluteWorkspacePath(path)
|| done && !block.isError && block.parentCallId === undefined
const canUseArgumentPath = argumentPath !== undefined && usableArgumentPath(argumentPath)
// A lone added or updated file keeps the whole-summary link; several files or a move link each file.
const fileTargets = patch !== undefined && (patch.targets.length > 1 || patch.targets.some(target => target.from !== undefined))
? patch.targets.map(target => target.filePath === undefined || usableArgumentPath(target.filePath) ? target
: { ...target, filePath: undefined })
: undefined
const filePath = argumentPath === undefined ? undefined
: recordedPath ?? (canUseArgumentPath ? argumentPath : undefined)
const state: ToolRowState = !done ? block.phase === 'preparing' ? 'preparing' : 'running'
: block.error?.code === 'interrupted' ? 'stopped'
: block.isError || stopped ? 'error' : 'ok'
// The argument view serves every stage; the raw text is the fallback when it carries nothing useful.
const base = toolName === 'apply_patch' ? '' : primary.summary !== '' || argsRaw === null ? primary.summary
// An incomplete patch keeps an empty summary instead of falling back to the raw patch text.
const base = toolName === 'apply_patch' || primary.summary !== '' || argsRaw === null ? primary.summary
: argsRaw === '' ? block.callId
: abbreviateHomePath(relativizeToCwd(deriveSummary(variant, argsRaw), cwd), home)
const summary = [titleKey === 'tool.title.generic' ? toolName : '', base].filter(Boolean).join(' · ')
@@ -338,6 +411,7 @@ export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: strin
titleKey,
summary,
filePath,
fileTargets,
bodyRaw,
output,
errorSummary,
@@ -58,6 +58,10 @@ export function FileMutationRow({
diff={diff}
state={model.state}
filePath={model.filePath}
fileTargets={model.fileTargets}
fileTargetContextMenuProps={target => getTriggerProps(() => ({
kind: 'file', value: { sessionId, path: resolveFilePath(target) },
}))}
onOpenFile={openFile}
inspect={inspect}
/>
@@ -257,7 +257,7 @@ describe('FileMutationRow diff card', () => {
expect(model.state).toBe('error')
expect(model.errorSummary).toBe('Patch stopped after 1 of 3 operations.')
const view = render(<FileMutationRow {...rowProps(block, 'apply_patch')} />)
expect(view.getByText('应用补丁')).toBeTruthy()
expect(view.getByText('编辑')).toBeTruthy()
toggleRow(view)
expect(view.container.querySelectorAll('[data-diff]').length).toBeGreaterThan(0)
expect(view.getByText('created')).toBeTruthy()
@@ -265,6 +265,70 @@ describe('FileMutationRow diff card', () => {
expect(view.container.textContent).toContain(output)
})
it('summarizes a complete patch by the files the executor parser reads', () => {
const patchRow = (input: string) => toolRowModel('apply_patch', settled({ call: { name: 'apply_patch', argsRaw: JSON.stringify({ input }) } }), '/w/app')
expect(patchRow('*** Begin Patch\n*** Update File: src/a.ts\n@@\n-old\n+new\n*** End Patch')).toMatchObject({
summary: 'src/a.ts', filePath: 'src/a.ts', fileTargets: undefined,
})
expect(patchRow([
'*** Begin Patch', '*** Add File: /w/app/docs/new.md', '+hello', '*** Update File: src/a.ts', '*** Move to: src/b.ts',
'@@', ' *** Delete File: context.txt', '-old', '+new', '*** Delete File: old.txt ', '*** End Patch',
].join('\n'))).toMatchObject({ summary: 'docs/new.md, src/a.ts → src/b.ts, old.txt', filePath: undefined, fileTargets: [
{ id: 2, label: 'docs/new.md', filePath: '/w/app/docs/new.md' },
{ id: 4, from: 'src/a.ts', label: 'src/b.ts', filePath: 'src/b.ts' },
{ id: 10, label: 'old.txt', filePath: undefined },
] })
expect(patchRow('*** Begin Patch\n*** Delete File: old.txt\n*** End Patch')).toMatchObject({ summary: 'old.txt', filePath: undefined, fileTargets: undefined })
expect(patchRow('*** Begin Patch\n*** Update File: a.ts\n*** Move to: b.ts\n@@\n-x\n+y\n*** End Patch')).toMatchObject({
summary: 'a.ts → b.ts', filePath: undefined, fileTargets: [{ id: 2, from: 'a.ts', label: 'b.ts', filePath: 'b.ts' }],
})
// Outside an update section the parser trims header lines, so these headers name files.
expect(patchRow('*** Begin Patch\n *** Update File: a.ts\n@@\n-old\n+new\n*** End Patch')).toMatchObject({ summary: 'a.ts', filePath: 'a.ts' })
expect(patchRow('*** Begin Patch\n*** Add File: a.md\n+x\n *** Update File: b.ts\n@@\n-old\n+new\n*** End Patch'))
.toMatchObject({ summary: 'a.md, b.ts' })
// A Move to after a hunk is hunk content the parser rejects, and so changes no file.
expect(patchRow('*** Begin Patch\n*** Update File: a.ts\n@@\n-old\n+new\n*** Move to: b.ts\n*** End Patch'))
.toMatchObject({ summary: '', filePath: undefined, fileTargets: undefined })
})
it('keeps only absolute patch paths openable before a successful result', () => {
const argsRaw = JSON.stringify({ input: '*** Begin Patch\n*** Add File: /w/app/a.md\n+a\n*** Update File: b.ts\n@@\n-x\n+y\n*** End Patch' })
const expected = [{ id: 2, label: 'a.md', filePath: '/w/app/a.md' }, { id: 4, label: 'b.ts', filePath: undefined }]
expect(toolRowModel('apply_patch', running({ name: 'apply_patch', argsRaw }), '/w/app').fileTargets).toEqual(expected)
expect(toolRowModel('apply_patch', settled({ call: { name: 'apply_patch', argsRaw }, isError: true }), '/w/app').fileTargets).toEqual(expected)
})
it('opens each file a multi-file patch names without toggling the row', () => {
const open = vi.fn()
const openFile = vi.fn()
const input = '*** Begin Patch\n*** Add File: docs/new.md\n+hi\n*** Update File: a.ts\n*** Move to: b.ts\n@@\n-x\n+y\n*** Delete File: old.txt\n*** End Patch'
const block = settled({ call: { name: 'apply_patch', argsRaw: JSON.stringify({ input }) } })
const view = render(<FileMutationRow {...{ ...rowProps(block, 'apply_patch'), openFile, useContextMenu: contextMenuHook(open) }} />)
expect([...view.container.querySelectorAll('button')].map(button => button.textContent)).toEqual(['docs/new.md', 'b.ts'])
expect(view.container.textContent).toContain('docs/new.md, a.ts → b.ts, old.txt')
// Enter on a link stays with the link: the row does not expand. Activation is the native button's.
fireEvent.keyDown(view.getByRole('button', { name: 'docs/new.md' }), { key: 'Enter' })
expect(view.container.querySelector('[data-diff]')).toBeNull()
fireEvent.click(view.getByRole('button', { name: 'b.ts' }))
fireEvent.click(view.getByRole('button', { name: 'docs/new.md' }))
expect(openFile.mock.calls).toEqual([['b.ts'], ['docs/new.md']])
expect(view.container.querySelector('[data-diff]')).toBeNull()
fireEvent.contextMenu(view.getByRole('button', { name: 'docs/new.md' }))
expect(open).toHaveBeenCalledWith({ kind: 'file', value: { sessionId: SID, path: 'docs/new.md' } }, expect.anything())
})
it('keeps running and failed multi-file patches as plain summary text', () => {
const input = '*** Begin Patch\n*** Add File: /w/app/a.md\n+a\n*** Update File: /w/app/b.ts\n@@\n-x\n+y\n*** End Patch'
const argsRaw = JSON.stringify({ input })
const live = render(<FileMutationRow {...rowProps(running({ name: 'apply_patch', argsRaw }), 'apply_patch')} />)
expect(live.container.querySelectorAll('button')).toHaveLength(0)
expect(live.container.textContent).toContain('a.md, b.ts')
cleanup()
const stopped = settled({ call: { name: 'apply_patch', argsRaw }, meta: { stopped: true, diffs: DIFFS } })
const view = render(<FileMutationRow {...rowProps(stopped, 'apply_patch')} />)
expect(view.container.querySelectorAll('button')).toHaveLength(0)
})
it('collapses to the summary row; expanding reveals the applied diff card', () => {
const view = render(<FileMutationRow {...rowProps(settled())} />)
// The diff card is collapsed by default — not in the DOM until expanded.
@@ -46,7 +46,7 @@ describe('tool preparation', () => {
})
it.each([
['read', ReadRow], ['read_image', ReadImageRow], ['write', FileMutationRow], ['edit', FileMutationRow],
['read', ReadRow], ['read_image', ReadImageRow], ['write', FileMutationRow], ['edit', FileMutationRow], ['apply_patch', FileMutationRow],
['grep', SearchRow], ['glob', SearchRow], ['web_search', WebRow], ['web_fetch', WebRow],
['todo_write', TodoRow], ['ask_user_question', AskQuestionRow], ['subagent', DetailsRow], ['subagent_fork', DetailsRow],
['run_code', GenericToolCard], ['custom_tool', GenericToolCard],
@@ -107,6 +107,20 @@ describe('tool preparation', () => {
expect(view.getByText('child-1')).toBeTruthy()
})
it('names patch files once the streamed patch text completes', () => {
const args = new PartialArguments()
const props = preparation('apply_patch', args)
const view = render(<FileMutationRow {...props} />)
args.append(String.raw`{"input":"*** Begin Patch\n*** Update File: src/a.ts\n@@\n-old\n+new`)
view.rerender(<FileMutationRow {...props} block={{ ...props.block }} />)
expect(toolRowModel('apply_patch', props.block, '/workspace').summary).toBe('')
expect(view.queryByText('src/a.ts')).toBeNull()
args.append(String.raw`\n*** End Patch"}`)
view.rerender(<FileMutationRow {...props} block={{ ...props.block }} />)
expect(view.getByText('Edit')).toBeTruthy()
expect(view.getByText('src/a.ts')).toBeTruthy()
})
it('retains the file row through streamed arguments, dispatch, and result', () => {
const args = new PartialArguments()
const props = preparation('write', args)
+3
View File
@@ -11,6 +11,9 @@
{
"path": "../../spill/spill-policy"
},
{
"path": "../../fs/fs-patch"
},
{
"path": "../../attachment/attachment"
},
+4 -4
View File
@@ -9,8 +9,8 @@
en: fc8f28deebe5fa6b
zh: 738c6ad45034da88
/deepseek-ai-dsh-tool-fs/summary:
en: c324e1f6369b38b9
zh: 5e4fd0d5f64b0746
en: 173acfd5398446eb
zh: 7dc971cd218fc2e3
/deepseek-ai-dsh-tool-fs/table-of-contents:
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
@@ -138,8 +138,8 @@
en: e24083366d909456
zh: 003e7533d417bfe5
/deepseek-ai-dsh-tool-fs/model-experience/apply-patch/what-the-model-sees:
en: f42d71271fa0e757
zh: 3a203266d3406414
en: 880d555f2d766845
zh: 3fbdea165a5708ff
/deepseek-ai-dsh-tool-fs/model-experience/apply-patch/what-the-model-sees/system-guidance:
en: 3e353846d8e13cdf
zh: 3d93eaadc65898b3
+2 -2
View File
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
Use `dsh-tool-fs` to let a model read UTF-8 files with line numbers, read supported images, create or atomically replace files, apply targeted literal edits, and apply Codex-style multi-file patches. Results are capped, and failures provide stable error codes and recovery instructions. Add `dsh-fs-observation-policy` when writes and edits must follow a successful read; without it, mutations remain atomic but are unconditional. Image reads require durable attachment storage and an image-capable routed model. Choose the sibling discovery package for glob or grep searches.
Use `dsh-tool-fs` to let a model read UTF-8 files with line numbers, read supported images, create or atomically replace files, apply targeted literal edits, and apply multi-file patches. Results are capped, and failures provide stable error codes and recovery instructions. Add `dsh-fs-observation-policy` when writes and edits must follow a successful read; without it, mutations remain atomic but are unconditional. Image reads require durable attachment storage and an image-capable routed model. Choose the sibling discovery package for glob or grep searches.
## Table of Contents
@@ -260,7 +260,7 @@ Append-only; newly visible content follows the reusable request prefix and does
#### What the model sees
The `apply_patch` schema requires one `input` string (the Codex parameter name, which models trained on that tool send unprompted) containing `*** Begin Patch` / `*** End Patch`, Add/Update/Delete headers, optional Move to, and context/add/remove hunk lines. Paths are Session-relative. A confining backend adds the same escalation fields as write/edit. Success lines group A/M/D and a completed move reports `M <destination>`, matching Codex rust-v0.158.0. An empty patch renders `Success. No operations in patch.`. A stopped patch includes only the applicable Completed, Failed, Outcome unknown and Not executed sections; unknown outcomes end with the re-read remedy. Syntax errors keep the parser message.
The `apply_patch` schema requires one `input` string containing `*** Begin Patch` / `*** End Patch`, Add/Update/Delete headers, optional Move to, and context/add/remove hunk lines. Paths are Session-relative. A confining backend adds the same escalation fields as write/edit. Success lines group A/M/D and a completed move reports `M <destination>`, matching Codex rust-v0.158.0. An empty patch renders `Success. No operations in patch.`. A stopped patch includes only the applicable Completed, Failed, Outcome unknown and Not executed sections; unknown outcomes end with the re-read remedy. Syntax errors keep the parser message.
##### System guidance
+2 -2
View File
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
使用 `dsh-tool-fs` 可让模型带行号读取 UTF-8 文件、读取受支持的图片、创建或原子地替换文件,执行有针对性的字面量编辑,以及应用 Codex 风格的多文件补丁。结果都有上限,失败会提供稳定错误码与恢复指令。当写入和编辑必须在成功读取后执行时,请添加 `dsh-fs-observation-policy`;省略它时,变更仍是原子的,但不受此条件约束。图片读取需要持久附件存储和支持图片输入的路由模型。glob 或 grep 搜索请选择同级的发现工具包。
使用 `dsh-tool-fs` 可让模型带行号读取 UTF-8 文件、读取受支持的图片、创建或原子地替换文件,执行有针对性的字面量编辑,以及应用多文件补丁。结果都有上限,失败会提供稳定错误码与恢复指令。当写入和编辑必须在成功读取后执行时,请添加 `dsh-fs-observation-policy`;省略它时,变更仍是原子的,但不受此条件约束。图片读取需要持久附件存储和支持图片输入的路由模型。glob 或 grep 搜索请选择同级的发现工具包。
## 目录
@@ -260,7 +260,7 @@ Read a file before editing it unless you just created or edited it in this sessi
#### 模型看到的内容
`apply_patch` schema 要求一个 `input` 字符串(沿用 Codex 的参数名,在该工具上训练过的模型会不经提示地发送这个键),包含 `*** Begin Patch` / `*** End Patch`、Add/Update/Delete 文件头、可选 Move to,以及上下文/新增/删除 hunk 行。路径相对于 Session 工作目录。有围栏后端追加与 write/edit 相同的提权字段。成功行按 A/M/D 分组,完成的移动显示 `M <destination>`,与 Codex rust-v0.158.0 一致。空补丁显示 `Success. No operations in patch.`。停止的补丁只包含适用的 Completed、Failed、Outcome unknown 与 Not executed 小节;结果不确定时以重读建议结束。语法错误保留解析器消息。
`apply_patch` schema 要求一个 `input` 字符串,包含 `*** Begin Patch` / `*** End Patch`、Add/Update/Delete 文件头、可选 Move to,以及上下文/新增/删除 hunk 行。路径相对于 Session 工作目录。有围栏后端追加与 write/edit 相同的提权字段。成功行按 A/M/D 分组,完成的移动显示 `M <destination>`,与 Codex rust-v0.158.0 一致。空补丁显示 `Success. No operations in patch.`。停止的补丁只包含适用的 Completed、Failed、Outcome unknown 与 Not executed 小节;结果不确定时以重读建议结束。语法错误保留解析器消息。
##### 系统提示
+3 -4
View File
@@ -1,4 +1,4 @@
/** Codex-style multi-file patch tool over the guarded patch executor. */
/** Multi-file patch tool over the guarded patch executor. */
import type { Context } from '@deepseek-ai/cordis'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { executePatch } from './patch/index.ts'
@@ -25,12 +25,11 @@ export function applyApplyPatchTool(ctx: Context, sandbox: FsSandboxController):
})
ctx.tools.register(defineTool({
name: 'apply_patch',
description: 'Create, update, delete, or move UTF-8 text files with one Codex-style patch; '
description: 'Create, update, delete, or move UTF-8 text files with one patch; '
+ 'prefer it over multiple edit calls when a change spans several files or separated regions.',
parameters: {
// Named `input` as in the Codex apply_patch tool; models trained on it send that key.
input: { type: 'string', required: true,
description: 'Codex patch text: start with *** Begin Patch and end with *** End Patch. '
description: 'Patch text: start with *** Begin Patch and end with *** End Patch. '
+ 'Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, '
+ 'with @@ or @@ context and space-prefixed context, + added, or - removed lines; '
+ '*** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. '
@@ -27,7 +27,7 @@ it('omits patch registration and guidance when disabled', async () => {
it('registers patch guidance when enabled and removes tool and section on disposal', async () => {
const t = await setup()
expect(t.ctx.tools.get('apply_patch')?.description).toBe('Create, update, delete, or move UTF-8 text files with one Codex-style patch; '
expect(t.ctx.tools.get('apply_patch')?.description).toBe('Create, update, delete, or move UTF-8 text files with one patch; '
+ 'prefer it over multiple edit calls when a change spans several files or separated regions.')
const key = {}
let scope!: Scope
+3
View File
@@ -6841,6 +6841,9 @@ importers:
'@deepseek-ai/dsh-client-ui-slots':
specifier: workspace:*
version: link:../ui-slots
'@deepseek-ai/dsh-fs-patch':
specifier: workspace:*
version: link:../../fs/fs-patch
'@deepseek-ai/dsh-llm':
specifier: workspace:*
version: link:../../llm/llm
+27
View File
@@ -0,0 +1,27 @@
/** Shared assertions for original-build routing and artifact identity in packaging workflows. */
import { expect } from 'vitest'
/**
* Require archival steps to retain the original machine, directory and build identity.
* @param job Parsed archival job from a packaging workflow.
* @param count Expected number of artifact upload steps.
* @returns The checked upload steps, preserving platform-specific fields.
*/
export function expectDesktopArchive<S extends { uses?: string; with?: Record<string, unknown> }>(
job: { 'runs-on': string | string[]; env: Record<string, string>; steps: S[] }, count: number,
): S[] {
expect(job['runs-on']).toEqual(['self-hosted', '${{ needs.package.outputs.runner }}'])
expect(job.env).toMatchObject({
DESKTOP_RETAINED_DIRECTORY: '${{ needs.package.outputs.directory }}',
DESKTOP_PACKAGE_ATTEMPT: '${{ needs.package.outputs.attempt }}',
DESKTOP_PACKAGE_RUNNER: '${{ needs.package.outputs.runner-name }}',
})
const uploads = job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(count)
for (const step of uploads) {
expect(step.with?.name).toContain('${{ needs.package.outputs.version }}')
expect(step.with?.name).toContain('${{ needs.package.outputs.attempt }}')
expect(step.with?.name).not.toContain('github.run_attempt')
}
return uploads
}
+4
View File
@@ -23,6 +23,7 @@ it.each(['macos', 'windows'])('%s packaging accepts test branches but preserves
mkdirSync(join(root, 'apps/desktop/scripts'), { recursive: true })
writeFileSync(join(root, 'package.json'), '{"version":"1.0.0"}')
writeFileSync(join(root, 'apps/desktop/scripts/desktop-ci-version.mjs'), 'PACKAGE_VERSION_MODE')
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), '--check-runner')
git('add', '.')
git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '-m', 'fixture')
const sha = git('rev-parse', 'HEAD')
@@ -51,6 +52,9 @@ it.each(['macos', 'windows'])('%s packaging accepts test branches but preserves
}
for (const preset of ['test', 'production']) expect(run(preset, 'dsh-v1.0.0').status).toBe(0)
expect(run('test', 'dsh-v2.0.0').status).not.toBe(0)
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), 'old archival adapter')
expect(run('test', 'dsh-v1.0.0').stderr).toContain('independent Desktop artifact archival support')
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), '--check-runner')
writeFileSync(join(root, 'apps/desktop/scripts/desktop-ci-version.mjs'), 'old adapter')
expect(run('test', 'dsh-v1.0.0').status).not.toBe(0)
} finally { rmSync(root, { recursive: true, force: true, maxRetries: 3 }) }
+23
View File
@@ -9,6 +9,7 @@ const workflow = yaml.load(readFileSync(resolve(import.meta.dirname, '../.github
permissions: Record<string, string>
jobs: Record<string, {
defaults?: unknown
concurrency?: { group: string; 'cancel-in-progress': boolean }
needs?: string | string[]
env?: Record<string, string>
if?: string
@@ -78,3 +79,25 @@ it('rejects non-master dispatch before scheduling a self-hosted job', () => {
if (result.status !== 0) expect(result.stderr).toContain('must be dispatched from master')
}
})
it('defaults to production website upload and separates cache-only recovery', () => {
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { upload_website: { type: 'boolean', default: true } } })
expect(workflow.jobs.prepare!.env?.DESKTOP_UPLOAD_WEBSITE).toBe('${{ inputs.upload_website }}')
expect(workflow.jobs.prepare!.env?.DOWNLOAD_PROD_EO_ZONE_ID).toBe('${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}')
const upload = workflow.jobs['upload-website-installer']!
const purge = workflow.jobs['purge-website-installer']!
expect(purge.needs).toEqual(['route', 'prepare', 'upload-website-installer'])
expect(upload.concurrency).toEqual({ group: 'desktop-website-upload-${{ needs.prepare.outputs.website-destination }}', 'cancel-in-progress': false })
expect(purge.concurrency).toEqual({ group: 'desktop-website-purge-${{ needs.prepare.outputs.website-destination }}', 'cancel-in-progress': false })
for (const job of [upload, purge]) {
expect(job.if).toBe("inputs.upload_website && needs.prepare.outputs.preset != 'test'")
expect(job.environment).toBe('desktop-production')
const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop/scripts/preflight-desktop-publish-local.mjs')
expect(preflight).toBeGreaterThan(-1)
expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile'))
expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}')
}
expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts upload')
expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts purge')
expect(purge.steps.some(step => step.run?.includes('publish-desktop-ci.ts'))).toBe(false)
})
+17 -6
View File
@@ -1,3 +1,4 @@
import { expectDesktopArchive } from './desktop-archive-workflow-test.ts'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import yaml from 'js-yaml'
@@ -24,6 +25,12 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
}>
}
it('archives using the same persistent pnpm store as packaging', () => {
const cache = (job: string) => workflow.jobs[job]!.steps.find(step => step.name === 'Configure persistent package caches')
expect(cache('upload-artifact')).toEqual(cache('package'))
expect(cache('upload-artifact')?.run).toContain('PNPM_CONFIG_STORE_DIR=')
})
it('confines signed Mac packaging to manual dispatch and a dedicated Apple Silicon runner', () => {
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
expect(workflow.jobs.package).not.toHaveProperty('name')
@@ -36,11 +43,14 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
expect(steps.find(step => step.id === 'checkout')?.with).toMatchObject({ 'persist-credentials': false, clean: true })
for (const step of steps) expect(step.run ?? '').not.toContain('${{ inputs.')
const uploads = steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(2)
expect(uploads).toHaveLength(1)
const archive = workflow.jobs['upload-artifact']!
expect(archive['runs-on']).toEqual(['self-hosted', '${{ needs.package.outputs.runner }}'])
const installer = archive.steps.find(step => step.uses?.startsWith('actions/upload-artifact@'))!
expect(uploads[0]?.if).toBe("always() && steps.checkout.outcome == 'success'")
expect(uploads[1]?.if).toBe('success()')
expect(uploads[1]?.with?.path).toBe('${{ steps.retained.outputs.directory }}/*')
expect(uploads[1]?.with?.['compression-level']).toBe(0)
expect(installer.if).toBe('success()')
expect(installer.with?.path).toBe('${{ needs.package.outputs.directory }}/*')
expect(installer.with?.['compression-level']).toBe(0)
})
it('defaults to notarization and labels the explicit debugging option', () => {
@@ -50,7 +60,7 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
} } })
const steps = workflow.jobs.package!.steps
expect(steps.filter(step => step.run?.includes('args+=(--skip-notarization)'))).toHaveLength(2)
expect(steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain('${{ steps.settings.outputs.mode }}')
expect(workflow.jobs['upload-artifact']!.steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain('${{ needs.package.outputs.mode }}')
})
it('retains build inputs outside checkout and run-specific pnpm installations', () => {
@@ -85,13 +95,14 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
})
it('passes the same target to preparation, packaging and retention', () => {
expectDesktopArchive(workflow.jobs['upload-artifact']!, 1)
const job = workflow.jobs.package!
expect(job.env.DSH_DESKTOP_TARGET_PLATFORM).toBe('darwin')
expect(job.env.DSH_DESKTOP_TARGET_ARCH).toBe(arch)
const builds = job.steps.filter(step => step.run?.includes('pnpm run package:desktop:mac:'))
expect(builds).toHaveLength(2)
for (const step of builds) expect(step.run).toContain(`package:desktop:mac:${arch}`)
expect(job.steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain(`macos-${arch}-`)
expect(workflow.jobs['upload-artifact']!.steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain(`macos-${arch}-`)
if (arch === 'x64') {
const rosetta = job.steps.findIndex(step => step.run === 'arch -x86_64 /usr/bin/true')
expect(rosetta).toBeGreaterThan(-1)
-3
View File
@@ -1449,9 +1449,6 @@
"746ebc5aade01a50cc9a74fc07b1023addf021aef80b62c069a437ac140c9e64": 1,
"c920d88f6eb309ef5991608642a1ab0fd972690538b33c34d86c68d07ddd6edf": 1
},
"packages/session-query/session-log-export/tests/dialog.client.spec.tsx": {
"a9b1969d76db0b05f87c862956f8ff45c52f1f4a5b32a206339de0c9fee99a77": 1
},
"packages/session-query/session-log-export/tests/loader-composition.host.spec.ts": {
"59c63f734e8bba862325f776e3fcbebd78a84cfb4161f8df41c216950d9bf351": 1,
"e12d49327a6708ae3ace371e28ed0deb471dc8895c584ba94a86af344c15cec3": 1
+14 -4
View File
@@ -1,3 +1,4 @@
import { expectDesktopArchive } from './desktop-archive-workflow-test.ts'
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -11,7 +12,8 @@ const workflow = yaml.load(readFileSync(resolve(root, '.github/workflows/windows
permissions: Record<string, string>
concurrency: { group: string; 'cancel-in-progress': boolean }
jobs: Record<string, {
'runs-on': string
defaults?: { run: { shell: string } }
'runs-on': string | string[]
env: Record<string, string>
steps: Array<{
id?: string
@@ -105,15 +107,16 @@ it('validates before building and passes the same mode and version to checks and
it('retains failure diagnostics and uploads only the selected successful installer', () => {
const uploads = job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(3)
expect(uploads).toHaveLength(1)
const archival = expectDesktopArchive(workflow.jobs['upload-artifact']!, 2)
expect(uploads[0]!.if).toBe("always() && steps.checkout.outcome == 'success'")
expect(uploads[0]!.with).toMatchObject({
path: '${{ github.workspace }}/apps/desktop/.desktop-build/packaging-runs/',
'include-hidden-files': true,
})
for (const mode of ['unsigned', 'signed']) {
const upload = uploads.find(step => step.if === `success() && inputs.signing == '${mode}'`)!
expect(upload.with).toMatchObject({ path: '${{ steps.retained.outputs.directory }}/*', 'if-no-files-found': 'error', 'compression-level': 0 })
const upload = archival.find(step => step.if === `success() && inputs.signing == '${mode}'`)!
expect(upload.with).toMatchObject({ path: '${{ needs.package.outputs.directory }}/*', 'if-no-files-found': 'error', 'compression-level': 0 })
}
})
@@ -211,3 +214,10 @@ it.skipIf(process.platform !== 'win32')('stages helpers that remain usable when
rmSync(directory, { recursive: true, force: true, maxRetries: 3 })
}
})
it('archives with native PowerShell and the persistent packaging store', () => {
const archival = workflow.jobs['upload-artifact']!
expect(archival.defaults?.run.shell).toBe('pwsh')
expect(archival.steps.find(step => step.name === 'Configure persistent pnpm store')?.run)
.toBe(job.steps.find(step => step.name === 'Configure persistent pnpm store')?.run)
})
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -55,9 +55,9 @@ Program-only SDK bindings:
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
interface ToolArgsMap {
/** Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions. */
/** Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions. */
apply_patch: {
/** Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory. */
/** Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory. */
input: string;
/** The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval. */
sandbox_permissions?: "workspace-write" | "danger-full-access";
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -935,13 +935,13 @@
[
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -1883,13 +1883,13 @@
[
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2831,13 +2831,13 @@
[
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -3779,13 +3779,13 @@
[
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -651,13 +651,13 @@
[
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -91,9 +91,9 @@ Program-only SDK bindings:
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
interface ToolArgsMap {
/** Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions. */
/** Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions. */
apply_patch: {
/** Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory. */
/** Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory. */
input: string;
/** The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval. */
sandbox_permissions?: "workspace-write" | "danger-full-access";
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -91,9 +91,9 @@ Program-only SDK bindings:
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
interface ToolArgsMap {
/** Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions. */
/** Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions. */
apply_patch: {
/** Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory. */
/** Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory. */
input: string;
/** The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval. */
sandbox_permissions?: "workspace-write" | "danger-full-access";
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -731,13 +731,13 @@
[
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -2,13 +2,13 @@
"initial": [
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",
@@ -651,13 +651,13 @@
[
{
"name": "apply_patch",
"description": "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
"description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
},
"sandbox_permissions": {
"type": "string",

Some files were not shown because too many files have changed in this diff Show More