From 263c093b6507c2f002e1a2164e700baa38aff252 Mon Sep 17 00:00:00 2001 From: ZacharyZcR Date: Fri, 26 Jun 2026 15:04:35 +0800 Subject: [PATCH] Fix mobile host list proxy fallback --- app/main-axios.ts | 72 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 4 deletions(-) diff --git a/app/main-axios.ts b/app/main-axios.ts index d633a55..19f6e33 100644 --- a/app/main-axios.ts +++ b/app/main-axios.ts @@ -446,6 +446,19 @@ function getHostBase(defaultPort: number): string { return `http://localhost:${defaultPort}/host`; } +function getHostApiBaseCandidates(defaultPort: number): string[] { + const rootBase = getRootBase(defaultPort).replace(/\/$/, ""); + const sshBase = getSshBase(defaultPort).replace(/\/$/, ""); + const candidates = [ + getHostBase(defaultPort).replace(/\/$/, ""), + `${sshBase}/host`, + sshBase, + rootBase, + ]; + + return [...new Set(candidates)]; +} + function initializeApiInstances() { sshHostApi = createApiInstance(getHostBase(8081), "SSH_HOST"); @@ -789,11 +802,62 @@ function normalizeSSHHost(host: SSHHost): SSHHost { } export async function getSSHHosts(): Promise { + let lastError: unknown = null; + let firstEmptyHosts: { api: AxiosInstance; hosts: SSHHost[] } | null = null; + + const normalizeHostResponse = (data: unknown): SSHHost[] | null => { + const hostList = Array.isArray(data) + ? data + : Array.isArray((data as { hosts?: unknown })?.hosts) + ? ((data as { hosts: SSHHost[] }).hosts as unknown[]) + : null; + + return hostList ? (hostList as SSHHost[]).map(normalizeSSHHost) : null; + }; + try { - const response = await sshHostApi.get("/db/host"); - return Array.isArray(response.data) - ? response.data.map(normalizeSSHHost) - : response.data; + for (const baseURL of getHostApiBaseCandidates(8081)) { + try { + const candidateApi = createApiInstance(baseURL, "SSH_HOST"); + const response = await candidateApi.get("/db/host", { + headers: { + Accept: "application/json", + "Cache-Control": "no-cache", + }, + }); + const hosts = normalizeHostResponse(response.data); + if (hosts) { + if (hosts.length === 0) { + firstEmptyHosts ??= { api: candidateApi, hosts }; + continue; + } + + sshHostApi = candidateApi; + return hosts; + } + + lastError = new Error( + `Unexpected host list response from ${baseURL}/db/host`, + ); + } catch (error: any) { + lastError = error; + const status = error?.response?.status; + if (status === 401 || status === 403) { + throw error; + } + } + } + + if (firstEmptyHosts) { + sshHostApi = firstEmptyHosts.api; + return firstEmptyHosts.hosts; + } + + if (lastError) { + throw lastError; + } + + return []; } catch (error) { handleApiError(error, "fetch SSH hosts"); }