Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(web): address a BYOK endpoint by base URL, path and endpoint
LeoXingf8a4473639b0
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex c74e45ef..58e00c47 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -30,8 +30,12 @@ build:assets` to check the initial JS budget.Local model; the page never holds a saved API key (reusing a saved key onlyfor the saved endpoint's origin, clearing entered keys after saving, offeringmanual model ID entry even when endpoints list models, and disabling BYOK- edits while offline), and a switch refused with `AGENT_HAS_ACTIVE_RUNS`- retries with `force_terminate` only after the owner confirms. The Local model+ edits while offline). BYOK addresses requests as base URL + path + endpoint+ and sends the format the address's ending names (else the Runtime's own);+ it lists models only on request and shows a Test result as a floating+ message, with the Computer's own message for endpoint refusals. A switch+ refused with `AGENT_HAS_ACTIVE_RUNS` retries with `force_terminate` only+ after the owner confirms. The Local modeltab is one Computer's model library as TeamHub last stored it. The Computerdecides fit, availability, placement, the recommendation and memory; the pageonly orders and labels them, picks the Make room default (includingdiff --git a/apps/web/src/features/local-models/byok-combobox.tsx b/apps/web/src/features/local-models/byok-combobox.tsxnew file mode 100644index 00000000..947782e7--- /dev/null+++ b/apps/web/src/features/local-models/byok-combobox.tsx@@ -0,0 +1,253 @@+import { ArrowDown01Icon } from "@hugeicons/core-free-icons";+import {+ type CSSProperties,+ type KeyboardEvent,+ type ReactNode,+ useEffect,+ useEffectEvent,+ useRef,+} from "react";++import {+ DropdownOption,+ DropdownOptions,+} from "@/components/ui/dropdown-options";+import { Icon } from "@/components/ui/icon";+import { cn } from "@/lib/cn";++export interface ByokComboboxOption {+ /** A second line under the value. */+ detail?: string;+ value: string;+}++/**+ * A field that takes any typed value and suggests some in a list, which+ * opens from its caret or the Down key. An empty value shows as "-".+ */+export function ByokCombobox({+ "aria-describedby": ariaDescribedBy,+ "aria-invalid": ariaInvalid,+ className,+ disabled,+ filled = false,+ heading,+ id,+ inputClassName,+ inputStyle,+ label,+ menuClassName = "-left-px",+ note,+ onCommit,+ onOpenChange,+ onValueChange,+ open,+ options,+ placeholder,+ value,+}: {+ "aria-describedby"?: string;+ "aria-invalid"?: boolean;+ className?: string;+ disabled: boolean;+ /** The value is a default Linger filled in, shown in grey. */+ filled?: boolean;+ heading?: string;+ id: string;+ inputClassName?: string;+ inputStyle?: CSSProperties;+ label: string;+ /** Which edge of the box the suggestions line up with; the left by default. */+ menuClassName?: string;+ /** A line above the suggestions, such as why there are none. */+ note?: ReactNode;+ /** Tidies the typed value once the owner leaves the field. */+ onCommit?: () => void;+ onOpenChange: (open: boolean) => void;+ onValueChange: (value: string) => void;+ open: boolean;+ options: readonly ByokComboboxOption[];+ placeholder: string;+ value: string;+}) {+ const rootRef = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const menuRef = useRef<HTMLDivElement>(null);+ const focusOptionOnOpen = useRef(false);+ const menuId = `${id}-menu`;+ const close = useEffectEvent(() => onOpenChange(false));++ useEffect(() => {+ if (!open) return undefined;+ if (focusOptionOnOpen.current) {+ focusOptionOnOpen.current = false;+ const menu = menuRef.current;+ (+ menu?.querySelector<HTMLElement>('[aria-selected="true"]') ??+ menu?.querySelector<HTMLElement>('[role="option"]')+ )?.focus();+ }+ const closeOutside = (event: PointerEvent) => {+ if (!rootRef.current?.contains(event.target as Node)) close();+ };+ document.addEventListener("pointerdown", closeOutside);+ return () => document.removeEventListener("pointerdown", closeOutside);+ }, [open]);++ function closeToInput() {+ onOpenChange(false);+ inputRef.current?.focus();+ }++ function choose(next: string) {+ onValueChange(next);+ closeToInput();+ }++ function handleInputKeyDown(event: KeyboardEvent<HTMLInputElement>) {+ if (event.key === "ArrowDown") {+ event.preventDefault();+ focusOptionOnOpen.current = true;+ if (open) {+ menuRef.current?.querySelector<HTMLElement>('[role="option"]')?.focus();+ focusOptionOnOpen.current = false;+ } else onOpenChange(true);+ } else if (event.key === "Enter") {+ // Enter settles the typed value rather than submitting the form.+ event.preventDefault();+ onCommit?.();+ onOpenChange(false);+ } else if (event.key === "Escape" && open) {+ event.preventDefault();+ event.stopPropagation();+ onOpenChange(false);+ }+ }++ function handleMenuKeyDown(event: KeyboardEvent<HTMLDivElement>) {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ closeToInput();+ return;+ }+ if (event.key === "Tab") {+ onOpenChange(false);+ return;+ }+ const step =+ event.key === "ArrowDown" ? 1 : event.key === "ArrowUp" ? -1 : 0;+ if (!step) return;+ event.preventDefault();+ const items = [+ ...(menuRef.current?.querySelectorAll<HTMLElement>('[role="option"]') ??+ []),+ ];+ const at = items.findIndex((item) => item === document.activeElement);+ items[(at + step + items.length) % items.length]?.focus();+ }++ return (+ <div+ className={cn(+ "ui-field-control relative flex items-center gap-1 py-0 pr-1 focus-within:border-[var(--app-field-focus)] focus-within:shadow-[0_0_0_2px_var(--app-ring)] has-[:disabled]:bg-[var(--app-field-disabled-surface)]",+ className,+ )}+ ref={rootRef}+ >+ <input+ aria-autocomplete="none"+ aria-controls={open ? menuId : undefined}+ aria-describedby={ariaDescribedBy}+ aria-expanded={open}+ aria-invalid={ariaInvalid || undefined}+ autoComplete="off"+ className={cn(+ "h-full min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-app-placeholder disabled:cursor-not-allowed",+ filled ? "text-muted-foreground" : "text-foreground",+ inputClassName,+ )}+ disabled={disabled}+ id={id}+ onBlur={() => onCommit?.()}+ onChange={(event) => {+ onValueChange(event.target.value);+ if (open) onOpenChange(false);+ }}+ onKeyDown={handleInputKeyDown}+ placeholder={placeholder}+ ref={inputRef}+ role="combobox"+ spellCheck={false}+ style={inputStyle}+ value={value}+ />+ <button+ aria-label={`Show ${label} suggestions`}+ className="grid size-6 shrink-0 place-items-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50"+ disabled={disabled}+ onClick={() => {+ onOpenChange(!open);+ inputRef.current?.focus();+ }}+ onMouseDown={(event) => event.preventDefault()}+ tabIndex={-1}+ type="button"+ >+ <Icon+ className={cn("transition-transform", open && "rotate-180")}+ icon={ArrowDown01Icon}+ size={14}+ />+ </button>+ {open ? (+ <DropdownOptions+ aria-label={`${label} suggestions`}+ className={cn(+ "absolute top-full z-30 mt-1 w-max min-w-[calc(100%+2px)] max-w-[min(22rem,86vw)]",+ menuClassName,+ )}+ id={menuId}+ onKeyDown={handleMenuKeyDown}+ onMouseDown={(event) => event.preventDefault()}+ ref={menuRef}+ role="listbox"+ >+ {heading ? (+ <p className="px-2 pb-1 pt-1.5 text-xs text-muted-foreground">+ {heading}+ </p>+ ) : null}+ {note ? (+ <p className="max-w-80 px-2 py-1.5 text-xs text-muted-foreground [overflow-wrap:anywhere]">+ {note}+ </p>+ ) : null}+ {options.map((option) => (+ <DropdownOption+ aria-label={+ option.detail+ ? `${option.value || "-"} ${option.detail}`+ : option.value || "-"+ }+ aria-selected={option.value === value}+ key={option.value}+ onClick={() => choose(option.value)}+ role="option"+ tabIndex={-1}+ >+ <span className="block truncate font-mono text-[13px]">+ {option.value || "-"}+ </span>+ {option.detail ? (+ <span className="block truncate text-xs text-muted-foreground">+ {option.detail}+ </span>+ ) : null}+ </DropdownOption>+ ))}+ </DropdownOptions>+ ) : null}+ </div>+ );+}diff --git a/apps/web/src/features/local-models/byok-endpoint.ts b/apps/web/src/features/local-models/byok-endpoint.tsnew file mode 100644index 00000000..2a8fef4e--- /dev/null+++ b/apps/web/src/features/local-models/byok-endpoint.ts@@ -0,0 +1,92 @@+import type { components } from "@linger/wire-contracts/teamhub-public/types";++type Schemas = components["schemas"];+type ByokProtocol = Schemas["ByokProtocol"];+type ModelSourceRuntime = Schemas["ModelSourceRuntime"];++/** Each Runtime's own wire format, which Bifrost forwards untranslated. */+const runtimeProtocols: Record<ModelSourceRuntime, ByokProtocol> = {+ claude: "anthropic",+ codex: "openai-responses",+ pi: "openai-chat",+};++const protocolEndpoints: Record<ByokProtocol, string> = {+ anthropic: "/messages",+ "openai-chat": "/chat/completions",+ "openai-responses": "/responses",+};++/** The path most providers serve their API under. */+export const DEFAULT_BYOK_PATH = "/v1";++/** Paths some providers document; any other path can be typed. */+export const byokPathSuggestions: readonly { label: string; value: string }[] =+ [+ { label: "Most providers", value: DEFAULT_BYOK_PATH },+ {+ label: "Zhipu GLM (base https://open.bigmodel.cn)",+ value: "/api/paas/v4",+ },+ { label: "Volcano Engine Ark", value: "/api/v3" },+ { label: "Gemini", value: "/v1beta/openai" },+ { label: "No path. The base URL already has it.", value: "" },+ ];++/** The three endpoints whose ending names a wire format, then none. */+export const byokEndpointSuggestions: readonly {+ protocol?: ByokProtocol;+ value: string;+}[] = [+ { protocol: "openai-chat", value: protocolEndpoints["openai-chat"] },+ {+ protocol: "openai-responses",+ value: protocolEndpoints["openai-responses"],+ },+ { protocol: "anthropic", value: protocolEndpoints.anthropic },+ { value: "" },+];++/** The endpoint a Runtime's requests go to unless the owner picks another. */+export function defaultByokEndpoint(runtime: ModelSourceRuntime) {+ return protocolEndpoints[runtimeProtocols[runtime]];+}++const URL_PATH = /^(?:\/[^/?#\s\\]+)*$/u;+const MAX_URL_PATH = 256;++/** A typed path as it is sent: trimmed, led by one slash, no trailing slash. */+export function normalizeByokPath(value: string) {+ const trimmed = value.trim().replace(/\/+$/u, "");+ return trimmed && !trimmed.startsWith("/") ? `/${trimmed}` : trimmed;+}++/** Whether a normalized path only appends whole segments to the base URL. */+export function validByokPath(path: string) {+ return path.length <= MAX_URL_PATH && URL_PATH.test(path);+}++/** A base URL as it is sent: trimmed, without a trailing slash. */+export function normalizeByokBaseUrl(value: string) {+ return value.trim().replace(/\/+$/u, "");+}++/**+ * The wire format of a request address: its ending names one, else the+ * Runtime's own format applies. Nothing is probed.+ */+export function byokProtocolFor(url: string, runtime: ModelSourceRuntime) {+ const named = (Object.keys(protocolEndpoints) as ByokProtocol[]).find(+ (protocol) => url.endsWith(protocolEndpoints[protocol]),+ );+ return named+ ? { fromUrl: true, protocol: named }+ : { fromUrl: false, protocol: runtimeProtocols[runtime] };+}++/** A context window as the BYOK form shows it. */+export function byokContextLabel(tokens: number) {+ return tokens < 1024+ ? `${tokens}-token context`+ : `${Math.round(tokens / 1024)}K context`;+}diff --git a/apps/web/src/features/local-models/byok-panel.tsx b/apps/web/src/features/local-models/byok-panel.tsxnew file mode 100644index 00000000..3ab7c4cf--- /dev/null+++ b/apps/web/src/features/local-models/byok-panel.tsx@@ -0,0 +1,581 @@+import {+ AlertCircleIcon,+ Cancel01Icon,+ CheckmarkCircle02Icon,+ RefreshIcon,+} from "@hugeicons/core-free-icons";+import { useMutation } from "@tanstack/react-query";+import {+ type CSSProperties,+ type FormEvent,+ type ReactNode,+ useEffect,+ useEffectEvent,+ useId,+ useRef,+ useState,+} from "react";++import { Button } from "@/components/ui/button";+import { fieldControlClassName } from "@/components/ui/field";+import { Icon } from "@/components/ui/icon";+import { Select, SelectItem } from "@/components/ui/select";+import { TeamHubError } from "@/features/teamhub/teamhub-error";+import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";+import { cn } from "@/lib/cn";++import { ByokCombobox } from "./byok-combobox";+import {+ byokContextLabel,+ byokEndpointSuggestions,+ byokPathSuggestions,+ byokProtocolFor,+ DEFAULT_BYOK_PATH,+ defaultByokEndpoint,+ normalizeByokBaseUrl,+ normalizeByokPath,+ validByokPath,+} from "./byok-endpoint";+import {+ byokFailureCopy,+ byokProtocolLabels,+ modelSourceRuntimeLabels,+} from "./local-models-copy";+import type { ModelSourceSwitcher } from "./model-source-panel";+import {+ type ByokEndpointInput,+ type ByokInput,+ type ByokTestRequest,+ listByokModels,+ type ModelSourceRuntime,+ type ModelSourceStatus,+ testByokEndpoint,+} from "./model-source-queries";++const byokRuntimes: readonly ModelSourceRuntime[] = ["claude", "codex", "pi"];++type ByokMenu = "endpoint" | "model" | "path";++function sameEndpointOrigin(savedUrl: string | undefined, nextUrl: string) {+ const trimmedSaved = savedUrl?.trim();+ const trimmedNext = nextUrl.trim();+ if (!trimmedSaved || !trimmedNext) return false;+ if (trimmedSaved === trimmedNext) return true;+ try {+ return new URL(trimmedSaved).origin === new URL(trimmedNext).origin;+ } catch {+ return false;+ }+}++/** A path or endpoint box sized to its value, at full width when stacked. */+function fittedWidth(value: string): CSSProperties {+ return {+ "--byok-fit": `${Math.max(value.length, 1) + 1}ch`,+ } as CSSProperties;+}++const failureCopy = (error: unknown) =>+ error instanceof TeamHubError+ ? byokFailureCopy(error.code, error.message)+ : byokFailureCopy(undefined, "");++/**+ * The person's own endpoint, addressed as base URL + path + endpoint. The API+ * key goes to the Computer, which keeps it private; Linger never shows it+ * again.+ */+export function ByokPanel({+ computerId,+ disabled,+ status,+ switcher,+ tenantId,+}: {+ computerId: string;+ disabled: boolean;+ status: ModelSourceStatus;+ switcher: ModelSourceSwitcher;+ tenantId: string;+}) {+ const { client } = useTeamHubRuntime();+ const saved = status.byok;+ const savedRuntime = status.mode === "byok" ? status.runtime : "claude";+ const [runtime, setRuntime] = useState<ModelSourceRuntime>(savedRuntime);+ const [baseUrl, setBaseUrl] = useState(saved.base_url ?? "");+ // A saved endpoint reports an empty path or endpoint by leaving it out.+ const [path, setPath] = useState(+ saved.configured ? (saved.path ?? "") : DEFAULT_BYOK_PATH,+ );+ // null follows the Runtime's default endpoint.+ const [endpoint, setEndpoint] = useState<string | null>(() => {+ const value = saved.configured ? (saved.endpoint ?? "") : null;+ return value === defaultByokEndpoint(savedRuntime) ? null : value;+ });+ const [apiKey, setApiKey] = useState("");+ const [modelId, setModelId] = useState(saved.model_id ?? "");+ const [menu, setMenu] = useState<ByokMenu | null>(null);+ const [toastShown, setToastShown] = useState(false);+ const ids = useId();++ const base = normalizeByokBaseUrl(baseUrl);+ const pathValue = normalizeByokPath(path);+ const runtimeEndpoint = defaultByokEndpoint(runtime);+ const endpointValue = normalizeByokPath(endpoint ?? runtimeEndpoint);+ const requestUrl = `${base}${pathValue}${endpointValue}`;+ const modelsUrl = `${base}${pathValue}/models`;+ const format = byokProtocolFor(requestUrl, runtime);+ const addressValid = validByokPath(pathValue) && validByokPath(endpointValue);+ // Never reuse a saved key when the owner points BYOK at a different host.+ const canReuseSavedKey =+ saved.key_saved &&+ (!saved.base_url || sameEndpointOrigin(saved.base_url, base));+ const address: ByokEndpointInput = {+ base_url: base,+ endpoint: endpointValue,+ path: pathValue,+ protocol: format.protocol,+ ...(apiKey+ ? { api_key: apiKey }+ : canReuseSavedKey+ ? { reuse_saved_key: true }+ : {}),+ };+ const input: ByokInput = { ...address, model_id: modelId.trim() };+ // The Computer decides whether the endpoint needs a key: one on this+ // computer or the local network may have none.+ const complete = base !== "" && input.model_id !== "" && addressValid;+ const active = status.mode === "byok";++ const models = useMutation({+ mutationFn: (body: ByokEndpointInput) =>+ listByokModels(client, tenantId, computerId, body),+ });+ const test = useMutation({+ mutationFn: (body: ByokTestRequest) =>+ testByokEndpoint(client, tenantId, computerId, body),+ });+ const listed = models.data?.models ?? [];+ const modelOptions = listed.map((model) => ({+ detail:+ [+ model.name,+ model.context_window+ ? byokContextLabel(model.context_window)+ : undefined,+ ]+ .filter(Boolean)+ .join(" · ") || undefined,+ value: model.id,+ }));+ const modelHint = models.isPending+ ? `Listing models from ${modelsUrl}…`+ : models.isError+ ? failureCopy(models.error)+ : models.data+ ? `${listed.length} ${listed.length === 1 ? "model" : "models"} listed from ${models.data.url}.`+ : "List the endpoint's models, or type an ID.";++ // Changing the address or key makes listed models and a test result stale;+ // changing only the endpoint, model or Runtime keeps the listed models.+ function resetTest() {+ test.reset();+ setToastShown(false);+ }+ function resetAll() {+ models.reset();+ resetTest();+ }++ function save(event: FormEvent) {+ event.preventDefault();+ switcher.request({ byok: input, mode: "byok", runtime });+ }++ const sendsHow = format.fromUrl+ ? byokProtocolLabels[format.protocol]+ : `${byokProtocolLabels[format.protocol]} (the ${modelSourceRuntimeLabels[runtime]} format)`;+ const addressHintId = `${ids}-address-hint`;+ const modelHintId = `${ids}-model-hint`;++ return (+ <form+ aria-label="BYOK"+ className="mt-6 rounded-xl border border-border"+ onSubmit={save}+ >+ <div className="grid grid-cols-1 gap-4 px-4 py-4">+ <div>+ <p className="mb-1.5 text-sm font-medium text-foreground">+ AI runtime+ </p>+ <Select+ aria-label="AI runtime"+ className="w-full"+ disabled={disabled}+ onValueChange={(value) => {+ setRuntime(value as ModelSourceRuntime);+ resetTest();+ }}+ value={runtime}+ >+ {byokRuntimes.map((item) => (+ <SelectItem key={item} value={item}>+ {modelSourceRuntimeLabels[item]}+ </SelectItem>+ ))}+ </Select>+ </div>+ <fieldset className="min-w-0">+ <legend className="mb-1.5 text-sm font-medium text-foreground">+ API address+ </legend>+ <div className="grid grid-cols-2 gap-x-1.5 gap-y-2 sm:grid-cols-[minmax(0,1fr)_auto_auto]">+ <div className="col-span-2 min-w-0 sm:col-span-1">+ <AddressLabel htmlFor={`${ids}-base`}>Base URL</AddressLabel>+ <input+ aria-describedby={addressHintId}+ autoComplete="off"+ className={fieldControlClassName}+ disabled={disabled}+ id={`${ids}-base`}+ onBlur={() => setBaseUrl(normalizeByokBaseUrl)}+ onChange={(event) => {+ setBaseUrl(event.target.value);+ resetAll();+ }}+ placeholder="https://api.example.com"+ inputMode="url"+ spellCheck={false}+ value={baseUrl}+ />+ </div>+ <div className="min-w-0">+ <AddressLabel htmlFor={`${ids}-path`}>Path</AddressLabel>+ <ByokCombobox+ aria-describedby={addressHintId}+ aria-invalid={!validByokPath(pathValue)}+ className="sm:w-max"+ disabled={disabled}+ filled={path === DEFAULT_BYOK_PATH}+ heading="Path · optional"+ menuClassName="-left-px sm:left-auto sm:-right-px"+ id={`${ids}-path`}+ inputClassName="font-mono text-[13px] sm:w-(--byok-fit) sm:flex-none"+ inputStyle={fittedWidth(path)}+ label="Path"+ onCommit={() => setPath(normalizeByokPath)}+ onOpenChange={(open) => setMenu(open ? "path" : null)}+ onValueChange={(value) => {+ setPath(value);+ resetAll();+ }}+ open={menu === "path"}+ options={byokPathSuggestions.map((option) => ({+ detail:+ option.value === DEFAULT_BYOK_PATH+ ? `${option.label} · Default`+ : option.label,+ value: option.value,+ }))}+ placeholder="-"+ value={path}+ />+ </div>+ <div className="min-w-0">+ <AddressLabel htmlFor={`${ids}-endpoint`}>Endpoint</AddressLabel>+ <ByokCombobox+ aria-describedby={addressHintId}+ aria-invalid={!validByokPath(endpointValue)}+ className="sm:w-max"+ disabled={disabled}+ filled={endpoint === null}+ heading="Endpoint · optional"+ menuClassName="-right-px"+ id={`${ids}-endpoint`}+ inputClassName="font-mono text-[13px] sm:w-(--byok-fit) sm:flex-none"+ inputStyle={fittedWidth(endpoint ?? runtimeEndpoint)}+ label="Endpoint"+ onCommit={() =>+ setEndpoint((current) => {+ if (current === null) return null;+ const value = normalizeByokPath(current);+ return value === runtimeEndpoint ? null : value;+ })+ }+ onOpenChange={(open) => setMenu(open ? "endpoint" : null)}+ onValueChange={(value) => {+ setEndpoint(value === runtimeEndpoint ? null : value);+ resetTest();+ }}+ open={menu === "endpoint"}+ options={byokEndpointSuggestions.map((option) => ({+ detail: option.protocol+ ? option.value === runtimeEndpoint+ ? `${byokProtocolLabels[option.protocol]} · ${modelSourceRuntimeLabels[runtime]} default`+ : byokProtocolLabels[option.protocol]+ : "No endpoint. The base URL is the full address.",+ value: option.value,+ }))}+ placeholder="-"+ value={endpoint ?? runtimeEndpoint}+ />+ </div>+ </div>+ <div+ className="mt-1.5 grid gap-0.5 text-xs text-muted-foreground"+ id={addressHintId}+ >+ <p>+ Base URL from your provider's docs. Path and endpoint are+ optional: pick one, type your own, or clear it.+ </p>+ {!addressValid ? (+ <p className="text-destructive">+ Path and endpoint take segments like /v1, without spaces, ?, #+ or \.+ </p>+ ) : base ? (+ <p>+ Sends {sendsHow} requests to <Url>{requestUrl}</Url>+ </p>+ ) : null}+ </div>+ </fieldset>+ <div>+ <label+ className="mb-1.5 block text-sm font-medium text-foreground"+ htmlFor={`${ids}-key`}+ >+ API key+ </label>+ <input+ aria-describedby={`${ids}-key-hint`}+ autoComplete="new-password"+ className={fieldControlClassName}+ disabled={disabled}+ id={`${ids}-key`}+ onChange={(event) => {+ setApiKey(event.target.value);+ resetAll();+ }}+ type="password"+ value={apiKey}+ />+ <p+ className="mt-1.5 text-xs text-muted-foreground"+ id={`${ids}-key-hint`}+ >+ {canReuseSavedKey+ ? "A key is saved on this computer. Leave blank to keep it."+ : "Optional for an endpoint on this computer or your local network."}+ </p>+ </div>+ <div>+ <label+ className="mb-1.5 block text-sm font-medium text-foreground"+ htmlFor={`${ids}-model`}+ >+ Model+ </label>+ <div className="relative flex gap-1.5">+ <ByokCombobox+ aria-describedby={modelHintId}+ className="min-w-0 flex-1"+ disabled={disabled}+ id={`${ids}-model`}+ label="Model"+ note={modelOptions.length ? undefined : modelHint}+ onCommit={() => setModelId((current) => current.trim())}+ onOpenChange={(open) => setMenu(open ? "model" : null)}+ onValueChange={(value) => {+ setModelId(value);+ resetTest();+ }}+ open={menu === "model"}+ options={modelOptions}+ placeholder="provider/model-name"+ value={modelId}+ />+ <Button+ aria-label="List models"+ disabled={disabled || base === "" || !addressValid}+ loading={models.isPending}+ onClick={() =>+ models.mutate(address, { onSuccess: () => setMenu("model") })+ }+ size="large"+ title="List models"+ >+ {models.isPending ? null : <Icon icon={RefreshIcon} size={16} />}+ </Button>+ <Button+ disabled={disabled || !complete}+ loading={test.isPending}+ onClick={() => {+ setToastShown(false);+ test.mutate(+ { byok: input },+ { onSettled: () => setToastShown(true) },+ );+ }}+ size="large"+ >+ Test+ </Button>+ {toastShown && test.isSuccess ? (+ <TestToast+ onDismiss={() => setToastShown(false)}+ title="Connected"+ tone="success"+ >+ {test.data.model_id} ·{" "}+ {byokContextLabel(test.data.context_window)} ·{" "}+ {byokProtocolLabels[test.data.protocol]}+ <br />+ <Url>{test.data.url}</Url>+ </TestToast>+ ) : null}+ {toastShown && test.isError ? (+ <TestToast+ onDismiss={() => setToastShown(false)}+ title="Couldn't connect"+ tone="danger"+ >+ {failureCopy(test.error)}+ </TestToast>+ ) : null}+ </div>+ <p+ className={cn(+ "mt-1.5 text-xs [overflow-wrap:anywhere]",+ models.isError ? "text-destructive" : "text-muted-foreground",+ )}+ id={modelHintId}+ >+ {modelHint}+ </p>+ </div>+ </div>+ <footer className="flex flex-wrap items-center justify-end gap-2 rounded-b-xl border-t border-border bg-muted/40 px-4 py-3">+ <Button+ disabled={disabled || !complete}+ loading={switcher.pending?.mode === "byok"}+ size="large"+ tone="primary"+ type="submit"+ >+ {active ? "Save" : "Save & Switch to BYOK"}+ </Button>+ </footer>+ </form>+ );+}++function AddressLabel({+ children,+ htmlFor,+}: {+ children: ReactNode;+ htmlFor: string;+}) {+ return (+ <label+ className="mb-1 block text-xs font-medium text-muted-foreground"+ htmlFor={htmlFor}+ >+ {children}+ </label>+ );+}++function Url({ children }: { children: string }) {+ return (+ <span className="font-mono text-[0.95em] [overflow-wrap:anywhere]">+ {children}+ </span>+ );+}++/**+ * A test result floating under the Test button. A success fades on its own+ * unless the pointer rests on it; a failure stays until dismissed, a click+ * elsewhere, or a changed input. A click on Test replaces it.+ */+function TestToast({+ children,+ onDismiss,+ title,+ tone,+}: {+ children: ReactNode;+ onDismiss: () => void;+ title: string;+ tone: "danger" | "success";+}) {+ const toastRef = useRef<HTMLDivElement>(null);+ const [leaving, setLeaving] = useState(false);+ const [hovered, setHovered] = useState(false);+ const [fadeAfter, setFadeAfter] = useState(3500);+ const dismiss = useEffectEvent(onDismiss);++ useEffect(() => {+ if (leaving) {+ const timer = setTimeout(dismiss, 200);+ return () => clearTimeout(timer);+ }+ if (tone !== "success" || hovered) return undefined;+ const timer = setTimeout(() => setLeaving(true), fadeAfter);+ return () => clearTimeout(timer);+ }, [fadeAfter, hovered, leaving, tone]);++ useEffect(() => {+ const leaveOnOutsideClick = (event: PointerEvent) => {+ if (!toastRef.current?.contains(event.target as Node)) setLeaving(true);+ };+ document.addEventListener("pointerdown", leaveOnOutsideClick);+ return () =>+ document.removeEventListener("pointerdown", leaveOnOutsideClick);+ }, []);++ return (+ <div+ className={cn(+ "absolute right-0 top-full z-40 mt-2 grid w-[min(22rem,100%)] grid-cols-[16px_minmax(0,1fr)_20px] items-start gap-2 rounded-lg bg-primary py-2.5 pl-3 pr-2 text-left text-xs text-primary-foreground/80 shadow-lg before:absolute before:-top-1 before:right-6 before:size-2.5 before:rotate-45 before:rounded-[2px] before:bg-primary before:content-[''] motion-reduce:animate-none",+ leaving+ ? "animate-[town-dropdown-out_200ms_ease_both]"+ : "animate-[town-dropdown-in_var(--app-floating-duration)_ease_both]",+ )}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => {+ setHovered(false);+ setFadeAfter(1500);+ }}+ ref={toastRef}+ role={tone === "success" ? "status" : "alert"}+ >+ <Icon+ className={cn(+ "mt-px",+ tone === "success" ? "text-app-success" : "text-destructive",+ )}+ icon={tone === "success" ? CheckmarkCircle02Icon : AlertCircleIcon}+ size={16}+ />+ <div className="min-w-0">+ <p className="text-[13px] font-medium text-primary-foreground">+ {title}+ </p>+ <p className="mt-0.5 [overflow-wrap:anywhere]">{children}</p>+ </div>+ <button+ aria-label="Dismiss"+ className="grid size-5 place-items-center rounded-sm text-primary-foreground/60 transition-colors hover:bg-primary-foreground/10 hover:text-primary-foreground"+ onClick={() => setLeaving(true)}+ type="button"+ >+ <Icon icon={Cancel01Icon} size={14} />+ </button>+ </div>+ );+}diff --git a/apps/web/src/features/local-models/local-models-copy.ts b/apps/web/src/features/local-models/local-models-copy.tsindex 0df39e44..29aac7f5 100644--- a/apps/web/src/features/local-models/local-models-copy.ts+++ b/apps/web/src/features/local-models/local-models-copy.ts@@ -240,7 +240,8 @@ const modelSourceRefusals: Record<Schemas["ModelSourceErrorCode"], string> = {BYOK_AUTH_FAILED: "The endpoint rejected the API key.",BYOK_INVALID_CONFIG:"The computer can't use this endpoint. An HTTPS endpoint needs an API key; plain HTTP works only on this computer or your local network.",- BYOK_MODEL_NOT_FOUND: "The endpoint doesn't serve this model ID.",+ BYOK_NOT_FOUND:+ "Nothing answered at the endpoint's address, or it doesn't serve this model ID.",BYOK_UNREACHABLE: "The computer couldn't reach the endpoint.",BYOK_UPSTREAM_REJECTED: "The endpoint rejected the test request.",LOCAL_COMPUTER_OFFLINE:@@ -267,6 +268,22 @@ export function modelSourceErrorCopy(code: string | undefined) {: "Something went wrong. Try again.";}+// For these the Computer's own message names the address it sent to and the+// endpoint's HTTP status, so it is shown as it is.+const byokEndpointRefusals = new Set([+ "BYOK_AUTH_FAILED",+ "BYOK_NOT_FOUND",+ "BYOK_UNREACHABLE",+ "BYOK_UPSTREAM_REJECTED",+]);++/** Why a request to a BYOK endpoint (a test or a model listing) failed. */+export function byokFailureCopy(code: string | undefined, message: string) {+ return code && byokEndpointRefusals.has(code) && message+ ? message+ : modelSourceErrorCopy(code);+}+/** Why reading a Computer's model source failed. */export function modelSourceReadErrorCopy(code: string | undefined) {if (code === "MODEL_SOURCE_SERVICE_UNAVAILABLE") {diff --git a/apps/web/src/features/local-models/local-models-page.test.tsx b/apps/web/src/features/local-models/local-models-page.test.tsxindex edf0eeb2..ccd88d0c 100644--- a/apps/web/src/features/local-models/local-models-page.test.tsx+++ b/apps/web/src/features/local-models/local-models-page.test.tsx@@ -1,5 +1,6 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import {+ act as reactAct,cleanup,fireEvent,render,@@ -9,7 +10,7 @@ import {} from "@testing-library/react";import { Suspense } from "react";import { MemoryRouter, Route, Routes, useLocation } from "react-router";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { TeamHubEventSync } from "@/features/rooms/event-sync";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";@@ -1914,16 +1915,24 @@ describe("Model source", () => {"/v0/tenants/{tenantId}/local-computers/{computerId}/model-source/models";const byokStatus = {byok: {- base_url: "https://api.example.com/v1",+ base_url: "https://api.example.com",configured: true,+ endpoint: "/chat/completions",key_saved: true,model_id: "vendor/model",+ path: "/v1",protocol: "openai-chat",},mode: "byok",runtime: "codex",runtime_model: "localmodels-byok",};+ const unconfigured = {+ byok: { configured: false, key_saved: false },+ mode: "subscription",+ runtime: "claude",+ runtime_model: "",+ };function withSource(fixture: Fixture, status: object) {const switches: unknown[] = [];@@ -1933,11 +1942,11 @@ describe("Model source", () => {.on("POST", modelsPath, ({ body }) => {listings.push(body);return Response.json({- base_url: "https://api.example.com",models: [{ context_window: 131_072, id: "vendor/model", name: "Vendor" },{ id: "vendor/other" },],+ url: "https://api.example.com/v1/models",});}).on("GET", switchPath, ({ params }) =>@@ -1950,12 +1959,15 @@ describe("Model source", () => {).on("POST", testPath, ({ body }) => {tests.push(body);+ const { byok } = body as {+ byok: { base_url: string; endpoint: string; path: string };+ };return Response.json({- base_url: "https://api.example.com",context_window: 131_072,model_id: "vendor/model",ok: true,protocol: "openai-chat",+ url: byok.base_url + byok.path + byok.endpoint,});});return { listings, switches, tests };@@ -1977,14 +1989,21 @@ describe("Model source", () => {expect(screen.getByText("Agents on lab-118 use BYOK · vendor/model"),).toBeInTheDocument();- expect(- screen.getByText("In use, through OpenAI Chat Completions."),- ).toBeInTheDocument();expect(screen.queryByText(/Stored privately/u)).not.toBeInTheDocument();expect(screen.queryByLabelText("API format")).not.toBeInTheDocument();expect(screen.getByLabelText("Base URL")).toHaveValue(- "https://api.example.com/v1",+ "https://api.example.com",+ );+ expect(screen.getByRole("combobox", { name: "Path" })).toHaveValue("/v1");+ expect(screen.getByRole("combobox", { name: "Endpoint" })).toHaveValue(+ "/chat/completions",);+ expect(+ screen.getByText(/^Sends OpenAI Chat Completions requests to/u),+ ).toHaveTextContent("https://api.example.com/v1/chat/completions");+ expect(+ screen.queryByRole("button", { name: "Test connection" }),+ ).not.toBeInTheDocument();});it("asks before ending running tasks and switches only once confirmed", async () => {@@ -2111,19 +2130,23 @@ describe("Model source", () => {await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));- expect(- await screen.findByRole("combobox", { name: "Model" }),- ).toHaveTextContent("vendor/model Vendor · 128K tokens");- fireEvent.click(screen.getByRole("button", { name: "Test connection" }));- expect(- await screen.findByText(- "Connected to https://api.example.com through OpenAI Chat Completions. vendor/model has 128K tokens of context.",- ),- ).toBeInTheDocument();- fireEvent.click(screen.getByRole("combobox", { name: "Model" }));+ expect(await screen.findByLabelText("Model")).toHaveValue("vendor/model");+ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ const connected = (await screen.findByText("Connected")).closest(+ '[role="status"]',+ );+ expect(connected).toHaveTextContent(+ "vendor/model · 128K context · OpenAI Chat Completions",+ );+ expect(connected).toHaveTextContent(+ "https://api.example.com/v1/chat/completions",+ );++ fireEvent.click(screen.getByRole("button", { name: "List models" }));fireEvent.click(await screen.findByRole("option", { name: "vendor/other" }),);+ expect(screen.getByLabelText("Model")).toHaveValue("vendor/other");fireEvent.change(screen.getByLabelText("API key"), {target: { value: "sk-new" },});@@ -2134,159 +2157,262 @@ describe("Model source", () => {await waitFor(() => expect(switches).toHaveLength(1));fireEvent.click(await screen.findByRole("tab", { name: "Local model" }));fireEvent.click(screen.getByRole("tab", { name: /BYOK/u }));- expect(- await screen.findByRole("combobox", { name: "Model" }),- ).toHaveTextContent("vendor/other");+ expect(await screen.findByLabelText("Model")).toHaveValue("vendor/other");+ const address = {+ base_url: "https://api.example.com",+ endpoint: "/chat/completions",+ path: "/v1",+ protocol: "openai-chat",+ };expect(tests).toEqual([{- byok: {- base_url: "https://api.example.com/v1",- model_id: "vendor/model",- reuse_saved_key: true,- },- runtime: "claude",+ byok: { ...address, model_id: "vendor/model", reuse_saved_key: true },},]);expect(switches).toEqual([{- byok: {- api_key: "sk-new",- base_url: "https://api.example.com/v1",- model_id: "vendor/other",- },+ byok: { ...address, api_key: "sk-new", model_id: "vendor/other" },mode: "byok",runtime: "claude",},]);});- it("lists the endpoint's models once its address and key are entered", async () => {+ it("sends requests to the base URL, path and endpoint as entered", async () => {const fixture = setup([labView()]);- const { listings, tests } = withSource(fixture, {- byok: { configured: false, key_saved: false },- mode: "subscription",- runtime: "claude",- runtime_model: "",- });+ const { listings, tests } = withSource(fixture, unconfigured);await renderPage(fixture);fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));+ const path = screen.getByRole("combobox", { name: "Path" });+ const endpoint = screen.getByRole("combobox", { name: "Endpoint" });+ expect(path).toHaveValue("/v1");+ expect(path).toHaveClass("text-muted-foreground");+ expect(endpoint).toHaveValue("/messages");+const baseUrl = screen.getByLabelText("Base URL");fireEvent.change(baseUrl, {- target: { value: "https://api.example.com/v1" },+ target: { value: " https://open.bigmodel.cn/ " },});- expect(listings).toEqual([]);fireEvent.blur(baseUrl);- const model = await screen.findByRole("combobox", { name: "Model" });- expect(model).toHaveTextContent("Choose a model");- fireEvent.click(model);+ expect(baseUrl).toHaveValue("https://open.bigmodel.cn");expect(- await screen.findByRole("option", {- name: "vendor/model Vendor · 128K tokens",- }),- ).toBeInTheDocument();- fireEvent.click(screen.getByRole("option", { name: "vendor/other" }));- expect(screen.getByRole("combobox", { name: "Model" })).toHaveTextContent(- "vendor/other",+ screen.getByText(/^Sends Anthropic Messages requests to/u),+ ).toHaveTextContent("https://open.bigmodel.cn/v1/messages");++ fireEvent.click(+ screen.getByRole("button", { name: "Show Path suggestions" }),);+ fireEvent.click(+ await screen.findByRole("option", { name: /^\/api\/paas\/v4 /u }),+ );+ expect(path).toHaveValue("/api/paas/v4");+ expect(path).toHaveClass("text-foreground");- const apiKey = screen.getByLabelText("API key");- fireEvent.change(apiKey, { target: { value: "sk-listed" } });- fireEvent.blur(apiKey);- await waitFor(() => expect(listings).toHaveLength(2));- expect(listings).toEqual([- { base_url: "https://api.example.com/v1" },- { api_key: "sk-listed", base_url: "https://api.example.com/v1" },- ]);- fireEvent.blur(apiKey);+ // An endpoint left at its default follows the Runtime.+ fireEvent.click(screen.getByRole("combobox", { name: "AI runtime" }));+ fireEvent.click(await screen.findByRole("option", { name: "Pi" }));+ expect(endpoint).toHaveValue("/chat/completions");+ expect(+ screen.getByText(/^Sends OpenAI Chat Completions requests to/u),+ ).toHaveTextContent(+ "https://open.bigmodel.cn/api/paas/v4/chat/completions",+ );++ // Without an endpoint the address names no format, so Pi's own applies.fireEvent.click(- await screen.findByRole("button", { name: "Test connection" }),+ screen.getByRole("button", { name: "Show Endpoint suggestions" }),);+ fireEvent.click(+ await screen.findByRole("option", {+ name: "- No endpoint. The base URL is the full address.",+ }),+ );+ expect(endpoint).toHaveValue("");+ expect(+ screen.getByText(+ /^Sends OpenAI Chat Completions \(the Pi format\) requests to/u,+ ),+ ).toHaveTextContent("https://open.bigmodel.cn/api/paas/v4");++ fireEvent.click(screen.getByRole("button", { name: "List models" }));+ await waitFor(() => expect(listings).toHaveLength(1));+ expect(listings[0]).toEqual({+ base_url: "https://open.bigmodel.cn",+ endpoint: "",+ path: "/api/paas/v4",+ protocol: "openai-chat",+ });++ fireEvent.change(screen.getByLabelText("Model"), {+ target: { value: " glm-5 " },+ });+ fireEvent.click(screen.getByRole("button", { name: "Test" }));await waitFor(() => expect(tests).toHaveLength(1));expect(tests[0]).toEqual({byok: {- api_key: "sk-listed",- base_url: "https://api.example.com/v1",- model_id: "vendor/other",+ base_url: "https://open.bigmodel.cn",+ endpoint: "",+ model_id: "glm-5",+ path: "/api/paas/v4",+ protocol: "openai-chat",},- runtime: "claude",});- expect(listings).toHaveLength(2);++ // A path carries only segments, never a query.+ fireEvent.change(path, { target: { value: "/v4?beta=1" } });+ expect(+ screen.getByText(/Path and endpoint take segments like \/v1/u),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Test" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "List models" })).toBeDisabled();});- it("lists the models again on request with the key as typed", async () => {+ it("lists the models only on request, with the key as typed", async () => {const fixture = setup([labView()]);const { listings } = withSource(fixture, byokStatus);await renderPage(fixture);- expect(await screen.findByText("2 models listed.")).toBeInTheDocument();+ expect(+ await screen.findByText("List the endpoint's models, or type an ID."),+ ).toBeInTheDocument();+ expect(listings).toEqual([]);+ fireEvent.click(screen.getByRole("button", { name: "List models" }));+ expect(+ await screen.findByText(+ "2 models listed from https://api.example.com/v1/models.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("option", {+ name: "vendor/model Vendor · 128K context",+ }),+ ).toBeInTheDocument();expect(listings).toEqual([- { base_url: "https://api.example.com/v1", reuse_saved_key: true },+ {+ base_url: "https://api.example.com",+ endpoint: "/chat/completions",+ path: "/v1",+ protocol: "openai-chat",+ reuse_saved_key: true,+ },]);+fireEvent.change(screen.getByLabelText("API key"), {target: { value: "sk-typed" },});+ expect(screen.queryByText(/models listed from/u)).not.toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "List models" }));-await waitFor(() => expect(listings).toHaveLength(2));- expect(listings[1]).toEqual({- api_key: "sk-typed",- base_url: "https://api.example.com/v1",- });- expect(screen.getByRole("combobox", { name: "Model" })).toHaveTextContent(- "vendor/model Vendor · 128K tokens",- );+ expect(listings[1]).toMatchObject({ api_key: "sk-typed" });+ expect(listings[1]).not.toHaveProperty("reuse_saved_key");});it("falls back to typing the model ID when the endpoint lists none", async () => {const fixture = setup([labView()]);withSource(fixture, byokStatus);fixture.runtime.server.on("POST", modelsPath, () =>- Response.json(- {- error: {- code: "BYOK_MODEL_NOT_FOUND",- message: "not found",- request_id: "test-models",- },- },- { status: 409 },+ teamHubErrorResponse(+ 409,+ "BYOK_NOT_FOUND",+ "https://api.example.com/v1/models returned HTTP 404: the address or the model was not found.",),);await renderPage(fixture);+ fireEvent.click(await screen.findByRole("button", { name: "List models" }));expect(await screen.findByText(- "The endpoint didn't list its models. Type the model ID.",+ "https://api.example.com/v1/models returned HTTP 404: the address or the model was not found.",),).toBeInTheDocument();expect(screen.getByLabelText("Model")).toHaveValue("vendor/model");});- it("tests an endpoint on this computer without an API key", async () => {+ it("keeps a failed test in view until dismissed and lets a success fade", async () => {const fixture = setup([labView()]);- const { tests } = withSource(fixture, {- byok: { configured: false, key_saved: false },- mode: "subscription",- runtime: "claude",- runtime_model: "",+ const { tests } = withSource(fixture, byokStatus);+ fixture.runtime.server.on("POST", testPath, ({ body }) => {+ tests.push(body);+ return tests.length === 1+ ? teamHubErrorResponse(+ 409,+ "BYOK_NOT_FOUND",+ "https://api.example.com/v1/chat/completions returned HTTP 404: the address or the model was not found.",+ )+ : teamHubErrorResponse(+ 409,+ "BYOK_AUTH_FAILED",+ "https://api.example.com/v1/chat/completions rejected the API key (HTTP 401).",+ );});await renderPage(fixture);+ // Only the toast's own timers run fake, between requests to the server.+ function afterFakeTime(act: () => void, ...steps: number[]) {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ act();+ for (const step of steps)+ reactAct(() => {+ vi.advanceTimersByTime(step);+ });+ } finally {+ vi.useRealTimers();+ }+ }++ fireEvent.click(await screen.findByRole("button", { name: "Test" }));+ const failed = await screen.findByRole("alert");+ expect(failed).toHaveTextContent("Couldn't connect");+ expect(failed).toHaveTextContent(+ "https://api.example.com/v1/chat/completions returned HTTP 404: the address or the model was not found.",+ );+ afterFakeTime(() => undefined, 10_000);+ expect(failed).toBeInTheDocument();+ afterFakeTime(+ () =>+ fireEvent.click(+ within(failed).getByRole("button", { name: "Dismiss" }),+ ),+ 200,+ );+ expect(screen.queryByText("Couldn't connect")).not.toBeInTheDocument();- fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));- fireEvent.change(screen.getByLabelText("Base URL"), {- target: { value: "http://127.0.0.1:18486/v1" },- });- fireEvent.change(screen.getByLabelText("Model"), {- target: { value: "vendor/model" },- });- fireEvent.click(screen.getByRole("button", { name: "Test connection" }));+ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "https://api.example.com/v1/chat/completions rejected the API key (HTTP 401).",+ );+ afterFakeTime(() => fireEvent.pointerDown(document.body), 200);+ expect(screen.queryByText("Couldn't connect")).not.toBeInTheDocument();- await waitFor(() => expect(tests).toHaveLength(1));- expect(tests[0]).toEqual({- byok: { base_url: "http://127.0.0.1:18486/v1", model_id: "vendor/model" },- runtime: "claude",+ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ expect(await screen.findByRole("alert")).toBeInTheDocument();+ // Editing the address withdraws the result it no longer describes.+ fireEvent.change(screen.getByRole("combobox", { name: "Path" }), {+ target: { value: "/v2" },});+ expect(screen.queryByText("Couldn't connect")).not.toBeInTheDocument();++ fixture.runtime.server.on("POST", testPath, () =>+ Response.json({+ context_window: 2048,+ model_id: "vendor/model",+ ok: true,+ protocol: "openai-chat",+ url: "https://api.example.com/v2/chat/completions",+ }),+ );+ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ const connected = (await screen.findByText("Connected")).closest(+ '[role="status"]',+ )!;+ expect(connected).toHaveTextContent("vendor/model · 2K context");+ // Resting the pointer on a success keeps it; leaving lets it fade.+ fireEvent.mouseEnter(connected);+ afterFakeTime(() => undefined, 10_000);+ expect(connected).toBeInTheDocument();+ afterFakeTime(() => fireEvent.mouseLeave(connected), 1_500, 200);+ expect(screen.queryByText("Connected")).not.toBeInTheDocument();});it("switches back to a model already on the computer", async () => {@@ -2769,9 +2895,6 @@ describe("Model source", () => {viewer_is_owner: true,}),);- fixture.runtime.server.on("POST", modelsPath, () =>- Response.json({ base_url: "https://api.example.com", models: [] }),- );await renderPage(fixture);await findModels();@@ -2794,7 +2917,7 @@ describe("Model source", () => {expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();});- it("resets stale BYOK test feedback, protects saved keys across origins, clears models on empty URL, and allows manual model IDs", async () => {+ it("resets stale BYOK test feedback, protects saved keys across origins, clears models on a new address, and takes typed model IDs", async () => {const fixture = setup([labView()]);const { listings, switches, tests } = withSource(fixture, byokStatus);fixture.runtime.server.on("POST", switchPath, ({ body }) => {@@ -2808,57 +2931,48 @@ describe("Model source", () => {});await renderPage(fixture);- expect(await screen.findByText("2 models listed.")).toBeInTheDocument();- const tabs = screen.getByRole("tablist", { name: "Model source" });+ const tabs = await screen.findByRole("tablist", { name: "Model source" });expect(tabs).toHaveClass("self-start");-- // Manual model ID toggle lets owners type custom IDs even when models were listed.- fireEvent.click(- screen.getByRole("button", { name: "Enter model ID manually" }),- );- const manualInput = screen.getByLabelText("Model");- expect(manualInput).toHaveValue("vendor/model");- fireEvent.change(manualInput, { target: { value: "custom/alias" } });-- fireEvent.click(screen.getByRole("button", { name: "Test connection" }));+ fireEvent.click(await screen.findByRole("button", { name: "List models" }));expect(- await screen.findByText(/Connected to https:\/\/api\.example\.com/u),+ await screen.findByText(+ "2 models listed from https://api.example.com/v1/models.",+ ),).toBeInTheDocument();- // Changing Base URL to a different origin resets test feedback and stops reusing the saved key.+ // Any model ID can be typed even when the endpoint listed models.+ const model = screen.getByLabelText("Model");+ fireEvent.change(model, { target: { value: "custom/alias" } });+ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ expect(await screen.findByText("Connected")).toBeInTheDocument();++ // Another origin withdraws the result, the listed models and the saved key.const baseUrl = screen.getByLabelText("Base URL");fireEvent.change(baseUrl, {- target: { value: "https://other.example.net/v1" },+ target: { value: "https://other.example.net" },});+ expect(screen.queryByText("Connected")).not.toBeInTheDocument();expect(- screen.queryByText(/Connected to https:\/\/api\.example\.com/u),- ).not.toBeInTheDocument();+ screen.getByText("List the endpoint's models, or type an ID."),+ ).toBeInTheDocument();expect(screen.queryByText(/A key is saved on this computer/u),).not.toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Test connection" }));+ fireEvent.click(screen.getByRole("button", { name: "Test" }));await waitFor(() => expect(tests).toHaveLength(2));expect(tests[1]).toEqual({byok: {- base_url: "https://other.example.net/v1",+ base_url: "https://other.example.net",+ endpoint: "/chat/completions",model_id: "custom/alias",+ path: "/v1",+ protocol: "openai-chat",},- runtime: "codex",});- // Clearing Base URL clears stale listed models instead of keeping previous endpoint choices.- fireEvent.change(baseUrl, { target: { value: "" } });- fireEvent.blur(baseUrl);- expect(screen.queryByText("2 models listed.")).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "Choose from list" }),- ).not.toBeInTheDocument();-// Saving while already on BYOK clears the typed API key input cleanly.- fireEvent.change(baseUrl, {- target: { value: "https://api.example.com/v1" },- });+ fireEvent.change(baseUrl, { target: { value: "https://api.example.com" } });fireEvent.change(screen.getByLabelText("API key"), {target: { value: "sk-rotate" },});@@ -2867,7 +2981,7 @@ describe("Model source", () => {await waitFor(() =>expect(screen.getByLabelText("API key")).toHaveValue(""),);- expect(listings.length).toBeGreaterThanOrEqual(1);+ expect(listings).toHaveLength(1);});it("refreshes Tenant Agents after Use for Agents and lets SwitchToLocalNotice prefer a newly loaded model", async () => {diff --git a/apps/web/src/features/local-models/local-models-page.tsx b/apps/web/src/features/local-models/local-models-page.tsxindex 966bcee7..b565f507 100644--- a/apps/web/src/features/local-models/local-models-page.tsx+++ b/apps/web/src/features/local-models/local-models-page.tsx@@ -77,9 +77,9 @@ import {type ModelEntry,type ModelStatus,} from "./local-models-rules";+import { ByokPanel } from "./byok-panel";import {activeSourceLabel,- ByokPanel,ModelSourceTabs,SwitchToLocalNotice,useModelSourceSwitch,diff --git a/apps/web/src/features/local-models/model-source-panel.tsx b/apps/web/src/features/local-models/model-source-panel.tsxindex fff18fa3..a7bbe9dd 100644--- a/apps/web/src/features/local-models/model-source-panel.tsx+++ b/apps/web/src/features/local-models/model-source-panel.tsx@@ -1,16 +1,8 @@-import { RefreshIcon } from "@hugeicons/core-free-icons";-import {- keepPreviousData,- useMutation,- useQuery,- useQueryClient,-} from "@tanstack/react-query";-import { type FormEvent, useId, useState } from "react";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useState } from "react";import { Button } from "@/components/ui/button";-import { Field, fieldControlClassName } from "@/components/ui/field";import { FormFeedback } from "@/components/ui/form-feedback";-import { Icon } from "@/components/ui/icon";import { ModalDialog } from "@/components/ui/modal-dialog";import { Select, SelectItem } from "@/components/ui/select";import { Hint } from "@/features/local-computer/computer-hint";@@ -24,7 +16,6 @@ import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";import { cn } from "@/lib/cn";import {- byokProtocolLabels,modelSourceErrorCopy,modelSourceModeLabels,modelSourceRuntimeLabels,@@ -33,27 +24,20 @@ import {type LocalModel,tenantLocalModelsQueryKey,} from "./local-models-queries";-import { contextLabel, formatGigabytes } from "./local-models-rules";+import { formatGigabytes } from "./local-models-rules";import {- type ByokInput,- type ByokModel,- type ByokTestRequest,- byokModelsQueryOptions,type ModelSourceMode,- type ModelSourceRuntime,type ModelSourceStatus,type ModelSourceSwitchRequest,type ModelSourceView,modelSourceQueryKey,switchModelSource,- testByokEndpoint,} from "./model-source-queries";// Subscription is not offered: switching to it moves every Agent on the// Computer to one Runtime without checking that Runtime is signed in, and// unloads local models.const modes: readonly ModelSourceMode[] = ["local", "byok"];-const byokRuntimes: readonly ModelSourceRuntime[] = ["claude", "codex", "pi"];const byokExplanation ="Bring your own key: use your own OpenAI-compatible or Anthropic API endpoint. A gateway on this computer serves it to your Agents.";@@ -67,7 +51,7 @@ export function activeSourceLabel(status: ModelSourceStatus) {return "Local model";}-interface ModelSourceSwitcher {+export interface ModelSourceSwitcher {clearFeedback: () => void;failure: string | undefined;pending: ModelSourceSwitchRequest | undefined;@@ -340,332 +324,3 @@ export function SwitchToLocalNotice({</div>);}--/** A listed model: its ID, then its name and context window when known. */-function ByokModelOption({ model }: { model: ByokModel }) {- const details = [- model.name,- model.context_window ? contextLabel(model.context_window) : undefined,- ].filter(Boolean);- return (- <>- {details.length ? `${model.id} ` : model.id}- {details.length ? (- <span className="ml-1 text-xs text-muted-foreground">- {details.join(" · ")}- </span>- ) : null}- </>- );-}--function sameEndpointOrigin(savedUrl: string | undefined, nextUrl: string) {- const trimmedSaved = savedUrl?.trim();- const trimmedNext = nextUrl.trim();- if (!trimmedSaved || !trimmedNext) return false;- if (trimmedSaved === trimmedNext) return true;- try {- return new URL(trimmedSaved).origin === new URL(trimmedNext).origin;- } catch {- return false;- }-}--/**- * The person's own endpoint. The API key goes to the Computer, which keeps- * it private; Linger never shows it again.- */-export function ByokPanel({- computerId,- disabled,- status,- switcher,- tenantId,-}: {- computerId: string;- disabled: boolean;- status: ModelSourceStatus;- switcher: ModelSourceSwitcher;- tenantId: string;-}) {- const { client } = useTeamHubRuntime();- const saved = status.byok;- const [runtime, setRuntime] = useState<ModelSourceRuntime>(- status.mode === "byok" ? status.runtime : "claude",- );- const [baseUrl, setBaseUrl] = useState(saved.base_url ?? "");- const [apiKey, setApiKey] = useState("");- // Starts empty until a model is saved, then shows the saved one.- const [modelId, setModelId] = useState(saved.model_id ?? "");- const [manualModelEntry, setManualModelEntry] = useState(false);- // Models are listed for the address and key as they stand when a field is- // left, not on every keystroke.- const [listed, setListed] = useState({- baseUrl: saved.base_url ?? "",- keyRevision: 0,- });- const [keyEdited, setKeyEdited] = useState(false);- const trimmedBaseUrl = baseUrl.trim();- // Never reuse a saved key when the owner points BYOK at a different host.- const canReuseSavedKey =- saved.key_saved &&- (!saved.base_url || sameEndpointOrigin(saved.base_url, trimmedBaseUrl));- const credentials = apiKey- ? { api_key: apiKey }- : canReuseSavedKey- ? { reuse_saved_key: true }- : {};- const listedCanReuseSavedKey =- saved.key_saved &&- (!saved.base_url || sameEndpointOrigin(saved.base_url, listed.baseUrl));- const listedCredentials = apiKey- ? { api_key: apiKey }- : listedCanReuseSavedKey- ? { reuse_saved_key: true }- : {};- const input: ByokInput = {- base_url: trimmedBaseUrl,- model_id: modelId.trim(),- ...credentials,- };- const models = useQuery({- ...byokModelsQueryOptions(- client,- tenantId,- computerId,- { base_url: listed.baseUrl, ...listedCredentials },- listed.keyRevision,- ),- // A refresh keeps the current choices on screen until the new list lands,- // but clearing the address clears stale options.- placeholderData: listed.baseUrl ? keepPreviousData : undefined,- });- const listedModels = listed.baseUrl ? (models.data?.models ?? []) : [];- // A saved or typed ID the endpoint does not list stays choosable.- const modelOptions =- input.model_id === "" ||- listedModels.some((model) => model.id === input.model_id)- ? listedModels- : [{ id: input.model_id }, ...listedModels];- const modelControlId = useId();- const modelHintId = `${modelControlId}-hint`;- const modelHint = models.isFetching- ? "Listing the endpoint's models…"- : models.isError- ? "The endpoint didn't list its models. Type the model ID."- : listedModels.length- ? `${listedModels.length} ${listedModels.length === 1 ? "model" : "models"} listed.`- : undefined;- const showModelSelect = listedModels.length > 0 && !manualModelEntry;- // The Computer decides whether the endpoint needs a key: one on this- // computer or the local network may have none.- const complete = input.base_url !== "" && input.model_id !== "";- const test = useMutation({- mutationFn: (body: ByokTestRequest) =>- testByokEndpoint(client, tenantId, computerId, body),- });- const active = status.mode === "byok";-- function save(event: FormEvent) {- event.preventDefault();- switcher.request({ byok: input, mode: "byok", runtime });- }-- function listModels() {- setKeyEdited(false);- setListed((current) => ({- baseUrl: input.base_url,- keyRevision: current.keyRevision + 1,- }));- }-- return (- <form- aria-label="BYOK"- className="mt-6 overflow-hidden rounded-xl border border-border"- onSubmit={save}- >- <div className="grid grid-cols-1 gap-4 px-4 py-4">- {active && saved.protocol ? (- <p className="text-xs text-muted-foreground">- In use, through {byokProtocolLabels[saved.protocol]}.- </p>- ) : null}- <div>- <p className="mb-1.5 text-sm font-medium text-foreground">- AI runtime- </p>- <Select- aria-label="AI runtime"- className="w-full"- disabled={disabled}- onValueChange={(value) => {- setRuntime(value as ModelSourceRuntime);- // The runtime decides which API format is tried first.- test.reset();- }}- value={runtime}- >- {byokRuntimes.map((item) => (- <SelectItem key={item} value={item}>- {modelSourceRuntimeLabels[item]}- </SelectItem>- ))}- </Select>- </div>- <Field- autoComplete="off"- disabled={disabled}- label="Base URL"- onBlur={() =>- setListed((current) =>- current.baseUrl === input.base_url- ? current- : { ...current, baseUrl: input.base_url },- )- }- onChange={(event) => {- setBaseUrl(event.target.value);- test.reset();- }}- placeholder="https://api.example.com/v1"- spellCheck={false}- value={baseUrl}- />- <Field- autoComplete="new-password"- disabled={disabled}- hint={- canReuseSavedKey- ? "A key is saved on this computer. Leave blank to keep it."- : "Optional for an endpoint on this computer or your local network."- }- label="API key"- onBlur={() => {- if (!keyEdited) return;- setKeyEdited(false);- setListed((current) => ({- ...current,- keyRevision: current.keyRevision + 1,- }));- }}- onChange={(event) => {- setApiKey(event.target.value);- setKeyEdited(true);- test.reset();- }}- type="password"- value={apiKey}- />- <div>- <label- className="mb-1.5 block text-sm font-medium text-foreground"- htmlFor={modelControlId}- >- Model- </label>- <div className="flex flex-wrap gap-2">- <div className="min-w-48 flex-1">- {showModelSelect ? (- <Select- aria-describedby={modelHint ? modelHintId : undefined}- aria-label="Model"- className="w-full"- disabled={disabled}- id={modelControlId}- onValueChange={(value) => {- setModelId(value);- test.reset();- }}- placeholder="Choose a model"- value={input.model_id}- >- {modelOptions.map((model) => (- <SelectItem key={model.id} value={model.id}>- <ByokModelOption model={model} />- </SelectItem>- ))}- </Select>- ) : (- <input- aria-describedby={modelHint ? modelHintId : undefined}- autoComplete="off"- className={fieldControlClassName}- disabled={disabled}- id={modelControlId}- onChange={(event) => {- setModelId(event.target.value);- test.reset();- }}- placeholder="provider/model-name"- spellCheck={false}- value={modelId}- />- )}- </div>- <Button- disabled={disabled || input.base_url === ""}- loading={models.isFetching}- onClick={listModels}- onMouseDown={(event) => event.preventDefault()}- size="large"- >- {models.isFetching ? null : <Icon icon={RefreshIcon} size={16} />}- List models- </Button>- </div>- {modelHint || listedModels.length > 0 ? (- <div className="mt-1.5 flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">- <p id={modelHintId}>{modelHint}</p>- {listedModels.length > 0 ? (- <button- className="text-foreground underline underline-offset-2 disabled:opacity-50"- disabled={disabled}- onClick={() => setManualModelEntry((current) => !current)}- type="button"- >- {manualModelEntry- ? "Choose from list"- : "Enter model ID manually"}- </button>- ) : null}- </div>- ) : null}- </div>- {test.isSuccess ? (- <FormFeedback tone="success">- Connected to {test.data.base_url} through{" "}- {byokProtocolLabels[test.data.protocol]}. {test.data.model_id} has{" "}- {contextLabel(test.data.context_window)} of context.- </FormFeedback>- ) : null}- {test.isError ? (- <FormFeedback tone="danger">- {modelSourceErrorCopy(- test.error instanceof TeamHubError ? test.error.code : undefined,- )}- </FormFeedback>- ) : null}- </div>- <footer className="flex flex-wrap items-center justify-end gap-2 border-t border-border bg-muted/40 px-4 py-3">- <Button- disabled={disabled || !complete}- loading={test.isPending}- onClick={() => test.mutate({ byok: input, runtime })}- size="large"- >- Test connection- </Button>- <Button- disabled={disabled || !complete}- loading={switcher.pending?.mode === "byok"}- size="large"- tone="primary"- type="submit"- >- {active ? "Save" : "Save & Switch to BYOK"}- </Button>- </footer>- </form>- );-}diff --git a/apps/web/src/features/local-models/model-source-queries.ts b/apps/web/src/features/local-models/model-source-queries.tsindex 95953bc9..23756634 100644--- a/apps/web/src/features/local-models/model-source-queries.ts+++ b/apps/web/src/features/local-models/model-source-queries.ts@@ -13,7 +13,6 @@ export type ModelSourceSwitchRequest = Schemas["ModelSourceSwitchRequest"];export type ByokInput = Schemas["ByokInput"];export type ByokTestRequest = Schemas["ByokTestRequest"];export type ByokEndpointInput = Schemas["ByokEndpointInput"];-export type ByokModel = Schemas["ByokModel"];const modelSourcePath ="/v0/tenants/{tenantId}/local-computers/{computerId}/model-source";@@ -64,10 +63,7 @@ export function switchModelSource();}-/**- * Probes a BYOK endpoint from the Computer without saving it, finding the- * wire format it answers for the Runtime.- */+/** Sends one request to a BYOK endpoint's address from the Computer, without saving it. */export function testByokEndpoint(client: TeamHubClient,tenantId: string,@@ -83,38 +79,19 @@ export function testByokEndpoint(}/**- * The models a BYOK endpoint lists, asked from the Computer. `keyRevision`- * stands in for the API key, which stays out of the query key; it changes- * whenever the owner enters a different key.+ * The models a BYOK endpoint lists at its base URL + path + /models, asked+ * from the Computer each time the owner asks for them.*/-export function byokModelsQueryOptions(+export function listByokModels(client: TeamHubClient,tenantId: string,computerId: string,- endpoint: ByokEndpointInput,- keyRevision: number,+ body: ByokEndpointInput,) {- return queryOptions({- enabled: endpoint.base_url !== "",- gcTime: 0,- queryFn: ({ signal }) =>- teamHubData(- client.api.POST(modelSourceModelsPath, {- body: endpoint,- params: { path: { computerId, tenantId } },- signal,- }),- ),- queryKey: [- "teamhub",- tenantId,- "byok-models",- computerId,- endpoint.base_url,- keyRevision,- ] as const,- refetchOnWindowFocus: false,- retry: false,- staleTime: Number.POSITIVE_INFINITY,- });+ return teamHubData(+ client.api.POST(modelSourceModelsPath, {+ body,+ params: { path: { computerId, tenantId } },+ }),+ );}