DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ci): 新增夜间构建流水线并补齐更新检查兜底 (#955)
Mao Mr13351c1b2200
diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.ymlindex 192751b7..9df5ce95 100644--- a/.github/workflows/build-linux.yml+++ b/.github/workflows/build-linux.yml@@ -6,6 +6,11 @@ on:source_ref:required: truetype: string+ version:+ description: 注入的版本号;为空时沿用仓库内版本,仅夜间构建使用+ required: false+ type: string+ default: ''secrets:TAURI_SIGNING_PRIVATE_KEY:required: false@@ -59,6 +64,12 @@ jobs:- name: Install frontend dependenciesrun: pnpm install --frozen-lockfile+ - name: Stamp injected version+ if: inputs.version != ''+ env:+ STAMP_VERSION: ${{ inputs.version }}+ run: node scripts/stamp-version.mjs "$STAMP_VERSION"+- name: Build packagesenv:TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.ymlindex e6571046..afc34f60 100644--- a/.github/workflows/build-macos.yml+++ b/.github/workflows/build-macos.yml@@ -10,6 +10,11 @@ on:source_ref:required: truetype: string+ version:+ description: 注入的版本号;为空时沿用仓库内版本,仅夜间构建使用+ required: false+ type: string+ default: ''secrets:TAURI_SIGNING_PRIVATE_KEY:required: false@@ -82,6 +87,12 @@ jobs:if: steps.check.outputs.should_run == 'true'run: pnpm install --frozen-lockfile+ - name: Stamp injected version+ if: steps.check.outputs.should_run == 'true' && inputs.version != ''+ env:+ STAMP_VERSION: ${{ inputs.version }}+ run: node scripts/stamp-version.mjs "$STAMP_VERSION"+- name: Validate signing secretsif: steps.check.outputs.should_run == 'true'shell: bashdiff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.ymlindex 8aabfe04..57f51667 100644--- a/.github/workflows/build-windows.yml+++ b/.github/workflows/build-windows.yml@@ -6,6 +6,11 @@ on:source_ref:required: truetype: string+ version:+ description: 注入的版本号;为空时沿用仓库内版本,仅夜间构建使用+ required: false+ type: string+ default: ''secrets:TAURI_SIGNING_PRIVATE_KEY:required: false@@ -38,6 +43,14 @@ jobs:- name: Install frontend dependenciesrun: pnpm install --frozen-lockfile+ # windows-latest 默认 PowerShell,$STAMP_VERSION 会被当成本地变量读成空串;显式用 bash。+ - name: Stamp injected version+ if: inputs.version != ''+ shell: bash+ env:+ STAMP_VERSION: ${{ inputs.version }}+ run: node scripts/stamp-version.mjs "$STAMP_VERSION"+# WiX 只接受纯数字版本;NSIS 仍使用完整 SemVer。- name: Prepare MSI version overrideshell: bashdiff --git a/.github/workflows/release-nightly.yml b/.github/workflows/release-nightly.ymlnew file mode 100644index 00000000..a28e81e7--- /dev/null+++ b/.github/workflows/release-nightly.yml@@ -0,0 +1,386 @@+name: Build & Release (Nightly)++# 夜间版(dig-node 形态):滚动发布 main 的每日构建,保留最近 N 天。+# - 版本号固定注入 0.0.0(构建期写入、不入库):不占用正式版号段。+# - 每次构建写两个 Release:当日日期 tag (nightly-YYYYMMDD) 与滚动别名 nightly (均标记为 pre-release)。+# - workflow 名称故意不等于 "Build & Release",避免误触发 release-bundle.yml。+on:+ # UTC 18:00 = 北京时间次日 02:00+ schedule:+ - cron: '0 18 * * *'+ workflow_dispatch:+ inputs:+ force:+ description: 忽略「main 无新提交即跳过」,强制重新构建+ required: false+ default: false+ type: boolean++permissions:+ contents: read++concurrency:+ group: release-nightly+ cancel-in-progress: false++env:+ # 保留窗口:含当天在内最近 N 天,更早的连 tag 一起删除。+ NIGHTLY_RETAIN_DAYS: '10'+ # 夜间版说明(唯一出处):草稿阶段就写进 Release 正文,变更日志紧随其后;+ # 发布时在其后追加产物清单与构建时间。+ NIGHTLY_DESCRIPTION: |+ ### ⚠️重要通知+ 这是专为测试目的创建的**开发构建版本**。请注意:++ - 此版本**不适用于**生产环境+ - 功能可能不完整或不稳定+ - 仅用于在桌面环境中验证 PR 更改+ - 可能包含尚未经过全面审查的实验性代码+ - 不提供任何稳定性或可靠性方面的保证++ ### 预期用途+ - 针对 PR 变更进行重点测试+ - 验证桌面特定行为+ - 桌面平台上的 UI/UX 验证+ - 在目标设备上进行性能测试++ ---++jobs:+ prepare:+ name: Prepare Nightly+ runs-on: ubuntu-latest+ permissions:+ contents: write+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ GH_REPO: ${{ github.repository }}+ outputs:+ should_build: ${{ steps.plan.outputs.should_build }}+ version: ${{ steps.plan.outputs.version }}+ tag: ${{ steps.plan.outputs.tag }}+ source_ref: ${{ steps.plan.outputs.source_ref }}+ steps:+ - name: Checkout default branch+ uses: actions/checkout@v7+ with:+ ref: ${{ github.event.repository.default_branch }}+ fetch-depth: 0+ fetch-tags: true++ - name: Plan nightly version+ id: plan+ env:+ FORCE: ${{ github.event_name == 'workflow_dispatch' && inputs.force || 'false' }}+ run: |+ set -euo pipefail+ source_ref="$(git rev-parse HEAD)"+ date="$(date -u +%Y%m%d)"+ tag="nightly-$date"+ version="0.0.0"+ should_build="true"++ if [ "$FORCE" != "true" ]; then+ # 使用 gh jq 过滤获取最新一个 nightly-YYYYMMDD 标签,减少多重管道耗时+ last_tag="$(gh release list --limit 100 --json tagName -q '[.[].tagName | select(test("^nightly-[0-9]{8}$"))] | sort | last // ""')"+ if [ -n "$last_tag" ]; then+ last_sha="$(gh release view "$last_tag" --json body -q .body | sed -n 's/.*nightly-sha:\([0-9a-f]\{7,40\}\).*/\1/p' | head -1)"+ if [ -n "$last_sha" ] && [ "$last_sha" = "$source_ref" ]; then+ should_build="false"+ fi+ fi+ fi++ {+ echo "should_build=$should_build"+ echo "version=$version"+ echo "tag=$tag"+ echo "source_ref=$source_ref"+ } >> "$GITHUB_OUTPUT"++ if [ "$should_build" = "false" ]; then+ echo "::notice::main 自 $last_tag 以来没有新提交,跳过本次夜间构建"+ else+ echo "::notice::夜间版 $version(tag $tag,提交 $source_ref)"+ fi++ - name: Clean up leftover drafts+ if: steps.plan.outputs.should_build == 'true'+ env:+ NIGHTLY_TAG: ${{ steps.plan.outputs.tag }}+ run: |+ set -euo pipefail+ today="${NIGHTLY_TAG#nightly-}"++ # 清理当天与历史残留的草稿 Release+ gh api --paginate "repos/$GH_REPO/releases?per_page=100" \+ -q '.[] | select(.draft and (.tag_name | test("^nightly-[0-9]{8}$"))) | (.id|tostring) + " " + .tag_name' |+ while read -r id tag; do+ day="${tag#nightly-}"+ if [ "$day" -le "$today" ]; then+ echo "dropping draft release $id ($tag)"+ gh api -X DELETE "repos/$GH_REPO/releases/$id"+ fi+ done++ - name: Ensure draft release exists+ if: steps.plan.outputs.should_build == 'true'+ env:+ NIGHTLY_TAG: ${{ steps.plan.outputs.tag }}+ NIGHTLY_SHA: ${{ steps.plan.outputs.source_ref }}+ run: |+ set -euo pipefail+ day="${NIGHTLY_TAG#nightly-}"+ title="Nightly ${day:0:4}-${day:4:2}-${day:6:2} (${NIGHTLY_SHA:0:7})"++ if gh release view "$NIGHTLY_TAG" >/dev/null 2>&1; then+ # 当天已经发布过:构建期间原样保留,等三个平台都构建成功后再由 finalize 更新,+ # 避免构建失败时把已发布的 Release 打回草稿。+ if [ "$(gh release view "$NIGHTLY_TAG" --json isDraft -q .isDraft)" != "true" ]; then+ echo "::notice::$NIGHTLY_TAG 已经是已发布状态,构建期间原样保留。"+ exit 0+ fi++ body="$(gh release view "$NIGHTLY_TAG" --json body -q .body)"+ if [ "$(printf '%s\n' "$body" | head -1)" = "$(printf '%s\n' "$NIGHTLY_DESCRIPTION" | head -1)" ]; then+ echo "草稿 $NIGHTLY_TAG 已带说明。"+ exit 0+ fi+ {+ printf '%s\n' "$NIGHTLY_DESCRIPTION"+ echo+ printf '%s\n' "$body"+ } > draft_notes.md+ gh release edit "$NIGHTLY_TAG" --title "$title" --notes-file draft_notes.md+ exit 0+ fi++ printf '%s\n' "$NIGHTLY_DESCRIPTION" > draft_notes.md+ gh release create "$NIGHTLY_TAG" --draft --target "$NIGHTLY_SHA" \+ --title "$title" --prerelease --notes-file draft_notes.md+ gh release edit "$NIGHTLY_TAG" --title "$title" --notes-file draft_notes.md++ build-macos:+ name: Build macOS Artifacts+ needs: prepare+ if: needs.prepare.outputs.should_build == 'true'+ uses: ./.github/workflows/build-macos.yml+ with:+ source_ref: ${{ needs.prepare.outputs.source_ref }}+ version: ${{ needs.prepare.outputs.version }}+ secrets:+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}+ APPLE_ID: ${{ secrets.APPLE_ID }}+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}++ build-windows:+ name: Build Windows Artifacts+ needs: prepare+ if: needs.prepare.outputs.should_build == 'true'+ uses: ./.github/workflows/build-windows.yml+ with:+ source_ref: ${{ needs.prepare.outputs.source_ref }}+ version: ${{ needs.prepare.outputs.version }}+ secrets:+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}++ build-linux:+ name: Build Linux Artifacts+ needs: prepare+ if: needs.prepare.outputs.should_build == 'true'+ uses: ./.github/workflows/build-linux.yml+ with:+ source_ref: ${{ needs.prepare.outputs.source_ref }}+ version: ${{ needs.prepare.outputs.version }}+ secrets:+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}++ finalize:+ name: Publish Nightly Release+ needs: [prepare, build-macos, build-windows, build-linux]+ if: >-+ always() && needs.prepare.result == 'success' &&+ needs.prepare.outputs.should_build == 'true' &&+ needs.build-macos.result == 'success' &&+ needs.build-windows.result == 'success' &&+ needs.build-linux.result == 'success'+ runs-on: ubuntu-latest+ permissions:+ contents: write+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ GH_REPO: ${{ github.repository }}+ NIGHTLY_TAG: ${{ needs.prepare.outputs.tag }}+ NIGHTLY_SHA: ${{ needs.prepare.outputs.source_ref }}+ steps:+ - name: Download build outputs+ uses: actions/download-artifact@v7+ with:+ pattern: release-*+ # 放在 workspace 之外:下一步 actions/checkout 会清空 workspace 目录+ # (工作区还不是 git 仓库时会先「Deleting the contents of …」),产物会被删掉。+ path: ${{ runner.temp }}/release-assets+ merge-multiple: true++ - name: Verify downloaded assets+ run: |+ find "$RUNNER_TEMP/release-assets" -type f -print+ [ -n "$(find "$RUNNER_TEMP/release-assets" -type f -print -quit)" ] || {+ echo '::error::No nightly assets were downloaded'+ exit 1+ }++ # 三个平台都构建成功后才移动日期 tag、生成变更日志:构建失败时已发布的 Release+ # 及其 tag 保持原样。+ - name: Point dated nightly tag at this commit+ uses: actions/github-script@v8+ env:+ NIGHTLY_SHA: ${{ needs.prepare.outputs.source_ref }}+ NIGHTLY_TAG: ${{ needs.prepare.outputs.tag }}+ with:+ script: |+ const ref = `tags/${process.env.NIGHTLY_TAG}`;+ const sha = process.env.NIGHTLY_SHA;+ try {+ await github.rest.git.updateRef({ ...context.repo, ref, sha, force: true });+ } catch (error) {+ if (error.status !== 404 && error.status !== 422) throw error;+ await github.rest.git.createRef({ ...context.repo, ref: `refs/${ref}`, sha });+ }++ - name: Checkout source for changelog+ uses: actions/checkout@v7+ with:+ ref: ${{ needs.prepare.outputs.source_ref }}+ fetch-depth: 0+ fetch-tags: true++ - name: Setup Node.js and pnpm+ uses: ./.github/actions/setup-node-pnpm++ - name: Install changelog dependencies+ run: pnpm install --frozen-lockfile --ignore-scripts++ - name: Generate changelog+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: |+ set -euo pipefail+ git fetch --force origin "refs/tags/$NIGHTLY_TAG:refs/tags/$NIGHTLY_TAG"++ from="$(gh release list --limit 100 --json tagName -q '[.[].tagName | select(test("^nightly-[0-9]{8}$"))] | sort | .[]' |+ while read -r t; do+ if [[ "$t" < "$NIGHTLY_TAG" ]]; then echo "$t"; fi+ done | tail -1)"++ if [ -z "$from" ]; then+ from="$(git describe --tags --abbrev=0 --match 'v*' 2>/dev/null || true)"+ fi++ day="${NIGHTLY_TAG#nightly-}"+ title="Nightly ${day:0:4}-${day:4:2}-${day:6:2} (${NIGHTLY_SHA:0:7})"+ args=(--draft --prerelease --to "$NIGHTLY_TAG" --name "$title")+ if [ -n "$from" ]; then+ args+=(--from "$from")+ echo "变更日志范围:$from..$NIGHTLY_TAG"+ else+ echo '::warning::找不到变更日志起点,按全部历史生成'+ fi++ pnpm exec changelogithub "${args[@]}" || \+ echo '::warning::changelogithub 生成变更日志失败,Release 只保留产物与提示'++ - name: Upload assets to the draft release+ run: |+ set -euo pipefail+ mapfile -d '' assets < <(find "$RUNNER_TEMP/release-assets" -type f -print0)+ gh release upload "$NIGHTLY_TAG" "${assets[@]}" --clobber++ - name: Point rolling alias tag at this commit+ uses: actions/github-script@v8+ env:+ NIGHTLY_SHA: ${{ needs.prepare.outputs.source_ref }}+ with:+ script: |+ const ref = 'tags/nightly';+ const sha = process.env.NIGHTLY_SHA;+ try {+ await github.rest.git.updateRef({ ...context.repo, ref, sha, force: true });+ } catch (error) {+ if (error.status !== 404 && error.status !== 422) throw error;+ await github.rest.git.createRef({ ...context.repo, ref: `refs/${ref}`, sha });+ }++ - name: Compose release notes+ run: |+ set -euo pipefail+ body="$(gh release view "$NIGHTLY_TAG" --json body -q .body)"++ {+ # 说明固定排在最前:变更日志步骤会重写正文,这里按需补回。+ if [ "$(printf '%s\n' "$body" | head -1)" != "$(printf '%s\n' "$NIGHTLY_DESCRIPTION" | head -1)" ]; then+ printf '%s\n' "$NIGHTLY_DESCRIPTION"+ echo+ fi+ printf '%s\n' "$body"+ echo+ # 与正式版(release.yml 的 Append Artifacts section)保持同一份产物清单+ echo '### 📦 Artifacts'+ echo '- **macOS (Apple Silicon)**: 下载 `aarch64.dmg`'+ echo '- **macOS (Intel)**: 下载 `x64.dmg`'+ echo '- **Windows**: 下载 `.exe`'+ echo '- **Linux (x64)**: 下载 `.AppImage` 或 `.deb`(基于 Ubuntu 22.04 构建)'+ echo+ echo '> 文件名带 `_Bundle` 后缀的是**离线捆绑包**:安装包里已内置 Node.js 运行时、pnpm'+ echo '> 与打包好的 dsh 内核,首次启动无需联网即可直接运行。不带该后缀的是常规安装包,'+ echo '> 首次启动时按需下载运行时依赖。'+ echo+ echo "提交 \`$NIGHTLY_SHA\` · 构建时间 $(date -u '+%Y-%m-%d %H:%M UTC')"+ echo+ echo "<!-- nightly-sha:$NIGHTLY_SHA -->"+ } > nightly_notes.md++ day="${NIGHTLY_TAG#nightly-}"+ gh release edit "$NIGHTLY_TAG" --title "Nightly ${day:0:4}-${day:4:2}-${day:6:2} (${NIGHTLY_SHA:0:7})" \+ --notes-file nightly_notes.md --draft=false --prerelease --latest=false++ - name: Prune nightlies outside the retention window+ run: |+ set -euo pipefail+ cutoff="$(date -u -d "-$((NIGHTLY_RETAIN_DAYS - 1)) days" +%Y%m%d)"+ gh release list --limit 100 --json tagName -q '.[].tagName' |+ sed -n 's/^nightly-\([0-9]\{8\}\)$/\1/p' |+ while read -r day; do+ if [ "$day" -lt "$cutoff" ]; then+ echo "pruning nightly-$day"+ gh release delete "nightly-$day" --yes --cleanup-tag+ fi+ done++ - name: Refresh rolling nightly alias+ run: |+ set -euo pipefail+ day="${NIGHTLY_TAG#nightly-}"+ title="Nightly ${day:0:4}-${day:4:2}-${day:6:2} (${NIGHTLY_SHA:0:7})"+ if ! gh release view nightly >/dev/null 2>&1; then+ gh release create nightly --draft --target "$NIGHTLY_SHA" \+ --title "$title" --prerelease+ fi+ mapfile -d '' assets < <(find "$RUNNER_TEMP/release-assets" -type f -print0)+ gh release upload nightly "${assets[@]}" --clobber++ gh release view "$NIGHTLY_TAG" --json body -q .body > alias_notes.md+ {+ echo "> 滚动别名:本页资产始终是最近一版夜间版,本次对应 [\`$NIGHTLY_TAG\`](https://github.com/$GH_REPO/releases/tag/$NIGHTLY_TAG)。"+ echo+ sed "s|/download/$NIGHTLY_TAG/|/download/nightly/|g" alias_notes.md+ } > nightly_alias_notes.md++ gh release edit nightly --title "$title" --notes-file nightly_alias_notes.md \+ --draft=false --prerelease --latest=falsediff --git a/scripts/stamp-version.d.mts b/scripts/stamp-version.d.mtsnew file mode 100644index 00000000..6d502db8--- /dev/null+++ b/scripts/stamp-version.d.mts@@ -0,0 +1,15 @@+/**+ * `scripts/stamp-version.mjs` 的类型声明。+ *+ * 该脚本是给 CI 直接调用的纯 ESM,本身不带类型;这里声明它导出的函数,+ * 让 `test/stamp-version.test.ts` 的导入在 `pnpm typecheck` 下可解析。+ */++export interface StampResult {+ version: string+ files: string[]+}++export function stampCargoToml(content: string, version: string, label: string): string++export function stampVersion(repo: string, version: string): StampResultdiff --git a/scripts/stamp-version.mjs b/scripts/stamp-version.mjsnew file mode 100644index 00000000..34a7eb1c--- /dev/null+++ b/scripts/stamp-version.mjs@@ -0,0 +1,130 @@+import { readFileSync, writeFileSync } from 'node:fs'+import path from 'node:path'+import process from 'node:process'+import { pathToFileURL } from 'node:url'+import { parseSemver, readReleaseIdentity } from './release-identity.mjs'++function stampError(message) {+ return new Error(`STAMP_VERSION: ${message}`)+}++function replaceOnce(content, pattern, replacement, label) {+ const matches = [...content.matchAll(new RegExp(pattern.source, `${pattern.flags.replace('g', '')}g`))]+ if (matches.length !== 1)+ throw stampError(`${label}: expected exactly one version field, found ${matches.length}`)+ return content.replace(pattern, replacement)+}++function stampCargoToml(content, version, label) {+ const eol = content.includes('\r\n') ? '\r\n' : '\n'+ const lines = content.split(/\r?\n/)+ const targets = []+ let section = ''++ for (const [index, line] of lines.entries()) {+ const header = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line)+ if (header) {+ section = header[1].trim()+ continue+ }+ if (section === 'package' && /^\s*version\s*=/.test(line))+ targets.push(index)+ }++ if (targets.length !== 1)+ throw stampError(`${label}: expected exactly one [package] version field, found ${targets.length}`)++ const [target] = targets+ const stamped = lines[target].replace(/^(\s*version\s*=\s*")[^"]*(")/, `$1${version}$2`)+ if (stamped === lines[target])+ throw stampError(`${label}: [package] version is not a double-quoted string`)++ lines[target] = stamped+ return lines.join(eol)+}++const STAMPED_FILES = [+ {+ label: 'package.json',+ segments: ['package.json'],+ stamp: (content, version, label) =>+ replaceOnce(content, /^(\s*"version"\s*:\s*")[^"]*(")/m, `$1${version}$2`, label),+ },+ {+ label: 'src-tauri/Cargo.toml',+ segments: ['src-tauri', 'Cargo.toml'],+ stamp: stampCargoToml,+ },+ {+ label: 'src-tauri/tauri.conf.json',+ segments: ['src-tauri', 'tauri.conf.json'],+ stamp: (content, version, label) =>+ replaceOnce(content, /^(\s*"version"\s*:\s*")[^"]*(")/m, `$1${version}$2`, label),+ },+]++function parseStampedVersion(version) {+ try {+ parseSemver(version, 'stamped version')+ }+ catch (error) {+ const message = error instanceof Error ? error.message : String(error)+ throw stampError(message.replace(/^RELEASE_IDENTITY:\s*/, ''))+ }+}++function stampVersion(repo, version) {+ parseStampedVersion(version)++ const base = readReleaseIdentity(repo)+ if (base.version === version)+ throw stampError(`stamped version ${version} equals the checked-out release version`)++ const written = []+ for (const file of STAMPED_FILES) {+ const filePath = path.join(repo, ...file.segments)+ let content+ try {+ content = readFileSync(filePath, 'utf8')+ }+ catch (error) {+ throw stampError(`${file.label}: cannot be read (${error instanceof Error ? error.message : String(error)})`)+ }++ const stamped = file.stamp(content, version, file.label)+ if (stamped === content)+ continue+ writeFileSync(filePath, stamped, 'utf8')+ written.push(file.label)+ }++ const result = readReleaseIdentity(repo)+ if (result.version !== version)+ throw stampError(`stamped files report ${result.version} instead of ${version}`)++ return { version, files: written }+}++function main() {+ const [version] = process.argv.slice(2)+ if (!version)+ throw stampError('usage: node scripts/stamp-version.mjs <version>')++ const repo = process.env.GITHUB_WORKSPACE || process.cwd()+ const { files } = stampVersion(repo, version)+ console.log(`STAMP_VERSION: ${files.join(', ')} -> ${version}`)+}++const entryPoint = process.argv[1]+if (entryPoint && import.meta.url === pathToFileURL(path.resolve(entryPoint)).href) {+ try {+ main()+ }+ catch (error) {+ const message = error instanceof Error ? error.message : String(error)+ console.error(message.startsWith('STAMP_VERSION:') ? message : `STAMP_VERSION: ${message}`)+ process.exitCode = 1+ }+}++export { stampCargoToml, stampVersion }diff --git a/src-tauri/src/service/update/about.rs b/src-tauri/src/service/update/about.rsindex 7f3f1f56..d6d7969d 100644--- a/src-tauri/src/service/update/about.rs+++ b/src-tauri/src/service/update/about.rs@@ -1,6 +1,6 @@-//! About 对话框信息:版本来自编译常量,发布时间实时查询最新 Release(不缓存)。+//! About 对话框信息:版本来自编译常量,发布时间实时查询最新正式版 Release(不缓存)。-use super::meta::fetch_releases_meta;+use super::meta::fetch_latest_stable_published_at;use super::version::current_version;use super::{COPYRIGHT, POWERED_BY, REPO_URL};@@ -15,13 +15,11 @@ pub struct DesktopAboutInfo {pub powered_by: String,}-/// 关于信息:版本来自编译常量,发布时间每次实时查询最新 Release(不缓存),+/// 关于信息:版本来自编译常量,发布时间每次实时查询最新**正式版** Release(不缓存),/// 查询失败则留空、不影响展示。pub async fn about(app_handle: &tauri::AppHandle) -> DesktopAboutInfo {- let published_at = fetch_releases_meta(app_handle)+ let published_at = fetch_latest_stable_published_at(app_handle).await- .ok()- .and_then(|releases| releases.first().map(|(_, p)| p.clone())).unwrap_or_default();DesktopAboutInfo {version: current_version(),diff --git a/src-tauri/src/service/update/meta.rs b/src-tauri/src/service/update/meta.rsindex 4536db83..7abc734e 100644--- a/src-tauri/src/service/update/meta.rs+++ b/src-tauri/src/service/update/meta.rs@@ -7,6 +7,13 @@//! 更新判定只接受**正式版**(纯数字版本,见 [`super::version::is_stable`])://! rc/beta/alpha 等 pre-release 与手动测试 release(`test-*` tag)一律跳过,//! 用户不会收到非正式版的更新通知;装了 rc 的用户仍会按 semver 收到之后的正式版。+//!+//! 夜间构建(`nightly-YYYYMMDD` 的滚动 pre-release,见 `.github/workflows/release-nightly.yml`)+//! 同样被跳过,但 `releases.atom` 只保留最近 10 条:夜间版按天滚动后会把窗口占满,+//! 正式版全部被挤出,更新检查会静默失效(用户永远停在当前版本)。因此窗口里一条正式版+//! 都看不见时会再问一次 `/releases/latest`——该端点由 GitHub 保证指向最新正式版;若它+//! 恰好没有当前平台的安装包,再翻 `releases` 列表页(HTML,支持 `?page=`)继续找更旧的+//! 正式版——这是唯一能枚举历史的入口(atom feed 不接受 `?page=`,实测仍返回同一批 10 条)。use std::time::Duration;@@ -149,20 +156,16 @@ async fn fetch_expanded_assets(app_handle: &tauri::AppHandle, tag: &str) -> ResuOk((names, body))}-/// 查询最新可用的**正式版** Release(无缓存,每次实时检查,走 HTML/atom 而非-/// api.github.com)。+/// 从 atom feed 里筛出「严格高于当前版本的正式版」候选,按 feed 顺序(最新在前)。///-/// 按 feed 顺序(最新在前)扫描:跳过非法 semver(如手动测试 release 的-/// `test-*` tag)与 pre-release(rc/beta/alpha),只接受**纯数字正式版**且严格-/// 高于当前版本。首个命中即返回;当前平台无匹配安装包时继续看更旧的正式版。-///-/// 返回 `Ok(Some(LatestRelease))` 表示有更新且匹配到当前平台安装包;-/// `Ok(None)` 表示无更新(或未匹配到资产)。网络失败返回 Err。-pub(super) async fn fetch_latest_release(app_handle: &tauri::AppHandle) -> Result<Option<LatestRelease>, String> {- let current = current_version();- for (tag, published_at) in fetch_releases_meta(app_handle).await? {- let version = tag.trim_start_matches('v').to_string();- let Some(parsed) = parse_version(&version) else {+/// 同时回报窗口里是否出现过正式版:`releases.atom` 只保留最近 10 条,夜间版把窗口+/// 占满后该值为 false,调用方必须改用 `/releases/latest` 兜底。纯函数,便于测试。+fn stable_candidates(releases: &[(String, String)], current: &str) -> (Vec<(String, String)>, bool) {+ let mut candidates = Vec::new();+ let mut saw_stable = false;+ for (tag, published_at) in releases {+ let version = tag.trim_start_matches('v');+ let Some(parsed) = parse_version(version) else {log::debug!("UPDATE_SKIP: {tag} 非法 semver(手动测试 release?),跳过");continue;};@@ -170,17 +173,246 @@ pub(super) async fn fetch_latest_release(app_handle: &tauri::AppHandle) -> Resullog::debug!("UPDATE_SKIP: {tag} 为 pre-release(非正式版),不通知用户");continue;}- if !is_newer(&version, ¤t) {+ saw_stable = true;+ if !is_newer(version, current) {log::debug!("UPDATE_SKIP: {tag} 不高于当前版本 {current}");continue;}- if let Some(release) = fetch_release_assets(app_handle, &tag, &version, &published_at).await? {+ candidates.push((tag.clone(), published_at.clone()));+ }+ (candidates, saw_stable)+}++/// tag 是否为正式版(纯数字版本,`v` 前缀可选)——与 [`stable_candidates`] 同一套判定。+fn is_stable_tag(tag: &str) -> bool {+ parse_version(tag.trim_start_matches('v')).is_some_and(|parsed| is_stable(&parsed))+}++/// 从 `/releases/latest` 302 之后的最终 URL 解析 tag(纯函数,便于测试)。+///+/// 该端点由 GitHub 保证排除 pre-release 与草稿,解析结果必然是正式版 tag;tag 自带+/// `/` 的极端情况会被截断,本仓正式版 tag 形如 `v0.22.3`,不受影响。+fn parse_latest_tag(url: &str) -> Option<String> {+ const MARKER: &str = "/releases/tag/";+ let rest = &url[url.find(MARKER)? + MARKER.len()..];+ let end = rest+ .find(|c| matches!(c, '?' | '#' | '/'))+ .unwrap_or(rest.len());+ let tag = &rest[..end];+ (!tag.is_empty()).then(|| tag.to_string())+}++/// 从 releases 列表页(HTML,支持 `?page=N`)解析出现的 tag,按页面顺序去重。+///+/// `releases.atom` 只有最近 10 条且**不接受 `?page=`**(实测第 2 页与第 1 页内容相同),+/// 夜间版滚满窗口后 atom 里再也看不到正式版,而 `/releases/latest` 只能给一个 tag:+/// 当它没有当前平台安装包时,只有这个可翻页的 HTML 列表能继续往更旧的正式版找。+fn parse_release_listing_tags(html: &str) -> Vec<String> {+ const MARKER: &str = "/releases/tag/";+ let mut tags: Vec<String> = Vec::new();+ let mut from = 0;+ while let Some(offset) = html[from..].find(MARKER) {+ let start = from + offset + MARKER.len();+ let tail = &html[start..];+ // 形如 `…/releases/tag/v0.22.3"`(相对链接)或 `…/releases/tag/v0.22.3?expanded=true`+ let end = tail+ .find(|c: char| matches!(c, '"' | '\'' | '?' | '#' | '>'))+ .unwrap_or(tail.len());+ let tag = &tail[..end];+ if !tag.is_empty() && !tags.iter().any(|t| t == tag) {+ tags.push(tag.to_string());+ }+ // 必须前进:`end == 0` 时退回到 tag 起点,也至少比上一轮的 from 前进了一个 MARKER+ from = start + end;+ }+ tags+}++/// 从列表页解析出的 tag 里筛出可用的更旧正式版候选(最新在前),剔除已试过的 tag。+///+/// 与 [`stable_candidates`] 同一套过滤规则(非法 semver / pre-release / 不高于当前版本的+/// 全部跳过);差别是列表页只有相对时间,不值得为发布时间再多请求一次,故透传空串。+fn listed_stable_candidates(tags: &[String], current: &str, skip: &[String]) -> Vec<(String, String)> {+ tags.iter()+ .filter(|tag| !skip.iter().any(|s| tag == &s))+ .filter(|tag| is_stable_tag(tag) && is_newer(tag.trim_start_matches('v'), current))+ .map(|tag| (tag.clone(), String::new()))+ .collect()+}++/// 形如 `2026-10-06T16:11:01Z` 的 ISO-8601 UTC 时间戳。+fn is_iso_utc(value: &str) -> bool {+ let bytes = value.as_bytes();+ bytes.len() == 20+ && bytes[4] == b'-'+ && bytes[7] == b'-'+ && bytes[10] == b'T'+ && bytes[13] == b':'+ && bytes[16] == b':'+ && value.ends_with('Z')+ && value[..19]+ .bytes()+ .enumerate()+ .all(|(i, b)| matches!(i, 4 | 7 | 10 | 13 | 16) || b.is_ascii_digit())+}++/// 从 release 页面 HTML 解析发布时间:页面里第一个 ISO-8601 的 `datetime="…"`。+///+/// GitHub 在同一页里还会渲染提交时间等其它 `datetime`,其中展示用的那种形如+/// `2026-10-06 15:28:28 UTC`(不是 ISO),必须跳过,否则「发布日期」会取到提交时间。+fn parse_published_at(html: &str) -> Option<String> {+ const MARKER: &str = "datetime=\"";+ let mut rest = html;+ while let Some(pos) = rest.find(MARKER) {+ let tail = &rest[pos + MARKER.len()..];+ let end = tail.find('"')?;+ let value = &tail[..end];+ if is_iso_utc(value) {+ return Some(value.to_string());+ }+ rest = &tail[end..];+ }+ None+}++/// 查询 `/releases/latest`,返回最新正式版 tag(GitHub 侧已排除 pre-release 与草稿)。+///+/// 仓库一个正式版都没有时该端点直接 404:这是「无更新」而不是检查失败,必须返回+/// `Ok(None)`,否则界面会把「已是最新」显示成检查出错。+async fn fetch_latest_stable_tag(app_handle: &tauri::AppHandle) -> Result<Option<String>, String> {+ let response = http_client(app_handle)?+ .get(format!("{REPO_URL}/releases/latest"))+ .send()+ .await+ .map_err(|e| format!("UPDATE_LATEST: {e}"))?;+ if response.status() == reqwest::StatusCode::NOT_FOUND {+ return Ok(None);+ }+ let response = response+ .error_for_status()+ .map_err(|e| format!("UPDATE_LATEST: {e}"))?;+ Ok(parse_latest_tag(response.url().as_str()))+}++/// 翻 `releases` 列表页(HTML,支持 `?page=`)找比兜底候选更旧的可用正式版。+///+/// 一页只有 10 条且夜间版会占满前几页,因此逐页翻到出现候选为止(最多 `LISTING_PAGES`+/// 页)——第一页就可能拿到多个更旧的正式版,多了没有意义。返回空表示确实没有更旧的+/// 正式版(此时「没有可用更新」是正确结论,不是检查失败)。+async fn fetch_listed_stable_candidates(+ app_handle: &tauri::AppHandle,+ current: &str,+ skip: &[String],+) -> Result<Vec<(String, String)>, String> {+ const LISTING_PAGES: u32 = 3;+ let client = http_client(app_handle)?;+ let mut found: Vec<(String, String)> = Vec::new();+ for page in 1..=LISTING_PAGES {+ let body = client+ .get(format!("{REPO_URL}/releases?page={page}"))+ .send()+ .await+ .map_err(|e| format!("UPDATE_LISTING: {e}"))?+ .error_for_status()+ .map_err(|e| format!("UPDATE_LISTING: {e}"))?+ .text()+ .await+ .map_err(|e| format!("UPDATE_LISTING: {e}"))?;+ let tags = parse_release_listing_tags(&body);+ if tags.is_empty() {+ // 页面结构变化或已到末页:再翻下去只会重复拿到空列表+ break;+ }+ found.extend(listed_stable_candidates(&tags, current, skip));+ if !found.is_empty() {+ break;+ }+ }+ Ok(found)+}++/// 拉取某个 release 的 tag 页面并解析发布时间(解析不出来返回 `None`,不阻断更新检查)。+async fn fetch_tag_published_at(app_handle: &tauri::AppHandle, tag: &str) -> Result<Option<String>, String> {+ let body = http_client(app_handle)?+ .get(format!("{REPO_URL}/releases/tag/{tag}"))+ .send()+ .await+ .map_err(|e| format!("UPDATE_TAG: {e}"))?+ .error_for_status()+ .map_err(|e| format!("UPDATE_TAG: {e}"))?+ .text()+ .await+ .map_err(|e| format!("UPDATE_TAG: {e}"))?;+ Ok(parse_published_at(&body))+}++/// 按顺序(最新在前)返回首个在当前平台有匹配安装包的正式版。+///+/// 没有匹配安装包时继续看下一个候选(见 [`fetch_latest_release`] 的语义说明)。+async fn first_matching_release(+ app_handle: &tauri::AppHandle,+ candidates: Vec<(String, String)>,+) -> Result<Option<LatestRelease>, String> {+ for (tag, published_at) in candidates {+ let version = tag.trim_start_matches('v');+ if let Some(release) = fetch_release_assets(app_handle, &tag, version, &published_at).await? {return Ok(Some(release));}}Ok(None)}+/// 查询最新可用的**正式版** Release(无缓存,每次实时检查,走 HTML/atom 而非+/// api.github.com)。+///+/// 先按 feed 顺序(最新在前)扫描(见 [`stable_candidates`]):跳过非法 semver(如手动+/// 测试 release 的 `test-*` tag)、pre-release(rc/beta/夜间版)与不高于当前版本的 tag,+/// 首个命中的正式版即返回;当前平台无匹配安装包时继续看更旧的正式版。+///+/// feed 里一条正式版都看不见时(窗口被夜间版占满)改问 `/releases/latest`:GitHub 保证+/// 它指向最新正式版。只要窗口里看得见任一正式版,最新正式版必然也在窗口内,因此不必兜底+/// ——这条捷径也保证正式版没被挤出时,更新检查行为与旧实现完全一致。+///+/// 兜底候选(最新正式版)自己缺当前平台安装包时,两条路径的语义必须一致:继续往更旧的+/// 正式版找(`/releases/latest` 只给一个 tag,历史只能靠可翻页的列表页枚举),否则该平台+/// 会在夜间版占满窗口期间静默停在旧版本,用户永远收不到更新。+///+/// 返回 `Ok(Some(LatestRelease))` 表示有更新且匹配到当前平台安装包;+/// `Ok(None)` 表示无更新(或未匹配到资产)。网络失败返回 Err。+pub(super) async fn fetch_latest_release(app_handle: &tauri::AppHandle) -> Result<Option<LatestRelease>, String> {+ let current = current_version();+ let (candidates, saw_stable) = stable_candidates(&fetch_releases_meta(app_handle).await?, ¤t);++ // 窗口里看得见正式版:与旧实现完全一致,只按 feed 顺序找(最新正式版必在窗口内)+ if saw_stable {+ return first_matching_release(app_handle, candidates).await;+ }++ // 窗口被夜间版占满:先问 `/releases/latest`+ let mut fallback: Vec<(String, String)> = Vec::new();+ if let Some(tag) = fetch_latest_stable_tag(app_handle).await? {+ if is_stable_tag(&tag) && is_newer(tag.trim_start_matches('v'), ¤t) {+ // 发布时间只有 feed 正文才有:兜底路径不为它再多请求一次页面。该字段仅随+ // 更新信息透传给前端、界面不展示(关于对话框的发布日期走 `about.rs`)。+ fallback.push((tag, String::new()));+ } else {+ log::debug!("UPDATE_SKIP: {tag} 非可用正式版(非法/预发布/不高于 {current})");+ }+ }+ if fallback.is_empty() {+ // 一个正式版都没有(`/releases/latest` 404)或都不高于当前版本:确实没有更新+ return Ok(None);+ }+ let skip: Vec<String> = fallback.iter().map(|(tag, _)| tag.clone()).collect();+ if let Some(release) = first_matching_release(app_handle, fallback).await? {+ return Ok(Some(release));+ }++ // 兜底候选缺当前平台安装包:翻列表页继续找更旧的正式版+ let older = fetch_listed_stable_candidates(app_handle, ¤t, &skip).await?;+ first_matching_release(app_handle, older).await+}+/// 为选定的正式版 tag 挑选当前平台安装包并解析摘要。////// 摘要必须按**当前平台选中的资产**解析:多平台 release 的页面里每个安装包@@ -221,6 +453,31 @@ async fn fetch_release_assets(}))}+/// 最新**正式版**的发布时间(关于对话框的「发布日期」)。+///+/// feed 里混着 pre-release(rc/夜间版)且会被夜间版占满,直接取首条会把夜间版的构建+/// 时间当成正式版发布时间,因此必须先按 [`super::version::is_stable`] 过滤再取。+///+/// 窗口被夜间版占满时 feed 里一条正式版都没有:此时改问 `/releases/latest` 并读它自己的+/// tag 页面拿发布时间,否则「关于」对话框的发布日期会在整个夜间版周期里一直空着。+///+/// 首条正式版自己没带时间时同样补读它的 tag 页面:顺着列表往下找会显示更旧版本的日期。+pub(super) async fn fetch_latest_stable_published_at(app_handle: &tauri::AppHandle) -> Result<String, String> {+ let releases = fetch_releases_meta(app_handle).await?;+ if let Some((tag, published_at)) = releases.into_iter().find(|(tag, _)| is_stable_tag(tag)) {+ if !published_at.is_empty() {+ return Ok(published_at);+ }+ return Ok(fetch_tag_published_at(app_handle, &tag).await?.unwrap_or_default());+ }+ let Some(tag) = fetch_latest_stable_tag(app_handle).await? else {+ // 仓库一个正式版都没有:没有发布日期可显示+ return Ok(String::new());+ };+ // 页面结构解析不出来时保持旧行为(空串 → 界面显示 `-`),不把更新检查拖成错误+ Ok(fetch_tag_published_at(app_handle, &tag).await?.unwrap_or_default())+}+#[cfg(test)]mod tests {use super::*;@@ -320,4 +577,194 @@ mod tests {// 两个摘要必须不同才是「多资产 + 各自摘要」的有效回归用例assert_ne!(rpm_digest, picked_digest);}++ /// 回归:夜间版/滚动别名占满 feed 窗口时必须产出空候选,且 `saw_stable` 为 false+ /// —— 否则调用方不会走 `/releases/latest` 兜底,正式版用户的更新检查会静默失效+ /// (用户永远停在当前版本)。+ #[test]+ fn stable_candidates_reports_window_without_stable() {+ let nightlies: Vec<(String, String)> = (1..=10)+ .map(|day| {+ (+ format!("nightly-202610{day:02}"),+ format!("2026-10-{day:02}T18:00:00Z"),+ )+ })+ .collect();+ let (candidates, saw_stable) = stable_candidates(&nightlies, "0.22.3");+ assert!(candidates.is_empty());+ assert!(!saw_stable);++ // 滚动别名 tag(无日期)同样不参与判定,不得被误当成版本+ let mut mixed = nightlies.clone();+ mixed.insert(0, ("nightly".to_string(), "2026-10-11T18:00:00Z".to_string()));+ let (candidates, saw_stable) = stable_candidates(&mixed, "0.22.3");+ assert!(candidates.is_empty());+ assert!(!saw_stable);++ // 窗口里重新出现正式版:候选按 feed 顺序返回,且不再需要兜底+ mixed.push(("v0.22.4".to_string(), "2026-10-12T00:00:00Z".to_string()));+ let (candidates, saw_stable) = stable_candidates(&mixed, "0.22.3");+ assert_eq!(+ candidates,+ vec![("v0.22.4".to_string(), "2026-10-12T00:00:00Z".to_string())]+ );+ assert!(saw_stable);+ }++ /// 回归:rc/beta 与手动测试 tag 既不参与更新判定,也不影响「窗口里有正式版」的判定。+ #[test]+ fn stable_candidates_skips_prerelease_and_junk_tags() {+ let releases = vec![+ ("v0.23.0-rc.1".to_string(), "t1".to_string()),+ ("test-main-42".to_string(), "t2".to_string()),+ ("v0.22.3".to_string(), "t3".to_string()),+ ("v0.22.2".to_string(), "t4".to_string()),+ ];+ let (candidates, saw_stable) = stable_candidates(&releases, "0.22.3");+ assert!(candidates.is_empty());+ assert!(saw_stable);++ let (candidates, saw_stable) = stable_candidates(&releases, "0.22.2");+ assert_eq!(candidates, vec![("v0.22.3".to_string(), "t3".to_string())]);+ assert!(saw_stable);+ }++ /// `/releases/latest` 的最终 URL → tag;落到非 tag 页面时必须返回 None,不能猜一个 tag+ /// (无正式版时该端点 404,退回自身 URL 就是这种情况)。+ #[test]+ fn parse_latest_tag_reads_redirect_target() {+ assert_eq!(+ parse_latest_tag("https://github.com/x/y/releases/tag/v0.22.3").as_deref(),+ Some("v0.22.3")+ );+ assert_eq!(+ parse_latest_tag("https://github.com/x/y/releases/tag/v0.22.3?expanded=true").as_deref(),+ Some("v0.22.3")+ );+ assert_eq!(parse_latest_tag("https://github.com/x/y/releases/latest"), None);+ assert_eq!(parse_latest_tag("https://github.com/x/y/releases/tag/"), None);+ }++ /// 回归:`releases.atom` 不接受 `?page=`(实测第 2/3 页与第 1 页内容完全相同),夜间版+ /// 占满 10 条窗口后只能靠 HTML 列表页枚举历史正式版。解析要按页面顺序去重,不能把+ /// `releases/download/...` 之类的链接当成 tag,遇到空 tag 也不能原地打转。+ #[test]+ fn parse_release_listing_tags_extracts_unique_tags_in_order() {+ let html = r#"+ <a href="/x/y/releases/tag/nightly-20261007">n</a>+ <a href="/x/y/releases/tag/nightly">alias</a>+ <a href="/x/y/releases/tag/v0.22.3">a</a>+ <a href="/x/y/releases/tag/v0.22.3">dup</a>+ <a href="/x/y/releases/tag/v0.22.2?expanded=true">b</a>+ <a href="/x/y/releases/download/v0.22.2/x.dmg">asset</a>+ "#;+ assert_eq!(+ parse_release_listing_tags(html),+ vec!["nightly-20261007", "nightly", "v0.22.3", "v0.22.2"]+ );+ assert!(parse_release_listing_tags("").is_empty());+ assert!(parse_release_listing_tags(r#"<a href="/x/y/releases">list</a>"#).is_empty());+ assert!(parse_release_listing_tags(r#"<a href="/x/y/releases/tag/">x</a>"#).is_empty());+ }++ /// 回归:`/releases/latest` 只给一个 tag,它缺当前平台资产时要能继续枚举更旧的正式版。+ /// 候选过滤规则与 feed 路径一致,且必须剔除已经试过的 tag(否则会重复请求同一页面)。+ #[test]+ fn listed_stable_candidates_filters_and_skips_tried_tags() {+ let tags: Vec<String> = [+ "nightly-20261007",+ "nightly",+ "v0.23.0-rc.1",+ "test-main-42",+ "v0.22.3",+ "v0.22.2",+ "v0.22.1",+ ]+ .iter()+ .map(|tag| tag.to_string())+ .collect();+ let skip = vec!["v0.22.3".to_string()];+ assert_eq!(+ listed_stable_candidates(&tags, "0.22.0", &skip),+ vec![+ ("v0.22.2".to_string(), String::new()),+ ("v0.22.1".to_string(), String::new()),+ ]+ );+ // 不高于当前版本的一个都不返回:此时「没有更新」才是正确结论+ assert!(listed_stable_candidates(&tags, "0.22.3", &skip).is_empty());+ }++ /// 回归:release 页面里第一个 ISO 时间戳才是发布时间;同页展示用的+ /// `2026-10-06 15:28:28 UTC`(提交时间,非 ISO)不能被当成发布日期。+ #[test]+ fn parse_published_at_skips_display_only_datetimes() {+ let html = r#"<relative-time datetime="2026-10-06T16:11:01Z">last week</relative-time>+ <relative-time datetime="2026-10-06 15:28:28 UTC">committed</relative-time>"#;+ assert_eq!(parse_published_at(html).as_deref(), Some("2026-10-06T16:11:01Z"));+ // 页面结构变化时返回 None(调用方退回空串 → 界面显示 `-`),不猜一个时间+ assert_eq!(parse_published_at("<p>no datetime</p>"), None);+ assert_eq!(+ parse_published_at(r#"<p datetime="2026-10-06 15:28:28 UTC">x</p>"#),+ None+ );+ }++ /// 联网真实数据校验(默认 `#[ignore]`,不进 CI 门禁;CI 机器不依赖外网)。+ ///+ /// 手动运行:`cargo test --lib -- --ignored live_github_release_pages_are_parseable`+ /// 依次验证正式版更新链路依赖的 5 个端点——atom feed、`/releases/latest` 重定向、+ /// tag 页面发布时间、expanded_assets 资产清单、releases 列表页翻页。+ #[tokio::test]+ #[ignore = "联网测试:需手动 --ignored 运行,会访问真实 GitHub 页面"]+ async fn live_github_release_pages_are_parseable() {+ let client = reqwest::Client::builder()+ .user_agent("dsh-tauri-update-check-test")+ .timeout(std::time::Duration::from_secs(20))+ .build()+ .expect("构建测试用 HTTP 客户端失败");+ let fetch = |url: String| {+ let client = client.clone();+ async move {+ let response = client.get(url).send().await.expect("请求失败");+ assert!(response.status().is_success(), "HTTP {}", response.status());+ response.text().await.expect("读取正文失败")+ }+ };++ // 1) atom feed 仍能解析出 entry,且候选里的 tag 全部通过 is_stable 过滤+ let feed = fetch(format!("{REPO_URL}/releases.atom")).await;+ let entries = parse_atom_entries(&feed);+ assert!(!entries.is_empty(), "atom feed 解析不出 entry:页面结构可能已变化");+ let (candidates, _) = stable_candidates(&entries, "0.0.0");+ assert!(+ candidates.iter().all(|(tag, _)| is_stable_tag(tag)),+ "候选里混进了非正式版:{candidates:?}"+ );++ // 2) `/releases/latest` 跟随重定向后的 URL 能取出最新正式版 tag+ let response = client+ .get(format!("{REPO_URL}/releases/latest"))+ .send()+ .await+ .expect("请求 /releases/latest 失败");+ assert!(response.status().is_success(), "HTTP {}", response.status());+ let tag = parse_latest_tag(response.url().as_str()).expect("/releases/latest 未重定向到 tag 页面");+ assert!(is_stable_tag(&tag), "{tag} 不是正式版");++ // 3) tag 页面能解析出发布时间+ let page = fetch(format!("{REPO_URL}/releases/tag/{tag}")).await;+ assert!(parse_published_at(&page).is_some(), "解析不出 {tag} 的发布时间");++ // 4) expanded_assets 页面能列出该 release 的资产文件名+ let assets = fetch(format!("{REPO_URL}/releases/expanded_assets/{tag}")).await;+ let names = extract_asset_names(&assets, &tag);+ assert!(!names.is_empty(), "{tag} 的资产页解析不出文件名");++ // 5) 列表页能翻到更旧的正式版(兜底路径的枚举入口)+ let listing = fetch(format!("{REPO_URL}/releases?page=1")).await;+ let listed = listed_stable_candidates(&parse_release_listing_tags(&listing), "0.0.0", &[tag]);+ assert!(!listed.is_empty(), "列表页里找不到更旧的正式版");+ }}diff --git a/test/release-nightly.test.ts b/test/release-nightly.test.tsnew file mode 100644index 00000000..85c4dfee--- /dev/null+++ b/test/release-nightly.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest'+import { readSource } from './setup/read-source'++const WORKFLOW = '.github/workflows/release-nightly.yml'+const UPLOAD_STEPS = ['Upload assets to the draft release', 'Refresh rolling nightly alias']++function stepBody(source: string, name: string): string {+ const body = source.match(new RegExp(` {6}- name: ${name}\\n([\\s\\S]*?)(?=\\n {6}- |$)`))?.[1]+ expect(body, name).toBeTypeOf('string')+ return body ?? ''+}++describe('nightly release assets', () => {+ it('uploads assets without deleting any by file name', () => {+ const source = readSource(WORKFLOW)+ expect(source).not.toContain('delete-asset')+ for (const name of UPLOAD_STEPS) {+ const body = stepBody(source, name)+ expect(body, name).toContain('gh release upload')+ expect(body, name).toContain('--clobber')+ }+ })++ it('keeps downloaded assets outside the workspace that checkout wipes', () => {+ const lines = readSource(WORKFLOW)+ .split('\n')+ .filter(line => line.includes('release-assets') && !line.trimStart().startsWith('#'))+ expect(lines.length).toBeGreaterThan(3)+ for (const line of lines) {+ expect(line.includes('RUNNER_TEMP') || line.includes('runner.temp'), line).toBe(true)+ }+ })+})diff --git a/test/stamp-version.test.ts b/test/stamp-version.test.tsnew file mode 100644index 00000000..c5b7c327--- /dev/null+++ b/test/stamp-version.test.ts@@ -0,0 +1,163 @@+import { execFileSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterEach, describe, expect, it } from 'vitest'+import * as stampVersionModule from '../scripts/stamp-version.mjs'++interface StampResult {+ version: string+ files: string[]+}++interface StampVersionModule {+ stampCargoToml: (content: string, version: string, label: string) => string+ stampVersion: (repo: string, version: string) => StampResult+}++const stampVersionScript = fileURLToPath(new URL('../scripts/stamp-version.mjs', import.meta.url))+const stamp = stampVersionModule as StampVersionModule++const nightlyVersion = '0.22.3-nightly.20261007.abc1234'+const temporaryRepos: string[] = []++function readVersion(filePath: string) {+ return (JSON.parse(readFileSync(filePath, 'utf8')) as { version: string }).version+}++function writeRepo(versions: { packageJson: string, cargoToml: string, tauriConfig: string }) {+ const repo = mkdtempSync(path.join(tmpdir(), 'stamp-version-'))+ temporaryRepos.push(repo)+ mkdirSync(path.join(repo, 'src-tauri'))+ writeFileSync(path.join(repo, 'package.json'), [+ '{',+ ' "name": "deepseek-harness-desktop",',+ ` "version": "${versions.packageJson}",`,+ ' "private": true',+ '}',+ '',+ ].join('\n'))+ writeFileSync(path.join(repo, 'src-tauri', 'Cargo.toml'), [+ '[workspace.package]',+ 'version = "9.9.9"',+ '',+ '[dependencies]',+ 'version = "7.0.0"',+ '',+ '[package] # release identity',+ 'name = "deepseek-harness-desktop"',+ `version = "${versions.cargoToml}" # current release`,+ '',+ '[package.metadata.release]',+ 'version = "6.0.0"',+ '',+ ].join('\n'))+ writeFileSync(path.join(repo, 'src-tauri', 'tauri.conf.json'), [+ '{',+ ' "productName": "Deepseek Harness Desktop",',+ ` "version": "${versions.tauriConfig}",`,+ ' "identifier": "dsh-tauri",',+ ' "bundle": {',+ ' "active": true,',+ ' "targets": "all"',+ ' }',+ '}',+ '',+ ].join('\n'))+ return repo+}++afterEach(() => {+ for (const repo of temporaryRepos.splice(0))+ rmSync(repo, { recursive: true, force: true })+})++describe('nightly version stamping', () => {+ it('stamps the injected version into every release file and reports them', () => {+ const repo = writeRepo({ packageJson: '0.22.3', cargoToml: '0.22.3', tauriConfig: '0.22.3' })++ expect(stamp.stampVersion(repo, nightlyVersion)).toEqual({+ version: nightlyVersion,+ files: ['package.json', 'src-tauri/Cargo.toml', 'src-tauri/tauri.conf.json'],+ })++ expect(readVersion(path.join(repo, 'package.json'))).toBe(nightlyVersion)+ expect(readVersion(path.join(repo, 'src-tauri', 'tauri.conf.json'))).toBe(nightlyVersion)++ const cargo = readFileSync(path.join(repo, 'src-tauri', 'Cargo.toml'), 'utf8')+ expect(cargo).toContain(`version = "${nightlyVersion}" # current release`)+ expect(cargo).toContain('version = "9.9.9"')+ expect(cargo).toContain('version = "7.0.0"')+ expect(cargo).toContain('version = "6.0.0"')+ })++ it('rewrites only the Cargo [package] version', () => {+ const stamped = stamp.stampCargoToml([+ '[workspace.package]',+ 'version = "9.9.9"',+ '',+ '[package]',+ 'name = "desktop"',+ 'version = "0.22.3"',+ '',+ ].join('\n'), nightlyVersion, 'src-tauri/Cargo.toml')++ expect(stamped).toBe([+ '[workspace.package]',+ 'version = "9.9.9"',+ '',+ '[package]',+ 'name = "desktop"',+ `version = "${nightlyVersion}"`,+ '',+ ].join('\n'))+ })++ it('keeps CRLF line endings', () => {+ const stamped = stamp.stampCargoToml(+ '[package]\r\nname = "desktop"\r\nversion = "0.22.3"\r\n',+ nightlyVersion,+ 'src-tauri/Cargo.toml',+ )+ expect(stamped).toBe(`[package]\r\nname = "desktop"\r\nversion = "${nightlyVersion}"\r\n`)+ })++ it('stamps through the CLI entry point using GITHUB_WORKSPACE', () => {+ const repo = writeRepo({ packageJson: '0.22.3', cargoToml: '0.22.3', tauriConfig: '0.22.3' })++ const stdout = execFileSync(process.execPath, [stampVersionScript, nightlyVersion], {+ cwd: tmpdir(),+ env: { ...process.env, GITHUB_WORKSPACE: repo },+ encoding: 'utf8',+ })++ expect(stdout.trim()).toBe(+ `STAMP_VERSION: package.json, src-tauri/Cargo.toml, src-tauri/tauri.conf.json -> ${nightlyVersion}`,+ )+ expect(readVersion(path.join(repo, 'package.json'))).toBe(nightlyVersion)+ })++ it('rejects a version equal to the checked-out release version', () => {+ const repo = writeRepo({ packageJson: '0.22.3', cargoToml: '0.22.3', tauriConfig: '0.22.3' })+ expect(() => stamp.stampVersion(repo, '0.22.3')).toThrow(+ /^STAMP_VERSION: stamped version 0\.22\.3 equals the checked-out release version$/,+ )+ })++ it.each(['v0.22.3', '0.22.3-nightly.01.abc1234', '0.22.3-nightly.20261007+'])(+ 'rejects the non-SemVer version %s',+ (version) => {+ const repo = writeRepo({ packageJson: '0.22.3', cargoToml: '0.22.3', tauriConfig: '0.22.3' })+ expect(() => stamp.stampVersion(repo, version)).toThrow(+ /^STAMP_VERSION: stamped version is not strict SemVer 2\.0/,+ )+ },+ )++ it('rejects mismatched release files before writing anything', () => {+ const repo = writeRepo({ packageJson: '0.22.3', cargoToml: '0.22.4', tauriConfig: '0.22.3' })+ expect(() => stamp.stampVersion(repo, nightlyVersion)).toThrow(/release versions do not match/)+ expect(readVersion(path.join(repo, 'package.json'))).toBe('0.22.3')+ })+})