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(installer): address a BYOK endpoint by base URL, path and endpoint
LeoXing6438c8c87d3d
diff --git a/apps/linger-installer/src/server/server.ts b/apps/linger-installer/src/server/server.tsindex a8f97940..dd5e7c2f 100644--- a/apps/linger-installer/src/server/server.ts+++ b/apps/linger-installer/src/server/server.ts@@ -423,26 +423,37 @@ export async function startInstallerServer(options: ServerOptions) {) {const input = await body(req);const check = url.pathname === "/api/byok/check";- // Validate before the try, so a malformed body stays a plain 400.- const run = check- ? (() => {- const byok = validateByok(input);- return () =>- checkByokEndpoint(- options.home,- byok,- AbortSignal.timeout(45_000),- );- })()- : (() => {- const endpoint = validateByokEndpoint(input);- return () =>- listByokModels(- options.home,- endpoint,- AbortSignal.timeout(30_000),- );- })();+ let run: () => Promise<unknown>;+ try {+ if (check) {+ const byok = validateByok(input);+ run = () =>+ checkByokEndpoint(+ options.home,+ byok,+ AbortSignal.timeout(45_000),+ );+ } else {+ const endpoint = validateByokEndpoint(input);+ run = () =>+ listByokModels(+ options.home,+ endpoint,+ AbortSignal.timeout(30_000),+ );+ }+ } catch (invalid) {+ // The form shows why its address or key was refused.+ error(+ res,+ 400,+ "BYOK_INVALID_CONFIG",+ invalid instanceof Error+ ? invalid.message+ : "Invalid BYOK configuration.",+ );+ return;+ }try {json(res, 200, await run());} catch (failure) {diff --git a/apps/linger-installer/src/web/ByokPanel.tsx b/apps/linger-installer/src/web/ByokPanel.tsxnew file mode 100644index 00000000..64aaf390--- /dev/null+++ b/apps/linger-installer/src/web/ByokPanel.tsx@@ -0,0 +1,820 @@+import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type Dispatch,+ type KeyboardEvent,+ type ReactNode,+ type SetStateAction,+} from "react";+import type { components } from "@linger/wire-contracts/linger-installer/types";+import { request } from "./api.js";++type ByokProtocol = components["schemas"]["ByokProtocol"];+type ByokEndpoint = components["schemas"]["ByokEndpoint"];+type ByokCheckReport = components["schemas"]["ByokCheckReport"];+type ByokModelReport = components["schemas"]["ByokModelReport"];+type ByokRuntime = "claude" | "codex" | "pi";++/** What the person typed. A null endpoint follows the runtime's default. */+export interface ByokDraft {+ runtime: ByokRuntime;+ baseUrl: string;+ path: string;+ endpoint: string | null;+ apiKey: string;+ modelId: string;+}++const RUNTIME_LABELS: Record<ByokRuntime, string> = {+ claude: "Claude Code",+ codex: "Codex",+ pi: "Pi",+};+// Each runtime's own wire format, so the gateway forwards its requests untranslated.+const RUNTIME_PROTOCOL: Record<ByokRuntime, ByokProtocol> = {+ claude: "anthropic",+ codex: "openai-responses",+ pi: "openai-chat",+};+const FORMATS: Record<ByokProtocol, { ending: string; label: string }> = {+ "openai-chat": {+ ending: "/chat/completions",+ label: "OpenAI Chat Completions",+ },+ "openai-responses": { ending: "/responses", label: "OpenAI Responses" },+ anthropic: { ending: "/messages", label: "Anthropic Messages" },+};+const DEFAULT_PATH = "/v1";+const URL_PATH = /^(\/[^/?#\s\\]+)*$/;+const PATH_OPTIONS: ComboItem[] = [+ { value: DEFAULT_PATH, label: "Most providers", tag: "Default" },+ { value: "/api/paas/v4", label: "Zhipu GLM (base https://open.bigmodel.cn)" },+ { value: "/api/v3", label: "Volcano Engine Ark" },+ { value: "/v1beta/openai", label: "Gemini" },+ { value: "", label: "No path. The base URL already has it." },+];++export const emptyByokDraft: ByokDraft = {+ runtime: "claude",+ baseUrl: "",+ path: DEFAULT_PATH,+ endpoint: null,+ apiKey: "",+ modelId: "",+};++function normalizePath(value: string): string {+ const trimmed = value.trim().replace(/\/+$/, "");+ return trimmed && !trimmed.startsWith("/") ? `/${trimmed}` : trimmed;+}+function defaultEndpoint(runtime: ByokRuntime): string {+ return FORMATS[RUNTIME_PROTOCOL[runtime]].ending;+}+function requestUrl(endpoint: ByokEndpoint): string {+ return endpoint.baseUrl + endpoint.path + endpoint.endpoint;+}+function modelsUrl(endpoint: ByokEndpoint): string {+ return `${endpoint.baseUrl}${endpoint.path}/models`;+}+// The wire format follows the end of the address alone; any other ending uses the runtime's own.+function formatOf(draft: ByokDraft, url: string) {+ const fromUrl = (Object.keys(FORMATS) as ByokProtocol[]).find((protocol) =>+ url.endsWith(FORMATS[protocol].ending),+ );+ return {+ protocol: fromUrl ?? RUNTIME_PROTOCOL[draft.runtime],+ fromUrl: Boolean(fromUrl),+ };+}++/** The address and key the draft names, as the installer API takes them. */+export function byokEndpoint(draft: ByokDraft): ByokEndpoint {+ const baseUrl = draft.baseUrl.trim().replace(/\/+$/, "");+ const path = normalizePath(draft.path);+ const endpoint = normalizePath(+ draft.endpoint ?? defaultEndpoint(draft.runtime),+ );+ const apiKey = draft.apiKey.trim();+ return {+ baseUrl,+ path,+ endpoint,+ protocol: formatOf(draft, baseUrl + path + endpoint).protocol,+ ...(apiKey ? { apiKey } : {}),+ };+}++/** Why the draft's address cannot be sent, if it cannot. */+export function byokAddressProblem(+ draft: ByokDraft,+): { field: "base" | "path" | "endpoint"; message: string } | undefined {+ const endpoint = byokEndpoint(draft);+ if (!URL_PATH.test(endpoint.path) || endpoint.path.length > 256)+ return {+ field: "path",+ message: "Path must be empty or a path such as /v1.",+ };+ if (!URL_PATH.test(endpoint.endpoint) || endpoint.endpoint.length > 256)+ return {+ field: "endpoint",+ message: "Endpoint must be empty or a path such as /chat/completions.",+ };+ if (!/^https?:\/\/[^/]/i.test(endpoint.baseUrl))+ return {+ field: "base",+ message: "Enter a base URL that starts with https:// or http://.",+ };+}++function contextLabel(tokens: number): string {+ return tokens >= 1_048_576+ ? `${Math.round((tokens / 1_048_576) * 10) / 10}M`+ : `${Math.round(tokens / 1024)}k`;+}+function failure(error: unknown): string {+ return error instanceof Error+ ? error.message+ : "Could not reach the BYOK endpoint.";+}++type Listing =+ | { state: "loading" }+ | { state: "ok"; report: ByokModelReport }+ | { state: "failed"; message: string };+type Check =+ | { state: "checking" }+ | { state: "ok"; report: ByokCheckReport }+ | { state: "failed"; message: string };+type Menu = "path" | "endpoint" | "model";++export function ByokPanel({+ draft,+ onDraftChange,+}: {+ draft: ByokDraft;+ onDraftChange: Dispatch<SetStateAction<ByokDraft>>;+}) {+ const [listing, setListing] = useState<Listing>();+ const [check, setCheck] = useState<Check>();+ const [toast, setToast] = useState<{ leaving: boolean }>();+ const [menu, setMenu] = useState<Menu>();+ const [baseTouched, setBaseTouched] = useState(false);+ const checkRun = useRef(0);+ const listRun = useRef(0);+ const toastTimer = useRef<ReturnType<typeof setTimeout>>(undefined);++ const endpoint = byokEndpoint(draft);+ const url = requestUrl(endpoint);+ const format = formatOf(draft, url);+ const problem = byokAddressProblem(draft);+ const hasBase = endpoint.baseUrl !== "";+ const hasModel = draft.modelId.trim() !== "";++ const hideToast = useCallback(() => {+ clearTimeout(toastTimer.current);+ setToast((current) => (current ? { leaving: true } : current));+ toastTimer.current = setTimeout(() => setToast(undefined), 200);+ }, []);+ // A success fades on its own; a failure stays until dismissed or the input changes.+ const showToast = useCallback(+ (fades: boolean) => {+ clearTimeout(toastTimer.current);+ setToast({ leaving: false });+ if (fades) toastTimer.current = setTimeout(hideToast, 3500);+ },+ [hideToast],+ );+ useEffect(() => () => clearTimeout(toastTimer.current), []);+ useEffect(() => {+ if (!toast && !menu) return;+ const onPointerDown = (event: PointerEvent) => {+ const target = event.target instanceof Element ? event.target : null;+ if (toast && !target?.closest(".byok-toast, .byok-test")) hideToast();+ if (menu && !target?.closest(`[data-combo="${menu}"]`))+ setMenu(undefined);+ };+ document.addEventListener("pointerdown", onPointerDown);+ return () => document.removeEventListener("pointerdown", onPointerDown);+ }, [toast, menu, hideToast]);++ // A changed address or key makes an earlier listing stale; any change makes the test stale.+ function change(scope: "address" | "check", next: SetStateAction<ByokDraft>) {+ onDraftChange(next);+ checkRun.current += 1;+ setCheck(undefined);+ clearTimeout(toastTimer.current);+ setToast(undefined);+ if (scope === "address") {+ listRun.current += 1;+ setListing(undefined);+ }+ }++ async function runCheck() {+ const run = ++checkRun.current;+ if (problem) {+ setCheck({ state: "failed", message: problem.message });+ showToast(false);+ return;+ }+ setToast(undefined);+ setCheck({ state: "checking" });+ try {+ const report = await request<ByokCheckReport>("/byok/check", {+ ...endpoint,+ modelId: draft.modelId.trim(),+ });+ if (run !== checkRun.current) return;+ setCheck({ state: "ok", report });+ showToast(true);+ } catch (error) {+ if (run !== checkRun.current) return;+ setCheck({ state: "failed", message: failure(error) });+ showToast(false);+ }+ }+ async function listModels() {+ const run = ++listRun.current;+ setMenu(undefined);+ if (problem) {+ setListing({ state: "failed", message: problem.message });+ return;+ }+ setListing({ state: "loading" });+ try {+ const report = await request<ByokModelReport>("/byok/models", endpoint);+ if (run !== listRun.current) return;+ setListing({ state: "ok", report });+ setMenu("model");+ } catch (error) {+ if (run !== listRun.current) return;+ setListing({ state: "failed", message: failure(error) });+ }+ }++ const checking = check?.state === "checking";+ const listingNow = listing?.state === "loading";+ const runtimeDefault = defaultEndpoint(draft.runtime);+ const sends = (+ <>+ {"Sends "}+ {FORMATS[format.protocol].label}+ {format.fromUrl ? "" : ` (the ${RUNTIME_LABELS[draft.runtime]} format)`}+ {" requests to "}+ <span className="url">{url}</span>+ </>+ );+ // Path and endpoint problems show at once; a base URL problem waits until the box is left.+ const shownProblem =+ problem && (baseTouched || problem.field !== "base")+ ? problem.message+ : undefined;+ const status: { tone?: "err"; text: ReactNode } =+ listing?.state === "failed"+ ? { tone: "err", text: listing.message }+ : listingNow+ ? {+ text: (+ <>+ {"Listing models from "}+ <span className="url">{modelsUrl(endpoint)}</span>…+ </>+ ),+ }+ : hasBase && shownProblem+ ? { tone: "err", text: shownProblem }+ : hasBase+ ? { text: sends }+ : {+ text: "Grey values are defaults. Path and endpoint are optional.",+ };++ const models = listing?.state === "ok" ? listing.report.models : [];+ const modelNote: { tone?: "err"; text: ReactNode } =+ listing?.state === "ok"+ ? {+ text: (+ <>+ {models.length} {models.length === 1 ? "model" : "models"}+ {" from "}+ <span className="url">{listing.report.url}</span>+ </>+ ),+ }+ : listing?.state === "failed"+ ? { tone: "err", text: listing.message }+ : listingNow+ ? { text: "Listing models…" }+ : {+ text: "Use the refresh button to list the endpoint's models, or type an ID.",+ };++ return (+ <div className="byok-panel">+ <div className="byok-runtime">+ <span id="byok-runtime-label">{"AI runtime"}</span>+ <div+ className="byok-segments"+ role="radiogroup"+ aria-labelledby="byok-runtime-label"+ >+ {(Object.keys(RUNTIME_LABELS) as ByokRuntime[]).map((runtime) => (+ <label key={runtime}>+ <input+ type="radio"+ name="byok-runtime"+ value={runtime}+ checked={draft.runtime === runtime}+ onChange={() =>+ change("check", (current) => ({ ...current, runtime }))+ }+ />+ <span>{RUNTIME_LABELS[runtime]}</span>+ </label>+ ))}+ </div>+ </div>+ <div className="byok-address">+ <span className="byok-base">+ <input+ type="url"+ aria-label="Base URL"+ placeholder="Base URL (https://…)"+ autoComplete="off"+ spellCheck={false}+ maxLength={2048}+ value={draft.baseUrl}+ onChange={(event) => {+ const baseUrl = event.target.value;+ change("address", (current) => ({ ...current, baseUrl }));+ }}+ onBlur={() => {+ setBaseTouched(true);+ onDraftChange((current) => ({+ ...current,+ baseUrl: current.baseUrl.trim().replace(/\/+$/, ""),+ }));+ }}+ />+ </span>+ <Combobox+ kind="path"+ label="Path"+ fit+ heading="Path · optional"+ value={draft.path}+ isDefault={draft.path === DEFAULT_PATH}+ items={PATH_OPTIONS}+ open={menu === "path"}+ onOpenChange={(open) => setMenu(open ? "path" : undefined)}+ onInput={(path) =>+ change("address", (current) => ({ ...current, path }))+ }+ onCommit={() =>+ onDraftChange((current) => ({+ ...current,+ path: normalizePath(current.path),+ }))+ }+ />+ <Combobox+ kind="endpoint"+ label="Endpoint"+ fit+ heading="Endpoint · optional"+ value={draft.endpoint ?? runtimeDefault}+ isDefault={draft.endpoint === null}+ items={[+ ...Object.values(FORMATS).map(({ ending, label }) => ({+ value: ending,+ label,+ ...(ending === runtimeDefault+ ? { tag: `${RUNTIME_LABELS[draft.runtime]} default` }+ : {}),+ })),+ {+ value: "",+ label: "No endpoint. The base URL is the full address.",+ },+ ]}+ open={menu === "endpoint"}+ onOpenChange={(open) => setMenu(open ? "endpoint" : undefined)}+ onInput={(value) =>+ change("check", (current) => ({+ ...current,+ endpoint:+ value === defaultEndpoint(current.runtime) ? null : value,+ }))+ }+ onCommit={() =>+ onDraftChange((current) => {+ if (current.endpoint === null) return current;+ const value = normalizePath(current.endpoint);+ return {+ ...current,+ endpoint:+ value === defaultEndpoint(current.runtime) ? null : value,+ };+ })+ }+ />+ </div>+ <input+ className="byok-key"+ type="password"+ aria-label="API key"+ placeholder="API key (stored privately on this computer)"+ autoComplete="off"+ spellCheck={false}+ maxLength={4096}+ value={draft.apiKey}+ onChange={(event) => {+ const apiKey = event.target.value;+ change("address", (current) => ({ ...current, apiKey }));+ }}+ />+ <div className="byok-model-row">+ <Combobox+ kind="model"+ label="Model"+ placeholder="Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)"+ value={draft.modelId}+ items={models.map((model) => ({+ value: model.id,+ label: [+ model.name && model.name !== model.id ? model.name : "",+ model.contextWindow+ ? `${contextLabel(model.contextWindow)} context`+ : "",+ ]+ .filter(Boolean)+ .join(" · "),+ }))}+ note={modelNote}+ open={menu === "model"}+ onOpenChange={(open) => setMenu(open ? "model" : undefined)}+ onInput={(modelId) =>+ change("check", (current) => ({ ...current, modelId }))+ }+ onCommit={() =>+ onDraftChange((current) => ({+ ...current,+ modelId: current.modelId.trim(),+ }))+ }+ />+ <button+ type="button"+ className="byok-icon-button"+ aria-label={listingNow ? "Listing models" : "List models"}+ title="List models"+ data-busy={listingNow}+ disabled={!hasBase || listingNow}+ onClick={() => void listModels()}+ >+ <RefreshIcon />+ </button>+ <button+ type="button"+ className="byok-test"+ disabled={checking || !hasBase || !hasModel}+ onClick={() => void runCheck()}+ >+ {checking ? "Testing…" : "Test"}+ </button>+ <div className="byok-toast-region" role="status" aria-live="polite">+ {toast && check && check.state !== "checking" && (+ <TestToast+ check={check}+ leaving={toast.leaving}+ onDismiss={hideToast}+ onHold={(held) => {+ clearTimeout(toastTimer.current);+ // Hovering keeps a success on screen; leaving lets it fade.+ if (!held && check.state === "ok")+ toastTimer.current = setTimeout(hideToast, 1500);+ }}+ />+ )}+ </div>+ </div>+ <p className="byok-status" data-tone={status.tone}>+ {status.text}+ </p>+ </div>+ );+}++function TestToast({+ check,+ leaving,+ onDismiss,+ onHold,+}: {+ check: Exclude<Check, { state: "checking" }>;+ leaving: boolean;+ onDismiss: () => void;+ onHold: (held: boolean) => void;+}) {+ const ok = check.state === "ok";+ return (+ <div+ className="byok-toast"+ data-tone={ok ? "ok" : "err"}+ data-leaving={leaving}+ onMouseEnter={() => onHold(true)}+ onMouseLeave={() => onHold(false)}+ >+ <span className="byok-toast-icon">{ok ? <OkIcon /> : <ErrorIcon />}</span>+ <div>+ <strong>{ok ? "Connected" : "Couldn't connect"}</strong>+ {ok ? (+ <p>+ {check.report.modelId} · {contextLabel(check.report.contextWindow)}{" "}+ context · {FORMATS[check.report.protocol].label}+ <br />+ <span className="url">{check.report.url}</span>+ </p>+ ) : (+ <p>{check.message}</p>+ )}+ </div>+ <button+ type="button"+ className="byok-toast-close"+ aria-label="Dismiss"+ onClick={onDismiss}+ >+ <CloseIcon />+ </button>+ </div>+ );+}++interface ComboItem {+ value: string;+ label?: string;+ tag?: string;+}++/** Free text plus a list of suggestions; an empty value shows as "-". */+function Combobox({+ kind,+ label,+ heading,+ placeholder = "-",+ value,+ isDefault = false,+ fit = false,+ items,+ note,+ open,+ onOpenChange,+ onInput,+ onCommit,+}: {+ kind: Menu;+ label: string;+ heading?: string;+ placeholder?: string;+ value: string;+ isDefault?: boolean;+ /** Size the box to its value, for the short path and endpoint boxes. */+ fit?: boolean;+ items: ComboItem[];+ note?: { tone?: "err"; text: ReactNode };+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onInput: (value: string) => void;+ onCommit: () => void;+}) {+ const inputRef = useRef<HTMLInputElement>(null);+ const menuRef = useRef<HTMLDivElement>(null);+ const focusOption = useRef(false);+ const menuId = `byok-${kind}-menu`;+ useEffect(() => {+ if (!open || !focusOption.current) return;+ focusOption.current = false;+ const menu = menuRef.current;+ (+ menu?.querySelector<HTMLElement>('[aria-selected="true"]') ??+ menu?.querySelector<HTMLElement>("[role=option]")+ )?.focus();+ }, [open]);+ function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {+ if (event.key === "Escape" && open) {+ event.preventDefault();+ onOpenChange(false);+ inputRef.current?.focus();+ return;+ }+ if (event.target === inputRef.current) {+ if (event.key === "ArrowDown") {+ event.preventDefault();+ focusOption.current = true;+ onOpenChange(true);+ } else if (event.key === "Enter") {+ event.preventDefault();+ onCommit();+ onOpenChange(false);+ }+ return;+ }+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;+ event.preventDefault();+ const options = [+ ...(menuRef.current?.querySelectorAll<HTMLElement>("[role=option]") ??+ []),+ ];+ const at = options.indexOf(document.activeElement as HTMLElement);+ const step = event.key === "ArrowDown" ? 1 : -1;+ options[(at + step + options.length) % options.length]?.focus();+ }+ return (+ <div+ className={fit ? "byok-combo fit" : "byok-combo"}+ data-combo={kind}+ data-default={isDefault}+ data-open={open}+ onKeyDown={onKeyDown}+ >+ <input+ ref={inputRef}+ role="combobox"+ aria-label={label}+ aria-autocomplete="none"+ aria-expanded={open}+ aria-controls={menuId}+ autoComplete="off"+ spellCheck={false}+ maxLength={256}+ {...(fit ? { size: Math.max((value || placeholder).length, 2) } : {})}+ placeholder={placeholder}+ value={value}+ onChange={(event) => {+ onInput(event.target.value);+ onOpenChange(false);+ }}+ onBlur={onCommit}+ />+ <button+ type="button"+ className="byok-caret"+ tabIndex={-1}+ aria-label={`Show ${label} suggestions`}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => {+ onOpenChange(!open);+ inputRef.current?.focus();+ }}+ >+ <ChevronIcon />+ </button>+ {open && (+ <div+ ref={menuRef}+ id={menuId}+ className="byok-menu"+ role="listbox"+ aria-label={label}+ onMouseDown={(event) => event.preventDefault()}+ >+ {heading && <div className="byok-menu-head">{heading}</div>}+ {note && (+ <div className="byok-menu-note" data-tone={note.tone}>+ {note.text}+ </div>+ )}+ {items.map((item) => (+ <button+ type="button"+ role="option"+ key={item.value || "-"}+ aria-selected={item.value === value}+ onClick={() => {+ onInput(item.value);+ onOpenChange(false);+ inputRef.current?.focus();+ }}+ >+ <span className="byok-option-value">{item.value || "-"}</span>+ {(item.label || item.tag) && (+ <span className="byok-option-label">+ {item.label}+ {item.tag && <em>{item.tag}</em>}+ </span>+ )}+ <CheckIcon />+ </button>+ ))}+ </div>+ )}+ </div>+ );+}++function RefreshIcon() {+ return (+ <svg width="15" height="15" viewBox="0 0 16 16" aria-hidden="true">+ <path+ d="M13.2 6.4A5.3 5.3 0 0 0 3.4 4.6M2.8 9.6a5.3 5.3 0 0 0 9.8 1.8M3.2 2.2v2.6h2.6M12.8 13.8v-2.6h-2.6"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.4"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}+function ChevronIcon() {+ return (+ <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true">+ <path+ d="M2.5 3.8 5 6.3l2.5-2.5"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.4"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}+function CheckIcon() {+ return (+ <svg+ className="byok-option-check"+ width="14"+ height="14"+ viewBox="0 0 16 16"+ aria-hidden="true"+ >+ <path+ d="m3.5 8.5 3 3 6-7"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}+function OkIcon() {+ return (+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">+ <circle+ cx="8"+ cy="8"+ r="6.5"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.4"+ />+ <path+ d="m5.2 8.2 1.9 1.9 3.7-4"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}+function ErrorIcon() {+ return (+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">+ <circle+ cx="8"+ cy="8"+ r="6.5"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.4"+ />+ <path+ d="M8 4.6v4.2"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ />+ <circle cx="8" cy="11.2" r="0.9" fill="currentColor" />+ </svg>+ );+}+function CloseIcon() {+ return (+ <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true">+ <path+ d="m2 2 6 6M8 2 2 8"+ stroke="currentColor"+ strokeWidth="1.4"+ strokeLinecap="round"+ />+ </svg>+ );+}diff --git a/apps/linger-installer/src/web/SetupChoicePanel.test.tsx b/apps/linger-installer/src/web/SetupChoicePanel.test.tsxnew file mode 100644index 00000000..48294e24--- /dev/null+++ b/apps/linger-installer/src/web/SetupChoicePanel.test.tsx@@ -0,0 +1,229 @@+// @vitest-environment jsdom+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { byokEndpoint, emptyByokDraft } from "./ByokPanel.js";+import { SetupChoicePanel, type SetupReport } from "./SetupChoicePanel.js";+import { request } from "./api.js";+vi.mock("./api.js", () => ({ request: vi.fn() }));+afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.resetAllMocks();+});+const report = {+ choices: ["codex", "claude", "pi"],+ recommendation: "codex",+ runtimes: [],+ localModels: { estimate: { model: "" } },+} as unknown as SetupReport;+function renderByok() {+ const onInstall = vi.fn();+ render(+ <SetupChoicePanel+ report={report}+ choice="byok"+ onChange={() => {}}+ onInstall={onInstall}+ disabled={false}+ />,+ );+ return onInstall;+}+const status = () => document.querySelector(".byok-status")!;+const combobox = (name: string) =>+ screen.getByRole<HTMLInputElement>("combobox", { name });+function pick(box: string, option: RegExp) {+ fireEvent.click(+ screen.getByRole("button", { name: `Show ${box} suggestions` }),+ );+ fireEvent.click(screen.getByRole("option", { name: option }));+}++it("derives the wire format from the address ending, else the runtime", () => {+ const base = { ...emptyByokDraft, baseUrl: "https://ark.example.com/" };+ expect(byokEndpoint({ ...base, runtime: "codex" })).toEqual({+ baseUrl: "https://ark.example.com",+ path: "/v1",+ endpoint: "/responses",+ protocol: "openai-responses",+ });+ expect(+ byokEndpoint({+ ...base,+ baseUrl: "https://ark.example.com/api/v3/chat/completions",+ path: "",+ endpoint: "",+ runtime: "codex",+ }).protocol,+ ).toBe("openai-chat");+ expect(+ byokEndpoint({+ ...base,+ path: "v4/",+ endpoint: "/generate",+ apiKey: " k ",+ }),+ ).toEqual({+ baseUrl: "https://ark.example.com",+ path: "/v4",+ endpoint: "/generate",+ protocol: "anthropic",+ apiKey: "k",+ });+});++it("shows grey defaults that follow the runtime and says where requests go", () => {+ renderByok();+ expect(status().textContent).toBe(+ "Grey values are defaults. Path and endpoint are optional.",+ );+ fireEvent.change(screen.getByRole("textbox", { name: "Base URL" }), {+ target: { value: "http://192.168.1.20:8080" },+ });+ expect(combobox("Path").value).toBe("/v1");+ expect(combobox("Endpoint").value).toBe("/messages");+ expect(+ combobox("Endpoint")+ .closest("[data-default]")+ ?.getAttribute("data-default"),+ ).toBe("true");+ expect(status().textContent).toBe(+ "Sends Anthropic Messages requests to http://192.168.1.20:8080/v1/messages",+ );+ fireEvent.click(screen.getByRole("radio", { name: "Pi" }));+ expect(combobox("Endpoint").value).toBe("/chat/completions");+ pick("Endpoint", /^-No endpoint/);+ expect(combobox("Endpoint").value).toBe("");+ expect(status().textContent).toBe(+ "Sends OpenAI Chat Completions (the Pi format) requests to http://192.168.1.20:8080/v1",+ );+ fireEvent.change(combobox("Path"), { target: { value: "/v1?x" } });+ expect(status().textContent).toBe(+ "Path must be empty or a path such as /v1.",+ );+});++it("lists models, tests the one request address, and installs its parts", async () => {+ const onInstall = renderByok();+ vi.mocked(request).mockImplementation(async (path) =>+ path === "/byok/models"+ ? {+ url: "https://open.example.com/api/paas/v4/models",+ models: [{ id: "glm-5", name: "GLM 5", contextWindow: 131072 }],+ }+ : {+ ok: true,+ protocol: "openai-chat",+ url: "https://open.example.com/api/paas/v4/chat/completions",+ modelId: "glm-5",+ contextWindow: 131072,+ },+ );+ fireEvent.click(screen.getByRole("radio", { name: "Pi" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Base URL" }), {+ target: { value: "https://open.example.com/" },+ });+ fireEvent.blur(screen.getByRole("textbox", { name: "Base URL" }));+ fireEvent.change(combobox("Path"), { target: { value: "api/paas/v4/" } });+ fireEvent.blur(combobox("Path"));+ expect(combobox("Path").value).toBe("/api/paas/v4");+ fireEvent.change(screen.getByLabelText("API key"), {+ target: { value: "sk-test" },+ });+ fireEvent.click(screen.getByRole("button", { name: "List models" }));+ expect(request).toHaveBeenCalledWith("/byok/models", {+ baseUrl: "https://open.example.com",+ path: "/api/paas/v4",+ endpoint: "/chat/completions",+ protocol: "openai-chat",+ apiKey: "sk-test",+ });+ fireEvent.click(await screen.findByRole("option", { name: /^glm-5GLM 5/ }));+ expect(combobox("Model").value).toBe("glm-5");++ vi.useFakeTimers({ shouldAdvanceTime: true });+ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ expect(request).toHaveBeenLastCalledWith("/byok/check", {+ baseUrl: "https://open.example.com",+ path: "/api/paas/v4",+ endpoint: "/chat/completions",+ protocol: "openai-chat",+ apiKey: "sk-test",+ modelId: "glm-5",+ });+ expect(await screen.findByText("Connected")).toBeTruthy();+ expect(screen.getByRole("status").textContent).toContain(+ "glm-5 · 128k context · OpenAI Chat Completions",+ );+ act(() => void vi.advanceTimersByTime(3800));+ expect(screen.queryByText("Connected")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Install Linger" }));+ expect(onInstall).toHaveBeenCalledWith({+ baseUrl: "https://open.example.com",+ path: "/api/paas/v4",+ endpoint: "/chat/completions",+ protocol: "openai-chat",+ apiKey: "sk-test",+ modelId: "glm-5",+ runtime: "pi",+ });+ expect(screen.getByLabelText<HTMLInputElement>("API key").value).toBe("");+});++it("keeps a failed test on screen until the input changes", async () => {+ renderByok();+ vi.mocked(request).mockRejectedValue(+ new Error(+ "Nothing answered at https://api.example.com/v1/messages (HTTP 404).",+ ),+ );+ fireEvent.change(screen.getByRole("textbox", { name: "Base URL" }), {+ target: { value: "https://api.example.com" },+ });+ fireEvent.change(combobox("Model"), { target: { value: "m" } });+ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ expect(await screen.findByText("Couldn't connect")).toBeTruthy();+ expect(+ screen.getByText(+ "Nothing answered at https://api.example.com/v1/messages (HTTP 404).",+ ),+ ).toBeTruthy();+ fireEvent.pointerDown(screen.getByText("Couldn't connect"));+ expect(screen.getByText("Couldn't connect")).toBeTruthy();+ fireEvent.change(combobox("Model"), { target: { value: "m2" } });+ expect(screen.queryByText("Couldn't connect")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Test" }));+ expect(await screen.findByText("Couldn't connect")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ await waitFor(() =>+ expect(screen.queryByText("Couldn't connect")).toBeNull(),+ );+});++it("reports a listing failure in the status line and keeps the model box typeable", async () => {+ renderByok();+ vi.mocked(request).mockRejectedValue(+ new Error("https://api.example.com/v1/models answered HTTP 401."),+ );+ fireEvent.change(screen.getByRole("textbox", { name: "Base URL" }), {+ target: { value: "https://api.example.com" },+ });+ fireEvent.click(screen.getByRole("button", { name: "List models" }));+ await waitFor(() =>+ expect(status().textContent).toBe(+ "https://api.example.com/v1/models answered HTTP 401.",+ ),+ );+ expect(status().getAttribute("data-tone")).toBe("err");+ fireEvent.change(combobox("Model"), { target: { value: "typed-model" } });+ expect(combobox("Model").value).toBe("typed-model");+});diff --git a/apps/linger-installer/src/web/SetupChoicePanel.tsx b/apps/linger-installer/src/web/SetupChoicePanel.tsxindex c0fd50e4..009dadda 100644--- a/apps/linger-installer/src/web/SetupChoicePanel.tsx+++ b/apps/linger-installer/src/web/SetupChoicePanel.tsx@@ -1,15 +1,15 @@import { useState } from "react";import type { components } from "@linger/wire-contracts/linger-installer/types";-import { request } from "./api.js";+import {+ ByokPanel,+ byokAddressProblem,+ byokEndpoint,+ emptyByokDraft,+ type ByokDraft,+} from "./ByokPanel.js";export type SetupReport = components["schemas"]["SetupReport"];export type SetupChoice = components["schemas"]["SetupChoice"];export type ByokConfiguration = components["schemas"]["ByokConfiguration"];-type ByokCheckReport = components["schemas"]["ByokCheckReport"];-const byokProtocolLabels: Record<ByokCheckReport["protocol"], string> = {- anthropic: "Anthropic Messages",- "openai-chat": "OpenAI Chat Completions",- "openai-responses": "OpenAI Responses",-};export type PanelChoice = SetupChoice | "byok";export function bytes(value: number | null | undefined): string {if (value == null) return "—";@@ -35,13 +35,7 @@ export function SetupChoicePanel({disabled: boolean;blocker?: string;}) {- const [byokRuntime, setByokRuntime] =- useState<NonNullable<ByokConfiguration["runtime"]>>("claude");- const [baseUrl, setBaseUrl] = useState("");- const [apiKey, setApiKey] = useState("");- const [modelId, setModelId] = useState("");- const [checking, setChecking] = useState(false);- const [checkNote, setCheckNote] = useState("");+ const [byok, setByok] = useState<ByokDraft>(emptyByokDraft);const isByok = choice === "byok";const selected =choice === "local-models"@@ -56,30 +50,8 @@ export function SetupChoicePanel({: choice? { codex: "Codex", claude: "Claude Code", pi: "Pi" }[choice]: "";- const buildByok = (): ByokConfiguration => ({- baseUrl: baseUrl.trim(),- ...(apiKey.trim() ? { apiKey: apiKey.trim() } : {}),- modelId: modelId.trim(),- runtime: byokRuntime,- });- async function checkByok() {- if (!baseUrl.trim() || !modelId.trim()) return;- setChecking(true);- setCheckNote("Checking endpoint…");- try {- const report = await request<ByokCheckReport>("/byok/check", buildByok());- setCheckNote(- `Ready · ${report.modelId} (${Math.round(report.contextWindow / 1000)}k context) through ${byokProtocolLabels[report.protocol]}`,- );- } catch (error) {- setCheckNote(- error instanceof Error ? error.message : "BYOK endpoint check failed.",- );- } finally {- setChecking(false);- }- }- const byokIncomplete = isByok && (!baseUrl.trim() || !modelId.trim());+ const byokIncomplete =+ isByok && (!byok.modelId.trim() || Boolean(byokAddressProblem(byok)));return (<section className="setup-choice" aria-label={"Deployment plan"}><p className="recommended-plan">@@ -178,78 +150,19 @@ export function SetupChoicePanel({</span></label></div>+ {isByok && <ByokPanel draft={byok} onDraftChange={setByok} />}</div>- {isByok && (- <div className="byok-panel">- <label>- {"AI runtime"}- <select- value={byokRuntime}- onChange={(event) => {- setByokRuntime(- event.target.value as NonNullable<- ByokConfiguration["runtime"]- >,- );- // The runtime decides which API format is tried first.- setCheckNote("");- }}- >- <option value="claude">Claude Code</option>- <option value="codex">Codex</option>- <option value="pi">Pi</option>- </select>- </label>- <label>- {"Endpoint URL"}- <input- type="url"- value={baseUrl}- onChange={(event) => setBaseUrl(event.target.value)}- placeholder="https://api.example.com/v1"- maxLength={2048}- />- </label>- <label>- {"API key"}- <input- type="password"- autoComplete="off"- value={apiKey}- onChange={(event) => setApiKey(event.target.value)}- placeholder="Stored privately on this computer"- maxLength={4096}- />- </label>- <label>- {"Model ID"}- <input- value={modelId}- onChange={(event) => setModelId(event.target.value)}- placeholder="gpt-5.4 or claude-sonnet-4-6"- maxLength={256}- />- </label>- <div className="byok-check-row">- <button- type="button"- className="button compact"- disabled={checking || byokIncomplete}- onClick={() => void checkByok()}- >- {checking ? "Checking…" : "Check"}- </button>- {checkNote && <span role="status">{checkNote}</span>}- </div>- </div>- )}<buttonclassName="button primary deploy-action"disabled={disabled || byokIncomplete}onClick={() => {if (isByok) {- const payload = buildByok();- setApiKey("");+ const payload: ByokConfiguration = {+ ...byokEndpoint(byok),+ modelId: byok.modelId.trim(),+ runtime: byok.runtime,+ };+ setByok((current) => ({ ...current, apiKey: "" }));onInstall(payload);} else {onInstall();diff --git a/apps/linger-installer/src/web/styles.css b/apps/linger-installer/src/web/styles.cssindex c88cdebc..17191fc7 100644--- a/apps/linger-installer/src/web/styles.css+++ b/apps/linger-installer/src/web/styles.css@@ -420,6 +420,387 @@ main {border-color: #262626;background: #fafaf9;}++/* BYOK: base URL with optional path and endpoint, key, model, and a one-shot test. */+.byok-panel {+ --box-h: 30px;+ --box-border: #e2e2dc;+ --box-bg: #fafaf8;+ --filled: #9b9a90;+ --faint: #a3a39b;+ display: grid;+ gap: 7px;+ padding: 12px 14px;+ border: 1px solid var(--border);+ border-radius: 8px;+ font-size: 12px;+}+.byok-panel .url {+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ font-size: 0.95em;+ overflow-wrap: anywhere;+}+.byok-runtime {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ margin-bottom: 3px;+ color: var(--muted);+ font-weight: 500;+}+.byok-segments {+ display: flex;+ padding: 2px;+ border-radius: 9px;+ background: #f1f1ee;+}+.byok-segments label {+ position: relative;+ cursor: pointer;+}+.byok-segments input {+ position: absolute;+ opacity: 0;+ pointer-events: none;+}+.byok-segments span {+ display: block;+ padding: 4px 10px;+ border-radius: 7px;+ color: #6b6a60;+ font-weight: 500;+}+.byok-segments input:checked + span {+ background: #fff;+ color: #262626;+ box-shadow:+ 0 1px 2px rgba(20, 20, 16, 0.12),+ 0 0 0 0.5px rgba(20, 20, 16, 0.08);+}+.byok-segments input:focus-visible + span {+ outline: 2px solid var(--focus);+ outline-offset: 1px;+}+/* Path and endpoint menus open under the whole row, so they stay inside it at any width. */+.byok-address {+ position: relative;+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto auto;+ gap: 6px;+}+.byok-base,+.byok-combo,+.byok-key {+ height: var(--box-h);+ border: 1px solid var(--box-border);+ border-radius: 8px;+ background: var(--box-bg);+ color: #262626;+ transition:+ border-color 140ms ease,+ background-color 140ms ease;+}+.byok-base,+.byok-combo {+ display: flex;+ align-items: center;+ min-width: 0;+ padding: 0 4px 0 10px;+}+.byok-key {+ width: 100%;+ padding: 0 10px;+}+.byok-base:focus-within,+.byok-combo:focus-within,+.byok-key:focus {+ border-color: #262626;+ background: #fff;+}+.byok-base input,+.byok-combo input {+ flex: 1 1 auto;+ min-width: 0;+ height: 100%;+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;+ text-overflow: ellipsis;+}+.byok-base input:focus-visible,+.byok-combo input:focus-visible,+.byok-key:focus-visible {+ outline: none;+}+.byok-panel input::placeholder {+ color: var(--faint);+}+.byok-combo input::placeholder {+ font-style: italic;+}+/* The path and endpoint boxes size to their value, so the base URL keeps the room. */+.byok-combo.fit {+ max-width: 170px;+}+.byok-combo.fit input {+ field-sizing: content;+ min-width: 2ch;+}+.byok-combo[data-default="true"] input {+ color: var(--filled);+}+.byok-combo[data-default="true"] input:focus {+ color: #77766c;+}+.byok-caret {+ display: grid;+ flex: none;+ place-items: center;+ width: 20px;+ height: 20px;+ padding: 0;+ border: 0;+ border-radius: 5px;+ background: none;+ color: var(--faint);+}+.byok-caret:hover,+.byok-combo[data-open="true"] .byok-caret {+ background: rgba(20, 20, 16, 0.06);+ color: var(--muted);+}+.byok-menu {+ position: absolute;+ top: calc(100% + 5px);+ right: 0;+ z-index: 30;+ display: grid;+ gap: 1px;+ min-width: min(220px, 100%);+ width: max-content;+ max-width: min(320px, 100%);+ max-height: 252px;+ overflow-y: auto;+ padding: 4px;+ border: 1px solid rgba(20, 20, 16, 0.08);+ border-radius: 11px;+ background: #fff;+ box-shadow: 0 16px 36px -14px rgba(20, 20, 16, 0.35);+ line-height: 1.4;+ cursor: default;+ animation: byok-pop-in 160ms cubic-bezier(0.22, 1, 0.36, 1);+}+.byok-model-row .byok-menu {+ right: auto;+ left: -1px;+ min-width: calc(100% + 2px);+ max-width: min(320px, 86vw);+}+.byok-menu [role="option"] {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 16px;+ align-items: center;+ gap: 1px 10px;+ padding: 6px 8px;+ border: 0;+ border-radius: 7px;+ background: none;+ color: #262626;+ text-align: left;+}+.byok-menu [role="option"]:hover,+.byok-menu [role="option"]:focus-visible {+ outline: none;+ background: #f4f4f0;+}+.byok-option-value {+ font:+ 500 12px ui-monospace,+ SFMono-Regular,+ Menlo,+ Consolas,+ monospace;+ overflow-wrap: anywhere;+}+.byok-option-label {+ grid-column: 1;+ color: var(--muted);+ font-size: 11.5px;+}+.byok-option-label em {+ margin-left: 6px;+ color: #d9822b;+ font-style: normal;+ font-weight: 500;+}+.byok-option-check {+ grid-column: 2;+ grid-row: 1 / span 2;+ visibility: hidden;+}+[aria-selected="true"] > .byok-option-check {+ visibility: visible;+}+.byok-menu-head {+ padding: 5px 8px 3px;+ color: var(--faint);+ font-size: 11px;+ font-weight: 500;+}+.byok-menu-note {+ max-width: 300px;+ padding: 7px 8px;+ color: var(--muted);+ font-size: 11.5px;+}+.byok-menu-note[data-tone="err"] {+ color: #b5320a;+}+/* The model box, then the refresh and Test buttons; the test result floats under Test. */+.byok-model-row {+ position: relative;+ display: flex;+ gap: 6px;+}+.byok-model-row > .byok-combo {+ position: relative;+ flex: 1;+}+.byok-icon-button,+.byok-test {+ flex: none;+ height: var(--box-h);+ border: 1px solid #e6e6e1;+ border-radius: 8px;+ background: #fff;+ color: #262626;+ font-size: 12px;+ font-weight: 500;+}+.byok-icon-button {+ display: grid;+ place-items: center;+ width: var(--box-h);+ padding: 0;+ color: var(--muted);+}+.byok-test {+ padding: 0 12px;+}+.byok-icon-button:hover:not(:disabled),+.byok-test:hover:not(:disabled) {+ border-color: #c4c4bc;+ background: #fafaf8;+ color: #262626;+}+.byok-icon-button[data-busy="true"] svg {+ animation: byok-spin 0.9s linear infinite;+}+.byok-toast-region {+ position: absolute;+ top: calc(100% + 9px);+ right: 0;+ z-index: 40;+ width: min(330px, 100%);+}+.byok-toast {+ position: relative;+ display: grid;+ grid-template-columns: 16px minmax(0, 1fr) 20px;+ align-items: start;+ gap: 8px;+ padding: 10px 8px 10px 12px;+ border-radius: 10px;+ background: #1f1f1d;+ color: #c9c8bf;+ box-shadow: 0 14px 32px -10px rgba(20, 20, 16, 0.5);+ line-height: 1.45;+ text-align: left;+ animation: byok-pop-in 180ms cubic-bezier(0.22, 1, 0.36, 1);+}+.byok-toast::before {+ content: "";+ position: absolute;+ top: -4px;+ right: 22px;+ width: 9px;+ height: 9px;+ border-radius: 2px;+ background: inherit;+ transform: rotate(45deg);+}+.byok-toast[data-leaving="true"] {+ animation: byok-pop-out 200ms ease forwards;+}+.byok-toast strong {+ display: block;+ color: #fff;+ font-size: 12.5px;+ font-weight: 550;+}+.byok-toast p {+ margin-top: 2px;+ overflow-wrap: anywhere;+}+.byok-toast .url {+ color: #ecebe3;+}+.byok-toast-icon {+ display: grid;+ margin-top: 1px;+}+.byok-toast[data-tone="ok"] .byok-toast-icon {+ color: #74d08b;+}+.byok-toast[data-tone="err"] .byok-toast-icon {+ color: #ff9466;+}+.byok-toast-close {+ display: grid;+ place-items: center;+ width: 20px;+ height: 20px;+ padding: 0;+ border: 0;+ border-radius: 5px;+ background: none;+ color: #8f8e85;+}+.byok-toast-close:hover {+ background: rgba(255, 255, 255, 0.08);+ color: #fff;+}+.byok-status {+ color: var(--faint);+ font-size: 11.5px;+ line-height: 1.4;+}+.byok-status .url {+ color: var(--muted);+}+.byok-status[data-tone="err"],+.byok-status[data-tone="err"] .url {+ color: #b5320a;+}+@keyframes byok-pop-in {+ from {+ opacity: 0;+ transform: translateY(-3px);+ }+}+@keyframes byok-pop-out {+ to {+ opacity: 0;+ transform: translateY(-3px);+ }+}+@keyframes byok-spin {+ to {+ transform: rotate(360deg);+ }+}.runtime-sign-in {max-width: 400px;margin: 20px auto;@@ -489,6 +870,18 @@ main {margin-left: auto;}}+/* On a phone the base URL takes its own row above path and endpoint. */+@media (max-width: 400px) {+ .byok-address {+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);+ }+ .byok-base {+ grid-column: 1 / -1;+ }+ .byok-combo.fit {+ max-width: none;+ }+}@media (prefers-reduced-motion: reduce) {*,*::before,