diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.ts index 8db7ff8cb3..6ff2885126 100644 --- a/apps/desktop/electron/main/bootstrap/window.ts +++ b/apps/desktop/electron/main/bootstrap/window.ts @@ -35,6 +35,7 @@ import { } from "../work-panel-window"; import { readWindowState, writeWindowState } from "../window-preferences"; import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu"; +import { recoverRendererAfterGone } from "../renderer-recovery"; function windowsIconPath(): string | undefined { if (process.platform !== "win32") return undefined; @@ -468,12 +469,36 @@ export async function createWindow({ void safeOpenExternal(url).catch(() => undefined); return { action: "deny" }; }); + let windowCloseAccepted = false; window.webContents.on("did-start-loading", () => { windowState.notificationViewingSessionId = null; if (windowState.mainWindow === window) resetMenuRendererReady(window); }); - window.webContents.on("render-process-gone", () => { + window.webContents.on("render-process-gone", (_event, details) => { windowState.notificationViewingSessionId = null; + recoverRendererAfterGone(details, { + isCurrentWindow: windowState.mainWindow === window, + quitting: windowState.quitting, + windowCloseAccepted, + windowDestroyed: window.isDestroyed(), + webContentsDestroyed: window.webContents.isDestroyed(), + reload: () => window.webContents.reload(), + log: (rendererDetails, reloaded) => { + logger.app( + "diagnostics", + rendererDetails.reason === "clean-exit" ? "info" : "warn", + "renderer process exited", + { + event: "rendererProcessGone", + data: { + reason: rendererDetails.reason, + exitCode: rendererDetails.exitCode, + reloaded, + }, + }, + ); + }, + }); }); // Devtools shortcut, gated on developer mode. Frameless windows get no @@ -886,6 +911,7 @@ export async function createWindow({ windowState.quitting || windowsAllowedToClose.has(window) ) { + windowCloseAccepted = true; return; } event.preventDefault(); diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.ts index 06a4ec1344..8dedf64195 100644 --- a/apps/desktop/electron/main/ipc/provider-ipc.ts +++ b/apps/desktop/electron/main/ipc/provider-ipc.ts @@ -398,9 +398,8 @@ export function registerProviderIpc({ } }; - // A signed-in vendor account has no API key. Copilot and the static - // vendors are listed from pi-ai. xAI instead reads GET /v1/models with - // the account token inside VendorOAuth.listModels. + // A signed-in vendor account has no API key. VendorOAuth.listModels + // reads that account's model endpoint; pi-ai is only the fallback. if (req.source !== "cache" && provider?.authKind === OAUTH_AUTH_KIND) { try { const options = await vendorOAuth.listModels(provider.id); diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.ts index 99e9116a1d..11ff335805 100644 --- a/apps/desktop/electron/main/models-dev-catalog.ts +++ b/apps/desktop/electron/main/models-dev-catalog.ts @@ -1,5 +1,5 @@ import { readFile } from "node:fs/promises"; -import { modelIdsMatch } from "@pi-desktop/shared"; +import { MODEL_VENDOR_PREFIXES, catalogModelIdsMatch, stripVariantSuffix } from "@pi-desktop/shared"; import type { ModelCost, ModelCostTier, @@ -501,28 +501,6 @@ function normalizedModelId(value: string): string { return value.trim().toLowerCase(); } -const MODEL_VENDOR_PREFIXES = new Set([ - "anthropic", - "amazon", - "aws", - "cohere", - "deepseek", - "deepseek-ai", - "gemini", - "google", - "meta", - "minimax", - "mistral", - "moonshot", - "moonshotai", - "openai", - "qwen", - "z-ai", - "zai", - "zhipuai", - "x-ai", - "xai", -]); function modelVendorPrefixes(model: ModelsDevModel): string[] { const prefixes = new Set(); @@ -813,30 +791,70 @@ class ModelsDevLookupIndex { } candidates(requested: string): readonly IndexedModel[] { - return this.byModelId.get(requested) ?? EMPTY_CANDIDATES; + const keys = lookupCandidateKeys(requested); + if (keys.length === 0) return EMPTY_CANDIDATES; + if (keys.length === 1) { + return this.byModelId.get(keys[0]) ?? EMPTY_CANDIDATES; + } + const result: IndexedModel[] = []; + const seen = new Set(); + for (const key of keys) { + const bucket = this.byModelId.get(key); + if (!bucket) continue; + for (const entry of bucket) { + if (!seen.has(entry)) { + seen.add(entry); + result.push(entry); + } + } + } + return result; } } -/** The normalized id, the `@region`-less base, and every vendor-prefixed form - * `modelIdsMatch` treats as equivalent, so a query finds all matching catalog - * models through the index without a full scan. */ -function registrationKeys(modelId: string): string[] { +/** Index only aliases the matcher can accept: exact IDs, full slash-path + * leaves, known-vendor dash/dot prefixes, and the supported suffix variants. + * The matcher remains the final authority (including known-vendor conflicts). */ +function candidateKeys(modelId: string): string[] { + const normalized = normalizedModelId(modelId); + if (!normalized) return []; const keys = new Set(); - const raw = modelId.trim(); - keys.add(normalizedModelId(raw)); - const at = raw.indexOf("@"); - if (at > 0) keys.add(normalizedModelId(raw.slice(0, at))); - for (const separator of ["/", "-", "."] as const) { - for (const prefix of MODEL_VENDOR_PREFIXES) { - const head = `${prefix}${separator}`; - if (raw.startsWith(head) && raw.length > head.length) { - keys.add(normalizedModelId(raw.slice(head.length))); + const at = normalized.indexOf("@"); + const base = at > 0 ? normalized.slice(0, at) : normalized; + + const add = (value: string) => { + if (!value) return; + keys.add(value); + const slash = value.lastIndexOf("/"); + if (slash >= 0 && slash < value.length - 1) keys.add(value.slice(slash + 1)); + for (const separator of ["-", "."] as const) { + for (const vendor of MODEL_VENDOR_PREFIXES) { + const head = `${vendor}${separator}`; + if (value.startsWith(head) && value.length > head.length) { + keys.add(value.slice(head.length)); + } } } + }; + + // Strip a suffix only after the region, just as catalogModelIdsMatch does. Add + // aliases from both sides so a suffixed catalog ID or request can find its peer. + for (const value of new Set([normalized, base, stripVariantSuffix(base)])) { + add(value); + const slash = value.lastIndexOf("/"); + if (slash >= 0 && slash < value.length - 1) add(value.slice(slash + 1)); } return [...keys]; } +function registrationKeys(modelId: string): string[] { + return candidateKeys(modelId); +} + +function lookupCandidateKeys(requested: string): string[] { + return candidateKeys(requested); +} + const EMPTY_CANDIDATES: readonly IndexedModel[] = []; @@ -951,21 +969,27 @@ export class ModelsDevCatalog { } private providerFor(input: { vendorKey?: string; baseUrl?: string }): ModelsDevProvider | undefined { - const byApi = [...this.providers.values()].find((provider) => + const candidates = new Set(providerKeyCandidates(input.vendorKey)); + const apiProviders = [...this.providers.values()].filter((provider) => apiMatches(input.baseUrl, provider.api), ); - if (byApi) return byApi; - const candidates = new Set(providerKeyCandidates(input.vendorKey)); - for (const provider of this.providers.values()) { - if (candidates.has(normalizedProviderKey(provider.providerKey))) return provider; + if (apiProviders.length > 0) { + return apiProviders.find((provider) => + candidates.has(normalizedProviderKey(provider.providerKey)), + ) ?? apiProviders[0]; } const knownKey = Object.entries(KNOWN_PROVIDER_BASE_URLS).find(([, urls]) => urls.some((url) => apiMatches(input.baseUrl, url)), )?.[0]; - if (!knownKey) return undefined; - const knownCandidates = new Set(providerKeyCandidates(knownKey)); + if (knownKey) { + const knownCandidates = new Set(providerKeyCandidates(knownKey)); + const knownProvider = [...this.providers.values()].find((provider) => + knownCandidates.has(normalizedProviderKey(provider.providerKey)), + ); + if (knownProvider) return knownProvider; + } return [...this.providers.values()].find((provider) => - knownCandidates.has(normalizedProviderKey(provider.providerKey)), + candidates.has(normalizedProviderKey(provider.providerKey)), ); } @@ -992,7 +1016,9 @@ export class ModelsDevCatalog { } const candidates: Array<{ model: ModelsDevModel; score: number }> = []; for (const { model, provider } of [...preferred, ...rest]) { - if (!modelIdsMatch(model.modelId, requested)) continue; + // A known endpoint must not inherit another provider's capabilities. + if (preferredProvider && provider !== preferredProvider) continue; + if (!catalogModelIdsMatch(model.modelId, requested)) continue; let score = model.modelId.toLowerCase() === requested ? 20 : 10; if (provider === preferredProvider) score += 100; if (apiMatches(input.baseUrl, provider.api)) score += 80; diff --git a/apps/desktop/electron/main/oauth.ts b/apps/desktop/electron/main/oauth.ts index 9d1a342197..783fe2dcbb 100644 --- a/apps/desktop/electron/main/oauth.ts +++ b/apps/desktop/electron/main/oauth.ts @@ -41,7 +41,14 @@ import { type ModelConfig, type VendorModelBinding, } from "@pi-desktop/agent-runtime"; -import { discoverProviderModels } from "./model-discovery.ts"; +import { + isConversationModelId, + parseVendorModelIds, + pinnedSiblingId, + readVendorModelList, + vendorModelListRequest, + wireForLiveModel, +} from "./vendor-live-models.ts"; import { OAUTH_AUTH_KIND, type OAuthLoginEvent, @@ -91,9 +98,8 @@ export function protocolForApiStyle(apiStyle: string): string { return PROTOCOL_BY_API_STYLE[apiStyle] ?? "openai_compatible"; } -const XAI_VENDOR_ID = "xai"; -const XAI_MODELS_URL_BASE = "https://api.x.ai/v1"; -const XAI_LIVE_MODELS_TTL_MS = 30_000; +const LIVE_MODELS_TTL_MS = 30_000; +const LIVE_MODELS_NEGATIVE_TTL_MS = 15_000; const THINKING_LEVEL_ORDER = [ "off", "minimal", @@ -104,16 +110,9 @@ const THINKING_LEVEL_ORDER = [ "max", ] as const satisfies readonly ThinkingLevel[]; -/** - * xAI's `/models` list also publishes image and video generators. Those are not - * conversation models; the chat picker and session launch both reject them. - */ -const XAI_NON_CONVERSATION_MODEL = - /(?:^|[-_/])(?:imagine|image|video|tts|stt|embed(?:ding)?|whisper|aurora|flux)(?:$|[-_/])/i; - +/** xAI and the other account lists also publish generators. Those are not conversation models. */ export function isXaiConversationModel(modelId: string): boolean { - const id = modelId.trim(); - return id.length > 0 && !XAI_NON_CONVERSATION_MODEL.test(id); + return isConversationModelId(modelId); } function thinkingLevelsFromPiModel(model: Model): ThinkingLevel[] { @@ -171,6 +170,8 @@ export type VendorOAuthDeps = { option: OAuthModelOption; }) => Promise; newId?: () => string; + /** Test seam. Defaults to the process fetch. */ + fetch?: typeof fetch; }; /** @@ -234,8 +235,9 @@ export class VendorOAuth { private readonly logins = new Map(); /** One pi-ai collection and credential store per local OAuth account row. */ private readonly accountModels = new Map(); - /** Successful xAI `/models` responses, so one login does not refetch per model. */ - private readonly xaiLiveModels = new Map(); + /** Successful and failed account model lists, so launch does not refetch per model. */ + private readonly liveModelCache = new Map(); + private readonly liveModelLoads = new Map>(); /** Per-account write chain: `modify` must be a serialized read-modify-write. */ private readonly chains = new Map>(); private catalogPromise?: Promise; @@ -362,7 +364,8 @@ export class VendorOAuth { await running.finished?.catch(() => undefined); } this.accountModels.delete(providerId); - this.xaiLiveModels.delete(providerId); + this.liveModelCache.delete(providerId); + this.liveModelLoads.delete(providerId); await this.deps.call("providers.delete", { id: providerId }); } @@ -384,21 +387,17 @@ export class VendorOAuth { /** * Models the signed-in account may actually use. * - * Copilot and the other static vendors still come from pi-ai: `getAvailable` - * applies that vendor's `filterModels`. xAI is different. Its pinned catalog - * stops at whatever shipped in pi-ai, so a model Grok has already entitled - * (grok-4.7 today) never becomes selectable. For that vendor the account's - * own `GET /v1/models` list is the authority, and the pinned catalog is only - * the fallback when that request fails. + * The account's own model list is the authority. pi-ai (`getAvailable`, + * including a vendor `filterModels`) is used only when that request cannot + * be read. Radius keeps its gateway refresh and does not get a second probe. */ async listModels(providerId: string): Promise { return this.withRowHeaders(providerId, async () => { const account = await this.accountForProvider(providerId); if (!account) throw new Error(`unknown vendor account provider: ${providerId}`); - // Dynamic catalogs (radius, Copilot) are empty until refreshed; static and - // unconfigured providers are skipped inside pi-ai. + // Dynamic catalogs (radius) are empty until refreshed. await account.models.refresh({ providers: [account.vendorId] }); - const live = await this.liveXaiModels(account); + const live = await this.liveAccountModels(account); if (live) return live; const available = await account.models.getAvailable(account.vendorId); return available.map((model) => this.optionFor(model)); @@ -439,15 +438,14 @@ export class VendorOAuth { if (!account) return undefined; let model = account.models.getModel(account.vendorId, modelId); if (!model) { - // Dynamic catalogs are empty until the first refresh. await account.models.refresh({ providers: [account.vendorId] }); model = account.models.getModel(account.vendorId, modelId); } - const live = await this.liveXaiModels(account); + const live = await this.liveAccountModels(account); if (live) { const option = live.find((item) => item.modelId === modelId); - // A successful Grok list replaces the pinned catalog. An id it did not - // return is not offered, even when pi-ai still ships that id. + // A successful account list replaces the pinned catalog. An id it did + // not return is not offered, even when pi-ai still ships that id. if (!option) return undefined; return this.bindingFromOption(account, option); } @@ -456,52 +454,88 @@ export class VendorOAuth { } /** - * Chat models the signed-in xAI account can call right now. + * Chat models the signed-in account can call right now. * `undefined` means the live list could not be read; callers keep the - * pinned catalog. Image and video generators are dropped. + * pinned catalog. */ - private async liveXaiModels( + private async liveAccountModels( + account: AccountModels, + ): Promise { + if (account.vendorId === "radius") return undefined; + const cached = this.liveModelCache.get(account.providerId); + if (cached) { + const ttl = cached.models ? LIVE_MODELS_TTL_MS : LIVE_MODELS_NEGATIVE_TTL_MS; + if (Date.now() - cached.at < ttl) return cached.models ?? undefined; + } + const pending = this.liveModelLoads.get(account.providerId); + if (pending) return pending; + const load = this.loadLiveAccountModels(account).finally(() => { + this.liveModelLoads.delete(account.providerId); + }); + this.liveModelLoads.set(account.providerId, load); + return load; + } + + private rememberLiveModels( + providerId: string, + models: OAuthModelOption[] | null, + ): OAuthModelOption[] | undefined { + this.liveModelCache.set(providerId, { at: Date.now(), models }); + return models ?? undefined; + } + + private async loadLiveAccountModels( account: AccountModels, ): Promise { - if (account.vendorId !== XAI_VENDOR_ID) return undefined; - const cached = this.xaiLiveModels.get(account.providerId); - if (cached && Date.now() - cached.at < XAI_LIVE_MODELS_TTL_MS) return cached.models; let apiKey: string | undefined; - let baseUrl = XAI_MODELS_URL_BASE; + let baseUrl: string | undefined; try { const resolved = await account.models.getAuth(account.vendorId); apiKey = resolved?.auth.apiKey; - if (resolved?.auth.baseUrl) baseUrl = resolved.auth.baseUrl.replace(/\/+$/, ""); + baseUrl = resolved?.auth.baseUrl; } catch (error) { - this.log("warn", "xAI account auth unavailable for model list", { + this.log("warn", "vendor account auth unavailable for model list", { vendorId: account.vendorId, message: error instanceof Error ? error.message : String(error), }); return undefined; } - if (!apiKey) return undefined; + const request = vendorModelListRequest({ + vendorId: account.vendorId, + apiKey, + baseUrl, + }); + if (!request) return undefined; try { - const discovered = await discoverProviderModels({ - baseUrl, - apiKey, - apiStyle: "responses", + const body = await readVendorModelList(request, this.deps.fetch ?? globalThis.fetch); + const ids = parseVendorModelIds(account.vendorId, body, request.allowPolicyFallback); + if (!ids || ids.length === 0) return this.rememberLiveModels(account.providerId, null); + const pinned = await account.models.getAvailable(account.vendorId); + const known = new Map(pinned.map((model) => [model.id, model])); + const wires = pinned.map((model) => ({ + id: model.id, + api: model.api, + baseUrl: model.baseUrl, + })); + const models = ids.flatMap((modelId) => { + const pinnedModel = known.get(modelId); + if (pinnedModel) return [this.optionFor(pinnedModel)]; + const wire = wireForLiveModel(account.vendorId, modelId, wires, request.accountBaseUrl); + if (!wire?.api || !wire.baseUrl) return []; + return [{ + modelId, + apiStyle: apiStyleForWireApi(wire.api), + baseUrl: wire.baseUrl, + }]; }); - const models = discovered - .filter((model) => isXaiConversationModel(model.modelId)) - .map((model) => ({ - modelId: model.modelId, - apiStyle: apiStyleForWireApi("openai-responses"), - baseUrl, - })); - if (models.length === 0) return undefined; - this.xaiLiveModels.set(account.providerId, { at: Date.now(), models }); - return models; + if (models.length === 0) return this.rememberLiveModels(account.providerId, null); + return this.rememberLiveModels(account.providerId, models); } catch (error) { - this.log("warn", "xAI account model list failed", { + this.log("warn", "vendor account model list failed", { vendorId: account.vendorId, message: error instanceof Error ? error.message : String(error), }); - return undefined; + return this.rememberLiveModels(account.providerId, null); } } @@ -513,7 +547,7 @@ export class VendorOAuth { vendorKey: account.vendorId, option, }).catch(() => undefined); - const modelConfig = this.withPinnedXaiFallback(account, option, published); + const modelConfig = await this.withPinnedSiblingFallback(account, option, published); const capabilities = capabilitiesFromModelConfig(modelConfig); return { apiStyle: option.apiStyle, @@ -525,20 +559,25 @@ export class VendorOAuth { /** * models.dev is the metadata source when it already knows the id. A model - * that exists only on the live xAI list (the usual case for a just-released - * Grok) otherwise inherits limits and thinking levels from the newest pinned - * sibling, instead of the 128k generic shape. + * that exists only on the live list otherwise inherits limits and thinking + * levels from a pinned sibling of the same tier. xAI uses an explicit + * newest-first order so pin order cannot pick an older Grok. */ - private withPinnedXaiFallback( + private async withPinnedSiblingFallback( account: AccountModels, option: OAuthModelOption, published: ModelConfig | undefined, - ): ModelConfig { + ): Promise { const config = published ?? genericModelConfig(option.modelId, option.baseUrl); - if (account.vendorId !== XAI_VENDOR_ID || config.source !== "generic") return config; - const sibling = ["grok-4.6", "grok-4.5", "grok-4.3"] - .map((id) => account.models.getModel(account.vendorId, id)) - .find((model) => model !== undefined); + if (config.source !== "generic") return config; + const pinned = await account.models.getAvailable(account.vendorId); + if (pinned.some((model) => model.id === option.modelId)) return config; + const siblingId = pinnedSiblingId( + account.vendorId, + option.modelId, + pinned.map((model) => model.id), + ); + const sibling = siblingId ? pinned.find((model) => model.id === siblingId) : undefined; if (!sibling) return config; const input = (sibling.input ?? []).filter( (modality): modality is "text" | "image" => modality === "text" || modality === "image", diff --git a/apps/desktop/electron/main/renderer-recovery.ts b/apps/desktop/electron/main/renderer-recovery.ts new file mode 100644 index 0000000000..e48bfe7d7d --- /dev/null +++ b/apps/desktop/electron/main/renderer-recovery.ts @@ -0,0 +1,34 @@ +export type RendererGoneDetails = Readonly<{ + reason: string; + exitCode: number; +}>; + +export type RendererRecoveryDependencies = Readonly<{ + isCurrentWindow: boolean; + quitting: boolean; + windowCloseAccepted: boolean; + windowDestroyed: boolean; + webContentsDestroyed: boolean; + reload: () => void; + log: (details: RendererGoneDetails, reloaded: boolean) => void; +}>; + +/** Reload an unexpectedly exited renderer while its owning app window is live. */ +export function recoverRendererAfterGone( + details: RendererGoneDetails, + dependencies: RendererRecoveryDependencies, +): boolean { + const reloaded = + details.reason !== "clean-exit" && + dependencies.isCurrentWindow && + !dependencies.quitting && + !dependencies.windowCloseAccepted && + !dependencies.windowDestroyed && + !dependencies.webContentsDestroyed; + + dependencies.log(details, reloaded); + if (!reloaded) return false; + + dependencies.reload(); + return true; +} diff --git a/apps/desktop/electron/main/vendor-live-models.ts b/apps/desktop/electron/main/vendor-live-models.ts new file mode 100644 index 0000000000..31bad4fa6b --- /dev/null +++ b/apps/desktop/electron/main/vendor-live-models.ts @@ -0,0 +1,389 @@ +/** + * Live model lists for signed-in vendor accounts. + * + * Each vendor is probed on the endpoint that actually publishes the account's + * models. pi-ai's pinned catalog is not consulted here; callers use it only + * when this module cannot return a list. + */ + +const LIVE_MODELS_TIMEOUT_MS = 8_000; +const MAX_RETRY_DELAY_MS = 1_000; + +const NON_CONVERSATION_MODEL = + /(?:^|[-_/])(?:imagine|image|video|tts|stt|speech|embed(?:ding)?|whisper|aurora|flux|realtime|moderation)(?:$|[-_/])/i; + +const SINGLE_WIRE_API: Record = { + anthropic: "anthropic-messages", + "kimi-coding": "anthropic-messages", + meta: "openai-responses", + "openai-codex": "openai-codex-responses", + xai: "openai-responses", +}; + +const DEFAULT_BASE_URL: Record = { + anthropic: "https://api.anthropic.com", + "github-copilot": "https://api.individual.githubcopilot.com", + "kimi-coding": "https://api.kimi.com/coding", + meta: "https://api.meta.ai/v1", + "openai-codex": "https://chatgpt.com/backend-api", + openrouter: "https://openrouter.ai/api/v1", + xai: "https://api.x.ai/v1", +}; + +const COPILOT_HEADERS = { + "User-Agent": "GitHubCopilotChat/0.35.0", + "Editor-Version": "vscode/1.107.0", + "Editor-Plugin-Version": "copilot-chat/0.35.0", + "Copilot-Integration-Id": "vscode-chat", + "X-GitHub-Api-Version": "2026-06-01", +} as const; + +const COPILOT_INDIVIDUAL_BASE = "https://api.individual.githubcopilot.com"; +const XAI_SIBLING_ORDER = ["grok-4.6", "grok-4.5", "grok-4.3"] as const; +const TIER_TOKENS = new Set([ + "astra", + "fable", + "flash", + "haiku", + "luna", + "mini", + "nano", + "opus", + "pro", + "sol", + "sonnet", + "spark", + "terra", +]); + +export type VendorModelListRequest = { + url: string; + headers: Record; + /** Host stored on a model the pin does not know yet. */ + accountBaseUrl: string; + allowPolicyFallback: boolean; +}; + +export type PinnedWire = { + id: string; + api: string; + baseUrl: string; +}; + +export function isConversationModelId(modelId: string): boolean { + const id = modelId.trim(); + return id.length > 0 && !NON_CONVERSATION_MODEL.test(id); +} + +function asRecord(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +function trimBase(url: string | undefined, fallback: string): string { + const value = (url?.trim() || fallback).replace(/\/+$/, ""); + return value; +} + +function chatgptAccountId(token: string): string | undefined { + const part = token.split(".")[1]; + if (!part) return undefined; + try { + const padded = part.replace(/-/g, "+").replace(/_/g, "/"); + const payload = JSON.parse(Buffer.from(padded, "base64").toString("utf8")) as { + ["https://api.openai.com/auth"]?: { chatgpt_account_id?: unknown }; + }; + const id = payload?.["https://api.openai.com/auth"]?.chatgpt_account_id; + return typeof id === "string" && id.trim() ? id : undefined; + } catch { + return undefined; + } +} + +/** The account's model-list request, or undefined when this vendor has none. */ +export function vendorModelListRequest(input: { + vendorId: string; + apiKey?: string; + baseUrl?: string; +}): VendorModelListRequest | undefined { + const apiKey = input.apiKey?.trim() ?? ""; + if (!apiKey) return undefined; + const fallback = DEFAULT_BASE_URL[input.vendorId]; + if (!fallback && input.vendorId !== "github-copilot") return undefined; + const base = trimBase(input.baseUrl, fallback ?? COPILOT_INDIVIDUAL_BASE); + const bearer = { Authorization: `Bearer ${apiKey}`, Accept: "application/json" }; + + if (input.vendorId === "openai-codex") { + const accountId = chatgptAccountId(apiKey); + if (!accountId) return undefined; + return { + url: `${base}/codex/models`, + accountBaseUrl: base, + allowPolicyFallback: false, + headers: { + ...bearer, + "chatgpt-account-id": accountId, + originator: "pi", + }, + }; + } + + if (input.vendorId === "github-copilot") { + return { + url: `${base}/models`, + accountBaseUrl: base, + allowPolicyFallback: base === COPILOT_INDIVIDUAL_BASE, + headers: { ...bearer, ...COPILOT_HEADERS }, + }; + } + + if (input.vendorId === "anthropic") { + const root = base.endsWith("/v1") ? base : `${base}/v1`; + const oauth = apiKey.includes("sk-ant-oat"); + return { + url: `${root}/models?limit=1000`, + accountBaseUrl: base.endsWith("/v1") ? base.slice(0, -3) : base, + allowPolicyFallback: false, + headers: oauth + ? { + ...bearer, + "anthropic-version": "2023-06-01", + "anthropic-beta": "claude-code-20250219,oauth-2025-04-20", + "x-app": "cli", + "user-agent": "claude-cli/2.1.251", + } + : { + Accept: "application/json", + "x-api-key": apiKey, + "anthropic-version": "2023-06-01", + }, + }; + } + + if (input.vendorId === "kimi-coding") { + const root = base.endsWith("/v1") ? base : `${base}/v1`; + return { + url: `${root}/models?limit=1000`, + accountBaseUrl: base.endsWith("/v1") ? base.slice(0, -3) : base, + allowPolicyFallback: false, + headers: { ...bearer, "anthropic-version": "2023-06-01" }, + }; + } + + if ( + input.vendorId === "xai" || + input.vendorId === "meta" || + input.vendorId === "openrouter" + ) { + return { + url: `${base}/models`, + accountBaseUrl: base, + allowPolicyFallback: false, + headers: bearer, + }; + } + + return undefined; +} + +function conversationIds(ids: string[]): string[] { + const seen = new Set(); + const out: string[] = []; + for (const id of ids) { + const modelId = id.trim(); + if (!isConversationModelId(modelId) || seen.has(modelId)) continue; + seen.add(modelId); + out.push(modelId); + } + return out; +} + +function parseDataIds(body: unknown): string[] | null { + const record = asRecord(body); + const data = Array.isArray(record?.data) + ? record.data + : Array.isArray(body) + ? body + : null; + if (!data) return null; + return conversationIds( + data.flatMap((entry) => { + const id = asRecord(entry)?.id; + return typeof id === "string" ? [id] : []; + }), + ); +} + +function parseCodexIds(body: unknown): string[] | null { + const models = asRecord(body)?.models; + if (!Array.isArray(models)) return null; + return conversationIds( + models.flatMap((entry) => { + const item = asRecord(entry); + const slug = item?.slug ?? item?.id; + if (!item || typeof slug !== "string") return []; + const visibility = item.visibility; + if (visibility === "hide" || visibility === "hidden") return []; + return [slug]; + }), + ); +} + +function parseCopilotIds(body: unknown, allowPolicyFallback: boolean): string[] | null { + const data = asRecord(body)?.data; + if (!Array.isArray(data)) return null; + const accountModels = data.flatMap((entry) => { + const item = asRecord(entry); + const id = item?.id; + if (!item || typeof id !== "string") return []; + const supports = asRecord(asRecord(item.capabilities)?.supports); + if (supports?.tool_calls === false) return []; + const policyState = asRecord(item.policy)?.state; + return [{ + id, + pickerEnabled: item.model_picker_enabled === true, + policyState: typeof policyState === "string" ? policyState : undefined, + }]; + }); + const pickerIds = accountModels + .filter((model) => model.pickerEnabled && model.policyState !== "disabled") + .map((model) => model.id); + const available = pickerIds.length > 0 || !allowPolicyFallback + ? pickerIds + : accountModels + .filter((model) => model.policyState === "enabled") + .map((model) => model.id); + return conversationIds(available); +} + +/** Parsed chat-model ids, or null when the payload is not that vendor's list. */ +export function parseVendorModelIds( + vendorId: string, + body: unknown, + allowPolicyFallback = false, +): string[] | null { + if (vendorId === "github-copilot") return parseCopilotIds(body, allowPolicyFallback); + if (vendorId === "openai-codex") return parseCodexIds(body); + return parseDataIds(body); +} + +export function familyKey(modelId: string): string { + const slash = modelId.indexOf("/"); + const head = slash > 0 ? modelId.slice(0, slash) : modelId.split("-")[0] ?? ""; + return head.trim().toLowerCase(); +} + +/** + * Wire API for an id the pin does not contain. + * A vendor with one wire API uses that. Copilot and OpenRouter only keep an + * id whose family already maps to exactly one wire API in the pin. + */ +export function wireForLiveModel( + vendorId: string, + modelId: string, + pinned: readonly PinnedWire[], + accountBaseUrl: string, +): { api: string; baseUrl: string } | undefined { + const single = SINGLE_WIRE_API[vendorId]; + if (single) return { api: single, baseUrl: accountBaseUrl }; + const family = familyKey(modelId); + if (!family) return undefined; + const same = pinned.filter((model) => familyKey(model.id) === family); + const apis = new Set(same.map((model) => model.api)); + if (apis.size !== 1) return undefined; + return { + api: [...apis][0] ?? "", + baseUrl: accountBaseUrl || same[0]?.baseUrl || "", + }; +} + +function versionKey(id: string): number[] { + return (id.match(/\d+(?:\.\d+)*/g) ?? []).flatMap((part) => + part.split(".").map((piece) => Number(piece)), + ); +} + +function newerFirst(a: string, b: string): number { + const left = versionKey(a); + const right = versionKey(b); + const length = Math.max(left.length, right.length); + for (let index = 0; index < length; index += 1) { + const delta = (right[index] ?? 0) - (left[index] ?? 0); + if (delta !== 0) return delta; + } + return a.localeCompare(b); +} + +function tierToken(modelId: string): string | undefined { + return modelId + .toLowerCase() + .split(/[-/]/) + .find((part) => TIER_TOKENS.has(part)); +} + +/** + * Pinned id whose limits a just-released model may inherit. + * xAI keeps an explicit newest-first order. Every other vendor inherits only + * from the same tier (luna, sonnet, …), never from a different flagship. + */ +export function pinnedSiblingId( + vendorId: string, + modelId: string, + pinnedIds: readonly string[], +): string | undefined { + if (vendorId === "xai" && familyKey(modelId) === "grok") { + const preferred = XAI_SIBLING_ORDER.find((id) => pinnedIds.includes(id)); + if (preferred) return preferred; + } + const tier = tierToken(modelId); + if (!tier) return undefined; + const family = familyKey(modelId); + const candidates = pinnedIds.filter( + (id) => familyKey(id) === family && tierToken(id) === tier, + ); + candidates.sort(newerFirst); + return candidates[0]; +} + +function retryDelayMs(response: Response): number { + const header = response.headers.get("retry-after"); + if (!header) return 500; + const seconds = Number(header); + const delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now(); + if (!Number.isFinite(delay) || delay < 0) return 500; + return Math.min(delay, MAX_RETRY_DELAY_MS); +} + +/** GET the vendor model list. Retries one HTTP 429, then throws. */ +export async function readVendorModelList( + request: VendorModelListRequest, + fetchImpl: typeof fetch, +): Promise { + let waitMs = 0; + for (let attempt = 0; attempt < 2; attempt += 1) { + if (waitMs > 0) { + await new Promise((resolve) => setTimeout(resolve, waitMs)); + } + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), LIVE_MODELS_TIMEOUT_MS); + try { + const response = await fetchImpl(request.url, { + headers: request.headers, + signal: controller.signal, + }); + if (response.status === 429 && attempt === 0) { + waitMs = retryDelayMs(response); + await response.body?.cancel(); + continue; + } + if (!response.ok) { + throw new Error(`model list request failed (${response.status})`); + } + return await response.json(); + } finally { + clearTimeout(timer); + } + } + throw new Error("model list request failed"); +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 8312872cc9..a201d1c9a5 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -34,7 +34,7 @@ "electron-updater": "^6.8.9" }, "devDependencies": { - "@earendil-works/pi-ai": "0.86.1", + "@earendil-works/pi-ai": "0.87.0", "@pi-desktop/agent-host": "workspace:*", "@pi-desktop/agent-runtime": "workspace:*", "@pi-desktop/host-runtime": "workspace:*", diff --git a/apps/desktop/src/components/ChatSurface.tsx b/apps/desktop/src/components/ChatSurface.tsx index 70b3e293e5..3832bda04a 100644 --- a/apps/desktop/src/components/ChatSurface.tsx +++ b/apps/desktop/src/components/ChatSurface.tsx @@ -1,5 +1,9 @@ -import { memo, useMemo } from "react"; +import { memo, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; +import { + messageHasTranscriptContent, + vendorAccountOmitsSessionModel, +} from "../lib/chat-launch-error"; import { Composer } from "./Composer"; import { HomeMascotLogo } from "./HomeMascotLogo"; import { HomeProjectSwitcher } from "./HomeProjectSwitcher"; @@ -40,7 +44,11 @@ function projectName(path?: string | null, name?: string | null) { * per-session drafts already, and remounting it on every switch discarded its * measured metrics and focus. */ -export const ChatSurface = memo(function ChatSurface() { +export const ChatSurface = memo(function ChatSurface({ + visible = true, +}: { + visible?: boolean; +}) { const { t } = useTranslation(); const activeSessionId = useAppStore((state) => state.activeSessionId); const selectingSessionId = useAppStore((state) => state.selectingSessionId); @@ -53,6 +61,10 @@ export const ChatSurface = memo(function ChatSurface() { const error = useAppStore((state) => state.error); const errorCode = useAppStore((state) => state.errorCode); const errorRetriable = useAppStore((state) => state.errorRetriable); + const [hiddenVendorModelKey, setHiddenVendorModelKey] = useState( + null, + ); + const providers = useAppStore((state) => state.providers); const activeSession = useAppStore((state) => state.activeSessionId ? state.sessions.find((session) => session.id === state.activeSessionId) @@ -107,19 +119,28 @@ export const ChatSurface = memo(function ChatSurface() { const hasTranscript = Boolean(activePermission) || askPending || - messages.some((message) => { - const hasContent = Boolean((message.content || "").trim()); - const hasThinking = - typeof message.thinking === "string" && - Boolean(message.thinking.trim()); - if (message.role === "assistant") return hasContent || hasThinking; - return hasContent || message.role === "tool"; - }); + messages.some((message) => messageHasTranscriptContent(message)); // The empty state belongs to the session on screen. While a cold switch is // still resolving, the visible pane keeps its own transcript, so the hero must // not take over just because the destination projection is still empty. const showEmptyState = !hasTranscript && (!visibleSessionId || visibleSessionId === activeSessionId); + const vendorModelMissing = vendorAccountOmitsSessionModel( + activeSession, + providers, + ); + const vendorModelKey = vendorModelMissing + ? `${activeSession?.providerId ?? ""}:${activeSession?.modelId ?? ""}` + : null; + const showVendorModelError = + vendorModelKey !== null && hiddenVendorModelKey !== vendorModelKey; + const noticeError = + error ?? (showVendorModelError ? t("errors.MODEL_NOT_CONFIGURED") : null); + const noticeCode = error + ? errorCode + : showVendorModelError + ? "MODEL_NOT_CONFIGURED" + : null; return (
))}
@@ -185,17 +206,23 @@ export const ChatSurface = memo(function ChatSurface() { )} - {error ? ( + {noticeError ? (
- - {errorCode && i18nHasError(t, errorCode) - ? t(`errors.${errorCode}`) - : error} + + {noticeCode && i18nHasError(t, noticeCode) + ? t(`errors.${noticeCode}`) + : noticeError} + {showVendorModelError && !error && activeSession?.modelId ? ( + <> + {" "} + {activeSession.modelId} + + ) : null} - {(errorCode === "MODEL_NOT_CONFIGURED" || - errorCode === "PROVIDER_SECRET_MISSING" || - errorCode === "PROVIDER_UNAUTHORIZED") && ( + {(noticeCode === "MODEL_NOT_CONFIGURED" || + noticeCode === "PROVIDER_SECRET_MISSING" || + noticeCode === "PROVIDER_UNAUTHORIZED") && (
); diff --git a/apps/desktop/src/components/NotificationCenter.tsx b/apps/desktop/src/components/NotificationCenter.tsx index ccdf184d9f..b5c4f10f40 100644 --- a/apps/desktop/src/components/NotificationCenter.tsx +++ b/apps/desktop/src/components/NotificationCenter.tsx @@ -7,7 +7,7 @@ import { useState, type KeyboardEvent as ReactKeyboardEvent, } from "react"; -import { createPortal } from "react-dom"; +import { portalToBody } from "../lib/portal-visibility"; import type { AppNotification } from "@pi-desktop/shared"; import { useTranslation } from "react-i18next"; import { useAppStore } from "../stores/app-store"; @@ -254,7 +254,7 @@ export function NotificationCenter({ {open && popoverPos && typeof document !== "undefined" - ? createPortal( + ? portalToBody(
)}
, - document.body, ) : null}
diff --git a/apps/desktop/src/components/ProjectDeleteDialog.tsx b/apps/desktop/src/components/ProjectDeleteDialog.tsx index 545ff13c14..8d61b74936 100644 --- a/apps/desktop/src/components/ProjectDeleteDialog.tsx +++ b/apps/desktop/src/components/ProjectDeleteDialog.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from "react"; -import { createPortal } from "react-dom"; +import { portalToBody } from "../lib/portal-visibility"; import { useTranslation } from "react-i18next"; import { ErrorCodes } from "@pi-desktop/shared"; import { useAppStore } from "../stores/app-store"; @@ -183,5 +183,5 @@ export function ProjectDeleteDialog({ ); - return typeof document === "undefined" ? dialog : createPortal(dialog, document.body); + return typeof document === "undefined" ? dialog : portalToBody(dialog); } diff --git a/apps/desktop/src/components/ProjectEditDialog.tsx b/apps/desktop/src/components/ProjectEditDialog.tsx index 58a57288b8..2014d6b251 100644 --- a/apps/desktop/src/components/ProjectEditDialog.tsx +++ b/apps/desktop/src/components/ProjectEditDialog.tsx @@ -1,5 +1,5 @@ import { useEffect, useEffectEvent, useRef, useState } from "react"; -import { createPortal } from "react-dom"; +import { portalToBody } from "../lib/portal-visibility"; import { useTranslation } from "react-i18next"; import type { ProjectGroupRecord, ProjectGroupRoot } from "@pi-desktop/shared"; import { api } from "../lib/api"; @@ -366,5 +366,5 @@ export function ProjectEditDialog({ ); - return typeof document === "undefined" ? dialog : createPortal(dialog, document.body); + return typeof document === "undefined" ? dialog : portalToBody(dialog); } diff --git a/apps/desktop/src/components/SessionRenameDialog.tsx b/apps/desktop/src/components/SessionRenameDialog.tsx index a5094c5b7b..5e4de76d33 100644 --- a/apps/desktop/src/components/SessionRenameDialog.tsx +++ b/apps/desktop/src/components/SessionRenameDialog.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState, type FormEvent } from "react"; -import { createPortal } from "react-dom"; +import { portalToBody } from "../lib/portal-visibility"; import { useTranslation } from "react-i18next"; import { MAX_SESSION_TITLE_LENGTH } from "@pi-desktop/shared"; import type { SessionSummary } from "@pi-desktop/shared"; @@ -179,7 +179,7 @@ function RenameDialog({ return typeof document === "undefined" ? dialog - : createPortal(dialog, document.body); + : portalToBody(dialog); } export function SessionRenameDialog({ diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsx index 26542f2959..7b3a8801cd 100644 --- a/apps/desktop/src/components/Sidebar.tsx +++ b/apps/desktop/src/components/Sidebar.tsx @@ -15,7 +15,7 @@ import { TooltipButton, cx } from "./ui"; /** Default number of most-recent sessions shown per project group before the rest fold. */ const MAX_VISIBLE_SESSIONS = 10; -import { createPortal } from "react-dom"; +import { portalToBody } from "../lib/portal-visibility"; import { useTranslation } from "react-i18next"; import { api } from "../lib/api"; import { SessionHoverCard } from "../features/sessions/SessionHoverCard"; @@ -1849,7 +1849,7 @@ export function Sidebar({ ? t("nav.newTemporarySession") : t("nav.newProject"); const Icon = isSessions ? IconNewSession : IconNewProject; - return createPortal( + return portalToBody(
{label}
, - document.body, ); } if (sortOpen) { - return createPortal( + return portalToBody(
{showArchived ? "✓" : ""}
, - document.body, ); } const session = sessionMenu @@ -1914,7 +1912,7 @@ export function Sidebar({ ? projectEntries.find((item) => item.key === projectMenu) : undefined; if (!session && !entry) return null; - return createPortal( + return portalToBody(
) : null}
, - document.body, ); }; diff --git a/apps/desktop/src/components/settings/ConfigSyncError.tsx b/apps/desktop/src/components/settings/ConfigSyncError.tsx new file mode 100644 index 0000000000..07ed5c46b9 --- /dev/null +++ b/apps/desktop/src/components/settings/ConfigSyncError.tsx @@ -0,0 +1,16 @@ +import { useTranslation } from "react-i18next"; +import { configSyncErrorKind } from "../../features/settings/config-sync-error"; + +export function ConfigSyncError({ message }: { message: string }) { + const { t } = useTranslation(); + return ( +
+ {t("settings.configSync.errorTitle")} +

{t(`settings.configSync.errors.${configSyncErrorKind(message)}`)}

+
+ {t("settings.configSync.errorDetails")} +
{message}
+
+
+ ); +} diff --git a/apps/desktop/src/components/settings/ConfigSyncPage.tsx b/apps/desktop/src/components/settings/ConfigSyncPage.tsx index 809d1b2863..520721b55e 100644 --- a/apps/desktop/src/components/settings/ConfigSyncPage.tsx +++ b/apps/desktop/src/components/settings/ConfigSyncPage.tsx @@ -14,8 +14,14 @@ import { Badge, Button, Field, Input, PasswordInput, cx } from "../ui"; import { IconCloudDown, IconRefresh, IconShield, IconTrash } from "../icons"; import { SettingsCard, SettingsRow } from "../../features/settings/primitives"; import { configSyncProgressView } from "../../features/settings/config-sync-progress"; +import { ConfigSyncError } from "./ConfigSyncError"; import { SettingsMenuSelect } from "./SettingsMenuSelect"; +function formatStamp(value: string): string { + const date = new Date(value); + return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); +} + const CATEGORIES: Array<{ id: Exclude; label: string; @@ -106,7 +112,12 @@ export function ConfigSyncPage() { directory: next.directory ?? current.directory, deviceLabel: next.deviceLabel ?? current.deviceLabel, })); - setSelection((current) => ({ ...current, ...next.categories })); + setSelection((current) => ({ + ...current, + ...next.categories, + credentials: next.includeSecrets, + memory: next.includeMemory, + })); if (!next.locked) { try { setHistory(await api.configSyncListHistory()); @@ -373,6 +384,10 @@ export function ConfigSyncPage() { const configured = state?.configured === true; const locked = state?.locked === true; const categories = selection; + const vaultPasswordReady = + form.backupPassword.length === 0 + ? configured && !locked + : form.backupPassword.length >= 8; // The report only exists for a sync this page started: an automatic run stays // quiet, and no report outlives the request that produced it. Enabling a // vault runs the same full sync as "sync now", so both operations are watched. @@ -383,6 +398,9 @@ export function ConfigSyncPage() { return (
+ {error || state?.lastError ? ( + + ) : null} void run("configure")} - disabled={busy !== null || !form.endpoint || !form.backupPassword} + disabled={busy !== null || !form.endpoint || !vaultPasswordReady} > {configured ? t("settings.configSync.save") : t("settings.configSync.enable")} @@ -579,18 +597,14 @@ export function ConfigSyncPage() { detail={ state?.lastSuccessAt ? t("settings.configSync.lastSuccess", { - date: state.lastSuccessAt, + date: formatStamp(state.lastSuccessAt), }) : undefined } > {statusLabel} - {state?.lastError ? ( - - {state.lastError} - - ) : null} + {locked ? ( + + {t("settings.configSync.previewPending", { + count: state.preview.pendingActivation, + })} + + + {t("settings.configSync.previewConflicts", { + count: state.preview.conflicts, + })} +
) : null} @@ -846,7 +870,8 @@ export function ConfigSyncPage() { : entry.revisionId}
- {entry.createdAt} · {entry.entityCount} {t("settings.configSync.historyItems")} + {formatStamp(entry.createdAt)} · {entry.entityCount}{" "} + {t("settings.configSync.historyItems")}
+ + )} +
)} - {archMismatch && ( -
- - - {t("status.archMismatch", { - buildArch: t( - `status.archNames.${archMismatch.platform}.${archMismatch.processArch}`, - { defaultValue: archMismatch.processArch }, - ), - machineArch: t( - `status.archNames.${archMismatch.platform}.${archMismatch.machineArch}`, - { defaultValue: archMismatch.machineArch }, - ), - })} - - -
- )} + {!workPanelMaximized && ( +
+ {page === "chat" ? ( + void runMenuCommand("newTask")} + onOpenSearch={() => setSearchOpen(true)} + /> + ) : ( +
+ {sidebarCollapsed && ( +
+ void runMenuCommand("newTask")} + sidebarToggleShortcut={sidebarToggleShortcut} + /> +
+ )} +
+ )} + {page !== "settings" ? : null} - }> - {page === "pulls" ? ( -
- -
- ) : page === "scheduled" ? ( -
- -
- ) : page === "plugins" ? ( -
- -
- ) : ( - - )} -
-
- )} + {backendDown && ( +
+ + + {backendDown.fatal + ? backendDown.message === "GLIBC_UNSUPPORTED" + ? t("status.unsupportedGlibc") + : backendDown.message === "DB_SCHEMA_TOO_NEW" + ? t("status.dbSchemaTooNew", { + found: backendDown.schema?.found ?? "?", + supported: backendDown.schema?.supported ?? "?", + }) + : t("status.fatal") + : t("status.restarting")} + + {backendDown.fatal && ( + + )} +
+ )} - {(presentedWorkPanelOpen || workPanelExiting) && ( - - finishWorkPanelExit(workPanelExitGeneration.current) - } - subagentPanel={subagentPanelOpen ? subagentPanel : null} - onCloseSubagentPanel={closeSubagentPanel} - containerWidth={shellWidth} - sidebarWidth={sidebarWidth} - sidebarCollapsed={sidebarCollapsed} - sidebarExiting={sidebarExiting} - onAutoCollapseSidebar={autoCollapseSidebar} - maximized={workPanelMaximized} - onToggleMaximize={toggleWorkPanelMaximize} - /> - )} + {archMismatch && ( +
+ + + {t("status.archMismatch", { + buildArch: t( + `status.archNames.${archMismatch.platform}.${archMismatch.processArch}`, + { defaultValue: archMismatch.processArch }, + ), + machineArch: t( + `status.archNames.${archMismatch.platform}.${archMismatch.machineArch}`, + { defaultValue: archMismatch.machineArch }, + ), + })} + + +
+ )} - - - - - - + }> + {page === "pulls" ? ( +
+ +
+ ) : page === "scheduled" ? ( +
+ +
+ ) : page === "plugins" ? ( +
+ +
+ ) : ( + + )} +
+ + )} - setSearchOpen(false)} /> - - - - ); - } + {(presentedWorkPanelOpen || workPanelExiting) && ( + + finishWorkPanelExit(workPanelExitGeneration.current) + } + subagentPanel={subagentPanelOpen ? subagentPanel : null} + onCloseSubagentPanel={closeSubagentPanel} + containerWidth={shellWidth} + sidebarWidth={sidebarWidth} + sidebarCollapsed={sidebarCollapsed} + sidebarExiting={sidebarExiting} + onAutoCollapseSidebar={autoCollapseSidebar} + maximized={workPanelMaximized} + onToggleMaximize={toggleWorkPanelMaximize} + /> + )} + + + + + + + + + + {page === "settings" ? ( + }> + + + ) : null} + setSearchOpen(false)} /> + + + {page === "settings" ? : null} + + ); } return ( diff --git a/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsx b/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsx index d561e65a15..aa03bd3b2c 100644 --- a/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsx +++ b/apps/desktop/src/features/chat/composer/ComposerImagePreview.tsx @@ -1,10 +1,10 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; import { IconChevronLeft, IconChevronRight, IconClose, IconDownload, IconMinus, IconPlus } from "../../../components/icons"; import { useBlockingOverlay } from "../../../lib/blocking-overlay"; -import { useImagePreviewPan } from "./hooks/useImagePreviewPan"; +import { portalToBody } from "../../../lib/portal-visibility"; import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreview"; +import { useImagePreviewPan } from "./hooks/useImagePreviewPan"; import "../../../styles/composer-image-preview.css"; export function ComposerImagePreview({ controller }: { controller: ComposerImagePreviewController }) { @@ -94,7 +94,7 @@ function ImagePreviewDialog({ controller, preview }: { const dismissBackground = (event: React.MouseEvent) => { if (event.target === event.currentTarget) controller.close(); }; - return createPortal( + return portalToBody( = 8} onClick={() => changeZoom(zoom * 1.25)} aria-label={t("menu.zoomIn")}> - , document.body, + , ); } diff --git a/apps/desktop/src/features/sessions/SessionHoverCard.tsx b/apps/desktop/src/features/sessions/SessionHoverCard.tsx index 5fa4393015..d4b626e8fa 100644 --- a/apps/desktop/src/features/sessions/SessionHoverCard.tsx +++ b/apps/desktop/src/features/sessions/SessionHoverCard.tsx @@ -1,5 +1,5 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { createPortal } from "react-dom"; +import { portalToBody } from "../../lib/portal-visibility"; import { useTranslation } from "react-i18next"; import type { ProjectWorkspace, SessionCollaborationSummary, SessionReference } from "@pi-desktop/shared"; import { api } from "../../lib/api"; @@ -99,7 +99,7 @@ export function SessionHoverCard({ void onOpenSession(reference.sessionId); }; - return createPortal( + return portalToBody(
, - document.body, ); } diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsx index 7167312261..606de64a18 100644 --- a/apps/desktop/src/features/settings/SettingsPage.tsx +++ b/apps/desktop/src/features/settings/SettingsPage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import type { AppSettings, @@ -70,6 +70,7 @@ type NavItem = { titleKey: string; icon: ReactNode; group: SettingsNavGroupId; + experimentalBadgeKey?: string; /** i18n keys of the rows inside the tab; search matches their translations. */ keywordKeys: string[]; }; @@ -79,6 +80,7 @@ export function SettingsPage() { const tab = useAppStore((s) => s.settingsTab); const setSettingsTab = useAppStore((s) => s.setSettingsTab); const settingsAnchor = useAppStore((s) => s.settingsAnchor); + const settingsTabNonce = useAppStore((s) => s.settingsTabNonce); const setSettingsAnchor = useAppStore((s) => s.setSettingsAnchor); const setPage = useAppStore((s) => s.setPage); const settings = useAppStore((s) => s.settings); @@ -86,8 +88,8 @@ export function SettingsPage() { const refreshProviders = useAppStore((s) => s.refreshProviders); const platform = (window.piDesktop?.platform ?? "darwin") as ShortcutPlatform; - // Developer-only destinations (Remote Hosts) exist only while developer - // mode is on; the rail, the page, and settings search drop them together. + // Developer-only destinations (Cloud sync and Remote Hosts) exist only + // while developer mode is on; the rail, page, and search drop them together. const developerMode = settings?.developerMode === true; const navEntries = useMemo(() => visibleSettingsNav(developerMode), [developerMode]); const tabHidden = isSettingsDestinationHidden(tab, developerMode); @@ -97,6 +99,24 @@ export function SettingsPage() { const [settingsRecoveryFailed, setSettingsRecoveryFailed] = useState(false); const [extensions, setExtensions] = useState([]); const [activeExtension, setActiveExtension] = useState(null); + const seenSettingsTabNonce = useRef(settingsTabNonce); + // setSettingsTab means "show this built-in category", even when the tab id + // does not change. Dismiss a plugin page before paint; an anchor-only deep + // link has to do the same or the row lookup hits the plugin instead. + if ( + seenSettingsTabNonce.current !== settingsTabNonce || + (activeExtension && settingsAnchor) + ) { + seenSettingsTabNonce.current = settingsTabNonce; + if (activeExtension) setActiveExtension(null); + } + const contentRef = useRef(null); + const destination = activeExtension ? `extension:${activeExtension.ref}` : `builtin:${tab}`; + + useLayoutEffect(() => { + // Reset before paint and before the search-anchor effect positions its row. + if (contentRef.current) contentRef.current.scrollTop = 0; + }, [destination]); useEffect(() => { const refresh = () => void api.listPluginScenicThemesDestinations().then(setExtensions, () => setExtensions([])); @@ -112,8 +132,8 @@ export function SettingsPage() { }, [activeExtension, extensions, setSettingsTab]); // A hidden destination must not keep rendering: leave the page the rail no - // longer offers (for example Remote Hosts once developer mode is switched - // off) and fall back to General. + // longer offers (for example Cloud sync or Remote Hosts after developer mode + // is switched off) and fall back to General. useEffect(() => { if (!settings || !tabHidden) return; setSettingsTab("general"); @@ -138,10 +158,12 @@ export function SettingsPage() { }, [settings, recoverSettings]); // Arriving from the global search dialog: scroll to and flash the row - // whose title matches the pending anchor key. Rows are located by their - // translated title so async tab content (providers, import) needs no - // per-row wiring; a short retry window covers late mounts. - useEffect(() => { + // whose title matches the pending anchor key. This runs after the + // destination reset and before paint, so a category change does not flash + // the top. Rows are located by their translated title so async tab content + // (providers, import) needs no per-row wiring; a short retry window covers + // late mounts. + useLayoutEffect(() => { if (!settingsAnchor) return; const target = t(settingsAnchor).trim(); let cancelled = false; @@ -216,6 +238,7 @@ export function SettingsPage() { titleKey: entry.titleKey, icon: iconFor[entry.id], group: entry.group, + experimentalBadgeKey: entry.experimentalBadgeKey, keywordKeys: entry.keywordKeys, })); }, [navEntries]); @@ -245,8 +268,8 @@ export function SettingsPage() { return [...groups.entries()].map(([id, items]) => ({ id, items })); }, [filteredItems]); - const activeTitleKey = - navItems.find((item) => item.id === tab)?.titleKey ?? "settings.title"; + const activeNavItem = navItems.find((item) => item.id === tab); + const activeTitleKey = activeNavItem?.titleKey ?? "settings.title"; const tabNeedsSettings = ["general", "ai", "shortcuts", "agent"].includes(tab); return ( @@ -289,9 +312,9 @@ export function SettingsPage() { > {item.icon} {t(item.labelKey)} - {item.id === "remoteHosts" ? ( + {item.experimentalBadgeKey ? ( - {t("settings.remoteHosts.experimental")} + {t(item.experimentalBadgeKey)} ) : null} @@ -338,13 +361,13 @@ export function SettingsPage() { -
+

{activeExtension?.label ?? t(activeTitleKey)} - {!activeExtension && tab === "remoteHosts" && !tabHidden ? ( - {t("settings.remoteHosts.experimental")} + {!activeExtension && activeNavItem?.experimentalBadgeKey ? ( + {t(activeNavItem.experimentalBadgeKey)} ) : null}

@@ -523,7 +546,7 @@ export function SettingsPage() { {tab === "projects" && } - {tab === "sync" && } + {tab === "sync" && !tabHidden && } {tab === "remoteHosts" && !tabHidden && } diff --git a/apps/desktop/src/features/settings/config-sync-error.ts b/apps/desktop/src/features/settings/config-sync-error.ts new file mode 100644 index 0000000000..8df52dd6f8 --- /dev/null +++ b/apps/desktop/src/features/settings/config-sync-error.ts @@ -0,0 +1,27 @@ +const ERROR_KINDS = { + AUTH: "auth", + PERMISSION: "permission", + NOT_FOUND: "notFound", + CONFLICT: "conflict", + QUOTA: "quota", + RATE_LIMIT: "rateLimit", + SERVER: "server", + TIMEOUT: "network", + NETWORK: "network", + REDIRECT: "redirect", + UNSUPPORTED: "unsupported", + LOCKED: "locked", + INVALID: "invalid", + DECRYPT: "password", + PASSWORD: "password", + CRYPTO: "password", + LIMIT_EXCEEDED: "limit", +} as const; + +/** Map a host error to a stable recovery message. Server text stays opt-in. */ +export function configSyncErrorKind(message: string): string { + const code = /CONFIG_SYNC_([A-Z0-9_]+)/.exec(message)?.[1]; + return code && Object.hasOwn(ERROR_KINDS, code) + ? ERROR_KINDS[code as keyof typeof ERROR_KINDS] + : "unknown"; +} diff --git a/apps/desktop/src/lib/chat-launch-error.ts b/apps/desktop/src/lib/chat-launch-error.ts new file mode 100644 index 0000000000..2803554ca1 --- /dev/null +++ b/apps/desktop/src/lib/chat-launch-error.ts @@ -0,0 +1,49 @@ +import { modelIdsMatch, OAUTH_AUTH_KIND } from "@pi-desktop/shared"; + +type TranscriptMessage = { + role: string; + content?: string; + thinking?: string; + error?: unknown; +}; + +/** An assistant row that only carries a launch error is still the conversation. */ +export function messageHasTranscriptContent(message: TranscriptMessage): boolean { + const hasContent = Boolean((message.content || "").trim()); + const hasThinking = + typeof message.thinking === "string" && Boolean(message.thinking.trim()); + if (message.role === "assistant") { + return hasContent || hasThinking || Boolean(message.error); + } + return hasContent || message.role === "tool"; +} + +type VendorSessionModel = { + providerId?: string | null; + modelId?: string | null; +}; + +type VendorModelProvider = { + id: string; + authKind?: string; + models?: ReadonlyArray<{ id: string }>; +}; + +/** + * Vendor accounts refuse a session model the account list did not return. + * An empty list means the catalog has not loaded, not that the account + * offers nothing, so it must not turn a normal empty chat into an error. + */ +export function vendorAccountOmitsSessionModel( + session: VendorSessionModel | null | undefined, + providers: readonly VendorModelProvider[], +): boolean { + const providerId = session?.providerId?.trim(); + const modelId = session?.modelId?.trim(); + if (!providerId || !modelId) return false; + const provider = providers.find((item) => item.id === providerId); + if (!provider || provider.authKind !== OAUTH_AUTH_KIND) return false; + const models = provider.models ?? []; + if (models.length === 0) return false; + return !models.some((model) => modelIdsMatch(model.id, modelId)); +} diff --git a/apps/desktop/src/lib/portal-visibility.tsx b/apps/desktop/src/lib/portal-visibility.tsx new file mode 100644 index 0000000000..c296e49695 --- /dev/null +++ b/apps/desktop/src/lib/portal-visibility.tsx @@ -0,0 +1,32 @@ +import { createContext, type ReactNode } from "react"; +import { createPortal } from "react-dom"; + +export const PortalVisibilityContext = createContext(true); + +export function PortalVisibilityProvider({ + visible, + children, +}: { + visible: boolean; + children: ReactNode; +}) { + return ( + + {children} + + ); +} + +export function visiblePortalContent(node: ReactNode) { + return ( + + {(visible) => (visible ? node : null)} + + ); +} + +export function portalToBody(node: ReactNode) { + return typeof document === "undefined" + ? node + : createPortal(visiblePortalContent(node), document.body); +} diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts index 575f24e237..b320ba431d 100644 --- a/apps/desktop/src/lib/settings-search.ts +++ b/apps/desktop/src/lib/settings-search.ts @@ -48,6 +48,8 @@ export type SettingsNavEntry = { * rail, the page, and settings search drop it together. */ developerOnly?: true; + /** Localized Experimental badge shown beside the rail row and page title. */ + experimentalBadgeKey?: string; }; export const SETTINGS_NAV: SettingsNavEntry[] = [ @@ -245,6 +247,8 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [ labelKey: "settings.nav.sync", titleKey: "settings.configSync.title", group: "system", + developerOnly: true, + experimentalBadgeKey: "settings.configSync.experimental", keywordKeys: [ "settings.configSync.connectionTitle", "settings.configSync.endpoint", @@ -260,6 +264,7 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [ titleKey: "settings.remoteHosts.title", group: "system", developerOnly: true, + experimentalBadgeKey: "settings.remoteHosts.experimental", keywordKeys: [ "settings.remoteHosts.title", "settings.remoteHosts.addTitle", diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts index 093175da1a..3cf9e08e0f 100644 --- a/apps/desktop/src/stores/app-state.ts +++ b/apps/desktop/src/stores/app-state.ts @@ -175,6 +175,8 @@ export type AppState = { settingsTab: SettingsTabId; /** Pending row anchor (i18n key) to flash after landing on a settings tab. */ settingsAnchor: string | null; + /** Bumped by every setSettingsTab so a same-tab navigation is observable. */ + settingsTabNonce: number; navStack: Array<{ page: AppState["page"]; sessionId?: string }>; navIndex: number; error?: string | null; diff --git a/apps/desktop/src/stores/slices/initial-state.ts b/apps/desktop/src/stores/slices/initial-state.ts index bd1f40d956..998f3eeb57 100644 --- a/apps/desktop/src/stores/slices/initial-state.ts +++ b/apps/desktop/src/stores/slices/initial-state.ts @@ -75,6 +75,7 @@ export function createInitialState(): AppStateData { page: "chat", settingsTab: "general", settingsAnchor: null, + settingsTabNonce: 0, navStack: [{ page: "chat" }], navIndex: 0, toasts: [], diff --git a/apps/desktop/src/stores/slices/interaction-slice.ts b/apps/desktop/src/stores/slices/interaction-slice.ts index 20be24ac04..bf22605c48 100644 --- a/apps/desktop/src/stores/slices/interaction-slice.ts +++ b/apps/desktop/src/stores/slices/interaction-slice.ts @@ -72,7 +72,10 @@ export function createInteractionSlice({ setSettingsTab: (settingsTab) => { get().setPage("settings"); - set({ settingsTab }); + set((state) => ({ + settingsTab, + settingsTabNonce: state.settingsTabNonce + 1, + })); }, setSettingsAnchor: (settingsAnchor) => set({ settingsAnchor }), canNavBack: () => get().navIndex > 0, diff --git a/apps/desktop/src/styles/base.css b/apps/desktop/src/styles/base.css index a95c08f47a..d6e236e197 100644 --- a/apps/desktop/src/styles/base.css +++ b/apps/desktop/src/styles/base.css @@ -170,6 +170,16 @@ html { color: var(--ds-text-primary); } +/* Keep the chat tree mounted while Settings is open without changing the + shell's flex layout or exposing the hidden tree to focus and accessibility. */ +.app-chat-shell { + display: contents; +} + +.app-chat-shell[hidden] { + display: none; +} + .app-scenic-backdrop { position: fixed; inset: 0; diff --git a/apps/desktop/src/styles/chrome.css b/apps/desktop/src/styles/chrome.css index 2a96e807da..af8bb14375 100644 --- a/apps/desktop/src/styles/chrome.css +++ b/apps/desktop/src/styles/chrome.css @@ -1102,7 +1102,7 @@ } /* Follow the adjacent titlebar surface when the dock occupies the right edge. */ -.app-shell:has(> .work-panel) > .window-controls { +.app-shell:has(.work-panel) > .window-controls { background: var(--ds-bg-dock-raised); } @@ -1225,7 +1225,7 @@ /* Match the scenic backdrop's child-layer specificity so preview navigation * stays above the work panel while non-control pixels remain pass-through. */ -.app-shell > .window-chrome-row { +.app-shell > :where(.app-chat-shell) > .window-chrome-row { position: absolute; top: 0; right: 0; diff --git a/apps/desktop/src/styles/model-config.css b/apps/desktop/src/styles/model-config.css index ec4a437d10..93b5861aed 100644 --- a/apps/desktop/src/styles/model-config.css +++ b/apps/desktop/src/styles/model-config.css @@ -482,6 +482,14 @@ line-height: var(--leading-relaxed); } +/* Quieter than the import error: folding is informational, not a refusal. */ +.provider-setup-header-note { + margin: 0; + color: var(--ds-text-muted); + font-size: var(--text-2xs); + line-height: var(--leading-relaxed); +} + /* Pick on the left, review on the right; both stretch to the same height. */ .provider-setup-panes { flex: 1; diff --git a/apps/desktop/test/anthropic-oauth-retry.test.mjs b/apps/desktop/test/anthropic-oauth-retry.test.mjs index 2b200f7513..9dbaad2f7a 100644 --- a/apps/desktop/test/anthropic-oauth-retry.test.mjs +++ b/apps/desktop/test/anthropic-oauth-retry.test.mjs @@ -59,7 +59,10 @@ async function fixture(outcomes, run) { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); globalThis.fetch = (input, init) => { - assert.equal(String(input), TOKEN_URL, "OAuth fixture must never call an external endpoint"); + const url = String(input); + if (url !== TOKEN_URL) { + return Promise.reject(new Error(`blocked ${url}`)); + } return originalFetch(`http://127.0.0.1:${server.address().port}/token`, init); }; const host = hostFixture(); diff --git a/apps/desktop/test/chat-context-menu-surface.test.mjs b/apps/desktop/test/chat-context-menu-surface.test.mjs index 418d1a5173..1df34d56ec 100644 --- a/apps/desktop/test/chat-context-menu-surface.test.mjs +++ b/apps/desktop/test/chat-context-menu-surface.test.mjs @@ -22,8 +22,7 @@ const assistantTurnSource = await readFile( ); test("the pointer-anchored menu portals, measures, and closes without trapping focus", () => { - assert.match(menuSource, /createPortal\(/); - assert.match(menuSource, /document\.body/); + assert.match(menuSource, /portalToBody\(/); assert.match(menuSource, /placeContextMenu\(/); assert.match(menuSource, /className=\{`context-menu\$\{placement \? " is-open" : ""\}`\}/); assert.match(menuSource, /window\.addEventListener\("pointerdown", onOutside, true\)/); diff --git a/apps/desktop/test/chat-launch-error.test.mjs b/apps/desktop/test/chat-launch-error.test.mjs new file mode 100644 index 0000000000..008fe1f046 --- /dev/null +++ b/apps/desktop/test/chat-launch-error.test.mjs @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + messageHasTranscriptContent, + vendorAccountOmitsSessionModel, +} from "../src/lib/chat-launch-error.ts"; + +const oauth = (models) => [{ id: "chatgpt", authKind: "oauth", models }]; + +test("a launch error with no assistant text still counts as a transcript", () => { + assert.equal( + messageHasTranscriptContent({ + role: "assistant", + content: "", + error: { code: "MODEL_NOT_CONFIGURED", message: "missing" }, + }), + true, + ); + assert.equal( + messageHasTranscriptContent({ role: "assistant", content: " " }), + false, + ); + assert.equal( + messageHasTranscriptContent({ role: "user", content: "hello" }), + true, + ); +}); + +test("an empty vendor chat names a model the account did not return", () => { + const session = { providerId: "chatgpt", modelId: "gpt-6-luna" }; + assert.equal( + vendorAccountOmitsSessionModel(session, oauth([{ id: "gpt-5.6-luna" }])), + true, + ); + assert.equal( + vendorAccountOmitsSessionModel(session, oauth([{ id: "openai/gpt-6-luna" }])), + false, + ); + assert.equal(vendorAccountOmitsSessionModel(session, oauth([])), false); + assert.equal( + vendorAccountOmitsSessionModel(session, [ + { id: "chatgpt", authKind: "api_key", models: [{ id: "gpt-5.6-luna" }] }, + ]), + false, + ); +}); + +test("the chat surface shows that omission instead of an empty page", async () => { + const { readFile } = await import("node:fs/promises"); + const surface = await readFile( + new URL("../src/components/ChatSurface.tsx", import.meta.url), + "utf8", + ); + assert.match(surface, /messageHasTranscriptContent\(message\)/); + assert.match(surface, /vendorAccountOmitsSessionModel\(/); + assert.match(surface, /activeSession\.modelId/); + assert.match(surface, /noticeError \?/); +}); diff --git a/apps/desktop/test/config-sync-error.test.mjs b/apps/desktop/test/config-sync-error.test.mjs new file mode 100644 index 0000000000..4d290936ec --- /dev/null +++ b/apps/desktop/test/config-sync-error.test.mjs @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import { register } from "node:module"; +import { dirname, join } from "node:path"; +import test from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs"))); +const { configSyncErrorKind } = await import( + "../src/features/settings/config-sync-error.ts" +); + +test("cloud sync errors map to a recovery action", () => { + assert.equal( + configSyncErrorKind( + "CONFIG_SYNC_AUTH: enter the WebDAV app password for this server and account", + ), + "auth", + ); + assert.equal( + configSyncErrorKind("CONFIG_SYNC_REDIRECT: use the direct WebDAV endpoint"), + "redirect", + ); + assert.equal( + configSyncErrorKind("CONFIG_SYNC_CRYPTO: wrong vault password"), + "password", + ); + assert.equal(configSyncErrorKind("socket hang up"), "unknown"); +}); diff --git a/apps/desktop/test/config-sync-settings.test.mjs b/apps/desktop/test/config-sync-settings.test.mjs index 9d39021df2..3e8111d76d 100644 --- a/apps/desktop/test/config-sync-settings.test.mjs +++ b/apps/desktop/test/config-sync-settings.test.mjs @@ -24,9 +24,10 @@ const progressModel = await read( "../src/features/settings/config-sync-progress.ts", ); -test("cloud sync is a searchable settings destination", () => { - assert.match(settingsPage, /tab === "sync" && /); +test("cloud sync rendering follows the settings visibility gate", () => { + assert.match(settingsPage, /tab === "sync" && !tabHidden && /); assert.match(settingsIndex, /id: "sync"/); + assert.match(settingsIndex, /experimentalBadgeKey: "settings\.configSync\.experimental"/); assert.match(settingsIndex, /settings\.configSync\.connectionTitle/); }); diff --git a/apps/desktop/test/image-generation-default.test.mjs b/apps/desktop/test/image-generation-default.test.mjs index 8b3b898969..5fd405e7ff 100644 --- a/apps/desktop/test/image-generation-default.test.mjs +++ b/apps/desktop/test/image-generation-default.test.mjs @@ -343,3 +343,17 @@ test("saving the active provider preserves a still-selected default", () => { ); assert.deepEqual(plan.imageGeneration, binding("x", "current")); }); + +test("unchecking every image model on the active provider clears the settings check", () => { + const plan = planImageGenerationDefaults( + { + imageGenerationModels: [binding("x", "img-x"), binding("y", "img-y")], + imageGeneration: binding("x", "img-x"), + }, + "x", + [], + [provider("x", ["img-x"]), provider("y", ["img-y"])], + ); + assert.equal(plan.imageGeneration, null); + assert.deepEqual(plan.imageGenerationModels, [binding("y", "img-y")]); +}); diff --git a/apps/desktop/test/interaction-performance.test.mjs b/apps/desktop/test/interaction-performance.test.mjs index 11f8090d5f..637c1f79e7 100644 --- a/apps/desktop/test/interaction-performance.test.mjs +++ b/apps/desktop/test/interaction-performance.test.mjs @@ -28,11 +28,12 @@ const [app, appShell, chatSurface, pane, transcript, toolRow, transcriptShared, ]); test("streaming state stays inside the chat render boundary", () => { - assert.match(app, //); + assert.match(app, //); assert.doesNotMatch(app, /useAppStore\(\(s\) => s\.messages\)/); assert.doesNotMatch(app, / { }); -test("image generation selection is an attachment capability and keeps an unavailable row when unbound", () => { +test("image generation selection hides the summary when nothing can be chosen", () => { assert.match( pickerSource, /className="provider-chosen-capability-rows">[\s\S]*?settings\.setImageModel/, @@ -90,7 +90,8 @@ test("image generation selection is an attachment capability and keeps an unavai ); assert.match(pickerSource, /imageModelIds\?\.some\([\s\S]*?modelIdsMatch/); assert.match(pickerSource, /onImageModelChange\(binding\.id, event\.target\.checked\)/); - assert.match(imageModelRowSource, /imageGenerationBindings\(settings\.imageGenerationModels, binding\)/); + assert.match(imageModelRowSource, /imageGenerationBindings\(settings\.imageGenerationModels, null\)/); + assert.match(imageModelRowSource, /if \(!options\.some\(\(option\) => !option\.disabled\)\) return null;/); assert.match(imageModelRowSource, /if \(candidates\.length === 0\) return null;/); assert.match(imageModelRowSource, /imageModelUnavailable/); }); diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjs index 352b0806f8..8041e41cfb 100644 --- a/apps/desktop/test/models-dev-catalog.test.mjs +++ b/apps/desktop/test/models-dev-catalog.test.mjs @@ -3,7 +3,7 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { apiStyleForAdapter, modelIdsMatch } from "@pi-desktop/shared"; +import { apiStyleForAdapter, catalogModelIdsMatch, modelIdsMatch } from "@pi-desktop/shared"; import { MODELS_DEV_API_URL, @@ -158,6 +158,37 @@ test("cached matches remain scoped to the requested provider and endpoint", asyn } }); +test("a known endpoint cannot borrow another provider's catalog model", async (t) => { + const catalog = await loadFixtureCatalog(t, { + alpha: { api: "https://alpha.example/v1", models: { "alpha-only": { id: "alpha-only" } } }, + beta: { api: "https://beta.example/v1", models: { "proxy/shared-model": { id: "proxy/shared-model", reasoning: true } } }, + }); + assert.equal(catalog.findModel({ baseUrl: "https://alpha.example/v1", modelId: "shared-model" }), undefined); + assert.equal(catalog.findModel({ baseUrl: "https://beta.example/v1", modelId: "shared-model" })?.providerKey, "beta"); +}); + +test("a shared catalog API prefers the explicitly selected vendor", async (t) => { + const catalog = await loadFixtureCatalog(t, { + alpha: { api: "https://gateway.example/v1", models: { "alpha-only": { id: "alpha-only" } } }, + beta: { api: "https://gateway.example/v1", models: { "beta-only": { id: "beta-only" } } }, + }); + const input = { vendorKey: "beta", baseUrl: "https://gateway.example/v1" }; + assert.equal(catalog.findModel({ ...input, modelId: "beta-only" })?.providerKey, "beta"); + assert.equal(catalog.findModel({ ...input, modelId: "alpha-only" }), undefined); +}); + +test("a recognized endpoint takes priority over an unrelated vendor fallback", async (t) => { + const catalog = await loadFixtureCatalog(t, { + openai: { models: { "shared-model": { id: "shared-model" } } }, + deepseek: { models: { "shared-model": { id: "shared-model" } } }, + }); + assert.equal(catalog.findModel({ + vendorKey: "openai", + baseUrl: "https://api.deepseek.com", + modelId: "shared-model", + })?.providerKey, "deepseek"); +}); + test("model lookup memory is bounded by the catalog, not by query count", async (t) => { const catalog = await loadFixtureCatalog(t); const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" }; @@ -207,6 +238,120 @@ test("model IDs match provider namespaces without matching model variants", () = assert.equal(modelIdsMatch("anthropic/claude-opus-5", "claude-opus-5"), true); assert.equal(modelIdsMatch("claude-opus-5@default", "claude-opus-5"), true); assert.equal(modelIdsMatch("claude-opus-5-fast", "claude-opus-5"), false); + for (const suffix of ["agent", "latest", "thinking", "think"]) { + assert.equal(modelIdsMatch("foo", `foo-${suffix}`), false); + assert.equal(modelIdsMatch(`foo-${suffix}`, "foo"), false); + } + assert.equal(modelIdsMatch("gateway-a/foo", "gateway-b/foo"), false); + assert.equal(modelIdsMatch("foo@us-east", "foo@eu-west"), false); + assert.equal(modelIdsMatch("proxy/openai/gpt-4o", "openai/gpt-4o"), true); + assert.equal(modelIdsMatch("openai/gpt-4o", "proxy/gpt-4o"), false); +}); +test("catalog metadata IDs match exact proxy paths and supported variants", () => { + for (const [catalogId, request] of [ + ["claude-opus-4.6", "proxy/claude-opus-4.6"], + ["claude-opus-4.6", "custom/claude-opus-4.6"], + ["claude-opus-4.6", "relay/claude-opus-4.6"], + ["claude-opus-4.6", "gateway-01/claude-opus-4.6"], + ["openai/gpt-4o", "hub/openai/gpt-4o"], + ["claude-opus-4.6", "proxy/claude-opus-4.6-thinking"], + ["claude-opus-4.6", "claude-opus-4.6:thinking"], + ["claude-opus-4.6", "proxy/claude-opus-4.6-agent"], + ["claude-opus-4.6", "proxy/claude-opus-4.6-latest"], + ["claude-opus-4.6", "proxy/claude-opus-4.6-agent-thinking"], + ["proxy/nested/claude-opus-4.6@us-east", "claude-opus-4.6-thinking"], + ["anthropic-claude-opus-4.6", "claude-opus-4.6@us-east"], + ["google/gemini-pro-latest", "gemini-pro"], + ]) { + assert.equal(catalogModelIdsMatch(catalogId, request), true, `${catalogId} / ${request}`); + assert.equal(catalogModelIdsMatch(request, catalogId), true, `${request} / ${catalogId}`); + } + + for (const [catalogId, request] of [ + ["google/gemini-2.5-flash", "openai/gemini-2.5-flash"], + ["claude-opus-4.6", "myproxy-claude-opus-4.6"], + ["claude-opus-4.6", "myproxy-claude-opus-4.6-thinking"], + ["google/gemini-2.5-flash", "gemini-2.5-flash-high"], + ["google/gemini-2.5-flash", "gemini-2.5-flash-low"], + ["google/gemini-2.5-flash", "gemini-2.5-flash:minimal"], + ["claude-opus-5", "claude-opus-5-fast"], + ["gpt-4o", "gpt-4o-mini"], + ["gpt-4", "gpt-4o"], + ["model", "other-model"], + ["custom", "gemini-3.1-pro-preview-customtools"], + ["groq/whisper-large-v3", "deepseek-v3"], + ["vercel/bfl/flux-kontext-max", "qwen-max"], + ["alibaba/qwen3-asr-flash", "qwen-flash"], + ["openai/gpt-4o", "proxy/gpt-4o"], + ["google/gemini-2.5-flash", "proxy/gemini-2.5-flash"], + ["proxy/nested/claude-opus-4.6", "other/claude-opus-4.6"], + ["claude-opus-4-6-max", "qwen-max"], + ]) { + assert.equal(catalogModelIdsMatch(catalogId, request), false, `${catalogId} / ${request}`); + assert.equal(catalogModelIdsMatch(request, catalogId), false, `${request} / ${catalogId}`); + } + assert.equal(catalogModelIdsMatch("gateway-a/foo", "gateway-b/foo"), false); + assert.equal(catalogModelIdsMatch("foo", "foo-think"), true); + assert.equal(catalogModelIdsMatch("foo", "foo-agent"), true); + assert.equal(catalogModelIdsMatch("foo", "foo-latest"), true); +}); + +test("catalog lookup indexes exact path leaves and known vendor variants without broad aliases", async (t) => { + const ids = [ + "model", "custom", "groq/whisper-large-v3", "vercel/bfl/flux-kontext-max", + "alibaba/qwen3-asr-flash", "proxy/nested/claude-opus-4.6@us-east", + "anthropic-claude-sonnet-4", "openai.gpt-4o", "google/gemini-2.5-flash", + ]; + const catalog = await loadFixtureCatalog(t, { + gateway: { models: Object.fromEntries(ids.map((id) => [id, { id }])) }, + }); + for (const [request, expected] of [ + ["other-model", undefined], + ["gemini-3.1-pro-preview-customtools", undefined], + ["deepseek-v3", undefined], + ["qwen-max", undefined], + ["qwen-flash", undefined], + ["myproxy-claude-opus-4.6", undefined], + ["gemini-2.5-flash-high", undefined], + ["gemini-2.5-flash-low", undefined], + ["claude-opus-4.6-thinking", "proxy/nested/claude-opus-4.6@us-east"], + ["proxy/claude-opus-4.6-thinking", undefined], + ["claude-sonnet-4-agent", "anthropic-claude-sonnet-4"], + ["proxy/gemini-2.5-flash", undefined], + ["gpt-4o@eu", "openai.gpt-4o"], + ]) { + assert.equal(catalog.findModel({ vendorKey: "custom", modelId: request })?.modelId, expected, request); + } + assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "openai/gemini-2.5-flash" }), undefined); +}); + +test("matches supported proxy path and reasoning variants in catalog lookup", async (t) => { + const catalog = await loadFixtureCatalog(t); + for (const modelId of [ + "proxy/claude-opus-4.6", "proxy/claude-opus-4.6-thinking", + "proxy/claude-opus-4.6-agent", "claude-opus-4.6:thinking", + "anthropic-claude-opus-4.6", + ]) { + const match = catalog.findModel({ vendorKey: "custom", modelId }); + assert.equal(match?.modelId, "claude-opus-4.6", modelId); + assert.equal(match.reasoning, true); + } + for (const modelId of ["myproxy-claude-opus-4.6", "myproxy-claude-opus-4.6-thinking"]) { + assert.equal(catalog.findModel({ vendorKey: "custom", modelId }), undefined); + } +}); + +test("metadata lookup can share routed leaves and narrow suffix aliases without merging bindings", async (t) => { + const catalog = await loadFixtureCatalog(t, { + gateway: { models: { + "gateway-a/foo": { id: "gateway-a/foo" }, + "bar-agent": { id: "bar-agent" }, + } }, + }); + assert.equal(modelIdsMatch("gateway-a/foo", "gateway-b/foo"), false); + assert.equal(modelIdsMatch("bar", "bar-agent"), false); + assert.equal(catalog.findModel({ modelId: "gateway-b/foo" }), undefined); + assert.equal(catalog.findModel({ modelId: "bar-thinking" })?.modelId, "bar-agent"); }); test("models.dev records retain all published model parameters and modalities", () => { diff --git a/apps/desktop/test/notification-center.test.mjs b/apps/desktop/test/notification-center.test.mjs index 38f1d16fa4..48f52160c7 100644 --- a/apps/desktop/test/notification-center.test.mjs +++ b/apps/desktop/test/notification-center.test.mjs @@ -49,7 +49,7 @@ test("notification popover preserves keyboard and focus behavior", () => { assert.match(componentSource, /triggerRef\.current\?\.focus\(\)/); assert.match(componentSource, /rootRef\.current\?\.contains/); assert.match(componentSource, /popoverRef\.current\?\.contains/); - assert.match(componentSource, /createPortal/); + assert.match(componentSource, /portalToBody/); assert.match(componentSource, /notification-popover-portaled/); assert.match(componentSource, /\.notification-item\.unread, \.notification-item/); assert.match(componentSource, /\.notification-filter\.active/); diff --git a/apps/desktop/test/project-delete.test.mjs b/apps/desktop/test/project-delete.test.mjs index 46ee027494..b271b645bb 100644 --- a/apps/desktop/test/project-delete.test.mjs +++ b/apps/desktop/test/project-delete.test.mjs @@ -109,7 +109,7 @@ test("the delete dialog names the sessions and keeps the folder on disk", () => assert.match(dialogSource, /t\("project\.deleteSessions", \{ count: project\.sessionCount \}\)/); assert.match(dialogSource, /t\("project\.deleteDescription", \{ name: project\.name \}\)/); assert.match(dialogSource, /t\("project\.deleteFolderKept"\)/); - assert.match(dialogSource, /createPortal\(dialog, document\.body\)/); + assert.match(dialogSource, /portalToBody\(dialog\)/); }); test("the delete dialog is a labelled modal that blocks cancel while busy", () => { diff --git a/apps/desktop/test/provider-form-layout.test.mjs b/apps/desktop/test/provider-form-layout.test.mjs index c44c16da2f..bdc2230da2 100644 --- a/apps/desktop/test/provider-form-layout.test.mjs +++ b/apps/desktop/test/provider-form-layout.test.mjs @@ -356,3 +356,22 @@ test("the vendor account dialog hosts the same panes in the same shell", () => { assert.doesNotMatch(styles, /\.vendor-account-chosen/); assert.doesNotMatch(styles, /\.vendor-account-custom-model/); }); + +test("Advanced says a fullwidth value folds and a non-Latin-1 value is refused", () => { + // The rule itself lives in @pi-desktop/shared (unit-tested there) and is + // mirrored in host-core; this pins that the editor asks it and renders both + assert.match(headerEditorSource, /import \{ APP_VERSION, inspectHeaderValue \}/); + assert.match(headerEditorSource, /inspectHeaderValue\(pair\.value\)/); + // Only a row that will be persisted may claim it folds: the hint has to + // agree with what the host and the runtime do with the row. + assert.match(headerEditorSource, /pair\.key\.trim\(\) !== ""/); + assert.match(headerEditorSource, /header\.value !== ""/); + assert.match(headerEditorSource, /header\.fault === null/); + assert.match(headerEditorSource, /row\.storable && row\.header\.folded/); + assert.match(headerEditorSource, /provider-setup-header-note/); + assert.match(headerEditorSource, /role="status"/); + assert.match(headerEditorSource, /role="alert"/); + assert.match(headerEditorSource, /settings\.headersFullwidthFolded/); + assert.match(headerEditorSource, /settings\.headersValueNotLatin1/); + assert.match(block(".provider-setup-header-note"), /color: var\(--ds-text-muted\)/); +}); diff --git a/apps/desktop/test/renderer-recovery.test.mjs b/apps/desktop/test/renderer-recovery.test.mjs new file mode 100644 index 0000000000..382b48a50c --- /dev/null +++ b/apps/desktop/test/renderer-recovery.test.mjs @@ -0,0 +1,54 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { recoverRendererAfterGone } from "../electron/main/renderer-recovery.ts"; + +function recovery(overrides = {}) { + const calls = { reload: 0, logs: [] }; + const dependencies = { + isCurrentWindow: true, + quitting: false, + windowCloseAccepted: false, + windowDestroyed: false, + webContentsDestroyed: false, + reload: () => calls.reload++, + log: (details, reloaded) => calls.logs.push({ details, reloaded }), + ...overrides, + }; + return { calls, dependencies }; +} + +test("unexpected renderer exits reload the live main window and preserve diagnostics", () => { + const { calls, dependencies } = recovery(); + const details = { reason: "crashed", exitCode: 73 }; + + assert.equal(recoverRendererAfterGone(details, dependencies), true); + assert.equal(calls.reload, 1); + assert.deepEqual(calls.logs, [{ details, reloaded: true }]); +}); + +test("clean exits and windows outside the live main lifecycle are not reloaded", () => { + const cases = [ + [{ reason: "clean-exit", exitCode: 0 }, {}], + [{ reason: "crashed", exitCode: 1 }, { isCurrentWindow: false }], + [{ reason: "crashed", exitCode: 1 }, { quitting: true }], + [{ reason: "crashed", exitCode: 1 }, { windowCloseAccepted: true }], + [{ reason: "crashed", exitCode: 1 }, { windowDestroyed: true }], + [{ reason: "crashed", exitCode: 1 }, { webContentsDestroyed: true }], + ]; + + for (const [details, overrides] of cases) { + const { calls, dependencies } = recovery(overrides); + assert.equal(recoverRendererAfterGone(details, dependencies), false); + assert.equal(calls.reload, 0); + assert.deepEqual(calls.logs, [{ details, reloaded: false }]); + } +}); + +test("new renderer exit reasons remain recoverable by default", () => { + const { calls, dependencies } = recovery(); + assert.equal( + recoverRendererAfterGone({ reason: "future-electron-reason", exitCode: 2 }, dependencies), + true, + ); + assert.equal(calls.reload, 1); +}); diff --git a/apps/desktop/test/session-switch-performance.test.mjs b/apps/desktop/test/session-switch-performance.test.mjs index 4e52bab778..99330c6c1d 100644 --- a/apps/desktop/test/session-switch-performance.test.mjs +++ b/apps/desktop/test/session-switch-performance.test.mjs @@ -119,7 +119,7 @@ test("each retained session keeps its own mounted pane", () => { // already-painted pane instead of re-pointing one transcript (ADR 0137). assert.match( chatSurface, - /retainedSessionIds\.map\(\(id\) => \(\s*/, + /retainedSessionIds\.map\(\(id\) => \(\s*/, ); assert.match(chatSurface, /const visibleSessionId = retainedSessionIds\[0\]/); // The retention bound lives in a pure module, so eviction is unit-testable diff --git a/apps/desktop/test/settings-developer-only-destinations.test.mjs b/apps/desktop/test/settings-developer-only-destinations.test.mjs index 376d832a5d..c3bf21b05a 100644 --- a/apps/desktop/test/settings-developer-only-destinations.test.mjs +++ b/apps/desktop/test/settings-developer-only-destinations.test.mjs @@ -1,9 +1,9 @@ /** * Developer-only settings destinations contract. * - * Remote Hosts is an experimental surface that exists only while developer - * mode is on. The rail, the page, and settings search must add and drop it - * together, and a stale selection must fall back to General instead of + * Cloud sync and Remote Hosts are experimental surfaces that exist only while + * developer mode is on. The rail, page, and settings search must add and drop + * them together, and a stale selection must fall back to General instead of * rendering a page the rail no longer offers. */ import assert from "node:assert/strict"; @@ -31,18 +31,38 @@ test("developer mode alone decides which destinations exist", () => { const off = visibleSettingsNav(false).map((entry) => entry.id); const on = visibleSettingsNav(true).map((entry) => entry.id); + assert.equal(off.includes("sync"), false); + assert.equal(on.includes("sync"), true); assert.equal(off.includes("remoteHosts"), false); assert.equal(on.includes("remoteHosts"), true); - assert.deepEqual(off, on.filter((id) => id !== "remoteHosts")); - // Remote Hosts is the only gated destination today, and it carries the - // Experimental badge that the rail renders. + assert.deepEqual( + off, + on.filter((id) => id !== "sync" && id !== "remoteHosts"), + ); + // Both gated destinations carry the badge rendered by the rail and title. assert.deepEqual( SETTINGS_NAV.filter((entry) => entry.developerOnly === true).map((entry) => entry.id), - ["remoteHosts"], + ["sync", "remoteHosts"], + ); + assert.ok( + SETTINGS_NAV.filter((entry) => entry.developerOnly === true) + .every((entry) => entry.experimentalBadgeKey), + ); + assert.equal( + SETTINGS_NAV.find((entry) => entry.id === "sync")?.experimentalBadgeKey, + "settings.configSync.experimental", ); }); test("settings search mirrors the rail", () => { + assert.deepEqual( + searchSettings("configSync.connectionTitle", identity, { developerMode: false }), + [], + ); + assert.ok( + searchSettings("configSync.connectionTitle", identity, { developerMode: true }) + .some((hit) => hit.tab === "sync"), + ); assert.deepEqual(searchSettings("remotehosts", identity, { developerMode: false }), []); const hits = searchSettings("remotehosts", identity, { developerMode: true }); assert.ok(hits.some((hit) => hit.tab === "remoteHosts")); @@ -50,6 +70,8 @@ test("settings search mirrors the rail", () => { }); test("a stale developer-only selection is reported as hidden", () => { + assert.equal(isSettingsDestinationHidden("sync", false), true); + assert.equal(isSettingsDestinationHidden("sync", true), false); assert.equal(isSettingsDestinationHidden("remoteHosts", false), true); assert.equal(isSettingsDestinationHidden("remoteHosts", true), false); assert.equal(isSettingsDestinationHidden("general", false), false); @@ -60,6 +82,9 @@ test("the rail, the page, and the search dialog follow developer mode", () => { assert.match(settingsPage, /visibleSettingsNav\(developerMode\)/); assert.match(settingsPage, /isSettingsDestinationHidden\(tab, developerMode\)/); assert.match(settingsPage, /setSettingsTab\("general"\)/); + assert.match(settingsPage, /tab === "sync" && !tabHidden && /); + assert.match(settingsPage, /item\.experimentalBadgeKey/); + assert.match(settingsPage, /activeNavItem\?\.experimentalBadgeKey/); assert.match(settingsPage, /tab === "remoteHosts" && !tabHidden && /); assert.match(searchDialog, /searchSettings\(query, t, \{ developerMode \}\)/); }); diff --git a/apps/desktop/test/settings-remote-hosts.test.mjs b/apps/desktop/test/settings-remote-hosts.test.mjs index 8168c15e2a..c014c084ff 100644 --- a/apps/desktop/test/settings-remote-hosts.test.mjs +++ b/apps/desktop/test/settings-remote-hosts.test.mjs @@ -15,6 +15,10 @@ const page = readFileSync( new URL("../src/components/settings/RemoteHostsPage.tsx", import.meta.url), "utf8", ); +const settingsNav = readFileSync( + new URL("../src/lib/settings-search.ts", import.meta.url), + "utf8", +); const settings = readSettingsSourceSync(); const styles = loadStylesSync(); @@ -49,8 +53,12 @@ test("remote hosts omits instructional copy", () => { }); test("the remote-hosts destination is marked experimental", () => { - assert.match(settings, /item\.id === "remoteHosts"/); - assert.match(settings, /settings\.remoteHosts\.experimental/); + assert.match( + settingsNav, + /\{\s*id: "remoteHosts",[\s\S]*?experimentalBadgeKey: "settings\.remoteHosts\.experimental",/, + ); + assert.match(settings, /item\.experimentalBadgeKey \? \(/); + assert.match(settings, /activeNavItem\?\.experimentalBadgeKey \? \(/); assert.match(settings, /className="settings-nav-experimental"/); assert.match(cssRule(".settings-nav-experimental"), /font-size:\s*var\(--text-2xs\)/); assert.doesNotMatch(page, /EXPERIMENTAL_FEATURES/); diff --git a/apps/desktop/test/sidebar-settings-return.test.mjs b/apps/desktop/test/sidebar-settings-return.test.mjs index e7f3e92280..d14e26a1c8 100644 --- a/apps/desktop/test/sidebar-settings-return.test.mjs +++ b/apps/desktop/test/sidebar-settings-return.test.mjs @@ -6,6 +6,26 @@ import { loadStyles } from "./helpers/styles.mjs"; const idle = (collapsed = false, presented = true) => ({ collapsed, presented, phase: "idle" }); +test("Settings hides the mounted chat shell and keeps its portal layers out of view", async () => { + const [appShell, styles, portalVisibility] = await Promise.all([ + readFile(new URL("../src/features/app/AppShell.tsx", import.meta.url), "utf8"), + loadStyles(), + readFile(new URL("../src/lib/portal-visibility.tsx", import.meta.url), "utf8"), + ]); + assert.match(appShell, //); + assert.match(appShell, /className="app-chat-shell"[\s\S]*?hidden=\{page === "settings"\}/); + assert.match(appShell, /inert=\{page === "settings" \? true : undefined\}/); + assert.match(appShell, /aria-hidden=\{page === "settings" \? true : undefined\}/); + assert.match(appShell, /className="app-chat-shell"[\s\S]*?/); + assert.match(appShell, /\{page === "settings" \? \([\s\S]*?/); + assert.match(appShell, //); + assert.match(appShell, /[\s\S]*visible \? node : null/); + assert.match(portalVisibility, /createPortal\(visiblePortalContent\(node\), document\.body\)/); +}); + test("initial shell presentation and settings return never play sidebar entrance", () => { assert.deepEqual(nextSidebarTransition(idle(false, false), false, true), idle()); for (const collapsed of [false, true]) { diff --git a/apps/desktop/test/thinking-ui.test.mjs b/apps/desktop/test/thinking-ui.test.mjs index bc38087b41..6bfd0e27ca 100644 --- a/apps/desktop/test/thinking-ui.test.mjs +++ b/apps/desktop/test/thinking-ui.test.mjs @@ -29,6 +29,10 @@ const appSource = await readFile( new URL("../src/components/ChatSurface.tsx", import.meta.url), "utf8", ); +const launchErrorSource = await readFile( + new URL("../src/lib/chat-launch-error.ts", import.meta.url), + "utf8", +); const providerCatalogSource = await readMainModule("runtime/provider-catalog.ts"); const sessionIpcSource = await readMainModule("ipc/session-ipc.ts"); const sessionLaunchSource = await readMainModule("runtime/session-launch.ts"); @@ -285,8 +289,9 @@ test("activity headers omit the redundant status capsule", () => { }); test("thinking-only assistant streams open the transcript surface", () => { - assert.match(appSource, /typeof message\.thinking === "string"/); - assert.match(appSource, /hasContent \|\| hasThinking/); + assert.match(launchErrorSource, /typeof message\.thinking === "string"/); + assert.match(launchErrorSource, /hasContent \|\| hasThinking/); + assert.match(appSource, /messageHasTranscriptContent\(message\)/); }); test("provider settings persist model-local limits and thinking configuration", () => { diff --git a/apps/desktop/test/transcript-style.test.mjs b/apps/desktop/test/transcript-style.test.mjs index 1115885ec1..effedd231e 100644 --- a/apps/desktop/test/transcript-style.test.mjs +++ b/apps/desktop/test/transcript-style.test.mjs @@ -396,7 +396,7 @@ test("assistant context inspector keeps a compact summary and retry action wired assert.match(inspectorSource, /contextOccupancyTokens\(usage\)/); assert.match(inspectorSource, /usage\.cacheReadTokens/); assert.doesNotMatch(inspectorSource, /turnUsage\.cacheReadTokens/); - assert.match(inspectorSource, /createPortal\(popover, document\.body\)/); + assert.match(inspectorSource, /portalToBody\(popover\)/); assert.match(inspectorSource, /getBoundingClientRect\(\)/); assert.match(inspectorSource, /addEventListener\("scroll", handleViewportChange, true\)/); assert.match(inspectorSource, /ResizeObserver\(updatePopoverPosition\)/); diff --git a/apps/desktop/test/vendor-live-models.test.mjs b/apps/desktop/test/vendor-live-models.test.mjs new file mode 100644 index 0000000000..9104689654 --- /dev/null +++ b/apps/desktop/test/vendor-live-models.test.mjs @@ -0,0 +1,106 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + parseVendorModelIds, + pinnedSiblingId, + vendorModelListRequest, + wireForLiveModel, +} from "../electron/main/vendor-live-models.ts"; + +function codexToken() { + const payload = Buffer.from(JSON.stringify({ + "https://api.openai.com/auth": { chatgpt_account_id: "acct_123" }, + })).toString("base64url"); + return `header.${payload}.sig`; +} + +test("ChatGPT accounts list models from the Codex endpoint, not /models", () => { + const request = vendorModelListRequest({ + vendorId: "openai-codex", + apiKey: codexToken(), + }); + assert.equal(request?.url, "https://chatgpt.com/backend-api/codex/models"); + assert.equal(request?.headers["chatgpt-account-id"], "acct_123"); + assert.equal(parseVendorModelIds("openai-codex", { + models: [ + { slug: "gpt-6-luna", visibility: "list" }, + { slug: "gpt-6-hidden", visibility: "hide" }, + ], + })?.join(","), "gpt-6-luna"); + assert.equal(parseVendorModelIds("openai-codex", { + data: [{ id: "gpt-4o" }], + }), null); + assert.equal(vendorModelListRequest({ + vendorId: "openai-codex", + apiKey: "not-a-jwt", + }), undefined); +}); + +test("Copilot keeps picker flags and the API version header", () => { + const request = vendorModelListRequest({ + vendorId: "github-copilot", + apiKey: "copilot-token", + }); + assert.equal(request?.url, "https://api.individual.githubcopilot.com/models"); + assert.equal(request?.headers["X-GitHub-Api-Version"], "2026-06-01"); + assert.deepEqual(parseVendorModelIds("github-copilot", { + data: [ + { id: "gpt-6-luna", model_picker_enabled: true, policy: { state: "enabled" } }, + { id: "gpt-5.4", policy: { state: "enabled" } }, + { + id: "gpt-image", + model_picker_enabled: true, + capabilities: { supports: { tool_calls: false } }, + }, + ], + }, true), ["gpt-6-luna"]); +}); + +test("Anthropic OAuth sends the Claude Code identity headers", () => { + const request = vendorModelListRequest({ + vendorId: "anthropic", + apiKey: "sk-ant-oat01-test", + }); + assert.equal(request?.url, "https://api.anthropic.com/v1/models?limit=1000"); + assert.equal(request?.headers["x-app"], "cli"); + assert.equal(request?.headers.Authorization, "Bearer sk-ant-oat01-test"); + assert.match(request?.headers["anthropic-beta"] ?? "", /oauth-2025-04-20/); +}); + +test("a new Grok inherits the newest explicit sibling, not pin order", () => { + assert.equal( + pinnedSiblingId("xai", "grok-4.7", ["grok-4.3", "grok-4.5", "grok-4.6"]), + "grok-4.6", + ); +}); + +test("an unknown Claude does not inherit a different tier", () => { + assert.equal( + pinnedSiblingId("anthropic", "claude-3-5-sonnet-20241022", ["claude-fable-5", "claude-sonnet-4-6"]), + "claude-sonnet-4-6", + ); + assert.equal( + pinnedSiblingId("anthropic", "claude-3-5-sonnet-20241022", ["claude-fable-5"]), + undefined, + ); +}); + +test("Copilot only keeps a new id when its family has one wire API", () => { + const pinned = [ + { id: "gpt-5.4", api: "openai-responses", baseUrl: "https://api.individual.githubcopilot.com" }, + { id: "claude-sonnet-4-6", api: "anthropic-messages", baseUrl: "https://api.individual.githubcopilot.com" }, + ]; + assert.equal( + wireForLiveModel("github-copilot", "gpt-6-luna", pinned, pinned[0].baseUrl)?.api, + "openai-responses", + ); + assert.equal( + wireForLiveModel("github-copilot", "mystery-1", pinned, pinned[0].baseUrl), + undefined, + ); + assert.equal( + wireForLiveModel("openai-codex", "gpt-6-luna", pinned, "https://chatgpt.com/backend-api")?.api, + "openai-codex-responses", + ); +}); diff --git a/apps/desktop/test/vendor-oauth-login.test.mjs b/apps/desktop/test/vendor-oauth-login.test.mjs index d6722dc144..dd9e507a75 100644 --- a/apps/desktop/test/vendor-oauth-login.test.mjs +++ b/apps/desktop/test/vendor-oauth-login.test.mjs @@ -171,6 +171,11 @@ function harness(options = {}) { }, modelConfigFor: options.modelConfigFor, newId: () => `id-${++counter}`, + fetch: + options.fetch ?? + (async () => { + throw new Error("live model list disabled in test"); + }), }); // The store the module handed pi-ai, so a test can drive it the way a token // refresh would. @@ -602,8 +607,7 @@ test("conversation-model filter drops xAI image and video ids", () => { test("an xAI account offers the chat models its /models endpoint returns", async () => { const seen = []; - const previousFetch = globalThis.fetch; - globalThis.fetch = async (url, init) => { + const fetchModels = async (url, init) => { seen.push({ url: String(url), authorization: init?.headers?.Authorization, @@ -616,6 +620,8 @@ test("an xAI account offers the chat models its /models endpoint returns", async ], }), { status: 200, headers: { "content-type": "application/json" } }); }; + const previousFetch = globalThis.fetch; + globalThis.fetch = fetchModels; const xaiModel = { id: "grok-4.6", name: "Grok 4.6", @@ -639,6 +645,7 @@ test("an xAI account offers the chat models its /models endpoint returns", async }; try { const { host, events, oauth } = harness({ + fetch: fetchModels, provider: { id: "xai", name: "xAI", @@ -675,3 +682,49 @@ test("an xAI account offers the chat models its /models endpoint returns", async globalThis.fetch = previousFetch; } }); + +test("a new Grok inherits grok-4.6 even when an older Grok is first in the pin", async () => { + const fetchModels = async () => new Response(JSON.stringify({ + data: [{ id: "grok-4.7" }], + }), { status: 200, headers: { "content-type": "application/json" } }); + const older = { + id: "grok-4.3", + name: "Grok 4.3", + api: "openai-responses", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + input: ["text"], + reasoning: true, + thinkingLevelMap: { off: "off", low: "low", medium: "medium", high: "high" }, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 1_000_000, + maxTokens: 30_000, + }; + const newest = { + ...older, + id: "grok-4.6", + name: "Grok 4.6", + input: ["text", "image"], + thinkingLevelMap: { off: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh" }, + contextWindow: 500_000, + maxTokens: 500_000, + }; + const { events, oauth } = harness({ + fetch: fetchModels, + provider: { + id: "xai", + name: "xAI", + baseUrl: "https://api.x.ai/v1", + auth: { oauth: { name: "xAI", isSubscription: true, loginLabel: "Sign in" } }, + }, + models: [older, newest], + }); + const { loginId } = await oauth.start("xai"); + const prompt = await waitFor(events, "prompt"); + oauth.respond({ loginId, promptId: prompt.request.promptId, value: "abc" }); + const done = await waitFor(events, "done"); + const binding = await oauth.bindingFor(done.providerId, "grok-4.7"); + assert.equal(binding.modelConfig.contextWindow, 500_000); + assert.equal(binding.modelConfig.maxTokens, 500_000); + assert.deepEqual(binding.supportedThinkingLevels, ["low", "medium", "high", "xhigh"]); +}); diff --git a/crates/host-core/src/config_sync/apply.rs b/crates/host-core/src/config_sync/apply.rs index 0638402973..0585b6d280 100644 --- a/crates/host-core/src/config_sync/apply.rs +++ b/crates/host-core/src/config_sync/apply.rs @@ -150,6 +150,12 @@ fn apply_entity( object.insert("secretValue".into(), Value::String(secret.clone())); } } + // A bundle from a peer on an older build, or a backup taken before the + // header rule was tightened, can carry a value this build refuses. That + // is dropped here — the rule `config_headers` already applies when + // reading a store — so one stale row cannot fail the whole revision, + // which is what the strict write the editor goes through would do. + providers::retain_storable_headers(&mut payload); let exists = st .db .conn() diff --git a/crates/host-core/src/config_sync/crypto.rs b/crates/host-core/src/config_sync/crypto.rs index 9c2bbed6d4..fd15bc8284 100644 --- a/crates/host-core/src/config_sync/crypto.rs +++ b/crates/host-core/src/config_sync/crypto.rs @@ -256,7 +256,7 @@ pub fn unlock_vault(header: &VaultHeader, password: &str) -> Result { encrypted.extend_from_slice(&nonce); encrypted.extend_from_slice(&ciphertext); let plaintext = decrypt_with_key(&wrapping_key, "vault-key", &header.vault_id, &encrypted) - .context("unlock vault")?; + .map_err(|_| anyhow!("CONFIG_SYNC_CRYPTO: backup password did not open this vault"))?; let raw: [u8; KEY_BYTES] = plaintext .try_into() .map_err(|_| anyhow!("CONFIG_SYNC_CRYPTO: vault key has an invalid length"))?; @@ -312,7 +312,8 @@ mod tests { create_vault("correct horse battery staple", "vault-a").expect("create vault"); let unlocked = unlock_vault(&header, "correct horse battery staple").expect("unlock"); assert_eq!(unlocked.as_bytes(), key.as_bytes()); - assert!(unlock_vault(&header, "wrong password").is_err()); + let wrong = unlock_vault(&header, "wrong password").expect_err("wrong password"); + assert!(wrong.to_string().starts_with("CONFIG_SYNC_CRYPTO:")); let mut ciphertext = encrypt_object(&key, "test", "vault-a", b"portable settings").expect("encrypt"); diff --git a/crates/host-core/src/config_sync/engine.rs b/crates/host-core/src/config_sync/engine.rs index d119095297..24fb224434 100644 --- a/crates/host-core/src/config_sync/engine.rs +++ b/crates/host-core/src/config_sync/engine.rs @@ -867,7 +867,7 @@ fn config_from_input( .or_else(|| existing.map(|value| value.automatic_sync)) .unwrap_or(true), enabled: true, - paused: false, + paused: existing.is_some_and(|value| value.paused), vault_id: header.vault_id.clone(), vault_header: header, last_run_at: existing.and_then(|value| value.last_run_at.clone()), @@ -907,11 +907,15 @@ fn parse_remote_mode(value: &str) -> Result { fn mark_error(config: &mut StoredConfig, error: &anyhow::Error) { let message = error.to_string(); - config.last_error_code = if message.starts_with("CONFIG_SYNC_UNSUPPORTED") { + config.last_error_code = if message.starts_with("CONFIG_SYNC_UNSUPPORTED") + || message.starts_with("CONFIG_SYNC_REDIRECT") + { Some("UNSUPPORTED_SERVER".into()) } else if message.starts_with("CONFIG_SYNC_CONFLICT") { Some("CONFLICT".into()) - } else if message.starts_with("CONFIG_SYNC_CRYPTO") + } else if message.starts_with("CONFIG_SYNC_AUTH") + || message.starts_with("CONFIG_SYNC_PERMISSION") + || message.starts_with("CONFIG_SYNC_CRYPTO") || message.contains("401 Unauthorized") || message.contains("403 Forbidden") || message.contains("authentication") diff --git a/crates/host-core/src/config_sync/handlers.rs b/crates/host-core/src/config_sync/handlers.rs index 21a4428ee0..059beedc82 100644 --- a/crates/host-core/src/config_sync/handlers.rs +++ b/crates/host-core/src/config_sync/handlers.rs @@ -59,13 +59,13 @@ pub(crate) async fn test(state: Arc>, params: Value) -> Result>, params: Value) -> Res let backup_password = params .get("backupPassword") .and_then(Value::as_str) - .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: backup password is required"))?; - if backup_password.len() < 8 { + .unwrap_or("") + .trim(); + if !backup_password.is_empty() && backup_password.len() < 8 { bail!("CONFIG_SYNC_INVALID: backup password must be at least 8 characters"); } let (mut config, mut key, transport_password, had_existing) = { let st = state.lock().await; let existing = load_config(&st)?; - let vault_id = existing - .as_ref() - .map(|value| value.vault_id.clone()) - .unwrap_or_else(|| Uuid::new_v4().to_string()); - let (header, key) = if let Some(existing) = existing.as_ref() { - ( - existing.vault_header.clone(), - unlock_vault(&existing.vault_header, backup_password)?, - ) + let (header, key, had_existing) = if backup_password.is_empty() { + let saved = existing.as_ref().ok_or_else(|| { + anyhow!("CONFIG_SYNC_LOCKED: enter the vault password to set up sync") + })?; + let key = local_vault_key(&st, saved)? + .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?; + (saved.vault_header.clone(), key, true) } else { - create_vault(backup_password, &vault_id)? + let vault_id = existing + .as_ref() + .map(|value| value.vault_id.clone()) + .unwrap_or_else(|| Uuid::new_v4().to_string()); + let (header, key) = if let Some(saved) = existing.as_ref() { + ( + saved.vault_header.clone(), + unlock_vault(&saved.vault_header, backup_password)?, + ) + } else { + create_vault(backup_password, &vault_id)? + }; + (header, key, existing.is_some()) }; let config = config_from_input(existing.as_ref(), ¶ms, header)?; - let stored_password = if existing - .as_ref() - .is_some_and(|value| value.username == config.username) - { - st.secrets.get(WEBDAV_SECRET_REF)? - } else { - None - }; - let transport_password = params - .get("appPassword") - .and_then(Value::as_str) - .map(str::to_string) - .or(stored_password) - .unwrap_or_default(); - if !config.username.is_empty() && transport_password.is_empty() { - bail!("CONFIG_SYNC_INVALID: WebDAV app password is required"); - } - (config, key, transport_password, existing.is_some()) + let transport_password = connection_password( + &st, + existing.as_ref(), + &config.endpoint, + &config.username, + ¶ms, + )?; + (config, key, transport_password, had_existing) }; let app_password = params .get("appPassword") @@ -191,9 +192,7 @@ pub(crate) async fn configure(state: Arc>, params: Value) -> Res if had_existing && config.vault_id != remote.vault_id { bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault"); } - key = unlock_vault(&remote, backup_password)?; - config.vault_id = remote.vault_id.clone(); - config.vault_header = remote; + adopt_remote_vault(&mut key, &mut config, remote, backup_password)?; } else { if config.remote_mode == RemoteMode::AppendOnly { if had_existing { @@ -213,9 +212,7 @@ pub(crate) async fn configure(state: Arc>, params: Value) -> Res bail!("CONFIG_SYNC_REMOTE: vault header disappeared during initialization"); }; let remote: VaultHeader = serde_json::from_slice(&bytes)?; - key = unlock_vault(&remote, backup_password)?; - config.vault_id = remote.vault_id.clone(); - config.vault_header = remote; + adopt_remote_vault(&mut key, &mut config, remote, backup_password)?; } } if config.remote_mode == RemoteMode::AppendOnly { @@ -226,9 +223,7 @@ pub(crate) async fn configure(state: Arc>, params: Value) -> Res if had_existing && config.vault_id != remote.vault_id { bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault"); } - key = unlock_vault(&remote, backup_password)?; - config.vault_id = remote.vault_id.clone(); - config.vault_header = remote; + adopt_remote_vault(&mut key, &mut config, remote, backup_password)?; } } ensure_remote_collections(&transport, &config).await?; @@ -522,3 +517,105 @@ pub(crate) async fn disconnect(state: Arc>) -> Result { } public_state(&mut st) } + +/// A saved WebDAV password belongs to one endpoint and account. Changing either +/// must not send the previous server's secret. +fn connection_password( + st: &AppState, + existing: Option<&StoredConfig>, + endpoint: &str, + username: &str, + params: &Value, +) -> Result { + if username.is_empty() { + return Ok(String::new()); + } + let explicit = params.get("appPassword").and_then(Value::as_str); + let password = match explicit { + Some(value) => Some(value.to_string()), + None if existing + .is_some_and(|saved| saved.endpoint == endpoint && saved.username == username) => + { + st.secrets.get(WEBDAV_SECRET_REF)? + } + None => None, + }; + password.filter(|value| !value.is_empty()).ok_or_else(|| { + anyhow!("CONFIG_SYNC_AUTH: enter the WebDAV app password for this server and account") + }) +} + +fn adopt_remote_vault( + key: &mut VaultKey, + config: &mut StoredConfig, + remote: VaultHeader, + password: &str, +) -> Result<()> { + if password.is_empty() { + if config.vault_id != remote.vault_id { + bail!("CONFIG_SYNC_LOCKED: enter the vault password to open this backup"); + } + config.vault_header = remote; + return Ok(()); + } + *key = unlock_vault(&remote, password)?; + config.vault_id = remote.vault_id.clone(); + config.vault_header = remote; + Ok(()) +} + +#[cfg(test)] +mod credential_tests { + use super::*; + + #[test] + fn stored_password_stays_on_its_server_and_pause_survives_a_resave() -> Result<()> { + let dir = tempfile::tempdir()?; + let state = AppState::open(dir.path())?; + state.secrets.set(WEBDAV_SECRET_REF, "original-secret")?; + let (header, _) = create_vault("backup-password", "test-vault")?; + let mut config = config_from_input( + None, + &json!({ + "endpoint": "https://original.example/dav/", + "username": "alice", + "deviceLabel": "test" + }), + header.clone(), + )?; + config.paused = true; + assert_eq!( + connection_password(&state, Some(&config), &config.endpoint, "alice", &json!({}))?, + "original-secret" + ); + let resent = config_from_input( + Some(&config), + &json!({ + "endpoint": config.endpoint, + "username": "alice", + "deviceLabel": "test" + }), + header, + )?; + assert!(resent.paused); + for (endpoint, username) in [ + ("https://other.example/dav/", "alice"), + ("https://original.example/dav/", "bob"), + ] { + let error = connection_password(&state, Some(&config), endpoint, username, &json!({})) + .unwrap_err(); + assert!(error.to_string().starts_with("CONFIG_SYNC_AUTH:")); + } + assert_eq!( + connection_password( + &state, + Some(&config), + "https://other.example/", + "", + &json!({}) + )?, + "" + ); + Ok(()) + } +} diff --git a/crates/host-core/src/config_sync/transport.rs b/crates/host-core/src/config_sync/transport.rs index b613964713..02af4b2311 100644 --- a/crates/host-core/src/config_sync/transport.rs +++ b/crates/host-core/src/config_sync/transport.rs @@ -1,5 +1,5 @@ use anyhow::{bail, Context, Result}; -use reqwest::header::{HeaderMap, HeaderValue, ETAG, IF_MATCH, IF_NONE_MATCH, LOCATION}; +use reqwest::header::{HeaderMap, HeaderValue, ETAG, IF_MATCH, IF_NONE_MATCH}; use reqwest::{Client, Method, StatusCode, Url}; use std::net::IpAddr; use uuid::Uuid; @@ -174,7 +174,17 @@ impl WebDavTransport { body: Option>, headers: HeaderMap, ) -> Result { - let url = self.url(relative)?; + self.send_url(method, self.url(relative)?, body, headers) + .await + } + + async fn send_url( + &self, + method: Method, + url: Url, + body: Option>, + headers: HeaderMap, + ) -> Result { let mut request = self.client.request(method, url).headers(headers); if let Some(body) = body { request = request.body(body); @@ -183,36 +193,52 @@ impl WebDavTransport { .authenticated(request) .send() .await - .context("WebDAV request failed")?; - if response.headers().get(LOCATION).is_some() || response.status().is_redirection() { - bail!("CONFIG_SYNC_SECURITY: WebDAV redirects are not permitted"); + .map_err(request_error)?; + // A 201 often carries Location. Only a 3xx is a redirect, and the + // client is built not to follow one. + if response.status().is_redirection() { + bail!( + "CONFIG_SYNC_REDIRECT: use the direct WebDAV endpoint; redirects are not followed" + ); } Ok(response) } - /// Create a single collection below the configured vault directory. A - /// WebDAV server may report 405 when the collection already exists; that - /// is a successful idempotent result for this helper. We intentionally do - /// not follow redirects or try to infer a different root. + /// Create every missing collection from the selected endpoint down to + /// `relative`. A nested remote directory such as `backups/pi` otherwise + /// fails because its parent does not exist yet. Ancestors outside the + /// endpoint are never created. pub async fn ensure_collection(&self, relative: &str) -> Result<()> { - let response = self - .send( - Method::from_bytes(b"MKCOL").expect("MKCOL is a valid method"), - relative, - None, - HeaderMap::new(), - ) - .await?; - match response.status() { - status - if status.is_success() - || status == StatusCode::METHOD_NOT_ALLOWED - || status == StatusCode::PRECONDITION_FAILED => - { - Ok(()) + let target = self.url(relative)?; + let base_path = self.base.path().trim_end_matches('/'); + let suffix = target + .path() + .trim_end_matches('/') + .strip_prefix(base_path) + .ok_or_else(|| anyhow::anyhow!("CONFIG_SYNC_INVALID: collection escaped endpoint"))?; + let mut path = base_path.to_string(); + for segment in suffix.split('/').filter(|segment| !segment.is_empty()) { + path.push('/'); + path.push_str(segment); + let mut url = self.base.clone(); + url.set_path(&path); + let response = self + .send_url( + Method::from_bytes(b"MKCOL").expect("MKCOL is a valid method"), + url, + None, + HeaderMap::new(), + ) + .await?; + match response.status() { + status + if status.is_success() + || status == StatusCode::METHOD_NOT_ALLOWED + || status == StatusCode::PRECONDITION_FAILED => {} + status => return Err(status_error("collection create", status)), } - status => bail!("CONFIG_SYNC_REMOTE: WebDAV collection create returned {status}"), } + Ok(()) } async fn limited_bytes(response: reqwest::Response) -> Result> { @@ -224,7 +250,7 @@ impl WebDavTransport { } let mut response = response; let mut result = Vec::new(); - while let Some(chunk) = response.chunk().await.context("read WebDAV response")? { + while let Some(chunk) = response.chunk().await.map_err(request_error)? { if result.len().saturating_add(chunk.len()) > MAX_REMOTE_OBJECT_BYTES { bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote object is too large"); } @@ -243,10 +269,7 @@ impl WebDavTransport { return Ok(None); } if !response.status().is_success() { - bail!( - "CONFIG_SYNC_REMOTE: WebDAV GET returned {}", - response.status() - ); + return Err(status_error("GET", response.status())); } let etag = strong_etag(response.headers()); Ok(Some((Self::limited_bytes(response).await?, etag))) @@ -257,10 +280,7 @@ impl WebDavTransport { .send(Method::PUT, relative, Some(body), HeaderMap::new()) .await?; if !response.status().is_success() { - bail!( - "CONFIG_SYNC_REMOTE: WebDAV unconditional write returned {}", - response.status() - ); + return Err(status_error("unconditional write", response.status())); } Ok(()) } @@ -294,10 +314,7 @@ impl WebDavTransport { bail!("CONFIG_SYNC_UNSUPPORTED: WebDAV directory listing is not supported"); } if response.status().as_u16() != 207 && !response.status().is_success() { - bail!( - "CONFIG_SYNC_REMOTE: WebDAV directory listing returned {}", - response.status() - ); + return Err(status_error("directory listing", response.status())); } let body = Self::limited_bytes(response).await?; let text = String::from_utf8(body).context("decode WebDAV directory listing")?; @@ -351,7 +368,7 @@ impl WebDavTransport { match response.status() { StatusCode::PRECONDITION_FAILED => Ok(false), status if status.is_success() => Ok(true), - status => bail!("CONFIG_SYNC_REMOTE: WebDAV create returned {status}"), + status => return Err(status_error("create", status)), } } @@ -367,7 +384,7 @@ impl WebDavTransport { match response.status() { StatusCode::PRECONDITION_FAILED => Ok(false), status if status.is_success() => Ok(true), - status => bail!("CONFIG_SYNC_REMOTE: WebDAV conditional write returned {status}"), + status => return Err(status_error("conditional write", status)), } } @@ -376,10 +393,7 @@ impl WebDavTransport { .send(Method::DELETE, relative, None, HeaderMap::new()) .await?; if response.status() != StatusCode::NOT_FOUND && !response.status().is_success() { - bail!( - "CONFIG_SYNC_REMOTE: WebDAV delete returned {}", - response.status() - ); + return Err(status_error("delete", response.status())); } Ok(()) } @@ -473,9 +487,41 @@ fn compatible_missing_object_status(value: Option) -> Option { (value == Some(StatusCode::BAD_GATEWAY.as_u16())).then_some(StatusCode::BAD_GATEWAY) } +fn request_error(error: reqwest::Error) -> anyhow::Error { + if error.is_timeout() { + anyhow::anyhow!("CONFIG_SYNC_TIMEOUT: WebDAV request timed out") + } else { + anyhow::anyhow!( + "CONFIG_SYNC_NETWORK: WebDAV connection failed; check the network and TLS certificate" + ) + } +} + +fn status_error(operation: &str, status: StatusCode) -> anyhow::Error { + let code = match status.as_u16() { + 401 => "AUTH", + 403 => "PERMISSION", + 404 => "NOT_FOUND", + 409 | 423 => "CONFLICT", + 413 | 507 => "QUOTA", + 429 => "RATE_LIMIT", + 500..=599 => "SERVER", + _ => "REMOTE", + }; + anyhow::anyhow!("CONFIG_SYNC_{code}: WebDAV {operation} returned {status}") +} + pub fn remote_error_is_offline(error: &anyhow::Error) -> bool { let text = error.to_string().to_lowercase(); - text.contains("request failed") + [ + "config_sync_network:", + "config_sync_timeout:", + "config_sync_server:", + "config_sync_rate_limit:", + ] + .iter() + .any(|prefix| text.starts_with(prefix)) + || text.contains("request failed") || text.contains("timed out") || text.contains("dns") || text.contains("connect") @@ -498,6 +544,7 @@ pub(crate) mod tests { weak_etag: bool, missing_status: Option, ignore_preconditions: bool, + require_parent: bool, } async fn read_request(stream: &mut TcpStream) -> Option<(String, String, HeaderMap, Vec)> { @@ -592,7 +639,20 @@ pub(crate) mod tests { let mut state = state.lock().expect("fixture state"); match method.as_str() { "MKCOL" => { - if state.collections.insert(path) { + let normalized = path.trim_end_matches('/').to_string(); + if state.require_parent { + let parent = normalized + .rsplit_once('/') + .map(|(parent, _)| parent) + .unwrap_or(""); + if !parent.is_empty() && !state.collections.contains(parent) { + (409, Vec::new(), None) + } else if state.collections.insert(normalized) { + (201, Vec::new(), None) + } else { + (405, Vec::new(), None) + } + } else if state.collections.insert(path) { (201, Vec::new(), None) } else { (405, Vec::new(), None) @@ -692,17 +752,18 @@ pub(crate) mod tests { } pub(crate) async fn fixture(weak_etag: bool) -> Fixture { - fixture_with_options(weak_etag, None, false).await + fixture_with_options(weak_etag, None, false, false).await } pub(crate) async fn fixture_ignoring_preconditions() -> Fixture { - fixture_with_options(false, None, true).await + fixture_with_options(false, None, true, false).await } async fn fixture_with_options( weak_etag: bool, missing_status: Option, ignore_preconditions: bool, + require_parent: bool, ) -> Fixture { let listener = TcpListener::bind("127.0.0.1:0") .await @@ -712,6 +773,7 @@ pub(crate) mod tests { weak_etag, missing_status, ignore_preconditions, + require_parent, ..FixtureState::default() })); let task = tokio::spawn(async move { @@ -773,6 +835,24 @@ pub(crate) mod tests { assert_eq!(strong_etag(&headers).as_deref(), Some("\"strong\"")); } + #[tokio::test] + async fn nested_directory_creates_missing_ancestors() { + let fixture = fixture_with_options(false, None, false, true).await; + let transport = WebDavTransport::new(&WebDavConfig { + endpoint: fixture.endpoint.clone(), + username: String::new(), + password: String::new(), + directory: "backups/pi/settings".into(), + allow_insecure_http: true, + missing_object_status: None, + }) + .expect("transport"); + transport + .ensure_collection("vault") + .await + .expect("nested collections"); + } + #[tokio::test] async fn local_fixture_proves_conditional_writes() { let fixture = fixture(false).await; @@ -785,7 +865,7 @@ pub(crate) mod tests { #[tokio::test] async fn probe_rejects_servers_that_ignore_conditional_headers() { - let fixture = fixture_with_options(false, None, true).await; + let fixture = fixture_with_options(false, None, true, false).await; let transport = fixture_transport(&fixture.endpoint); let probe = transport.probe().await.expect("probe"); assert!(!probe.conditional_writes); @@ -814,7 +894,7 @@ pub(crate) mod tests { #[tokio::test] async fn probe_records_bad_gateway_as_the_missing_object_status() { - let fixture = fixture_with_options(false, Some(502), false).await; + let fixture = fixture_with_options(false, Some(502), false, false).await; let transport = fixture_transport(&fixture.endpoint); let probe = transport.probe().await.expect("probe"); assert!(probe.conditional_writes); diff --git a/crates/host-core/src/providers.rs b/crates/host-core/src/providers.rs index 87c0f15ff8..14c0bdbaa9 100644 --- a/crates/host-core/src/providers.rs +++ b/crates/host-core/src/providers.rs @@ -42,13 +42,13 @@ pub(crate) use credentials::{ config_reasoning_override, config_value, config_with_headers, config_with_limit, config_with_oauth_account_label, config_with_reasoning_override, config_with_thinking_levels_override, ensure_config_object, limit_temperature_value, - limit_u32_value, limits_object, merge_provider_config_overrides, upsert_secret_meta, - LimitOverrides, + limit_u32_value, limits_object, merge_provider_config_overrides, retain_storable_headers, + upsert_secret_meta, LimitOverrides, }; pub(crate) use validation::{ - config_limit_f64, config_limit_u32, normalize_headers_input, normalize_one_header, - normalize_thinking_levels, valid_header_key, validate_model_aliases, MAX_HEADERS, - MAX_MODEL_ALIAS_CHARS, + config_limit_f64, config_limit_u32, fold_fullwidth, header_value_fault, + normalize_headers_input, normalize_one_header, normalize_thinking_levels, storable_headers, + valid_header_key, validate_model_aliases, MAX_HEADERS, MAX_MODEL_ALIAS_CHARS, }; #[cfg(test)] diff --git a/crates/host-core/src/providers/credentials.rs b/crates/host-core/src/providers/credentials.rs index 83b07be994..9bff92deef 100644 --- a/crates/host-core/src/providers/credentials.rs +++ b/crates/host-core/src/providers/credentials.rs @@ -32,20 +32,10 @@ pub(crate) fn config_headers(raw: &str) -> Option> { collected.insert("User-Agent".into(), user_agent.to_string()); } } - let mut by_lower: BTreeMap = BTreeMap::new(); - for (key, value) in collected { - if let Ok(Some((normalized_key, normalized_value))) = normalize_one_header(&key, &value) { - by_lower.insert( - normalized_key.to_ascii_lowercase(), - (normalized_key, normalized_value), - ); - } - } - let out: BTreeMap<_, _> = by_lower - .into_iter() - .take(MAX_HEADERS) - .map(|(_, pair)| pair) - .collect(); + // A stored map is read, not written: rows this build refuses (a value with + // a character no header can carry, a reserved name) are dropped rather than + // reported, so an older store cannot fail a turn. + let out = storable_headers(&collected); if out.is_empty() { None } else { @@ -53,6 +43,36 @@ pub(crate) fn config_headers(raw: &str) -> Option> { } } +/// Fold and drop the `headers` object of a provider payload before it is +/// deserialized into a write input. A bundle from a peer on an older build, or +/// a backup taken before the header rule was tightened, can carry a value this +/// build refuses; failing the whole sync revision over one stale row is worse +/// than dropping it, and the row is already invisible on read (`config_headers` +/// drops the same cases). +pub(crate) fn retain_storable_headers(payload: &mut serde_json::Value) { + let Some(object) = payload.as_object_mut() else { + return; + }; + let Some(headers) = object.get("headers").and_then(serde_json::Value::as_object) else { + return; + }; + let raw: BTreeMap = headers + .iter() + .filter_map(|(key, value)| Some((key.clone(), value.as_str()?.to_string()))) + .collect(); + if raw.is_empty() { + return; + } + let storable = storable_headers(&raw); + if storable.is_empty() { + object.remove("headers"); + } else { + object.insert( + "headers".into(), + serde_json::to_value(storable).unwrap_or_default(), + ); + } +} /// Set or clear optional headers. An empty map clears them and drops leftover `userAgent`. pub(crate) fn config_with_headers(raw: &str, headers: &BTreeMap) -> Result { let mut config = ensure_config_object(raw)?; @@ -292,6 +312,11 @@ pub(crate) fn upsert_secret_meta( Ok(()) } +/// Read a provider's API key, folding fullwidth IME input the same way header +/// values are folded. The key is signed into `Authorization` (or `x-api-key`) +/// headers, where a fullwidth character can never be valid, so a key stored +/// before this rule existed still authenticates after an upgrade. Applied on +/// read as well as on write because only this accessor feeds outbound requests. pub fn get_secret_for_provider( db: &Database, secrets: &SecretStore, @@ -304,7 +329,7 @@ pub fn get_secret_for_provider( .optional()? .flatten(); if let Some(sref) = secret_ref { - secrets.get(&sref) + Ok(secrets.get(&sref)?.map(|value| fold_fullwidth(&value))) } else { Ok(None) } diff --git a/crates/host-core/src/providers/repository.rs b/crates/host-core/src/providers/repository.rs index b994106783..0b180c1636 100644 --- a/crates/host-core/src/providers/repository.rs +++ b/crates/host-core/src/providers/repository.rs @@ -424,7 +424,9 @@ pub(crate) fn delete_provider_row(db: &Database, secrets: &SecretStore, id: &str /// `api_key` reference and the row's `secret_ref` change; no field the plugin's /// manifest owns is touched, so the next load still refreshes the declaration. /// -/// An empty value deletes the stored key and clears `secret_ref`. +/// An empty value deletes the stored key and clears `secret_ref`. A fullwidth +/// value is folded to half-width, the same rule header values follow, because +/// the key is signed into an HTTP header. pub fn set_provider_secret( db: &Database, secrets: &SecretStore, @@ -435,12 +437,10 @@ pub fn set_provider_secret( return Ok(None); } let api_key_ref = secret_ref_for_provider(id); - match secret_value - .map(str::trim) - .filter(|value| !value.is_empty()) - { + let secret_value = secret_value.map(str::trim).map(fold_fullwidth); + match secret_value.filter(|value| !value.is_empty()) { Some(value) => { - let backend = secrets.set(&api_key_ref, value)?; + let backend = secrets.set(&api_key_ref, &value)?; upsert_secret_meta(db, &api_key_ref, id, &backend)?; db.conn() .prepare_cached( diff --git a/crates/host-core/src/providers/tests.rs b/crates/host-core/src/providers/tests.rs index 38b4ff4794..8d05ea680b 100644 --- a/crates/host-core/src/providers/tests.rs +++ b/crates/host-core/src/providers/tests.rs @@ -1364,3 +1364,244 @@ fn degraded_model_array_cannot_be_overwritten_by_update() { Some("old-secret") ); } + +#[test] +fn header_values_fold_fullwidth_and_reject_non_latin1() { + let (_dir, db, secrets) = test_context(); + let headers = BTreeMap::from([ + ("X-Title".to_string(), "PI\u{3000}Desktop".to_string()), + ("X-Key".to_string(), "1234567\u{FF10}".to_string()), + ]); + let provider = create_provider( + &db, + &secrets, + ProviderCreateInput { + name: "Custom".into(), + vendor_key: None, + provider_type: None, + protocol: None, + base_url: None, + auth_kind: Some("none".into()), + models: None, + default_model_id: Some("model-1".into()), + secret_value: None, + api_style: None, + oauth_account_label: None, + headers: Some(headers), + context_window: None, + max_output_tokens: None, + temperature: None, + supports_reasoning: None, + supported_thinking_levels: None, + }, + ) + .unwrap(); + let stored = provider.headers.unwrap(); + assert_eq!(stored["X-Title"], "PI Desktop"); + assert_eq!(stored["X-Key"], "12345670"); + + // A value with no ASCII counterpart is refused at the boundary and names + // the character undici would have thrown on. + let err = create_provider( + &db, + &secrets, + ProviderCreateInput { + name: "Star".into(), + vendor_key: None, + provider_type: None, + protocol: None, + base_url: None, + auth_kind: Some("none".into()), + models: None, + default_model_id: Some("model-1".into()), + secret_value: None, + api_style: None, + oauth_account_label: None, + headers: Some(BTreeMap::from([( + "X-Title".to_string(), + "abc\u{661F}".to_string(), + )])), + context_window: None, + max_output_tokens: None, + temperature: None, + supports_reasoning: None, + supported_thinking_levels: None, + }, + ) + .unwrap_err() + .to_string(); + assert!(err.contains("HEADERS_INVALID"), "{err}"); + assert!(err.contains("U+661F"), "{err}"); + assert!(err.contains("character index 3"), "{err}"); + + // A control character is the same class of failure — it never reaches a + // header either — so it is named too. + let err = normalize_one_header("X-Title", "ab\u{0}cd") + .unwrap_err() + .to_string(); + assert!(err.contains("U+0000 at character index 2"), "{err}"); + + // A character above U+00FF is the fault wherever it sits, and the reported + // index counts code units exactly as undici would: a surrogate pair can + // never sit before the first fault, because it is one. + let err = normalize_one_header("X-Title", "\u{1F44D}abc") + .unwrap_err() + .to_string(); + assert!(err.contains("character index 0"), "{err}"); + + // Trim matches what JavaScript trims, so the host accepts a value the + // editor showed as clean: a pasted byte-order mark is whitespace to both, + // and U+0085 is whitespace to neither (it travels as Latin-1). + assert_eq!( + normalize_one_header("X-Title", "\u{FEFF}pi-desktop\u{FEFF}").unwrap(), + Some(("X-Title".to_string(), "pi-desktop".to_string())) + ); + assert_eq!( + normalize_one_header("X-Title", "\u{85}abc").unwrap(), + Some(("X-Title".to_string(), "\u{85}abc".to_string())) + ); + + // A value that is only the ideographic space folds to nothing, and an + // unnamed row is still absent rather than a missing-name error. + assert_eq!(normalize_one_header("X-Title", "\u{3000}").unwrap(), None); + assert_eq!(normalize_one_header("", "\u{3000}").unwrap(), None); + assert_eq!( + normalize_one_header("X-Title", "\u{FF10}").unwrap(), + Some(("X-Title".to_string(), "0".to_string())) + ); + + // Folding shrinks bytes, so a fullwidth value that was over the bound + // (4096 bytes, `MAX_HEADER_VALUE_BYTES`) becomes storable — the one input + // class this change newly accepts. + let long_fullwidth = "\u{FF41}".repeat(4096); + assert!(normalize_one_header("X-Title", &long_fullwidth) + .unwrap() + .is_some()); + let long_ascii = "a".repeat(4097); + let err = normalize_one_header("X-Title", &long_ascii) + .unwrap_err() + .to_string(); + assert!(err.contains("header value is too long"), "{err}"); + + // A store written before the rule existed is sanitized on read: fullwidth + // folds, and the row that cannot travel is dropped rather than thrown. + db.conn() + .execute( + "UPDATE providers SET config_json = ?1 WHERE id = ?2", + params![ + json!({ "headers": { "x-legacy": "\u{FF11}\u{FF12}\u{FF13}", "x-cjk": "星" } }) + .to_string(), + provider.id + ], + ) + .unwrap(); + let read = get_provider(&db, &secrets, &provider.id).unwrap().unwrap(); + let read = read.headers.unwrap(); + assert_eq!(read["x-legacy"], "123"); + assert!(!read.contains_key("x-cjk")); +} + +#[test] +fn provider_api_keys_fold_fullwidth_on_write_and_read() { + let (_dir, db, secrets) = test_context(); + let provider = create_provider( + &db, + &secrets, + ProviderCreateInput { + name: "Custom".into(), + vendor_key: None, + provider_type: None, + protocol: None, + base_url: None, + auth_kind: Some("api_key".into()), + models: None, + default_model_id: Some("model-1".into()), + secret_value: Some("sk-\u{FF10}\u{FF11}".into()), + api_style: None, + oauth_account_label: None, + headers: None, + context_window: None, + max_output_tokens: None, + temperature: None, + supports_reasoning: None, + supported_thinking_levels: None, + }, + ) + .unwrap(); + + // create/update store what they were handed (config-sync and the renderer + // both rely on that), so the fold has to hold on the read accessor — which + // is the only path outbound requests take. + assert_eq!( + secrets + .get(&secret_ref_for_provider(&provider.id)) + .unwrap() + .as_deref(), + Some("sk-\u{FF10}\u{FF11}") + ); + assert_eq!( + get_secret_for_provider(&db, &secrets, &provider.id) + .unwrap() + .as_deref(), + Some("sk-01") + ); + + // The settings save path folds on write too. + set_provider_secret( + &db, + &secrets, + &provider.id, + Some("\u{FF53}\u{FF4B}-\u{FF11}"), + ) + .unwrap(); + assert_eq!( + get_secret_for_provider(&db, &secrets, &provider.id) + .unwrap() + .as_deref(), + Some("sk-1") + ); +} + +#[test] +fn sync_payloads_keep_only_storable_headers() { + // A peer on an older build, or a backup taken before the header rule was + // tightened, can hand us rows this build refuses. Dropping them at the sync + // boundary is what keeps one stale row from failing a whole revision, and + // it is the same set `config_headers` drops when a store is read. + let mut payload = json!({ + "name": "Custom", + "headers": { + "X-Title": "PI\u{3000}Desktop", + "X-Key": "1234567\u{FF10}", + "X-CJK": "星", + "Authorization": "Bearer secret" + } + }); + retain_storable_headers(&mut payload); + assert_eq!(payload["headers"]["X-Title"], "PI Desktop"); + assert_eq!(payload["headers"]["X-Key"], "12345670"); + assert!(payload["headers"].get("X-CJK").is_none()); + assert!(payload["headers"].get("Authorization").is_none()); + // The write path that aborted the revision can no longer refuse it. + let headers: BTreeMap = + serde_json::from_value(payload["headers"].clone()).unwrap(); + assert!(normalize_headers_input(&headers).is_ok()); + + // Every row unusable: the key goes away instead of storing an empty map. + let mut payload = json!({ "headers": { "X-CJK": "星" } }); + retain_storable_headers(&mut payload); + assert!(payload.get("headers").is_none()); + + // A payload without headers, and one that is not an object, are untouched. + let mut payload = json!({ "name": "Custom" }); + retain_storable_headers(&mut payload); + assert_eq!(payload, json!({ "name": "Custom" })); + let mut payload = json!("not an object"); + retain_storable_headers(&mut payload); + assert_eq!(payload, json!("not an object")); + + // A row dropped here is also invisible to the read path, so a local store + // holding it behaves the same before and after this runs. + let raw = BTreeMap::from([("x-cjk".to_string(), "星".to_string())]); + assert!(storable_headers(&raw).is_empty()); +} diff --git a/crates/host-core/src/providers/validation.rs b/crates/host-core/src/providers/validation.rs index 7ee621f9fa..13172497fa 100644 --- a/crates/host-core/src/providers/validation.rs +++ b/crates/host-core/src/providers/validation.rs @@ -32,9 +32,61 @@ pub(crate) fn valid_header_key(key: &str) -> bool { first.is_ascii_alphanumeric() && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') } +/// Fold the fullwidth block (U+FF01–U+FF5E) and the ideographic space (U+3000) +/// onto ASCII. This is what a Chinese/Japanese IME or a fullwidth-formatted +/// page produces for plain ASCII — `0` is U+FF10 — so folding it back is the +/// user's intent, not a rewrite of it. +/// +/// Deliberately not a full NFKC pass: NFKC would also turn halfwidth katakana +/// `ア` into U+30A2 and emit combining marks, replacing one unusable value with +/// another. Mirrors `foldFullwidthHeaderValue` in `@pi-desktop/shared`. +pub(crate) fn fold_fullwidth(value: &str) -> String { + value + .chars() + .map(|ch| { + let code = ch as u32; + if (0xFF01..=0xFF5E).contains(&code) { + char::from_u32(code - 0xFEE0).unwrap_or(ch) + } else if code == 0x3000 { + ' ' + } else { + ch + } + }) + .collect() +} + +/// First character an HTTP header value cannot carry, with the code-unit index +/// undici would name in `Cannot convert argument to a ByteString because the +/// character at index N ...`. HTTP header values are ByteStrings: HTAB, +/// printable ASCII, and the Latin-1 supplement travel; NUL, the other C0 +/// controls, DEL, and every code point above U+00FF do not. Mirrors +/// `HEADER_VALUE_ALLOWED` in `@pi-desktop/shared`. +/// +/// The first fault always sits below U+0100, and every character before it is +/// below U+0100 too, so a char index and a UTF-16 code-unit index agree here — +/// the two engines cannot report different positions. +pub(crate) fn header_value_fault(value: &str) -> Option<(usize, char)> { + value.chars().enumerate().find(|(_, ch)| { + let code = *ch as u32; + !(code == 0x09 || (0x20..=0x7E).contains(&code) || (0x80..=0xFF).contains(&code)) + }) +} + +/// Trim exactly what `String.prototype.trim` trims, because the renderer and +/// the runtime normalize values with it: `char::is_whitespace` is the Unicode +/// White_Space property, which includes U+0085 (NEL) that JavaScript keeps, and +/// excludes U+FEFF (a byte-order mark pasted from a file) that JavaScript +/// removes. Diverging here would let the host refuse a value the editor showed +/// as clean, or store a byte the runtime would have stripped. +fn is_header_trim(ch: char) -> bool { + ch != '\u{85}' && (ch.is_whitespace() || ch == '\u{FEFF}') +} + pub(crate) fn normalize_one_header(key: &str, value: &str) -> Result> { - let key = key.trim(); - let value = value.trim(); + let key = key.trim_matches(is_header_trim); + let value = fold_fullwidth(value.trim_matches(is_header_trim)); + let value = value.as_str(); if key.is_empty() { if value.is_empty() { return Ok(None); @@ -56,6 +108,17 @@ pub(crate) fn normalize_one_header(key: &str, value: &str) -> Result) -> BTreeMap { + let mut by_lower: BTreeMap = BTreeMap::new(); + for (key, value) in raw { + if let Ok(Some((normalized_key, normalized_value))) = normalize_one_header(key, value) { + by_lower.insert( + normalized_key.to_ascii_lowercase(), + (normalized_key, normalized_value), + ); + } + } + by_lower.into_values().take(MAX_HEADERS).collect() +} + pub(crate) fn normalize_thinking_levels(levels: &[String]) -> Vec { let mut out = Vec::new(); for level in levels { diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 3d77464470..3df0156d72 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -166,15 +166,14 @@ const zhNav: DefaultTheme.NavItem[] = [ export default defineConfig({ title: 'PI-Desktop', - description: 'Local-first AI coding agent documentation', - appearance: true, + description: 'A modular desktop workspace for AI agents', + // Product shell is dark-base; lock docs to the same charcoal system. + appearance: 'force-dark', cleanUrls: true, lastUpdated: true, head: [ - ['meta', { name: 'theme-color', content: '#f8fafc' }], - ['link', { rel: 'preconnect', href: 'https://fonts.googleapis.com' }], - ['link', { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }], - ['link', { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap' }], + ['meta', { name: 'theme-color', content: '#0d0d0d' }], + ['meta', { name: 'color-scheme', content: 'dark light' }], ], locales: { root: { label: 'English', lang: 'en' }, @@ -182,7 +181,7 @@ export default defineConfig({ label: '简体中文', lang: 'zh-CN', title: 'PI-Desktop 文档', - description: '本地优先的 AI 编程代理文档', + description: '面向 AI 智能体的模块化桌面工作区', themeConfig: { nav: zhNav, sidebar: zhSidebar, @@ -195,7 +194,7 @@ export default defineConfig({ darkModeSwitchLabel: '外观', langMenuLabel: '切换语言', editLink: { pattern: 'https://github.com/vastsa/PI-Desktop/edit/main/docs/:path', text: '在 GitHub 上编辑此页' }, - footer: { message: '为本地优先开发而构建。 AIUO.NET', copyright: 'Copyright © 2026 PI-Desktop 贡献者' }, + footer: { message: '本地优先 · 模型可替换 · 插件可扩展。 AIUO.NET', copyright: 'Copyright © 2026 PI-Desktop 贡献者' }, }, }, }, @@ -212,7 +211,7 @@ export default defineConfig({ editLink: { pattern: 'https://github.com/vastsa/PI-Desktop/edit/main/docs/:path', text: 'Edit this page on GitHub' }, outline: { level: 'deep', label: 'On this page' }, docFooter: { prev: 'Previous', next: 'Next' }, - footer: { message: 'Built for local-first development. AIUO.NET', copyright: 'Copyright © 2026 PI-Desktop contributors' }, + footer: { message: 'Local-first · Model-agnostic · Plugin-powered. AIUO.NET', copyright: 'Copyright © 2026 PI-Desktop contributors' }, nav: enNav, sidebar: enSidebar, }, diff --git a/docs/.vitepress/theme/Layout.vue b/docs/.vitepress/theme/Layout.vue index 73a39ca1c5..9bde201f4a 100644 --- a/docs/.vitepress/theme/Layout.vue +++ b/docs/.vitepress/theme/Layout.vue @@ -11,10 +11,13 @@ const { frontmatter, localeIndex } = useData() diff --git a/docs/.vitepress/theme/components/HomeHeroVisual.vue b/docs/.vitepress/theme/components/HomeHeroVisual.vue index db36a2df9c..f8a08eb81a 100644 --- a/docs/.vitepress/theme/components/HomeHeroVisual.vue +++ b/docs/.vitepress/theme/components/HomeHeroVisual.vue @@ -1,35 +1,18 @@ diff --git a/docs/.vitepress/theme/components/HomeModules.vue b/docs/.vitepress/theme/components/HomeModules.vue index 6d6b64280a..230e441003 100644 --- a/docs/.vitepress/theme/components/HomeModules.vue +++ b/docs/.vitepress/theme/components/HomeModules.vue @@ -1,175 +1,196 @@