Compare commits
3 Commits
f38930b0ac
...
94c6b5d5a5
| Author | SHA1 | Date | |
|---|---|---|---|
| 94c6b5d5a5 | |||
| e54efdacee | |||
| 846a509c7d |
+2
-1
@@ -22,4 +22,5 @@ apps/*/firefox-mv*/
|
||||
*.log
|
||||
*.tmp
|
||||
apps/*/stats.html
|
||||
ops-api
|
||||
ops-api
|
||||
tmp/*
|
||||
@@ -21,6 +21,10 @@ type KnowledgeSourceType = 'document' | 'website' | 'text'
|
||||
type KnowledgeGroupLevel = 'root' | 'child'
|
||||
const MAX_WEBSITE_URLS = 3
|
||||
const MAX_TEXT_NAME_LENGTH = 20
|
||||
const MAX_UPLOAD_SIZE_MB = 30
|
||||
const MAX_UPLOAD_SIZE_BYTES = MAX_UPLOAD_SIZE_MB * 1024 * 1024
|
||||
const ALLOWED_UPLOAD_EXTENSIONS = ['docx', 'pdf', 'txt', 'md', 'xls', 'xlsx'] as const
|
||||
const UPLOAD_ACCEPT_ATTR = ALLOWED_UPLOAD_EXTENSIONS.map((ext) => `.${ext}`).join(',')
|
||||
|
||||
interface TreeNode {
|
||||
title: string
|
||||
@@ -458,7 +462,19 @@ function handleTreeSelect(keys: (string | number)[]): void {
|
||||
}
|
||||
|
||||
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
|
||||
uploadFiles.value.push(file as File)
|
||||
const rawFile = file as File
|
||||
const ext = rawFile.name.includes('.')
|
||||
? rawFile.name.slice(rawFile.name.lastIndexOf('.') + 1).toLowerCase()
|
||||
: ''
|
||||
if (!ALLOWED_UPLOAD_EXTENSIONS.includes(ext as (typeof ALLOWED_UPLOAD_EXTENSIONS)[number])) {
|
||||
message.error(`「${rawFile.name}」格式不支持,仅支持 ${ALLOWED_UPLOAD_EXTENSIONS.join('、')}`)
|
||||
return false
|
||||
}
|
||||
if (rawFile.size > MAX_UPLOAD_SIZE_BYTES) {
|
||||
message.error(`「${rawFile.name}」超过 ${MAX_UPLOAD_SIZE_MB}MB 大小限制`)
|
||||
return false
|
||||
}
|
||||
uploadFiles.value.push(rawFile)
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -718,6 +734,7 @@ function closeItemDetail(): void {
|
||||
:before-upload="beforeUpload"
|
||||
:file-list="uploadFiles"
|
||||
:multiple="true"
|
||||
:accept="UPLOAD_ACCEPT_ATTR"
|
||||
class="custom-dragger"
|
||||
@remove="handleRemoveFile"
|
||||
>
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
||||
import {
|
||||
appendFileSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
import type { DesktopAccountInfo } from '@geo/shared-types'
|
||||
@@ -21,6 +28,7 @@ import {
|
||||
buildDoubaoSessionCredentialEvidence,
|
||||
DOUBAO_AUTH_PROBE_URL,
|
||||
doubaoHasBoundAccountPageSignal,
|
||||
isDoubaoLoggedInCredentialCookieName,
|
||||
probeDoubaoAccountSession,
|
||||
readDoubaoAuthPageState,
|
||||
} from './adapters/doubao/auth-rules'
|
||||
@@ -291,6 +299,7 @@ type DongchediAccountInfoResponse = {
|
||||
|
||||
const activeBindOperations = new Map<string, ActiveBindOperation>()
|
||||
const MAX_CONCURRENT_BIND_WINDOWS = 2
|
||||
const ACCOUNT_BIND_DIAGNOSTIC_FILE = 'desktop-account-bind-events.jsonl'
|
||||
|
||||
const TOUTIAO_LOGIN_URL = 'https://mp.toutiao.com/auth/page/login'
|
||||
const TOUTIAO_CONSOLE_HOME_URL = 'https://mp.toutiao.com/profile_v4/index'
|
||||
@@ -398,6 +407,75 @@ function hashText(value: string): string {
|
||||
return createHash('sha1').update(value).digest('hex').slice(0, 20)
|
||||
}
|
||||
|
||||
function diagnosticHash(value: string | null | undefined): string | null {
|
||||
const normalized = value?.trim()
|
||||
if (!normalized) {
|
||||
return null
|
||||
}
|
||||
return createHash('sha256').update(normalized).digest('hex').slice(0, 16)
|
||||
}
|
||||
|
||||
function diagnosticUrl(value: string | null | undefined): string | null {
|
||||
const normalized = value?.trim()
|
||||
if (!normalized) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(normalized)
|
||||
return `${parsed.origin}${parsed.pathname}`
|
||||
} catch {
|
||||
return normalized.slice(0, 160)
|
||||
}
|
||||
}
|
||||
|
||||
function appendAccountBindDiagnostic(event: Record<string, unknown>): void {
|
||||
const target = join(app.getPath('userData'), ACCOUNT_BIND_DIAGNOSTIC_FILE)
|
||||
try {
|
||||
mkdirSync(dirname(target), { recursive: true })
|
||||
appendFileSync(target, `${JSON.stringify({ at: new Date().toISOString(), ...event })}\n`, 'utf8')
|
||||
} catch {
|
||||
// Best-effort diagnostics. Never block binding on local log writes.
|
||||
}
|
||||
}
|
||||
|
||||
async function summarizeDoubaoAuthCookies(
|
||||
session: Session,
|
||||
urls: Iterable<string>,
|
||||
): Promise<Array<{ url: string | null; cookieCount: number; authCookieCount: number; authCookies: string[] }>> {
|
||||
const summaries: Array<{
|
||||
url: string | null
|
||||
cookieCount: number
|
||||
authCookieCount: number
|
||||
authCookies: string[]
|
||||
}> = []
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const cookies = await session.cookies.get({ url })
|
||||
const authCookies = cookies
|
||||
.filter((cookie) => isDoubaoLoggedInCredentialCookieName(cookie.name))
|
||||
.map((cookie) => `${cookie.name}:${cookie.value.length}`)
|
||||
.sort()
|
||||
summaries.push({
|
||||
url: diagnosticUrl(url),
|
||||
cookieCount: cookies.length,
|
||||
authCookieCount: authCookies.length,
|
||||
authCookies,
|
||||
})
|
||||
} catch (error) {
|
||||
summaries.push({
|
||||
url: diagnosticUrl(url),
|
||||
cookieCount: 0,
|
||||
authCookieCount: 0,
|
||||
authCookies: [`error:${error instanceof Error ? error.message : String(error)}`],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return summaries
|
||||
}
|
||||
|
||||
function buildBilibiliMixinKey(imgKey: string, subKey: string): string {
|
||||
const raw = imgKey + subKey
|
||||
return BILIBILI_WBI_MIXIN_KEY_ENC_TAB.map((index) => raw.charAt(index))
|
||||
@@ -1463,45 +1541,107 @@ async function detectDoubaoPlatform(
|
||||
context: DetectContext,
|
||||
): Promise<DetectedAccount | null> {
|
||||
if (!context.webContents || context.webContents.isDestroyed()) {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'doubao_detect_failed',
|
||||
platform: platformId,
|
||||
reason: 'web_contents_destroyed',
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const currentURL = context.webContents.getURL()
|
||||
const platformMeta = aiPlatformCatalog.find((item) => item.id === platformId) ?? null
|
||||
if (!platformMeta) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (currentURL && looksLikeLoginRedirect(currentURL, platformMeta.loginUrl)) {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'doubao_detect_failed',
|
||||
platform: platformId,
|
||||
reason: 'platform_meta_missing',
|
||||
url: diagnosticUrl(currentURL),
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const pageState = await readDoubaoAuthPageState(context.webContents).catch(() => null)
|
||||
const urls = new Set([platformMeta.loginUrl, platformMeta.consoleUrl])
|
||||
const cookieSummary = await summarizeDoubaoAuthCookies(context.session, urls)
|
||||
const pageStateDiagnostic = {
|
||||
displayName: pageState?.displayName ?? null,
|
||||
hasAvatar: Boolean(pageState?.avatarUrl),
|
||||
currentPath: pageState?.currentPath ?? null,
|
||||
strongAuthSignalCount: pageState?.strongAuthSignalCount ?? 0,
|
||||
loginSignalCount: pageState?.loginSignalCount ?? 0,
|
||||
loggedOutSignalCount: pageState?.loggedOutSignalCount ?? 0,
|
||||
challengeSignalCount: pageState?.challengeSignalCount ?? 0,
|
||||
}
|
||||
|
||||
if ((pageState?.challengeSignalCount ?? 0) > 0) {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'doubao_detect_failed',
|
||||
platform: platformId,
|
||||
reason: 'challenge_required',
|
||||
url: diagnosticUrl(currentURL),
|
||||
pageState: pageStateDiagnostic,
|
||||
cookies: cookieSummary,
|
||||
})
|
||||
return null
|
||||
}
|
||||
if ((pageState?.loggedOutSignalCount ?? 0) > 0) {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'doubao_detect_failed',
|
||||
platform: platformId,
|
||||
reason: 'logged_out_signal',
|
||||
url: diagnosticUrl(currentURL),
|
||||
pageState: pageStateDiagnostic,
|
||||
cookies: cookieSummary,
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
// Doubao is intentionally platform-specific. It allows anonymous chat, but
|
||||
// our desktop binding requires the real sidebar account menu plus login cookies.
|
||||
if (!doubaoHasBoundAccountPageSignal(pageState)) {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'doubao_detect_failed',
|
||||
platform: platformId,
|
||||
reason: 'doubao_account_menu_missing',
|
||||
url: diagnosticUrl(currentURL),
|
||||
pageState: pageStateDiagnostic,
|
||||
cookies: cookieSummary,
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const urls = new Set([platformMeta.loginUrl, platformMeta.consoleUrl])
|
||||
const credentialEvidence = await buildDoubaoSessionCredentialEvidence(
|
||||
context.session,
|
||||
urls,
|
||||
pageState,
|
||||
)
|
||||
if (!credentialEvidence) {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'doubao_detect_failed',
|
||||
platform: platformId,
|
||||
reason: 'doubao_login_cookie_missing',
|
||||
url: diagnosticUrl(currentURL),
|
||||
pageState: pageStateDiagnostic,
|
||||
cookies: cookieSummary,
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const platformUid = boundedIdentity('doubao-session', credentialEvidence)
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'doubao_detect_success',
|
||||
platform: platformId,
|
||||
reason: 'detected',
|
||||
url: diagnosticUrl(currentURL),
|
||||
pageState: pageStateDiagnostic,
|
||||
cookies: cookieSummary,
|
||||
displayName: pageState?.displayName ?? `${label} 账号`,
|
||||
platformUidHash: diagnosticHash(platformUid),
|
||||
})
|
||||
|
||||
return sanitizeDetectedAccount({
|
||||
platformUid: boundedIdentity('doubao-session', credentialEvidence),
|
||||
platformUid,
|
||||
displayName: pageState?.displayName ?? `${label} 账号`,
|
||||
avatarUrl: pageState?.avatarUrl ?? null,
|
||||
})
|
||||
@@ -3995,6 +4135,13 @@ export async function bindPublishAccount(platformId: string): Promise<DesktopAcc
|
||||
}
|
||||
|
||||
const handle = createPendingSessionHandle(platformId)
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_window_opening',
|
||||
platform: definition.id,
|
||||
pendingAccountIdHash: diagnosticHash(handle.accountId),
|
||||
partition: handle.partition,
|
||||
loginUrl: diagnosticUrl(definition.loginUrl),
|
||||
})
|
||||
let window: BrowserWindow
|
||||
|
||||
try {
|
||||
@@ -4103,6 +4250,15 @@ export async function bindPublishAccount(platformId: string): Promise<DesktopAcc
|
||||
}
|
||||
checking = true
|
||||
try {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_detect_tick',
|
||||
platform: definition.id,
|
||||
detectReady,
|
||||
canProbe,
|
||||
loading: window.webContents.isLoading(),
|
||||
url: diagnosticUrl(currentURL),
|
||||
partition: handle.partition,
|
||||
})
|
||||
console.info('[desktop-bind] detect tick', {
|
||||
platform: definition.id,
|
||||
detectReady,
|
||||
@@ -4116,12 +4272,33 @@ export async function bindPublishAccount(platformId: string): Promise<DesktopAcc
|
||||
console.warn(`[desktop-bind] ${definition.id} detect failed`, {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_detect_exception',
|
||||
platform: definition.id,
|
||||
url: diagnosticUrl(currentURL),
|
||||
partition: handle.partition,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
return null
|
||||
})
|
||||
if (!detected) {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_detect_empty',
|
||||
platform: definition.id,
|
||||
url: diagnosticUrl(currentURL),
|
||||
partition: handle.partition,
|
||||
})
|
||||
return
|
||||
}
|
||||
let normalizedDetected = sanitizeDetectedAccount(detected)
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_detect_success',
|
||||
platform: definition.id,
|
||||
displayName: normalizedDetected.displayName,
|
||||
platformUidHash: diagnosticHash(normalizedDetected.platformUid),
|
||||
url: diagnosticUrl(currentURL),
|
||||
partition: handle.partition,
|
||||
})
|
||||
console.info('[desktop-bind] detect success', {
|
||||
platform: definition.id,
|
||||
displayName: normalizedDetected.displayName,
|
||||
@@ -4180,6 +4357,14 @@ export async function bindPublishAccount(platformId: string): Promise<DesktopAcc
|
||||
void flushSessionPersistence(handle.session)
|
||||
|
||||
try {
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_upsert_start',
|
||||
platform: definition.id,
|
||||
displayName: normalizedDetected.displayName,
|
||||
platformUidHash: diagnosticHash(normalizedDetected.platformUid),
|
||||
url: diagnosticUrl(currentURL),
|
||||
partition: handle.partition,
|
||||
})
|
||||
const account = await upsertDesktopAccount({
|
||||
platform: definition.id,
|
||||
platform_uid: normalizedDetected.platformUid,
|
||||
@@ -4195,6 +4380,14 @@ export async function bindPublishAccount(platformId: string): Promise<DesktopAcc
|
||||
await saveWangyihaoSessionCookies(account.id, handle.session)
|
||||
}
|
||||
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_upsert_success',
|
||||
platform: definition.id,
|
||||
accountIdHash: diagnosticHash(account.id),
|
||||
displayName: account.display_name,
|
||||
url: diagnosticUrl(currentURL),
|
||||
partition: handle.partition,
|
||||
})
|
||||
settleSuccess(account)
|
||||
} catch (error) {
|
||||
console.error('[desktop-bind] upsert failed', {
|
||||
@@ -4202,6 +4395,15 @@ export async function bindPublishAccount(platformId: string): Promise<DesktopAcc
|
||||
url: currentURL,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
appendAccountBindDiagnostic({
|
||||
action: 'bind_upsert_failed',
|
||||
platform: definition.id,
|
||||
displayName: normalizedDetected.displayName,
|
||||
platformUidHash: diagnosticHash(normalizedDetected.platformUid),
|
||||
url: diagnosticUrl(currentURL),
|
||||
partition: handle.partition,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
if (!window.isDestroyed()) {
|
||||
window.setTitle(`${definition.label} 绑定保存失败,保留窗口重试`)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { appendFileSync, mkdirSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
import { ApiClientError, createApiClient, type ApiClient } from '@geo/http-client'
|
||||
import type {
|
||||
ApiEnvelope,
|
||||
@@ -29,6 +33,7 @@ import type {
|
||||
ReportDesktopAccountHealthResponse,
|
||||
UpsertDesktopAccountRequest,
|
||||
} from '@geo/shared-types'
|
||||
import { app } from 'electron/main'
|
||||
|
||||
import {
|
||||
failObservedRequest,
|
||||
@@ -70,6 +75,7 @@ let transportSession: DesktopTransportSession = {
|
||||
clientToken: null,
|
||||
}
|
||||
const ACCOUNT_UPSERT_CACHE_TTL_MS = 5 * 60_000
|
||||
const ACCOUNT_UPSERT_DIAGNOSTIC_FILE = 'desktop-account-upsert-errors.jsonl'
|
||||
|
||||
interface AccountUpsertCacheEntry {
|
||||
signature: string
|
||||
@@ -185,6 +191,76 @@ function clearAccountUpsertCache(): void {
|
||||
accountUpsertCache.clear()
|
||||
}
|
||||
|
||||
function diagnosticHash(value: string | null | undefined): string | null {
|
||||
const normalized = value?.trim()
|
||||
if (!normalized) {
|
||||
return null
|
||||
}
|
||||
return createHash('sha256').update(normalized).digest('hex').slice(0, 16)
|
||||
}
|
||||
|
||||
function normalizeErrorForDiagnostics(error: unknown): Record<string, unknown> {
|
||||
if (error instanceof ApiClientError) {
|
||||
return {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
code: error.code,
|
||||
status: error.status ?? null,
|
||||
detail: error.detail ?? null,
|
||||
requestId: error.requestId ?? null,
|
||||
handled: error.handled === true,
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: typeof error,
|
||||
message: String(error),
|
||||
}
|
||||
}
|
||||
|
||||
function appendAccountUpsertDiagnostic(
|
||||
payload: UpsertDesktopAccountRequest,
|
||||
error: unknown,
|
||||
): void {
|
||||
const target = join(app.getPath('userData'), ACCOUNT_UPSERT_DIAGNOSTIC_FILE)
|
||||
const event = {
|
||||
at: new Date().toISOString(),
|
||||
action: 'desktop_account_upsert_failed',
|
||||
transport: {
|
||||
baseURL: transportState.baseURL,
|
||||
auth: transportState.auth,
|
||||
requestDebugMode: transportState.requestDebugMode,
|
||||
hasClient: desktopApiClient !== null,
|
||||
hasClientToken: Boolean(transportSession.clientToken),
|
||||
},
|
||||
request: {
|
||||
platform: payload.platform,
|
||||
platformUidHash: diagnosticHash(payload.platform_uid),
|
||||
accountFingerprintHash: diagnosticHash(payload.account_fingerprint ?? null),
|
||||
displayName: payload.display_name,
|
||||
health: payload.health,
|
||||
verifiedAt: payload.verified_at ?? null,
|
||||
tagCount: payload.tags?.length ?? 0,
|
||||
hasIfSyncVersion: typeof payload.if_sync_version === 'number',
|
||||
},
|
||||
error: normalizeErrorForDiagnostics(error),
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(dirname(target), { recursive: true })
|
||||
appendFileSync(target, `${JSON.stringify(event)}\n`, 'utf8')
|
||||
} catch {
|
||||
// Best-effort diagnostics. Never block account binding on local log writes.
|
||||
}
|
||||
}
|
||||
|
||||
function currentRequestDebugMode(): 'main-process' | 'renderer-devtools' {
|
||||
return canUseRendererDevtoolsProxy() ? 'renderer-devtools' : 'main-process'
|
||||
}
|
||||
@@ -521,6 +597,7 @@ export async function upsertDesktopAccount(
|
||||
if (accountUpsertCache.get(cacheKey)?.inFlight === request) {
|
||||
accountUpsertCache.delete(cacheKey)
|
||||
}
|
||||
appendAccountUpsertDiagnostic(payload, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user