diff --git a/backend/app/platform/sessions.py b/backend/app/platform/sessions.py index fc49fcd..bc921e4 100644 --- a/backend/app/platform/sessions.py +++ b/backend/app/platform/sessions.py @@ -143,7 +143,7 @@ async def _merge(changes: list[tuple[str, str, dict | None]]) -> None: async def available_accounts() -> list[dict]: - """并发向平台确认每条凭证。失效的删掉,暂时连不上的留着但不显示。""" + """并发向平台确认每条凭证。确认失效的删掉,暂时连不上的仍显示本机保存的信息。""" items = _read() probed = await asyncio.gather(*(_probe(item) for item in items)) changes: list[tuple[str, str, dict | None]] = [] @@ -151,8 +151,9 @@ async def available_accounts() -> list[dict]: for item, (status, record) in zip(items, probed): login_id = str(item.get("loginId") or "") changes.append((login_id, status, record)) - if status == "ok" and record is not None: - visible.append(public_view(record)) + if status == "drop": + continue + visible.append(public_view(record if status == "ok" and record is not None else item)) await _merge(changes) return visible diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index 279a94a..b5a90b5 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -415,7 +415,7 @@ async def _saved_accounts_keep_temporary_failures(tmp_path: Path, monkeypatch): monkeypatch.setattr(NqiClient, "export_cookies", exported) visible = await sessions.available_accounts() stored = {item["loginId"]: item for item in sessions._read()} - assert [item["loginId"] for item in visible] == ["a"] + assert [item["loginId"] for item in visible] == ["a", "down"] assert "dead" not in stored assert stored["down"]["cookies"][0]["value"] == "down" assert stored["a"]["cookies"][0]["value"] == "a-new" @@ -445,7 +445,7 @@ async def _saved_accounts_probe_together_and_timeout_keeps_cookie(tmp_path: Path visible = await sessions.available_accounts() assert time.monotonic() - started < 0.5 assert max(starts) - min(starts) < 0.2 - assert [item["loginId"] for item in visible] == ["b"] + assert [item["loginId"] for item in visible] == ["b", "slow"] stored = {item["loginId"]: item for item in sessions._read()} assert stored["slow"]["cookies"][0]["value"] == "slow" assert stored["b"]["cookies"][0]["value"] == "b-new" diff --git a/desktop/src/features/auth/LoginView.vue b/desktop/src/features/auth/LoginView.vue index f01a721..b44007f 100644 --- a/desktop/src/features/auth/LoginView.vue +++ b/desktop/src/features/auth/LoginView.vue @@ -2,7 +2,7 @@ import { onMounted, onUnmounted, ref } from "vue"; import { NAlert, NButton, NIcon, NInput, NModal, NSelect, NSpin, NTooltip } from "naive-ui"; import { HelpCircleOutline, MoonOutline, SunnyOutline } from "@vicons/ionicons5"; -import { ApiError, canRestartBackend, resetApi, restartBackend } from "../../shared/http"; +import { ApiError, canRestartBackend, initApi, resetApi, restartBackend } from "../../shared/http"; import { loadCaptcha, loadSaved, login, refreshCaptcha, resumeSaved, sendSms, type UserInfo } from "./api"; import { isDark, toggleTheme } from "../../shared/theme"; @@ -35,19 +35,31 @@ let timer = 0; onMounted(() => { void connect(); - void refreshSaved(); }); +function wait(ms: number) { + return new Promise((resolve) => window.setTimeout(resolve, ms)); +} + +function retryable(error: unknown) { + if (!(error instanceof ApiError)) return true; + if (error.status === 0 || error.status >= 500) return true; + return /连接失败|请求失败|后台服务没有启动|平台响应超时|服务出错/.test(error.message); +} + async function refreshSaved() { - try { - const result = await loadSaved(); - saved.value = result.accounts; - if (!result.accounts.some((item) => item.loginId === savedId.value)) { - savedId.value = result.accounts[0]?.loginId ?? null; + for (let attempt = 0; attempt < 5; attempt += 1) { + try { + const result = await loadSaved(); + saved.value = result.accounts; + if (!result.accounts.some((item) => item.loginId === savedId.value)) { + savedId.value = result.accounts[0]?.loginId ?? null; + } + return; + } catch (error) { + if (attempt === 4 || !retryable(error)) return; + await wait(400); } - } catch { - saved.value = []; - savedId.value = null; } } @@ -59,32 +71,44 @@ async function connect() { allowRestart.value = false; offline.value = ""; ready.value = false; - for (let attempt = 0; attempt < 40; attempt += 1) { + for (let attempt = 0; attempt < 3; attempt += 1) { + try { + await initApi(); + break; + } catch (error) { + backendUnavailable.value = error instanceof ApiError && error.message === "后台服务没有启动"; + if (attempt === 2) { + connecting.value = false; + connectFailed.value = true; + ready.value = false; + offline.value = backendUnavailable.value ? "后台服务没有启动" : "连接失败"; + allowRestart.value = backendUnavailable.value && canRestartBackend(); + return; + } + resetApi(); + await wait(500); + } + } + connecting.value = false; + void refreshSaved(); + for (let attempt = 0; attempt < 5; attempt += 1) { try { const result = await loadCaptcha(); sessionId.value = result.sessionId; captchaUrl.value = result.captcha; ready.value = true; - connecting.value = false; offline.value = ""; return; } catch (error) { - const failedLocally = !(error instanceof ApiError) || error.status === 0; - offline.value = error instanceof ApiError ? error.message : "连接失败"; - backendUnavailable.value = error instanceof ApiError && error.message === "后台服务没有启动"; - if (!failedLocally) { - ready.value = true; - connecting.value = false; + if (attempt === 4 || !retryable(error)) { + offline.value = error instanceof ApiError ? error.message : "连接失败"; + connectFailed.value = retryable(error); + ready.value = !connectFailed.value; return; } - await new Promise((resolve) => window.setTimeout(resolve, 500)); + await wait(500); } } - connecting.value = false; - connectFailed.value = true; - ready.value = false; - offline.value = backendUnavailable.value ? "后台服务没有启动" : "连接失败"; - allowRestart.value = backendUnavailable.value && canRestartBackend(); } async function onRestart() { diff --git a/desktop/src/shared/http.ts b/desktop/src/shared/http.ts index 3758159..4e478ac 100644 --- a/desktop/src/shared/http.ts +++ b/desktop/src/shared/http.ts @@ -86,12 +86,27 @@ function commandMissing(error: unknown, name: string) { return text.includes("not found") && text.includes(name.toLowerCase()); } +async function pingHealth(): Promise { + if (!apiBase) return false; + const controller = new AbortController(); + const timer = window.setTimeout(() => controller.abort(), 800); + try { + const response = await fetch(`${apiBase}/api/health`, { signal: controller.signal }); + return response.ok; + } catch { + return false; + } finally { + window.clearTimeout(timer); + } +} + async function probeBackend(): Promise { const { invoke } = await import("@tauri-apps/api/core"); try { const info = await invoke("backend_info"); restartAvailable = true; - return applyBackend(info); + if (!applyBackend(info)) return false; + return pingHealth(); } catch (error) { if (!commandMissing(error, "backend_info")) { restartAvailable = true; @@ -104,7 +119,7 @@ async function probeBackend(): Promise { const port = await invoke("backend_port"); if (port > 0) { apiBase = `http://127.0.0.1:${port}`; - return true; + return pingHealth(); } } catch { // 窗口可能比端口命令更早就绪。 @@ -115,10 +130,12 @@ async function probeBackend(): Promise { async function resolveApiBase(): Promise { if (!isTauri()) return; - const attempts = deepScanDone ? 1 : 50; - deepScanDone = true; + const attempts = deepScanDone ? 1 : 80; for (let attempt = 0; attempt < attempts; attempt += 1) { - if (await probeBackend()) return; + if (await probeBackend()) { + deepScanDone = true; + return; + } if (attempt + 1 < attempts) { await new Promise((resolve) => window.setTimeout(resolve, 100)); }