DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ci): 新增夜间构建流水线并补齐更新检查兜底
hairyf50b6efdfe9da
diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.ymlindex 192751b7..f81df649 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,10 @@ jobs:- name: Install frontend dependenciesrun: pnpm install --frozen-lockfile+ - name: Stamp injected version+ if: inputs.version != ''+ run: node scripts/stamp-version.mjs "${{ inputs.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..162e29c9 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,10 @@ 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 != ''+ run: node scripts/stamp-version.mjs "${{ inputs.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..410bd5e9 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,10 @@ jobs:- name: Install frontend dependenciesrun: pnpm install --frozen-lockfile+ - name: Stamp injected version+ if: inputs.version != ''+ run: node scripts/stamp-version.mjs "${{ inputs.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..032c96c9--- /dev/null+++ b/.github/workflows/release-nightly.yml@@ -0,0 +1,295 @@+name: Build & Release (Nightly)++# 夜间版(dig-node 形态):滚动发布 main 的每日构建,保留最近 N 天。+# - 版本号在 CI 期合成、不入库:`<package.json version>-nightly.<YYYYMMDD>.<短 sha>`。+# semver 上 `0.22.3-nightly.*` 低于同号正式版 0.22.3,装夜间版的人仍会收到之后的正式版更新。+# - 每次构建只写两个 Release:当日日期 tag(nightly-YYYYMMDD,独立资产)与滚动别名+# nightly(强制指向本次提交、同步同一批资产),两者都是 pre-release,永不成为 latest。+# - workflow 名称故意**不等于** "Build & Release":release-bundle.yml 用 workflow_run+# 监听正式流水线,夜间构建不应触发离线捆绑包。+on:+ # UTC 18:00 = 北京时间次日 02:00,构建完正好接上国内早晨。+ # 注意:仓库连续 60 天无活动后 GitHub 会自动停用 schedule 触发器且不会自动恢复,+ # 届时用 `gh workflow enable "Build & Release (Nightly)"` 重新启用。+ schedule:+ - cron: '0 18 * * *'+ workflow_dispatch:+ inputs:+ force:+ description: 忽略「main 无新提交即跳过」,强制重新构建+ required: false+ default: false+ type: boolean++permissions:+ contents: write++concurrency:+ group: release-nightly+ cancel-in-progress: false++env:+ # 保留窗口:含当天在内最近 N 天(每日一版即 N 个日期 Release),更早的连 tag 一起删除。+ NIGHTLY_RETAIN_DAYS: '10'++jobs:+ prepare:+ name: Prepare Nightly+ runs-on: ubuntu-latest+ 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:+ # 夜间版只代表 main:dispatch 时即使选了别的分支也固定检出默认分支,+ # 避免把特性分支的提交塞进日期 tag 的版本号里。+ - name: Checkout default branch+ uses: actions/checkout@v7+ with:+ ref: ${{ github.event.repository.default_branch }}+ fetch-depth: 1++ - name: Setup Node.js and pnpm+ uses: ./.github/actions/setup-node-pnpm++ - name: Plan nightly version+ id: plan+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ GH_REPO: ${{ github.repository }}+ FORCE: ${{ github.event_name == 'workflow_dispatch' && inputs.force || 'false' }}+ run: |+ set -euo pipefail+ short_sha="$(git rev-parse --short=7 HEAD)"+ # 前导零的纯数字短 sha(如 0123456)不是合法 semver 标识符(数字段禁止前导零),+ # 补一个字母前缀,免得 stamp-version.mjs 判成非法版本、整条夜间流水线中断。+ if [[ "$short_sha" =~ ^0[0-9]+$ ]]; then short_sha="g$short_sha"; fi+ source_ref="$(git rev-parse HEAD)"+ base_version="$(node -p "require('./package.json').version")"+ date="$(date -u +%Y%m%d)"+ tag="nightly-$date"+ version="$base_version-nightly.$date.$short_sha"+ should_build=true++ if [ "$FORCE" != "true" ]; then+ # main 没动就跳过:夜间版的唯一价值是多带出正式版之后的提交,重复构建白烧+ # runner 且会刷新资产名。上一版夜间版的提交 SHA 记在 Release 正文的标记里。+ last_tag="$(gh release list --limit 100 --json tagName -q '.[].tagName' | sed -n 's/^\(nightly-[0-9]\{8\}\)$/\1/p' | sort | tail -1)"+ 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++ 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 }}++ # 单一 writer:只有三平台全部构建成功才发布,避免出现「半套资产」的夜间版。+ 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+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ # finalize 未 checkout,gh 无法从 .git 推断仓库,需显式指定。+ GH_REPO: ${{ github.repository }}+ NIGHTLY_TAG: ${{ needs.prepare.outputs.tag }}+ NIGHTLY_VERSION: ${{ needs.prepare.outputs.version }}+ NIGHTLY_SHA: ${{ needs.prepare.outputs.source_ref }}+ # 夜间版 Release 描述(唯一出处,日期版与滚动别名共用),动态信息由各步骤追加在后面。+ NIGHTLY_DESCRIPTION: |+ ## ⚠️重要通知+ 这是专为测试目的创建的**开发构建版本**。请注意:++ - 此版本**不适用于**生产环境+ - 功能可能不完整或不稳定+ - 仅用于在桌面环境中验证 PR 更改+ - 可能包含尚未经过全面审查的实验性代码+ - 不提供任何稳定性或可靠性方面的保证++ ## 预期用途+ - 针对 PR 变更进行重点测试+ - 验证桌面特定行为+ - 桌面平台上的 UI/UX 验证+ - 在目标设备上进行性能测试++ 如发现任何问题,请直接提交 issue 报告。+ steps:+ - name: Download build outputs+ uses: actions/download-artifact@v7+ with:+ pattern: release-*+ path: release-assets+ merge-multiple: true++ - name: Verify downloaded assets+ run: |+ find release-assets -type f -print+ [ -n "$(find release-assets -type f -print -quit)" ] || {+ echo '::error::No nightly assets were downloaded'+ exit 1+ }++ - name: Publish dated nightly release+ run: |+ set -euo pipefail+ if ! gh release view "$NIGHTLY_TAG" >/dev/null 2>&1; then+ gh release create "$NIGHTLY_TAG" --draft --target "$NIGHTLY_SHA" \+ --title "Nightly $NIGHTLY_VERSION" --prerelease+ fi+ mapfile -d '' assets < <(find release-assets -type f -print0)+ gh release upload "$NIGHTLY_TAG" "${assets[@]}" --clobber++ # 同一天重复构建(main 又推进了)会换版本号,旧版本的资产名与新版不同、clobber+ # 覆盖不掉,而客户端的 pick_asset 是「按文件名模式取第一个匹配」,留着会取到旧包。+ new_names="$(cd release-assets && find . -type f -printf '%f\n')"+ gh release view "$NIGHTLY_TAG" --json assets -q '.assets[].name' | while read -r name; do+ [ -n "$name" ] || continue+ grep -qxF "$name" <<< "$new_names" || gh release delete-asset "$NIGHTLY_TAG" "$name" --yes+ done++ # 构建时间必须写进正文:Release 的 published_at 只在 tag 首次创建时更新,+ # 同日重建不会变,只有正文里的时间是真实的构建新鲜度信号。+ cat > nightly_notes.md << EOF+ $NIGHTLY_DESCRIPTION++ - 版本:\`$NIGHTLY_VERSION\`+ - 提交:\`$NIGHTLY_SHA\`+ - 构建时间:$(date -u '+%Y-%m-%d %H:%M UTC')++ <!-- nightly-sha:$NIGHTLY_SHA -->+ EOF+ gh release edit "$NIGHTLY_TAG" --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+ if ! gh release view nightly >/dev/null 2>&1; then+ gh release create nightly --draft --target "$NIGHTLY_SHA" \+ --title "Nightly (latest)" --prerelease+ fi+ mapfile -d '' assets < <(find release-assets -type f -print0)+ gh release upload nightly "${assets[@]}" --clobber++ # 别名始终只保留最新一版的资产:旧的 clobber 不掉,且会让按文件名取包的客户端选错版本。+ new_names="$(cd release-assets && find . -type f -printf '%f\n')"+ gh release view nightly --json assets -q '.assets[].name' | while read -r name; do+ [ -n "$name" ] || continue+ grep -qxF "$name" <<< "$new_names" || gh release delete-asset nightly "$name" --yes+ done++ {+ echo "$NIGHTLY_DESCRIPTION"+ echo+ echo "- 最新版本:\`$NIGHTLY_VERSION\`"+ echo "- 提交:\`$NIGHTLY_SHA\`"+ echo "- 构建时间:$(date -u '+%Y-%m-%d %H:%M UTC')"+ echo+ echo "### 最近 $NIGHTLY_RETAIN_DAYS 天"+ echo+ echo "| 日期 (UTC) | 版本 | Release |"+ echo "| :--- | :--- | :--- |"+ gh release list --limit 100 --json tagName,name -q '.[] | select(.tagName | test("^nightly-[0-9]{8}$")) | "\(.tagName)|\(.name)"' |+ sort -r |+ while IFS='|' read -r tag name; do+ [ -n "$tag" ] || continue+ day="${tag#nightly-}"+ echo "| ${day:0:4}-${day:4:2}-${day:6:2} | ${name#Nightly } | [下载](https://github.com/$GH_REPO/releases/tag/$tag) |"+ done+ echo+ echo "<!-- nightly-sha:$NIGHTLY_SHA -->"+ } > nightly_alias_notes.md++ gh release edit nightly --notes-file nightly_alias_notes.md \+ --draft=false --prerelease --latest=false++ # 别名必须先有 tag 再改指:github-script 走 API 强制移动 tag(release.yml 建 tag 的同一手法),+ # 不用删 Release 重建,因此 `releases/download/nightly/...` 的下载链接不会出现 404 空窗。+ - name: Point rolling nightly 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) throw error;+ await github.rest.git.createRef({ ...context.repo, ref: `refs/${ref}`, sha });+ }diff --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..fc6cfa1e 100644--- a/src-tauri/src/service/update/meta.rs+++ b/src-tauri/src/service/update/meta.rs@@ -7,6 +7,11 @@//! 更新判定只接受**正式版**(纯数字版本,见 [`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 保证指向最新正式版。use std::time::Duration;@@ -149,20 +154,16 @@ async fn fetch_expanded_assets(app_handle: &tauri::AppHandle, tag: &str) -> ResuOk((names, body))}-/// 查询最新可用的**正式版** Release(无缓存,每次实时检查,走 HTML/atom 而非-/// api.github.com)。-///-/// 按 feed 顺序(最新在前)扫描:跳过非法 semver(如手动测试 release 的-/// `test-*` tag)与 pre-release(rc/beta/alpha),只接受**纯数字正式版**且严格-/// 高于当前版本。首个命中即返回;当前平台无匹配安装包时继续看更旧的正式版。+/// 从 atom feed 里筛出「严格高于当前版本的正式版」候选,按 feed 顺序(最新在前)。///-/// 返回 `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,11 +171,83 @@ 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)+}++/// 从 `/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/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()))+}++/// 查询最新可用的**正式版** Release(无缓存,每次实时检查,走 HTML/atom 而非+/// api.github.com)。+///+/// 先按 feed 顺序(最新在前)扫描(见 [`stable_candidates`]):跳过非法 semver(如手动+/// 测试 release 的 `test-*` tag)、pre-release(rc/beta/夜间版)与不高于当前版本的 tag,+/// 首个命中的正式版即返回;当前平台无匹配安装包时继续看更旧的正式版。+///+/// feed 里一条正式版都看不见时(窗口被夜间版占满)改问 `/releases/latest`:GitHub 保证+/// 它指向最新正式版。只要窗口里看得见任一正式版,最新正式版必然也在窗口内,因此不必兜底+/// ——这条捷径也保证正式版没被挤出时,更新检查行为与旧实现完全一致。+///+/// 返回 `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 (mut candidates, saw_stable) =+ stable_candidates(&fetch_releases_meta(app_handle).await?, ¤t);++ if !saw_stable {+ if let Some(tag) = fetch_latest_stable_tag(app_handle).await? {+ let version = tag.trim_start_matches('v');+ if parse_version(version).is_some_and(|parsed| is_stable(&parsed)) && is_newer(version, ¤t) {+ // 发布时间只有 feed 正文才有:兜底路径不为它再多请求一次页面。该字段仅随+ // 更新信息透传给前端、界面不展示(关于对话框的发布日期走 `about.rs`)。+ candidates.push((tag, String::new()));+ } else {+ log::debug!("UPDATE_SKIP: {tag} 非可用正式版(非法/预发布/不高于 {current})");+ }+ }+ }++ 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));}}@@ -221,6 +294,21 @@ async fn fetch_release_assets(}))}+/// 最新**正式版**在 atom feed 里的发布时间(关于对话框的「发布日期」)。+///+/// feed 里混着 pre-release(rc/夜间版)且会被夜间版占满,直接取首条会把夜间版的构建+/// 时间当成正式版发布时间,因此必须先按 [`super::version::is_stable`] 过滤再取。+pub(super) async fn fetch_latest_stable_published_at(app_handle: &tauri::AppHandle) -> Result<String, String> {+ let releases = fetch_releases_meta(app_handle).await?;+ Ok(releases+ .into_iter()+ .find(|(tag, _)| {+ parse_version(tag.trim_start_matches('v')).is_some_and(|parsed| is_stable(&parsed))+ })+ .map(|(_, published_at)| published_at)+ .unwrap_or_default())+}+#[cfg(test)]mod tests {use super::*;@@ -320,4 +408,72 @@ 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);+ }}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')+ })+})