feat(desktop): add client release updater
Desktop Client Build / Resolve Build Metadata (push) Successful in 19s
Frontend CI / Frontend (push) Successful in 3m20s
Backend CI / Backend (push) Successful in 16m48s
Desktop Client Build / Build Desktop Client (push) Successful in 24m46s
Desktop Client Build / Publish Client Artifacts to NAS (push) Successful in 37s

This commit is contained in:
2026-05-25 19:23:49 +08:00
parent 41b4a765ac
commit 5f6e9f11da
46 changed files with 5508 additions and 160 deletions
@@ -0,0 +1,108 @@
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { AuthProbeResult } from './auth-types'
const probeAIAccountSession = vi.fn()
const probePublishAccountSession = vi.fn()
const silentRefreshAIAccountSession = vi.fn()
const silentRefreshPublishAccountSession = vi.fn()
const getSessionHandle = vi.fn()
const getPersistedPartition = vi.fn()
const emitRuntimeInvalidated = vi.fn()
vi.mock('electron/main', () => ({
app: {
getPath: () => join(tmpdir(), 'geo-rankly-account-health-test'),
},
}))
vi.mock('./account-binder', () => ({
probeAIAccountSession,
probePublishAccountSession,
silentRefreshAIAccountSession,
silentRefreshPublishAccountSession,
}))
vi.mock('./session-registry', () => ({
getSessionHandle,
getPersistedPartition,
}))
vi.mock('./runtime-events', () => ({
emitRuntimeInvalidated,
}))
const account = {
id: 'account-1',
platform: 'doubao',
platformUid: 'doubao-session:demo',
displayName: '豆包账号',
}
function challenge(reason: AuthProbeResult['reason'] = 'captcha_gate'): AuthProbeResult {
return {
verdict: 'challenge_required',
reason,
profile: null,
sessionFingerprint: null,
}
}
function active(): AuthProbeResult {
return {
verdict: 'active',
reason: 'probe_success',
profile: {
displayName: '豆包账号',
avatarUrl: null,
subjectUid: 'doubao-session:demo',
},
sessionFingerprint: 'fingerprint-live',
}
}
describe('account health challenge recheck', () => {
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
getSessionHandle.mockReturnValue({ partition: 'persist:test' })
getPersistedPartition.mockReturnValue('persist:test')
silentRefreshAIAccountSession.mockResolvedValue(true)
silentRefreshPublishAccountSession.mockResolvedValue(true)
})
it('hides a first challenge result when the automatic recheck succeeds', async () => {
probeAIAccountSession.mockResolvedValueOnce(challenge()).mockResolvedValueOnce(active())
const { probeTrackedAccount } = await import('./account-health')
const snapshot = await probeTrackedAccount(account, {
trigger: 'manual',
allowSilentRefresh: true,
force: true,
})
expect(probeAIAccountSession).toHaveBeenCalledTimes(2)
expect(snapshot.authState).toBe('active')
expect(snapshot.authReason).toBe('probe_success')
})
it('shows manual verification only after the automatic recheck still needs it', async () => {
probeAIAccountSession
.mockResolvedValueOnce(challenge('risk_control'))
.mockResolvedValueOnce(challenge('risk_control'))
const { probeTrackedAccount } = await import('./account-health')
const snapshot = await probeTrackedAccount(account, {
trigger: 'manual',
allowSilentRefresh: true,
force: true,
})
expect(probeAIAccountSession).toHaveBeenCalledTimes(2)
expect(snapshot.authState).toBe('challenge_required')
expect(snapshot.authReason).toBe('risk_control')
})
})
+87 -26
View File
@@ -13,7 +13,11 @@ import type {
AccountProbeState,
AuthProbeResult,
} from './auth-types'
import { getPlatformAdapter, type PlatformFailureInput } from './platform-auth-adapters'
import {
getPlatformAdapter,
type PlatformAdapter,
type PlatformFailureInput,
} from './platform-auth-adapters'
import { emitRuntimeInvalidated } from './runtime-events'
import { getPersistedPartition, getSessionHandle } from './session-registry'
@@ -30,6 +34,7 @@ const MAX_CONCURRENT_ACCOUNT_PROBES = 2
const MANUAL_PROBE_CACHE_TTL_MS = 5 * 60_000
const MANUAL_PROBE_MIN_INTERVAL_MS = 15_000
const ACCOUNT_PROBE_RETRY_BACKOFF_MS = [1_000, 3_000, 10_000] as const
const CHALLENGE_RECHECK_ATTEMPTS = 1
type ProbeTrigger = 'scheduled' | 'manual' | 'preflight' | 'confirm'
@@ -366,6 +371,62 @@ function applyNetworkResult(
return commitRecord(record, previousSignature)
}
function networkProbeResult(): AuthProbeResult {
return {
verdict: 'network_error',
reason: 'network_error',
profile: null,
sessionFingerprint: null,
}
}
async function probeAdapter(
adapter: PlatformAdapter,
account: PublishAccountIdentity,
partition: string,
): Promise<AuthProbeResult> {
return await adapter.probe(account, partition).catch<AuthProbeResult>(() => networkProbeResult())
}
async function recheckChallengeResult(
adapter: PlatformAdapter,
account: PublishAccountIdentity,
partition: string,
result: AuthProbeResult,
): Promise<AuthProbeResult> {
if (result.verdict !== 'challenge_required') {
return result
}
let confirmed = result
for (let attempt = 0; attempt < CHALLENGE_RECHECK_ATTEMPTS; attempt += 1) {
confirmed = await probeAdapter(adapter, account, partition)
if (confirmed.verdict !== 'challenge_required') {
return confirmed
}
}
return confirmed
}
function applyProbeResult(
record: AccountHealthRecord,
result: AuthProbeResult,
now: number,
trigger: ProbeTrigger,
): AccountHealthSnapshot {
switch (result.verdict) {
case 'active':
return applyActiveResult(record, result, now)
case 'expired':
return applyExpiredResult(record, result, now)
case 'challenge_required':
return applyChallengeResult(record, result, now)
default:
return applyNetworkResult(record, result, now, trigger)
}
}
async function performProbeLocked(
account: PublishAccountIdentity,
options: {
@@ -407,28 +468,18 @@ async function performProbeLocked(
}
}
const result = await adapter.probe(account, partition).catch<AuthProbeResult>(() => ({
verdict: 'network_error',
reason: 'network_error',
profile: null,
sessionFingerprint: null,
}))
const result = await probeAdapter(adapter, account, partition)
if (record.authRevision !== probeAuthRevision) {
return toPublicSnapshot(record)
}
const now = Date.now()
switch (result.verdict) {
case 'active':
return applyActiveResult(record, result, now)
case 'expired':
return applyExpiredResult(record, result, now)
case 'challenge_required':
return applyChallengeResult(record, result, now)
default:
return applyNetworkResult(record, result, now, options.trigger)
const confirmedResult = await recheckChallengeResult(adapter, account, partition, result)
if (record.authRevision !== probeAuthRevision) {
return toPublicSnapshot(record)
}
return applyProbeResult(record, confirmedResult, Date.now(), options.trigger)
}
function canUseCachedProbe(
@@ -922,15 +973,25 @@ export async function reportAccountFailure(
const now = Date.now()
if (classification === 'challenge' || classification === 'risk_control') {
record.authState = 'challenge_required'
record.probeState = 'idle'
record.authReason = classification === 'risk_control' ? 'risk_control' : 'captcha_gate'
record.lastAuthFailureAt = now
record.lastProbeAt = now
record.nextProbeAt = nextRegularProbeAt(now)
record.suspectedExpiredAt = null
record.confirmFailureCount = 0
return commitRecord(record, previousSignature)
record.probeState = 'probing'
commitRecord(record, previousSignature)
const partition = resolveKnownPartition(account.id)
const result = partition
? await recheckChallengeResult(adapter, account, partition, {
verdict: 'challenge_required',
reason: classification === 'risk_control' ? 'risk_control' : 'captcha_gate',
profile: null,
sessionFingerprint: null,
})
: {
verdict: 'expired' as const,
reason: 'missing_partition' as const,
profile: null,
sessionFingerprint: null,
}
return applyProbeResult(record, result, Date.now(), 'confirm')
}
if (classification === 'network') {
@@ -0,0 +1,9 @@
import { app } from 'electron/main'
export function getDesktopAppVersion(): string {
return app.getVersion()
}
export function getDesktopReleaseChannel(): string {
return process.env.DESKTOP_RELEASE_CHANNEL ?? (app.isPackaged ? 'stable' : 'dev')
}
+104 -9
View File
@@ -3,6 +3,7 @@ import { join } from 'node:path'
import type {
DesktopAccountInfo,
DesktopClientReleaseCheckResponse,
DesktopClientRotateResponse,
DesktopRuntimeSessionSyncRequest,
} from '@geo/shared-types'
@@ -31,23 +32,29 @@ import {
setDesktopAppSetting,
type DesktopAppSettingKey,
} from './app-settings'
import { resolveDesktopClientID, resolveDesktopDeviceInfo } from './device-id'
import { getDesktopAppVersion, getDesktopReleaseChannel } from './app-version'
import {
installObservedGlobalFetch,
registerObservedRequestRendererTarget,
} from './network-observer'
import { getPlaywrightCDPPort, startHiddenPlaywrightReaper } from './playwright-cdp'
defaultDesktopUpdateChannel,
startDesktopClientUpdate,
type DesktopClientUpdateProgressEvent,
} from './client-updater'
import { resolveDesktopClientID, resolveDesktopDeviceInfo } from './device-id'
import {
clearSavedLoginCredentials,
getSavedLoginCredentials,
saveLoginCredentials,
} from './login-credentials'
import {
installObservedGlobalFetch,
registerObservedRequestRendererTarget,
} from './network-observer'
import { getPlaywrightCDPPort, startHiddenPlaywrightReaper } from './playwright-cdp'
import { initProcessMetricsSampler } from './process-metrics'
import { registerRendererDevtoolsProxyTarget } from './renderer-devtools-proxy'
import {
getRuntimeControllerSnapshot,
noteRuntimeAccountBound,
refreshRuntimeAccounts,
getRuntimeControllerSnapshot,
releaseRuntimeSession,
requestRuntimeAccountProbe,
syncRuntimeSession,
@@ -59,8 +66,10 @@ import { initScheduler } from './scheduler'
import { initSessionRegistry } from './session-registry'
import { initSingleInstance } from './single-instance'
import {
checkDesktopClientRelease,
initTransport,
listDesktopPublishTasks,
resolveDesktopClientReleaseDownloadURL,
retryDesktopPublishTask,
rotateDesktopClient,
} from './transport/api-client'
@@ -772,15 +781,73 @@ function isSafeExternalUrl(url: string): boolean {
}
}
function desktopReleasePlatform(): string {
switch (process.platform) {
case 'darwin':
return 'darwin'
case 'win32':
return 'win32'
case 'linux':
return 'linux'
default:
return process.platform
}
}
function desktopReleaseArch(): string {
switch (process.arch) {
case 'x64':
case 'arm64':
case 'ia32':
return process.arch
default:
return 'universal'
}
}
async function checkCurrentDesktopClientRelease(): Promise<DesktopClientReleaseCheckResponse> {
const snapshot = getRuntimeControllerSnapshot()
if (!snapshot.session?.client_token) {
throw new Error('desktop_client_not_registered')
}
return checkDesktopClientRelease({
platform: desktopReleasePlatform(),
arch: desktopReleaseArch(),
version: getDesktopAppVersion(),
channel: snapshot.session.desktop_client?.channel || getDesktopReleaseChannel(),
})
}
async function resolveCurrentDesktopClientReleaseDownloadURL(): Promise<{ download_url: string }> {
const snapshot = getRuntimeControllerSnapshot()
if (!snapshot.session?.client_token) {
throw new Error('desktop_client_not_registered')
}
return resolveDesktopClientReleaseDownloadURL({
platform: desktopReleasePlatform(),
arch: desktopReleaseArch(),
version: getDesktopAppVersion(),
channel: snapshot.session.desktop_client?.channel || getDesktopReleaseChannel(),
})
}
function emitClientUpdateProgress(event: DesktopClientUpdateProgressEvent): void {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send('desktop:client-update-progress', event)
}
}
}
function registerDesktopProtocolClient(): void {
if (app.isDefaultProtocolClient(desktopDeepLinkScheme)) {
return
}
if (process.defaultApp && process.execPath) {
app.setAsDefaultProtocolClient(desktopDeepLinkScheme, process.execPath, [
process.argv[1] ?? '',
])
app.setAsDefaultProtocolClient(desktopDeepLinkScheme, process.execPath, [process.argv[1] ?? ''])
return
}
@@ -847,6 +914,34 @@ function handleDesktopDeepLink(rawUrl: string): void {
function registerBridgeHandlers(): void {
ipcMain.handle('desktop:ping', () => 'pong')
ipcMain.handle('desktop:version-info', () => ({
version: getDesktopAppVersion(),
channel: getDesktopReleaseChannel(),
}))
safeHandle('desktop:check-client-release', () => checkCurrentDesktopClientRelease())
safeHandle('desktop:client-release-download-url', () =>
resolveCurrentDesktopClientReleaseDownloadURL(),
)
safeHandle('desktop:quit-app', async () => {
app.quit()
return null
})
safeHandle('desktop:start-client-update', async () => {
const snapshot = getRuntimeControllerSnapshot()
if (!snapshot.session?.client_token) {
throw new Error('desktop_client_not_registered')
}
return startDesktopClientUpdate({
platform: desktopReleasePlatform(),
arch: desktopReleaseArch(),
channel: defaultDesktopUpdateChannel(snapshot.session.desktop_client?.channel),
notify: emitClientUpdateProgress,
beforeInstall: () => {
quitReleaseInFlight = true
},
})
})
ipcMain.handle('desktop:device-info', () => resolveDesktopDeviceInfo())
safeHandle(
'desktop:client-id',
@@ -0,0 +1,240 @@
import { autoUpdater, type ProgressInfo, type UpdateDownloadedEvent } from 'electron-updater'
import { app } from 'electron/main'
import { getDesktopAppVersion, getDesktopReleaseChannel } from './app-version'
import { resolveDesktopApiURL } from './transport/api-client'
export type DesktopClientUpdateStage =
| 'idle'
| 'checking'
| 'downloading'
| 'downloaded'
| 'installing'
| 'not-available'
| 'error'
export interface DesktopClientUpdateProgressEvent {
stage: DesktopClientUpdateStage
percent: number | null
transferred: number | null
total: number | null
bytesPerSecond: number | null
version: string | null
message?: string
}
export interface DesktopClientUpdateResult {
update_available: boolean
version: string | null
stage: DesktopClientUpdateStage
}
interface StartDesktopClientUpdateOptions {
platform: string
arch: string
channel: string
notify: (event: DesktopClientUpdateProgressEvent) => void
beforeInstall?: () => void
}
let updateInFlight: Promise<DesktopClientUpdateResult> | null = null
let updaterConfigured = false
let downloadedVersion: string | null = null
let progressNotifier: StartDesktopClientUpdateOptions['notify'] | null = null
function encodeFeedPathSegment(value: string): string {
return encodeURIComponent(value.trim())
}
function updaterFeedURL(options: StartDesktopClientUpdateOptions): string {
return resolveDesktopApiURL(
[
'/api/desktop/releases/updater',
encodeFeedPathSegment(options.platform),
encodeFeedPathSegment(options.arch),
encodeFeedPathSegment(options.channel),
encodeFeedPathSegment(getDesktopAppVersion()),
'',
].join('/'),
)
}
function emitProgress(
notify: StartDesktopClientUpdateOptions['notify'] | null,
event: DesktopClientUpdateProgressEvent,
): void {
notify?.(event)
}
function updaterErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
function isCodeSignatureValidationError(message: string): boolean {
return (
message.includes('Code signature') ||
message.includes('did not pass validation') ||
message.includes('代码未能满足指定的代码要求') ||
message.includes('code requirements')
)
}
function normalizeUpdaterError(error: unknown): string {
const message = updaterErrorMessage(error)
if (isCodeSignatureValidationError(message)) {
return 'desktop_client_update_signature_validation_failed'
}
return message || 'desktop_client_update_failed'
}
function configureUpdater(options: StartDesktopClientUpdateOptions): void {
progressNotifier = options.notify
autoUpdater.autoDownload = false
autoUpdater.autoInstallOnAppQuit = false
autoUpdater.disableDifferentialDownload = true
autoUpdater.allowDowngrade = false
autoUpdater.allowPrerelease = options.channel !== 'stable'
autoUpdater.channel = null
autoUpdater.logger = console
autoUpdater.setFeedURL({
provider: 'generic',
url: updaterFeedURL(options),
channel: 'latest',
})
if (updaterConfigured) {
return
}
updaterConfigured = true
autoUpdater.on('download-progress', (info: ProgressInfo) => {
emitProgress(progressNotifier, {
stage: 'downloading',
percent: Number.isFinite(info.percent) ? info.percent : null,
transferred: Number.isFinite(info.transferred) ? info.transferred : null,
total: Number.isFinite(info.total) ? info.total : null,
bytesPerSecond: Number.isFinite(info.bytesPerSecond) ? info.bytesPerSecond : null,
version: downloadedVersion,
})
})
autoUpdater.on('update-downloaded', (event: UpdateDownloadedEvent) => {
downloadedVersion = event.version
emitProgress(progressNotifier, {
stage: 'downloaded',
percent: 100,
transferred: null,
total: null,
bytesPerSecond: null,
version: event.version,
message: 'update_downloaded',
})
})
autoUpdater.on('error', (error) => {
console.warn('[desktop-updater] update failed', error)
emitProgress(progressNotifier, {
stage: 'error',
percent: null,
transferred: null,
total: null,
bytesPerSecond: null,
version: downloadedVersion,
message: normalizeUpdaterError(error),
})
})
}
export function startDesktopClientUpdate(
options: StartDesktopClientUpdateOptions,
): Promise<DesktopClientUpdateResult> {
if (updateInFlight) {
return updateInFlight
}
updateInFlight = runDesktopClientUpdate(options).finally(() => {
updateInFlight = null
})
return updateInFlight
}
async function runDesktopClientUpdate(
options: StartDesktopClientUpdateOptions,
): Promise<DesktopClientUpdateResult> {
if (!app.isPackaged && process.env.DESKTOP_ALLOW_DEV_UPDATER !== '1') {
throw new Error('desktop_update_requires_packaged_app')
}
downloadedVersion = null
configureUpdater(options)
emitProgress(options.notify, {
stage: 'checking',
percent: null,
transferred: null,
total: null,
bytesPerSecond: null,
version: null,
})
let checkResult
try {
checkResult = await autoUpdater.checkForUpdates()
} catch (error) {
throw new Error(normalizeUpdaterError(error))
}
if (!checkResult?.isUpdateAvailable) {
emitProgress(options.notify, {
stage: 'not-available',
percent: null,
transferred: null,
total: null,
bytesPerSecond: null,
version: checkResult?.updateInfo.version ?? null,
})
return {
update_available: false,
version: checkResult?.updateInfo.version ?? null,
stage: 'not-available',
}
}
downloadedVersion = checkResult.updateInfo.version
emitProgress(options.notify, {
stage: 'downloading',
percent: 0,
transferred: 0,
total: null,
bytesPerSecond: null,
version: checkResult.updateInfo.version,
})
try {
await autoUpdater.downloadUpdate(checkResult.cancellationToken)
} catch (error) {
throw new Error(normalizeUpdaterError(error))
}
emitProgress(options.notify, {
stage: 'installing',
percent: 100,
transferred: null,
total: null,
bytesPerSecond: null,
version: checkResult.updateInfo.version,
})
setTimeout(() => {
options.beforeInstall?.()
autoUpdater.quitAndInstall(process.platform === 'win32', true)
}, 250)
return {
update_available: true,
version: checkResult.updateInfo.version,
stage: 'installing',
}
}
export function defaultDesktopUpdateChannel(clientChannel: string | null | undefined): string {
return clientChannel?.trim() || getDesktopReleaseChannel()
}
@@ -54,6 +54,7 @@ import {
type MonitorAdapter,
type PublishAdapter,
} from './adapters'
import { getDesktopAppVersion, getDesktopReleaseChannel } from './app-version'
import {
getLeaseManagerSnapshot,
noteLeaseExtended,
@@ -1096,8 +1097,8 @@ async function sendHeartbeat(source: 'startup' | 'timer'): Promise<void> {
device_name: hostname() || state.client?.device_name || `Desktop ${process.platform}`,
os: process.platform,
cpu_arch: process.arch,
client_version: state.client?.client_version ?? '0.1.0-dev',
channel: state.client?.channel ?? 'dev',
client_version: getDesktopAppVersion(),
channel: state.client?.channel ?? getDesktopReleaseChannel(),
startup: source === 'startup',
account_ids: state.accounts
.filter((account) => shouldReportAccountPresence(account))
@@ -13,6 +13,7 @@ import type {
DesktopArticleContent,
DesktopClientHeartbeatRequest,
DesktopClientHeartbeatResponse,
DesktopClientReleaseCheckResponse,
DesktopClientRotateResponse,
DesktopPublishTaskListResponse,
DesktopRuntimeSessionSyncRequest,
@@ -35,13 +36,13 @@ import type {
} from '@geo/shared-types'
import { app } from 'electron/main'
import { normalizeDesktopApiBaseURL } from '../../shared/api-base-url'
import {
failObservedRequest,
resolveObservedRequest,
startObservedRequest,
} from '../network-observer'
import { canUseRendererDevtoolsProxy, rendererDevtoolsFetch } from '../renderer-devtools-proxy'
import { normalizeDesktopApiBaseURL } from '../../shared/api-base-url'
type TransportAuthState = 'pending' | 'registered' | 'expired'
type TransportDispatchState = 'idle' | 'connecting' | 'streaming'
@@ -225,10 +226,7 @@ function normalizeErrorForDiagnostics(error: unknown): Record<string, unknown> {
}
}
function appendAccountUpsertDiagnostic(
payload: UpsertDesktopAccountRequest,
error: unknown,
): void {
function appendAccountUpsertDiagnostic(payload: UpsertDesktopAccountRequest, error: unknown): void {
const target = join(app.getPath('userData'), ACCOUNT_UPSERT_DIAGNOSTIC_FILE)
const event = {
at: new Date().toISOString(),
@@ -514,6 +512,44 @@ export async function rotateDesktopClient(): Promise<DesktopClientRotateResponse
)
}
export async function checkDesktopClientRelease(params: {
platform: string
arch: string
version: string
channel?: string
}): Promise<DesktopClientReleaseCheckResponse> {
const search = new URLSearchParams({
platform: params.platform,
arch: params.arch,
version: params.version,
})
if (params.channel?.trim()) {
search.set('channel', params.channel.trim())
}
return desktopGet<DesktopClientReleaseCheckResponse>(
`/api/desktop/clients/releases/latest?${search.toString()}`,
)
}
export async function resolveDesktopClientReleaseDownloadURL(params: {
platform: string
arch: string
version: string
channel?: string
}): Promise<{ download_url: string; expires_in?: number | null }> {
const search = new URLSearchParams({
platform: params.platform,
arch: params.arch,
version: params.version,
})
if (params.channel?.trim()) {
search.set('channel', params.channel.trim())
}
return desktopGet<{ download_url: string; expires_in?: number | null }>(
`/api/desktop/clients/releases/download-url?${search.toString()}`,
)
}
export async function offlineDesktopClient(): Promise<void> {
await desktopPost<{ server_time: string }, Record<string, never>>(
'/api/desktop/clients/offline',