diff --git a/src/api/http.test.ts b/src/api/http.test.ts index 99ee10be..11bba741 100644 --- a/src/api/http.test.ts +++ b/src/api/http.test.ts @@ -1,5 +1,34 @@ import { describe, expect, it } from 'vitest' -import { buildQueryString } from './http' +import { buildQueryString, toAbsoluteBaseUrl } from './http' + +// ============================================ +// toAbsoluteBaseUrl 测试 +// ============================================ + +describe('toAbsoluteBaseUrl', () => { + it('resolves a same-origin prefix against the page origin', () => { + expect(toAbsoluteBaseUrl('/api')).toBe(`${window.location.origin}/api`) + }) + + it('strips trailing slashes from a resolved relative URL', () => { + expect(toAbsoluteBaseUrl('/api/')).toBe(`${window.location.origin}/api`) + }) + + it('resolves a protocol-relative URL against the page protocol', () => { + expect(toAbsoluteBaseUrl('//example.com/api')).toBe(`${window.location.protocol}//example.com/api`) + }) + + it('leaves absolute URLs unchanged', () => { + expect(toAbsoluteBaseUrl('http://127.0.0.1:4096')).toBe('http://127.0.0.1:4096') + expect(toAbsoluteBaseUrl('https://opencode.example.com:51133/api')).toBe( + 'https://opencode.example.com:51133/api', + ) + }) + + it('returns an empty value unchanged', () => { + expect(toAbsoluteBaseUrl('')).toBe('') + }) +}) // ============================================ // buildQueryString 测试 diff --git a/src/api/http.ts b/src/api/http.ts index dd04413e..0deefff8 100644 --- a/src/api/http.ts +++ b/src/api/http.ts @@ -5,13 +5,38 @@ import { serverStore, makeBasicAuthHeader } from '../store/serverStore' +/** + * 把相对 API 地址补成绝对地址。 + * + * `@opencode/client` 内部用 `new URL(options.baseUrl)` 构造请求地址, + * 只接受绝对 URL。Docker / standalone 镜像把 `VITE_API_BASE_URL` 设为 + * 同源前缀 `/api`,原样交给 SDK 会在**发请求前**抛 `Invalid URL`: + * 健康检查走原生 fetch(支持相对路径)显示在线,但会话、模型、消息、 + * 终端等所有 SDK 请求全部失败。 + * + * 这里按当前页面 origin 补全,既保留反代下的 `/api` 前缀部署方式, + * 也兼容 Tauri / 桌面端直接配置绝对地址的场景。 + */ +export function toAbsoluteBaseUrl(baseUrl: string): string { + if (!baseUrl) return baseUrl + // 已是绝对 URL(带 scheme)就原样返回,不去尾部斜杠,避免改掉用户配置 + if (/^[a-z][a-z\d+.-]*:\/\//i.test(baseUrl)) return baseUrl + if (typeof window === 'undefined') return baseUrl + // file:// 等非标准页面的 origin 是字符串 'null',不能作为 URL base + const origin = window.location.origin + if (!origin || origin === 'null') return baseUrl + return new URL(baseUrl, origin).toString().replace(/\/+$/, '') +} + /** * 获取 API Base URL * 优先使用 serverStore 中的活动服务器,回退到常量 + * 返回值保证是绝对地址(SDK / PTY 都要求完整 URL) * @param serverId 指定服务器(缺省用活动服务器) */ export function getApiBaseUrl(serverId?: string): string { - return serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const raw = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + return toAbsoluteBaseUrl(raw) } /** diff --git a/src/api/sdk.test.ts b/src/api/sdk.test.ts index 6f8d2132..be11ad51 100644 --- a/src/api/sdk.test.ts +++ b/src/api/sdk.test.ts @@ -62,6 +62,19 @@ describe('v2 client request lifecycle', () => { expect(client.__options.baseUrl).toBe('http://127.0.0.1:4096') }) + it('resolves a relative base URL before handing it to the SDK', async () => { + // 回归:standalone 镜像把 VITE_API_BASE_URL 设成 `/api`,SDK 内部 + // `new URL('/api')` 会抛 Invalid URL。必须按页面 origin 补全。 + getActiveBaseUrlMock.mockReturnValue('/api') + + const { getSDKClient } = await import('./sdk') + const client = getSDKClient() as unknown as MockClient + + expect(client.__options.baseUrl).toBe(`${window.location.origin}/api`) + // 缓存 key 也用补全后的地址,重复调用必须命中同一实例 + expect(getSDKClient()).toBe(client) + }) + it('aborts in-flight requests when the server endpoint changes', async () => { const { abortInFlightApiRequests, getSDKClient } = await import('./sdk') const client = getSDKClient() as unknown as MockClient diff --git a/src/api/sdk.ts b/src/api/sdk.ts index a8c921e4..56fe5059 100644 --- a/src/api/sdk.ts +++ b/src/api/sdk.ts @@ -14,6 +14,7 @@ import { OpenCode } from '@opencode/client/promise' import type { OpenCodeClient } from '@opencode/client/promise' import { serverStore, makeBasicAuthHeader } from '../store/serverStore' import { isTauri } from '../utils/tauri' +import { toAbsoluteBaseUrl } from './http' /** v2 客户端实例(内部 API 层的唯一形状) */ export type ServerApi = OpenCodeClient @@ -151,8 +152,20 @@ interface CachedClientEntry { const _cachedClients = new Map() +/** + * 读取当前服务器的 baseUrl,并补成 SDK 要求的绝对地址。 + * + * standalone 部署的 `VITE_API_BASE_URL=/api` 是相对前缀,直接用会被 + * `new URL('/api')` 判为 Invalid URL;缓存 key 也必须用补全后的值, + * 否则相对/绝对两种写法会各建一份客户端。 + */ +function resolveClientBaseUrl(serverId?: string): string { + const raw = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + return toAbsoluteBaseUrl(raw) +} + function buildCacheKey(serverId?: string): string { - const baseUrl = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const baseUrl = resolveClientBaseUrl(serverId) const auth = serverId ? serverStore.getServerAuth(serverId) : serverStore.getActiveAuth() const authPart = auth?.password ? `${auth.username}:${auth.password}` : '' return `${baseUrl}|${authPart}` @@ -179,7 +192,7 @@ export function getSDKClient(serverId?: string): ServerApi { return cached.client } - const baseUrl = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const baseUrl = resolveClientBaseUrl(serverId) const headers = buildHeaders(serverId) const generation = _apiRequestGeneration