diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.ts index ec64177..fac5f12 100644 --- a/src/cli/commands/update.test.ts +++ b/src/cli/commands/update.test.ts @@ -118,3 +118,71 @@ describe("getMirrorMode routing", () => { // Restore env process.env = originalEnv; }); + +describe("update command bgSave and cache integration", () => { + test("bgSave option saves cache silently without stdout output", async () => { + const { mkdtempSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { handleUpdateCommand } = await import("./update.js"); + const { loadUpdateCache, UPDATE_CACHE_FILE_ENV } = await import("../../core/update-cache.js"); + + const tempDir = mkdtempSync(join(tmpdir(), "seal-use-bg-save-test-")); + const tempCacheFile = join(tempDir, "update-cache.json"); + const prevEnv = process.env[UPDATE_CACHE_FILE_ENV]; + process.env[UPDATE_CACHE_FILE_ENV] = tempCacheFile; + + try { + const mockRuntime = { + appRoot: process.cwd(), + entryFile: join(process.cwd(), "src/cli.ts") + }; + + // Mock fetch to avoid real network calls during test + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => + new Response( + JSON.stringify([ + { + tag_name: "v0.10.99", + published_at: "2026-09-20T12:00:00Z", + html_url: "https://github.com/yunyingk/seal-use/releases/tag/v0.10.99", + assets: [] + } + ]), + { status: 200, headers: { "Content-Type": "application/json" } } + )) as any; + + let stdoutCaptured = ""; + const originalLog = console.log; + console.log = (msg: string) => { + stdoutCaptured += msg; + }; + + try { + await handleUpdateCommand(mockRuntime, { + checkOnly: true, + bgSave: true + }); + + // bgSave should NOT print to stdout + expect(stdoutCaptured).toBe(""); + + // Cache should be saved with latestVersion + const cache = loadUpdateCache(tempCacheFile); + expect(cache).not.toBeNull(); + expect(cache?.latestVersion).toBe("0.10.99"); + expect(cache?.publishedAt).toBe("2026-09-20T12:00:00Z"); + } finally { + globalThis.fetch = originalFetch; + console.log = originalLog; + } + } finally { + if (prevEnv !== undefined) { + process.env[UPDATE_CACHE_FILE_ENV] = prevEnv; + } else { + delete process.env[UPDATE_CACHE_FILE_ENV]; + } + rmSync(tempDir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 87245e1..ddcdeea 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -3,6 +3,7 @@ import { basename, dirname, join } from "node:path"; import { spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; import { readInstalledSkillVersion } from "../../core/embedded-skill.js"; +import { saveUpdateCache } from "../../core/update-cache.js"; import { VERSION, IS_RELEASE } from "../../version.js"; import { runServiceCommand, serviceStatus } from "../service.js"; import { printJson } from "../printer.js"; @@ -23,6 +24,7 @@ export type UpdateOptions = { force?: boolean; targetVersion?: string; repo?: string; + bgSave?: boolean; }; export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) { @@ -103,6 +105,18 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp const isUpgrade = isNewerVersion(latestVersion, VERSION); const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION)); + if (latestRelease?.version) { + saveUpdateCache({ + latestVersion: latestRelease.version, + publishedAt: latestRelease.publishedAt, + releaseUrl: latestRelease.htmlUrl + }); + } + + if (options.bgSave) { + return; + } + printJson({ updated: false, updateAvailable: isUpgrade, @@ -174,6 +188,18 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp const shouldUpdate = isUpgrade || Boolean(options.force); const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION)); + if (release?.version) { + saveUpdateCache({ + latestVersion: release.version, + publishedAt: release.publishedAt, + releaseUrl: release.htmlUrl + }); + } + + if (options.bgSave) { + return; + } + if (options.checkOnly) { printJson({ updated: false, @@ -277,6 +303,12 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp // function returns, and nothing is left running. const skillSync = installSkillFromInstalledBinary(execPath, latestVersion); + saveUpdateCache({ + latestVersion, + publishedAt: release.publishedAt, + releaseUrl: release.htmlUrl + }); + printJson({ updated: true, fromVersion: VERSION, diff --git a/src/cli/runner.test.ts b/src/cli/runner.test.ts index 9bf3f0f..ee19df5 100644 --- a/src/cli/runner.test.ts +++ b/src/cli/runner.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, test } from "bun:test"; import { runCli } from "./runner.js"; +import { saveUpdateCache, UPDATE_CACHE_FILE_ENV } from "../core/update-cache.js"; describe("CLI runner", () => { test("returns version output without touching the process lifecycle", async () => { @@ -98,4 +99,49 @@ describe("CLI runner", () => { expect(result.stderr).not.toContain("is an alias for 'seal-use update'"); expect(JSON.parse(result.stdout)).toMatchObject({ updated: false, targetVersion: "0.3.3" }); }); + + test("version output enriches with cache and alerts on newer version via stderr", async () => { + const tempDir = mkdtempSync(join(tmpdir(), "seal-use-version-test-")); + const tempCacheFile = join(tempDir, "update-cache.json"); + const prevEnv = process.env[UPDATE_CACHE_FILE_ENV]; + process.env[UPDATE_CACHE_FILE_ENV] = tempCacheFile; + + try { + // 1. Without cache: plain version output + const coldResult = await runCli(["version"]); + expect(coldResult.exitCode).toBe(0); + expect(coldResult.stderr).toBe(""); + const coldJson = JSON.parse(coldResult.stdout); + expect(coldJson.name).toBe("seal-use"); + expect(coldJson.latestVersion).toBeUndefined(); + + // 2. With cache (newer version available) + saveUpdateCache( + { + latestVersion: "99.0.0", + publishedAt: "2026-09-20T12:00:00Z", + releaseUrl: "https://github.com/yunyingk/seal-use/releases/tag/v99.0.0" + }, + tempCacheFile + ); + + const warmResult = await runCli(["version"]); + expect(warmResult.exitCode).toBe(0); + expect(warmResult.stderr).toContain("💡 发现新版本可用:"); + expect(warmResult.stderr).toContain("99.0.0"); + expect(warmResult.stderr).toContain("👉 Next action: seal-use update"); + + const warmJson = JSON.parse(warmResult.stdout); + expect(warmJson.latestVersion).toBe("99.0.0"); + expect(warmJson.updateAvailable).toBe(true); + expect(typeof warmJson.lastCheckedAt).toBe("string"); + } finally { + if (prevEnv !== undefined) { + process.env[UPDATE_CACHE_FILE_ENV] = prevEnv; + } else { + delete process.env[UPDATE_CACHE_FILE_ENV]; + } + rmSync(tempDir, { recursive: true, force: true }); + } + }); }); diff --git a/src/cli/runner.ts b/src/cli/runner.ts index eff583c..fc51bd2 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -32,7 +32,8 @@ import { handleSourceCommand } from "./commands/source.js"; import { handleTestCommand } from "./commands/test.js"; import { handleToolCommand } from "./commands/tool.js"; import { handleToolsListCommand } from "./commands/tools.js"; -import { handleUpdateCommand } from "./commands/update.js"; +import { handleUpdateCommand, isNewerVersion } from "./commands/update.js"; +import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js"; import { handleUsersCommand } from "./commands/users.js"; import { handleWebhookCommand, @@ -194,7 +195,30 @@ async function dispatch(argv: string[], runtime: CliRuntime) { Boolean(args.options.v) || Boolean(args.options.V) ) { - printJson(VERSION_INFO); + const cache = loadUpdateCache(); + const isUpgrade = cache?.latestVersion ? isNewerVersion(cache.latestVersion, VERSION_INFO.version) : false; + + const payload = { + ...VERSION_INFO, + ...(cache?.latestVersion + ? { + latestVersion: cache.latestVersion, + updateAvailable: isUpgrade, + lastCheckedAt: cache.checkedAt + } + : {}) + }; + + if (isUpgrade && cache?.latestVersion) { + console.error(`💡 发现新版本可用: v${VERSION_INFO.version} -> v${cache.latestVersion}`); + console.error(`👉 Next action: seal-use update\n`); + } + + printJson(payload); + + if (isUpdateCacheExpired(cache)) { + triggerBackgroundUpdateCheck(runtime.launcher); + } return; } @@ -292,18 +316,23 @@ async function dispatch(argv: string[], runtime: CliRuntime) { booleanOption(args.options.check) === true || booleanOption(args.options["check-only"]) === true; + const isBgSave = + booleanOption(args.options["bg-save"]) === true || + booleanOption(args.options["silent-save"]) === true; + const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? - (!isChangelog && !isCheck && action && !action.startsWith("-") ? action : undefined); + (!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined); await handleUpdateCommand(runtime, { - checkOnly: isCheck, + checkOnly: isCheck || isBgSave, changelogOnly: isChangelog, limit: numberOption(args.options.limit), force: booleanOption(args.options.force), targetVersion, - repo: stringOption(args.options.repo) + repo: stringOption(args.options.repo), + bgSave: isBgSave }); return; } diff --git a/src/core/update-cache.test.ts b/src/core/update-cache.test.ts new file mode 100644 index 0000000..141aa81 --- /dev/null +++ b/src/core/update-cache.test.ts @@ -0,0 +1,122 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + isUpdateCacheExpired, + loadUpdateCache, + resolveUpdateCacheFilePath, + saveUpdateCache, + triggerBackgroundUpdateCheck, + UPDATE_CACHE_FILE_ENV, + type UpdateCacheData +} from "./update-cache.js"; + +describe("update-cache", () => { + const originalEnv = process.env[UPDATE_CACHE_FILE_ENV]; + const originalDisable = process.env.SEAL_DISABLE_BG_UPDATE; + const originalNodeEnv = process.env.NODE_ENV; + const originalCi = process.env.CI; + let testDir: string; + let testCacheFile: string; + + beforeEach(() => { + testDir = join(tmpdir(), `seal-use-update-cache-test-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`); + mkdirSync(testDir, { recursive: true }); + testCacheFile = join(testDir, "update-cache.json"); + process.env[UPDATE_CACHE_FILE_ENV] = testCacheFile; + }); + + afterEach(() => { + if (originalEnv !== undefined) { + process.env[UPDATE_CACHE_FILE_ENV] = originalEnv; + } else { + delete process.env[UPDATE_CACHE_FILE_ENV]; + } + if (originalDisable !== undefined) { + process.env.SEAL_DISABLE_BG_UPDATE = originalDisable; + } else { + delete process.env.SEAL_DISABLE_BG_UPDATE; + } + if (originalNodeEnv !== undefined) { + process.env.NODE_ENV = originalNodeEnv; + } else { + delete process.env.NODE_ENV; + } + if (originalCi !== undefined) { + process.env.CI = originalCi; + } else { + delete process.env.CI; + } + + try { + rmSync(testDir, { recursive: true, force: true }); + } catch { + // ignore + } + }); + + test("resolves custom file path from environment variable", () => { + expect(resolveUpdateCacheFilePath()).toBe(testCacheFile); + }); + + test("loadUpdateCache returns null when file does not exist", () => { + expect(loadUpdateCache(testCacheFile)).toBeNull(); + }); + + test("loadUpdateCache returns null when file contains invalid json or missing fields", () => { + writeFileSync(testCacheFile, "invalid json"); + expect(loadUpdateCache(testCacheFile)).toBeNull(); + + writeFileSync(testCacheFile, JSON.stringify({ wrongField: 123 })); + expect(loadUpdateCache(testCacheFile)).toBeNull(); + }); + + test("saveUpdateCache writes atomically and loadUpdateCache reads correctly", () => { + const data = { + latestVersion: "0.10.33", + publishedAt: "2026-09-20T12:00:00Z", + releaseUrl: "https://github.com/yunyingk/seal-use/releases/tag/v0.10.33" + }; + + saveUpdateCache(data, testCacheFile); + expect(existsSync(testCacheFile)).toBe(true); + + const loaded = loadUpdateCache(testCacheFile); + expect(loaded).not.toBeNull(); + expect(loaded?.latestVersion).toBe("0.10.33"); + expect(loaded?.publishedAt).toBe("2026-09-20T12:00:00Z"); + expect(loaded?.releaseUrl).toBe("https://github.com/yunyingk/seal-use/releases/tag/v0.10.33"); + expect(typeof loaded?.checkedAt).toBe("string"); + }); + + test("isUpdateCacheExpired detects null, missing checkedAt, and expired timestamps", () => { + expect(isUpdateCacheExpired(null)).toBe(true); + expect(isUpdateCacheExpired({ latestVersion: "1.0.0", checkedAt: "invalid" })).toBe(true); + + const fresh: UpdateCacheData = { + latestVersion: "1.0.0", + checkedAt: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString() // 2 hours ago + }; + expect(isUpdateCacheExpired(fresh, 24 * 60 * 60 * 1000)).toBe(false); + + const expired: UpdateCacheData = { + latestVersion: "1.0.0", + checkedAt: new Date(Date.now() - 1000 * 60 * 60 * 25).toISOString() // 25 hours ago + }; + expect(isUpdateCacheExpired(expired, 24 * 60 * 60 * 1000)).toBe(true); + }); + + test("triggerBackgroundUpdateCheck respects test/CI environment guards", () => { + process.env.SEAL_DISABLE_BG_UPDATE = "1"; + expect(triggerBackgroundUpdateCheck({ command: "bun" })).toBe(false); + + delete process.env.SEAL_DISABLE_BG_UPDATE; + process.env.NODE_ENV = "test"; + expect(triggerBackgroundUpdateCheck({ command: "bun" })).toBe(false); + + delete process.env.NODE_ENV; + process.env.CI = "true"; + expect(triggerBackgroundUpdateCheck({ command: "bun" })).toBe(false); + }); +}); diff --git a/src/core/update-cache.ts b/src/core/update-cache.ts new file mode 100644 index 0000000..084e3ca --- /dev/null +++ b/src/core/update-cache.ts @@ -0,0 +1,108 @@ +import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { spawn } from "node:child_process"; +import type { LauncherConfig } from "./runtime.js"; + +export const UPDATE_CACHE_FILE_ENV = "SEAL_USE_UPDATE_CACHE_FILE"; +export const DEFAULT_UPDATE_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours + +const DEFAULT_UPDATE_CACHE_FILE = join(homedir(), ".config", "seal-use", "update-cache.json"); + +export interface UpdateCacheData { + checkedAt: string; + latestVersion: string; + publishedAt?: string; + releaseUrl?: string; +} + +export function resolveUpdateCacheFilePath(): string { + const custom = process.env[UPDATE_CACHE_FILE_ENV]?.trim(); + if (custom) return custom; + return DEFAULT_UPDATE_CACHE_FILE; +} + +export function loadUpdateCache(filePath = resolveUpdateCacheFilePath()): UpdateCacheData | null { + if (!existsSync(filePath)) { + return null; + } + try { + const raw = readFileSync(filePath, "utf-8"); + const parsed = JSON.parse(raw); + if ( + parsed && + typeof parsed === "object" && + typeof parsed.latestVersion === "string" && + typeof parsed.checkedAt === "string" + ) { + return parsed as UpdateCacheData; + } + return null; + } catch { + return null; + } +} + +export function saveUpdateCache( + data: Omit & { checkedAt?: string }, + filePath = resolveUpdateCacheFilePath() +): void { + try { + const dir = dirname(filePath); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + + const payload: UpdateCacheData = { + checkedAt: data.checkedAt ?? new Date().toISOString(), + latestVersion: data.latestVersion, + publishedAt: data.publishedAt, + releaseUrl: data.releaseUrl + }; + + const tmpPath = `${filePath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`; + writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { mode: 0o600 }); + renameSync(tmpPath, filePath); + } catch { + // Ignore cache persistence errors to guarantee non-blocking execution + } +} + +export function isUpdateCacheExpired( + cache: UpdateCacheData | null | undefined, + ttlMs = DEFAULT_UPDATE_CACHE_TTL_MS +): boolean { + if (!cache || !cache.checkedAt) return true; + const checkedTime = new Date(cache.checkedAt).getTime(); + if (Number.isNaN(checkedTime)) return true; + return Date.now() - checkedTime > ttlMs; +} + +export function triggerBackgroundUpdateCheck(launcher?: LauncherConfig): boolean { + if ( + process.env.SEAL_DISABLE_BG_UPDATE === "1" || + process.env.NODE_ENV === "test" || + process.env.CI + ) { + return false; + } + + if (!launcher || !launcher.command) { + return false; + } + + try { + const cmd = launcher.command; + const args = [...(launcher.args ?? []), "update", "check", "--bg-save"]; + const child = spawn(cmd, args, { + detached: true, + stdio: "ignore", + env: { + ...process.env, + SEAL_DISABLE_BG_UPDATE: "1" // Prevent nested spawns + } + }); + child.unref(); + return true; + } catch { + return false; + } +}