fix(desktop): stop forcing login window on business API 401
Desktop Client Build / Resolve Build Metadata (push) Successful in 29s
Frontend CI / Frontend (push) Successful in 4m48s
Desktop Client Build / Build Desktop Client (push) Successful in 26m5s
Desktop Client Build / Publish Client Artifacts to NAS (push) Successful in 42s

Business calls (heartbeat, account sync, lease/pull/resume tasks,
preempt monitoring lease) used to short-circuit any 401 into
handleAuthExpired, which tore down the runtime and switched the
window to login. That stole the screen on transient or per-request
auth glitches and conflicted with the renderer-side proactive token
renewal.

Now business 401s fall through to the existing warn/danger activity
log paths and runtime keeps running. The login redirect is owned
solely by the renderer's renewAuthenticatedSession → on refresh /
rotate failure → forceLogoutAfterRenewFailure path. Server-side
revocation via error code 40991 is unaffected.

Removed the now-orphan plumbing: handleAuthExpired,
isApiClientError helper, emitRuntimeAuthExpired /
onRuntimeAuthExpired events, and forceLoginWindowForAuthExpired
listener registration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-08 18:55:10 +08:00
parent e54efdacee
commit 94c6b5d5a5
3 changed files with 2 additions and 102 deletions
+1 -13
View File
@@ -48,7 +48,7 @@ import {
syncRuntimeSession,
unbindRuntimeAccount,
} from './runtime-controller'
import { onRuntimeAuthExpired, onRuntimeInvalidated } from './runtime-events'
import { onRuntimeInvalidated } from './runtime-events'
import { createRuntimeAccountSnapshot, createRuntimeSnapshot } from './runtime-snapshot'
import { initScheduler } from './scheduler'
import { initSessionRegistry } from './session-registry'
@@ -524,13 +524,6 @@ function queueWindowModeSwitch(
return nextSwitch
}
async function forceLoginWindowForAuthExpired(message: string): Promise<void> {
console.warn('[desktop-main] runtime auth expired; switching to login window', { message })
syncRuntimeSession(null)
await clearRendererDesktopSessions()
await queueWindowModeSwitch('login', { source: 'logout', animate: true }, currentMainWindow())
}
async function openSettingsWindow(): Promise<void> {
const window = await ensureSettingsWindow()
const parent = settingsWindowParent()
@@ -1006,11 +999,6 @@ if (!hasSingleInstanceLock) {
}
mainRendererContents.send('desktop:runtime-invalidated', event)
})
onRuntimeAuthExpired((event) => {
void forceLoginWindowForAuthExpired(event.message).catch((error) => {
console.error('[desktop-main] auth-expired window transition failed', error)
})
})
await queueWindowModeSwitch(currentWindowMode)
initTray(() => {
revealActiveWindowSafely('tray')
@@ -84,11 +84,7 @@ import {
notePublishTaskLeaseMiss,
selectNextPublishTask,
} from './publish-scheduler'
import {
emitRuntimeAuthExpired,
emitRuntimeInvalidated,
onRuntimeInvalidated,
} from './runtime-events'
import { emitRuntimeInvalidated, onRuntimeInvalidated } from './runtime-events'
import {
initScheduler,
noteSchedulerAccountsSync,
@@ -943,11 +939,6 @@ async function handleMonitoringTaskControl(event: DesktopTaskEventMessage): Prom
recordActivity('info', '已取消旧监控租约', `${existing.title} 已从本地排队队列中移除。`)
await pullMonitoringTasks('rabbitmq-primary')
} catch (error) {
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
const message = errorMessage(error)
if (existing) {
existing.summary = `收到抢占请求,但取消租约失败:${message}`
@@ -1005,11 +996,6 @@ async function sendHeartbeat(source: 'startup' | 'timer'): Promise<void> {
noteTransportHeartbeat(false)
setSchedulerError(state.lastError)
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
if (source === 'startup' || previousStatus !== 'failed') {
recordActivity('danger', '心跳连接失败', state.lastError)
}
@@ -1133,11 +1119,6 @@ async function syncAccounts(source: 'startup' | 'manual'): Promise<void> {
state.lastError = message
setSchedulerError(message)
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
recordActivity('warn', '账号同步失败', message)
}
}
@@ -1554,11 +1535,6 @@ async function leaseSpecificTask(
notePublishTaskLeaseMiss(request.taskId)
}
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
state.lastError = errorMessage(error)
setSchedulerError(state.lastError)
recordActivity('warn', '指定任务领取失败', `${request.taskId} 未能成功领取:${state.lastError}`)
@@ -1598,11 +1574,6 @@ async function pullNextTask(kind: 'publish' | 'monitor'): Promise<void> {
state.lastError = errorMessage(error)
noteTransportPull(false)
setSchedulerError(state.lastError)
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
} finally {
state.leaseInFlightKinds.delete('monitor')
syncSchedulerSurface()
@@ -1644,11 +1615,6 @@ async function pullNextTask(kind: 'publish' | 'monitor'): Promise<void> {
noteTransportPull(false)
setSchedulerError(state.lastError)
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
recordActivity('warn', '兜底拉取失败', state.lastError)
} finally {
state.leaseInFlightKinds.delete('publish')
@@ -1684,11 +1650,6 @@ async function pullMonitoringTasks(routing: RuntimeTaskRouting): Promise<void> {
noteTransportPull(false)
setSchedulerError(state.lastError)
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
recordActivity('warn', '监控任务拉取失败', state.lastError)
} finally {
state.leaseInFlightKinds.delete('monitor')
@@ -1713,10 +1674,6 @@ async function resumeLeasedMonitoringTasks(source: 'startup' | 'reconnect'): Pro
}
void pullNextTask('monitor')
} catch (error) {
if (isApiClientError(error, 401)) {
handleAuthExpired(error)
return
}
recordActivity('warn', '恢复监控租约失败', errorMessage(error))
}
}
@@ -3275,15 +3232,6 @@ function clampInteger(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, Math.floor(value)))
}
function handleAuthExpired(error: unknown): void {
const message = errorMessage(error)
state.lastError = message
setTransportAuthState('expired')
recordActivity('danger', '客户端令牌已过期', message)
stopRuntime()
emitRuntimeAuthExpired(message)
}
function selectPublishAdapter(platform: string): PublishAdapter | null {
if (platform === toutiaoAdapter.platform) {
return toutiaoAdapter
@@ -3621,10 +3569,6 @@ function parseTimestamp(value: string | null | undefined): number | null {
return Number.isNaN(timestamp) ? null : timestamp
}
function isApiClientError(error: unknown, status: number): error is ApiClientError {
return error instanceof ApiClientError && error.status === status
}
function isDesktopTaskEvent(value: unknown): value is DesktopTaskEventMessage {
if (typeof value !== 'object' || value === null) {
return false
@@ -1,11 +1,5 @@
type RuntimeInvalidationReason = 'account-health' | 'publish-task-lease'
type RuntimeAuthExpiredListener = (event: {
reason: 'client-auth-expired'
at: number
message: string
}) => void
type RuntimeInvalidationListener = (event: {
reason: RuntimeInvalidationReason
at: number
@@ -14,7 +8,6 @@ type RuntimeInvalidationListener = (event: {
}) => void
const listeners = new Set<RuntimeInvalidationListener>()
const authExpiredListeners = new Set<RuntimeAuthExpiredListener>()
export function emitRuntimeInvalidated(
reason: RuntimeInvalidationReason,
@@ -44,28 +37,3 @@ export function onRuntimeInvalidated(listener: RuntimeInvalidationListener): ()
listeners.delete(listener)
}
}
export function emitRuntimeAuthExpired(message: string): void {
const event = {
reason: 'client-auth-expired',
at: Date.now(),
message,
} as const
for (const listener of authExpiredListeners) {
try {
listener(event)
} catch (error) {
console.warn('[desktop-runtime] auth-expired listener failed', {
message: error instanceof Error ? error.message : String(error),
})
}
}
}
export function onRuntimeAuthExpired(listener: RuntimeAuthExpiredListener): () => void {
authExpiredListeners.add(listener)
return () => {
authExpiredListeners.delete(listener)
}
}