Skip to content

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(desktop): address a BYOK endpoint by base URL, path and endpoint

LeoXing79ba1433a571
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index c054af6d..5cc78fa8 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -82,8 +82,15 @@ Gateway and runs Agents. The daemon exits with the app.
printed link and Claude Code's paste-code form sit behind "Having
trouble?"; Cancel stops the login (`DELETE /api/runtime-login`); the
dialog also offers installing another runtime instead (a new job with
- that `setupChoice`). No secret passes through the page. Then it saves the
- installed runtime's executable and profile paths
+ that `setupChoice`). No sign-in secret passes through the page. The
+ dialog also offers BYOK, with the same form as Customize's BYOK
+ (`byokFields` in `setup.html`): a base URL used verbatim, an optional path
+ (default `/v1`) and endpoint (default the runtime's own), key and model.
+ Its refresh button and Test run the installer headless
+ (`--list-byok-models`, `--check-byok`, the endpoint and key on stdin),
+ which lists `base + path + /models` and sends one request to
+ `base + path + endpoint` in the format the page derived from that address.
+ Then it saves the installed runtime's executable and profile paths
(`GET /api/instances/desktop/runtime`) as `runtimeEnvironment` in the
Desktop config, and the runtime its `setupChoice` runs (`local-models` runs
on Pi) as `preferredRuntime`. The daemon config carries that as
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index 5400d90d..ff55bd37 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -83,6 +83,9 @@ import {
import type {
SetupByokCheck,
SetupByokConfig,
+ SetupByokEndpoint,
+ SetupByokModels,
+ SetupByokProtocol,
SetupReason,
} from "../shared/setup.js";
@@ -288,6 +291,7 @@ export interface LocalServerStatus {
// While the "signin" step waits for the person.
readonly signIn?: RuntimeSignIn;
readonly byokCheck?: SetupByokCheck;
+ readonly byokModels?: SetupByokModels;
// Where this installation moved the data of the earlier Simplex app,
// which it could not upgrade.
readonly legacyBackup?: string;
@@ -446,6 +450,7 @@ export class LocalServerModule implements Module {
#daemonConnection: string | undefined;
#signIn: RuntimeSignIn | undefined;
#byokCheck: SetupByokCheck | undefined;
+ #byokModels: SetupByokModels | undefined;
#legacyBackup: string | undefined;
// The installer that runs the sign-in, and what the person asked for
// while the step waits.
@@ -628,6 +633,7 @@ export class LocalServerModule implements Module {
...(this.#origin ? { origin: this.#origin } : {}),
...(this.#signIn ? { signIn: this.#signIn } : {}),
...(this.#byokCheck ? { byokCheck: this.#byokCheck } : {}),
+ ...(this.#byokModels ? { byokModels: this.#byokModels } : {}),
...(this.#legacyBackup ? { legacyBackup: this.#legacyBackup } : {}),
};
}
@@ -734,16 +740,79 @@ export class LocalServerModule implements Module {
this.inspect();
}
+ // Tests the endpoint with one request from this computer. The page reads
+ // the outcome from byokCheck in the state its command returns, and tells
+ // a test in flight by itself.
async checkByok(byok: SetupByokConfig): Promise<void> {
- if (this.#byokCheck?.state === "checking") return;
- this.#byokCheck = { state: "checking" };
- this.#ctx?.bus.emit("local-server.changed");
+ const out = await this.#byokCommand("--check-byok", byok, 50_000);
+ this.#byokCheck =
+ out.ok === true &&
+ isByokProtocol(out.protocol) &&
+ typeof out.url === "string"
+ ? {
+ state: "ready",
+ protocol: out.protocol,
+ url: out.url,
+ modelId:
+ typeof out.modelId === "string" ? out.modelId : byok.modelId,
+ contextWindow:
+ typeof out.contextWindow === "number"
+ ? out.contextWindow
+ : 131_072,
+ }
+ : {
+ state: "failed",
+ message: byokFailure(out, "Could not test the BYOK endpoint."),
+ };
+ }
+
+ // Lists the models the endpoint serves at its base URL + path + /models,
+ // read back like a test from byokModels.
+ async listByokModels(endpoint: SetupByokEndpoint): Promise<void> {
+ const out = await this.#byokCommand("--list-byok-models", endpoint, 35_000);
+ this.#byokModels =
+ typeof out.url === "string" && Array.isArray(out.models)
+ ? {
+ state: "ready",
+ url: out.url,
+ models: (out.models as unknown[]).flatMap((row) => {
+ const { id, name, contextWindow } = (row ?? {}) as Record<
+ string,
+ unknown
+ >;
+ return typeof id === "string" && id
+ ? [
+ {
+ id,
+ ...(typeof name === "string" && name ? { name } : {}),
+ ...(typeof contextWindow === "number"
+ ? { contextWindow }
+ : {}),
+ },
+ ]
+ : [];
+ }),
+ }
+ : {
+ state: "failed",
+ message: byokFailure(out, "Could not list the endpoint's models."),
+ };
+ }
+
+ // Runs the installer's headless BYOK command: the endpoint and key go on
+ // stdin, never in argv, and its last stdout line is the JSON answer. A
+ // failure to run it comes back as { ok: false, message }.
+ async #byokCommand(
+ flag: "--check-byok" | "--list-byok-models",
+ input: SetupByokEndpoint,
+ timeoutMs: number,
+ ): Promise<Record<string, unknown>> {
const home = this.#location ?? this.#home;
try {
const output = await new Promise<string>((resolve, reject) => {
const child = spawn(
process.execPath,
- [this.#installerScript(), "--home", home, "--check-byok"],
+ [this.#installerScript(), "--home", home, flag],
{
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
@@ -752,7 +821,7 @@ export class LocalServerModule implements Module {
ELECTRON_RUN_AS_NODE: "1",
LINGER_HOME: home,
},
- signal: AbortSignal.timeout(45_000),
+ signal: AbortSignal.timeout(timeoutMs),
},
);
let last = "";
@@ -761,49 +830,18 @@ export class LocalServerModule implements Module {
});
child.once("error", reject);
child.once("close", () => resolve(last));
- child.stdin.end(JSON.stringify(byok));
+ child.stdin.end(JSON.stringify(input));
});
- const parsed = JSON.parse(output) as {
- ok?: unknown;
- protocol?: unknown;
- modelId?: unknown;
- contextWindow?: unknown;
- message?: unknown;
- };
- if (
- parsed.ok === true &&
- (parsed.protocol === "openai-chat" ||
- parsed.protocol === "openai-responses" ||
- parsed.protocol === "anthropic")
- ) {
- this.#byokCheck = {
- state: "ready",
- protocol: parsed.protocol,
- modelId: String(parsed.modelId ?? byok.modelId),
- contextWindow:
- typeof parsed.contextWindow === "number"
- ? parsed.contextWindow
- : 131_072,
- };
- } else {
- this.#byokCheck = {
- state: "failed",
- message:
- typeof parsed.message === "string" && parsed.message
- ? parsed.message
- : "Could not verify BYOK endpoint.",
- };
- }
+ const parsed: unknown = JSON.parse(output);
+ return parsed && typeof parsed === "object"
+ ? (parsed as Record<string, unknown>)
+ : {};
} catch (error) {
- this.#byokCheck = {
- state: "failed",
- message:
- error instanceof Error
- ? error.message
- : "Could not verify BYOK endpoint.",
+ return {
+ ok: false,
+ message: error instanceof Error ? error.message : String(error),
};
}
- this.#ctx?.bus.emit("local-server.changed");
}
async #inspect(
@@ -3355,6 +3393,16 @@ interface RuntimeLogin {
}
// The runtime an installation's setup choice runs; local models run on pi.
+const isByokProtocol = (value: unknown): value is SetupByokProtocol =>
+ value === "openai-chat" ||
+ value === "openai-responses" ||
+ value === "anthropic";
+
+// The installer's own words when it failed with { ok: false, message }:
+// localmodels names the address and HTTP status there.
+const byokFailure = (out: Record<string, unknown>, fallback: string): string =>
+ typeof out.message === "string" && out.message ? out.message : fallback;
+
const setupRuntime = (choice: string | undefined): LocalRuntime | undefined =>
choice === "local-models"
? "pi"
diff --git a/apps/desktop/src/main/setup-command.test.ts b/apps/desktop/src/main/setup-command.test.ts
index b863cd4a..7aa736fe 100644
--- a/apps/desktop/src/main/setup-command.test.ts
+++ b/apps/desktop/src/main/setup-command.test.ts
@@ -61,19 +61,45 @@ describe("parseSetupCommand", () => {
parseSetupCommand({
op: "local.byok.check",
byok: {
- baseUrl: " https://api.example.com/v1 ",
+ baseUrl: " https://api.example.com ",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
apiKey: "sk-test",
modelId: " gpt-5.4 ",
- runtime: "claude",
+ runtime: "codex",
},
}),
).toEqual({
op: "local.byok.check",
byok: {
- baseUrl: "https://api.example.com/v1",
+ baseUrl: "https://api.example.com",
+ path: "/v1",
+ endpoint: "/responses",
+ protocol: "openai-responses",
apiKey: "sk-test",
modelId: "gpt-5.4",
- runtime: "claude",
+ runtime: "codex",
+ },
+ });
+ // A pasted full address: no path or endpoint appended.
+ expect(
+ parseSetupCommand({
+ op: "local.byok.models",
+ byok: {
+ baseUrl: "https://ark.example.com/api/v3/chat/completions",
+ path: "",
+ endpoint: "",
+ protocol: "openai-chat",
+ },
+ }),
+ ).toEqual({
+ op: "local.byok.models",
+ byok: {
+ baseUrl: "https://ark.example.com/api/v3/chat/completions",
+ path: "",
+ endpoint: "",
+ protocol: "openai-chat",
},
});
expect(
@@ -81,6 +107,9 @@ describe("parseSetupCommand", () => {
op: "local.signin.byok",
byok: {
baseUrl: "https://api.anthropic.com",
+ path: "/v1",
+ endpoint: "/messages",
+ protocol: "anthropic",
modelId: "claude-sonnet-4-6",
runtime: "pi",
},
@@ -89,12 +118,45 @@ describe("parseSetupCommand", () => {
op: "local.signin.byok",
byok: {
baseUrl: "https://api.anthropic.com",
+ path: "/v1",
+ endpoint: "/messages",
+ protocol: "anthropic",
modelId: "claude-sonnet-4-6",
runtime: "pi",
},
});
});
+ it("takes only a path or endpoint that extends the base URL's path", () => {
+ const check = (fields: Record<string, unknown>) =>
+ parseSetupCommand({
+ op: "local.byok.models",
+ byok: {
+ baseUrl: "https://api.example.com",
+ path: "/v1",
+ endpoint: "/messages",
+ protocol: "anthropic",
+ ...fields,
+ },
+ });
+ for (const path of [
+ "v1",
+ "/v1/",
+ "//evil.example",
+ "/v1?x=1",
+ "/v1#x",
+ "/a b",
+ "/a\\b",
+ "/" + "x".repeat(256),
+ ]) {
+ expect(() => check({ path })).toThrow();
+ expect(() => check({ endpoint: path })).toThrow();
+ }
+ expect(() => check({ protocol: "gemini" })).toThrow();
+ expect(() => check({ modelId: "gpt-5.4" })).toThrow();
+ expect(() => check({ path: undefined })).toThrow();
+ });
+
it("takes provider keys with local.start, trimmed, and nothing else", () => {
expect(
parseSetupCommand({
diff --git a/apps/desktop/src/main/setup-command.ts b/apps/desktop/src/main/setup-command.ts
index 942fa16a..2e0a7825 100644
--- a/apps/desktop/src/main/setup-command.ts
+++ b/apps/desktop/src/main/setup-command.ts
@@ -9,10 +9,24 @@ const providerKey = z
.trim()
.regex(/^[A-Za-z0-9._~+/=:-]{0,512}$/, "Invalid key");
+// Empty, or whole segments each led by one slash, so a path or endpoint can
+// only extend the base URL's path.
+const byokUrlPath = z
+ .string()
+ .max(256)
+ .regex(/^(\/[^/?#\s\\]+)*$/, "Invalid path");
+
+const byokEndpointFields = {
+ baseUrl: z.string().trim().min(1).max(2048),
+ path: byokUrlPath,
+ endpoint: byokUrlPath,
+ protocol: z.enum(["openai-chat", "openai-responses", "anthropic"]),
+ apiKey: z.string().max(4096).optional(),
+};
+
const byokConfig = z
.object({
- baseUrl: z.string().trim().min(1).max(2048),
- apiKey: z.string().max(4096).optional(),
+ ...byokEndpointFields,
modelId: z
.string()
.trim()
@@ -46,6 +60,12 @@ const setupCommand = z.discriminatedUnion("op", [
byok: byokConfig,
})
.strict(),
+ z
+ .object({
+ op: z.literal("local.byok.models"),
+ byok: z.object(byokEndpointFields).strict(),
+ })
+ .strict(),
z.object({ op: z.literal("local.recheck") }).strict(),
z.object({ op: z.literal("local.location.pick") }).strict(),
z.object({ op: z.literal("local.location.reset") }).strict(),
diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.ts
index 6bad886a..d60b640a 100644
--- a/apps/desktop/src/main/setup-window.ts
+++ b/apps/desktop/src/main/setup-window.ts
@@ -243,6 +243,11 @@ export class SetupWindowModule implements Module {
case "local.byok.check":
await ctx.get<LocalServerModule>("LocalServer").checkByok(command.byok);
return;
+ case "local.byok.models":
+ await ctx
+ .get<LocalServerModule>("LocalServer")
+ .listByokModels(command.byok);
+ return;
case "local.recheck":
ctx.get<LocalServerModule>("LocalServer").recheck();
return;
@@ -456,6 +461,8 @@ const localServerState = (
location,
keys,
signIn,
+ byokCheck,
+ byokModels,
legacyBackup,
} = local.status();
const home = os.homedir();
@@ -479,6 +486,8 @@ const localServerState = (
},
keys,
...(signIn ? { signIn } : {}),
+ ...(byokCheck ? { byokCheck } : {}),
+ ...(byokModels ? { byokModels } : {}),
...(legacyBackup ? { legacyBackup: shown(legacyBackup) } : {}),
...(account ? { account } : {}),
};
diff --git a/apps/desktop/src/shared/setup.ts b/apps/desktop/src/shared/setup.ts
index 3ec2ccd4..c569b81c 100644
--- a/apps/desktop/src/shared/setup.ts
+++ b/apps/desktop/src/shared/setup.ts
@@ -49,8 +49,9 @@ export interface SetupLocalServer {
};
// While the "signin" step shows: the AI runtime's own sign-in.
readonly signIn?: SetupRuntimeSignIn;
- // Latest BYOK endpoint check requested from the setup page.
+ // The latest BYOK endpoint test and model listing asked for on the page.
readonly byokCheck?: SetupByokCheck;
+ readonly byokModels?: SetupByokModels;
// Once installed: the owner account, for signing in again after logging
// out.
readonly account?: SetupLocalAccount;
@@ -64,24 +65,50 @@ export type SetupByokProtocol =
| "openai-responses"
| "anthropic";
-export interface SetupByokConfig {
+// A BYOK endpoint's address and key: requests go to baseUrl + path +
+// endpoint in protocol, and models are listed at baseUrl + path + /models.
+// The page derives protocol from the end of that address, else from the
+// runtime's own format.
+export interface SetupByokEndpoint {
readonly baseUrl: string;
+ readonly path: string;
+ readonly endpoint: string;
+ readonly protocol: SetupByokProtocol;
readonly apiKey?: string;
+}
+
+export interface SetupByokConfig extends SetupByokEndpoint {
readonly modelId: string;
readonly runtime: "claude" | "codex" | "pi";
}
+// One request to the endpoint's address from this computer. message is
+// localmodels' own, naming the address and HTTP status.
export type SetupByokCheck =
- | { readonly state: "idle" | "checking" }
| {
readonly state: "ready";
- // The wire format the endpoint answered, found by the check.
readonly protocol: SetupByokProtocol;
+ readonly url: string;
readonly modelId: string;
readonly contextWindow: number;
}
| { readonly state: "failed"; readonly message: string };
+export interface SetupByokModel {
+ readonly id: string;
+ readonly name?: string;
+ readonly contextWindow?: number;
+}
+
+// The models the endpoint lists at url.
+export type SetupByokModels =
+ | {
+ readonly state: "ready";
+ readonly url: string;
+ readonly models: readonly SetupByokModel[];
+ }
+ | { readonly state: "failed"; readonly message: string };
+
// The owner account in the installation's local-account.json. The password
// is present only while the person chose to show it; error says why the
// file could not be read.
@@ -237,10 +264,15 @@ export type SetupCommand =
readonly byok?: SetupByokConfig;
readonly keys?: SetupProviderKeys;
}
+ // Tests the BYOK endpoint with one request, or lists its models.
| {
readonly op: "local.byok.check";
readonly byok: SetupByokConfig;
}
+ | {
+ readonly op: "local.byok.models";
+ readonly byok: SetupByokEndpoint;
+ }
// Checks this computer for a local model again.
| { readonly op: "local.recheck" }
// Picks the install folder with the system picker, or goes back to the
diff --git a/apps/desktop/src/shell/setup-page.test.ts b/apps/desktop/src/shell/setup-page.test.ts
index fa4b1e35..fc52f257 100644
--- a/apps/desktop/src/shell/setup-page.test.ts
+++ b/apps/desktop/src/shell/setup-page.test.ts
@@ -559,8 +559,31 @@ describe("setup page Quick Install recommendation", () => {
);
});
- it("configures BYOK across all runtimes with tooltip, Check, and secret scrubbing", async () => {
- const { run, push } = await openPage(welcome(small), "welcome");
+ // Types into a field as a person does.
+ const type = (id: string, value: string) => {
+ const input = $(id) as HTMLInputElement;
+ input.value = value;
+ input.dispatchEvent(new Event("input"));
+ };
+ const pick = (comboId: string, value: string) => {
+ (
+ $(comboId).parentElement!.querySelector(".cb-caret") as HTMLButtonElement
+ ).click();
+ $(`${comboId}-menu`)
+ .querySelector<HTMLButtonElement>(`[data-value="${value}"]`)!
+ .click();
+ };
+ const words = (id: string) => $(id).textContent!.replace(/\s+/g, " ").trim();
+ const withLocal = (
+ base: SetupState,
+ localServer: Partial<SetupState["localServer"]>,
+ ): SetupState => ({
+ ...base,
+ localServer: { ...base.localServer, ...localServer },
+ });
+
+ it("builds the request address from base URL, path and endpoint, with tooltip, refresh, Test and secret scrubbing", async () => {
+ const { run } = await openPage(welcome(small), "welcome");
$("local-customize").click();
const byokSource = document.querySelector<HTMLButtonElement>(
'[data-plan="source"] [data-value="byok"]',
@@ -572,73 +595,154 @@ describe("setup page Quick Install recommendation", () => {
expect($("local-row").hidden).toBe(true);
expect($("subscription-row").hidden).toBe(true);
expect(($("local-install") as HTMLButtonElement).disabled).toBe(true);
+ // Grey defaults: /v1, and the runtime's own endpoint.
+ const path = $("byok-path") as HTMLInputElement;
+ const endpoint = $("byok-endpoint") as HTMLInputElement;
+ expect(path.value).toBe("/v1");
+ expect(endpoint.value).toBe("/messages");
+ expect(path.parentElement!.dataset.default).toBe("true");
+ expect(endpoint.parentElement!.dataset.default).toBe("true");
+ expect($("byok-status").textContent).toBe(
+ "Grey values are defaults. Path and endpoint are optional.",
+ );
document
.querySelector<HTMLButtonElement>(
'[data-byok="runtime"] [data-value="codex"]',
)!
.click();
- const urlInput = $("byok-url") as HTMLInputElement;
- const keyInput = $("byok-key") as HTMLInputElement;
- const modelInput = $("byok-model") as HTMLInputElement;
- urlInput.value = "https://api.example.com/v1";
- urlInput.dispatchEvent(new Event("input"));
- keyInput.value = "sk-top-secret";
- keyInput.dispatchEvent(new Event("input"));
- modelInput.value = "gpt-5.4";
- modelInput.dispatchEvent(new Event("input"));
-
- expect(($("local-install") as HTMLButtonElement).disabled).toBe(false);
- expect($("plan-summary").textContent).toBe("BYOK · Codex · gpt-5.4");
+ expect(endpoint.value).toBe("/responses");
+ type("byok-url", "https://open.bigmodel.cn/");
+ pick("byok-path", "/api/paas/v4");
+ expect(path.value).toBe("/api/paas/v4");
+ expect(path.parentElement!.dataset.default).toBe("false");
+ pick("byok-endpoint", "/chat/completions");
+ expect($("byok-status").textContent).toBe(
+ "Sends OpenAI Chat Completions requests to https://open.bigmodel.cn/api/paas/v4/chat/completions",
+ );
+ type("byok-key", "sk-top-secret");
- $("byok-check").click();
- await vi.waitFor(() =>
- expect(run).toHaveBeenCalledWith({
- op: "local.byok.check",
- byok: {
- runtime: "codex",
- baseUrl: "https://api.example.com/v1",
- apiKey: "sk-top-secret",
- modelId: "gpt-5.4",
+ // Refresh lists the endpoint's models and opens them.
+ expect(($("byok-test") as HTMLButtonElement).disabled).toBe(true);
+ run.mockImplementationOnce(async () =>
+ withLocal(welcome(small), {
+ byokModels: {
+ state: "ready",
+ url: "https://open.bigmodel.cn/api/paas/v4/models",
+ models: [
+ { id: "glm-4.6", contextWindow: 204_800 },
+ { id: "glm-4.5-air" },
+ ],
},
}),
);
- const checkedState = welcome(small);
- push({
- ...checkedState,
- localServer: {
- ...checkedState.localServer,
+ $("byok-list").click();
+ const endpointOf = {
+ baseUrl: "https://open.bigmodel.cn",
+ path: "/api/paas/v4",
+ endpoint: "/chat/completions",
+ protocol: "openai-chat",
+ apiKey: "sk-top-secret",
+ };
+ expect(run).toHaveBeenCalledWith({
+ op: "local.byok.models",
+ byok: endpointOf,
+ });
+ await vi.waitFor(() => expect($("byok-model-menu").hidden).toBe(false));
+ expect(words("byok-model-menu")).toContain(
+ "2 models from https://open.bigmodel.cn/api/paas/v4/models",
+ );
+ expect(words("byok-model-menu")).toContain("glm-4.6 200k context");
+ $("byok-model-menu")
+ .querySelector<HTMLButtonElement>('[data-value="glm-4.6"]')!
+ .click();
+ expect(($("byok-model") as HTMLInputElement).value).toBe("glm-4.6");
+ expect(($("local-install") as HTMLButtonElement).disabled).toBe(false);
+ expect($("plan-summary").textContent).toBe("BYOK · Codex · glm-4.6");
+
+ // Test sends one request and floats the outcome under the button.
+ run.mockImplementationOnce(async () =>
+ withLocal(welcome(small), {
byokCheck: {
state: "ready",
- protocol: "openai-responses",
- modelId: "gpt-5.4",
- contextWindow: 200_000,
+ protocol: "openai-chat",
+ url: "https://open.bigmodel.cn/api/paas/v4/chat/completions",
+ modelId: "glm-4.6",
+ contextWindow: 204_800,
},
- },
- });
- expect($("byok-status").textContent).toBe(
- "Ready · gpt-5.4 (200k context) through OpenAI Responses",
+ }),
+ );
+ $("byok-test").click();
+ const config = { ...endpointOf, modelId: "glm-4.6", runtime: "codex" };
+ expect(run).toHaveBeenCalledWith({ op: "local.byok.check", byok: config });
+ await vi.waitFor(() => expect($("byok-toast").hidden).toBe(false));
+ expect($("byok-toast").dataset.tone).toBe("ok");
+ expect(words("byok-toast")).toBe(
+ "Connected glm-4.6 · 200k context · OpenAI Chat Completionshttps://open.bigmodel.cn/api/paas/v4/chat/completions",
);
$("local-install").click();
await vi.waitFor(() => {
expect(installed(run)).toEqual([
- {
- op: "local.start",
- runtime: "codex",
- byok: {
- runtime: "codex",
- baseUrl: "https://api.example.com/v1",
- apiKey: "sk-top-secret",
- modelId: "gpt-5.4",
- },
- },
+ { op: "local.start", runtime: "codex", byok: config },
]);
- expect(keyInput.value).toBe("");
+ expect(($("byok-key") as HTMLInputElement).value).toBe("");
+ });
+ });
+
+ it("sends a pasted full address as is, and keeps a failed test until the fields change", async () => {
+ const { run } = await openPage(welcome(small), "welcome");
+ $("local-customize").click();
+ document
+ .querySelector<HTMLButtonElement>(
+ '[data-plan="source"] [data-value="byok"]',
+ )!
+ .click();
+ type("byok-url", "https://llm.example.com/gateway");
+ pick("byok-path", "");
+ pick("byok-endpoint", "");
+ expect(($("byok-path") as HTMLInputElement).value).toBe("");
+ // No known ending: the Claude Code runtime's own format.
+ expect($("byok-status").textContent).toBe(
+ "Sends Anthropic Messages (the Claude Code format) requests to https://llm.example.com/gateway",
+ );
+ type("byok-path", "a//b");
+ expect($("byok-status").dataset.tone).toBe("err");
+ expect(($("byok-list") as HTMLButtonElement).disabled).toBe(true);
+ type("byok-path", "");
+ type("byok-model", "claude-sonnet-4-6");
+
+ run.mockImplementationOnce(async () =>
+ withLocal(welcome(small), {
+ byokCheck: {
+ state: "failed",
+ message:
+ "Nothing answered at https://llm.example.com/gateway (HTTP 404).",
+ },
+ }),
+ );
+ $("byok-test").click();
+ expect(run).toHaveBeenCalledWith({
+ op: "local.byok.check",
+ byok: {
+ baseUrl: "https://llm.example.com/gateway",
+ path: "",
+ endpoint: "",
+ protocol: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ runtime: "claude",
+ },
});
+ await vi.waitFor(() => expect($("byok-toast").hidden).toBe(false));
+ expect($("byok-toast").dataset.tone).toBe("err");
+ expect(words("byok-toast")).toBe(
+ "Couldn't connect Nothing answered at https://llm.example.com/gateway (HTTP 404).",
+ );
+ type("byok-model", "claude-opus-4-1");
+ expect($("byok-toast").hidden).toBe(true);
});
- it("offers Use BYOK instead inside the runtime OAuth sign-in modal", async () => {
+ it("offers the same BYOK fields inside the runtime sign-in dialog", async () => {
const base = state("installing");
const { run } = await openPage({
...base,
@@ -653,15 +757,14 @@ describe("setup page Quick Install recommendation", () => {
expect($("runtime-signin-byok").hidden).toBe(true);
$("runtime-signin-byok-toggle").click();
expect($("runtime-signin-byok").hidden).toBe(false);
- const url = $("signin-byok-url") as HTMLInputElement;
- const key = $("signin-byok-key") as HTMLInputElement;
- const model = $("signin-byok-model") as HTMLInputElement;
- url.value = "https://api.anthropic.com";
- url.dispatchEvent(new Event("input"));
- key.value = "sk-ant-fallback";
- key.dispatchEvent(new Event("input"));
- model.value = "claude-sonnet-4-6";
- model.dispatchEvent(new Event("input"));
+ expect(($("signin-byok-endpoint") as HTMLInputElement).value).toBe(
+ "/messages",
+ );
+ expect($("signin-byok-list")).not.toBeNull();
+ expect($("signin-byok-test")).not.toBeNull();
+ type("signin-byok-url", "https://api.anthropic.com");
+ type("signin-byok-key", "sk-ant-fallback");
+ type("signin-byok-model", "claude-sonnet-4-6");
$("runtime-signin-byok").dispatchEvent(
new Event("submit", { cancelable: true }),
);
@@ -671,12 +774,15 @@ describe("setup page Quick Install recommendation", () => {
byok: {
runtime: "claude",
baseUrl: "https://api.anthropic.com",
+ path: "/v1",
+ endpoint: "/messages",
+ protocol: "anthropic",
apiKey: "sk-ant-fallback",
modelId: "claude-sonnet-4-6",
},
}),
);
- expect(key.value).toBe("");
+ expect(($("signin-byok-key") as HTMLInputElement).value).toBe("");
});
});
diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.html
index 1f6464ec..bd63a759 100644
--- a/apps/desktop/src/shell/setup.html
+++ b/apps/desktop/src/shell/setup.html
@@ -25,6 +25,8 @@
--field: #f4f4f0;
--ok: #2f9e44;
--error: #b5320a;
+ --filled: #9b9a90;
+ --mono: ui-monospace, SFMono-Regular, Menlo, monospace;
--ease: cubic-bezier(0.22, 1, 0.36, 1);
color-scheme: light;
}
@@ -714,48 +716,337 @@
font-size: 12px;
font-weight: 500;
}
- .byok-grid {
+ /* BYOK fields, built once by byokFields() for the setup form and the
+ sign-in dialog: the base URL and two optional comboboxes (path and
+ endpoint) on one row, the key, then the model with List models and
+ Test beside it, and one status line. */
+ .byok-fields {
display: grid;
gap: 7px;
+ font-size: 12px;
+ text-align: left;
}
- .byok-grid input,
- .signin-byok input,
- .signin-byok select {
- width: 100%;
+ .byok-fields .ep {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto auto;
+ gap: 6px;
+ }
+ .byok-fields .ep-base-wrap,
+ .byok-fields .ep > .cb,
+ .byok-fields .cb.standalone,
+ .byok-fields .byok-key {
+ display: flex;
+ align-items: center;
+ min-width: 0;
height: 30px;
- padding: 0 10px;
+ padding: 0 4px 0 10px;
border: 1px solid #e2e2dc;
border-radius: 8px;
background: #fafaf8;
+ transition:
+ border-color 140ms ease,
+ background-color 140ms ease;
+ }
+ .byok-fields .byok-key {
+ width: 100%;
+ padding-right: 10px;
color: var(--ink);
font: inherit;
- font-size: 12px;
+ user-select: text;
+ -webkit-user-select: text;
}
- .byok-grid input:focus,
- .signin-byok input:focus,
- .signin-byok select:focus {
+ .byok-fields .ep-base-wrap:focus-within,
+ .byok-fields .ep > .cb:focus-within,
+ .byok-fields .cb.standalone:focus-within,
+ .byok-fields .byok-key:focus {
outline: none;
border-color: var(--ink);
background: #fff;
}
- .byok-actions {
- display: flex;
+ .ep-base,
+ .cb-input {
+ flex: 1 1 auto;
+ width: 100%;
+ min-width: 0;
+ height: 100%;
+ padding: 0;
+ border: 0;
+ outline: none;
+ background: transparent;
+ color: var(--ink);
+ font: inherit;
+ text-overflow: ellipsis;
+ user-select: text;
+ -webkit-user-select: text;
+ }
+ /* Path and endpoint boxes are as wide as their value; the base URL
+ takes the rest of the row. */
+ .ep > .cb .cb-input {
+ field-sizing: content;
+ width: auto;
+ min-width: 1ch;
+ max-width: 17ch;
+ }
+ .byok-fields input::placeholder {
+ color: var(--faint);
+ }
+ .cb-input::placeholder {
+ font-style: italic;
+ }
+ /* Grey: the default Linger fills in, which is still sent. */
+ .cb[data-default="true"] .cb-input {
+ color: var(--filled);
+ }
+ .cb[data-default="true"] .cb-input:focus {
+ color: #77766c;
+ }
+
+ /* Combobox: type anything, or pick from the list. */
+ .cb {
+ position: relative;
+ }
+ .cb-caret {
+ display: grid;
+ flex: none;
+ place-items: center;
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ border: 0;
+ border-radius: 5px;
+ background: none;
+ color: var(--faint);
+ }
+ .cb-caret:hover:not(:disabled),
+ .cb[data-open="true"] .cb-caret {
+ background: rgba(20, 20, 16, 0.06);
+ color: var(--muted);
+ }
+ .cb-menu {
+ position: absolute;
+ top: calc(100% + 5px);
+ left: -1px;
+ z-index: 30;
+ display: grid;
+ gap: 1px;
+ min-width: calc(100% + 2px);
+ width: max-content;
+ max-width: min(320px, 86vw);
+ 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);
+ font-size: 12px;
+ line-height: 1.4;
+ cursor: default;
+ animation: menu-in 160ms var(--ease);
+ }
+ .cb-menu[hidden] {
+ display: none;
+ }
+ .ep > .cb .cb-menu {
+ left: auto;
+ right: -1px;
+ }
+ @keyframes menu-in {
+ from {
+ opacity: 0;
+ transform: translateY(-3px);
+ }
+ }
+ .cb-menu [role="option"] {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 16px;
align-items: center;
- justify-content: space-between;
- gap: 10px;
+ gap: 1px 10px;
+ padding: 6px 8px;
+ border: 0;
+ border-radius: 7px;
+ background: none;
+ text-align: left;
}
- .byok-status {
- flex: 1;
+ .cb-menu [role="option"]:hover,
+ .cb-menu [role="option"]:focus-visible {
+ background: #f4f4f0;
+ outline: none;
+ }
+ .opt-main {
+ color: var(--ink);
+ font: 500 12px var(--mono);
+ overflow-wrap: anywhere;
+ }
+ .opt-label {
+ grid-column: 1;
+ color: var(--muted);
+ font-size: 11.5px;
+ }
+ .opt-label em {
+ margin-left: 6px;
+ color: #d9822b;
+ font-style: normal;
+ font-weight: 500;
+ }
+ .opt-check {
+ grid-column: 2;
+ grid-row: 1 / span 2;
+ visibility: hidden;
+ color: var(--ink);
+ }
+ [aria-selected="true"] > .opt-check {
+ visibility: visible;
+ }
+ .cb-head {
+ padding: 5px 8px 3px;
color: var(--faint);
+ font-size: 11px;
+ font-weight: 500;
+ }
+ .cb-note {
+ max-width: 300px;
+ padding: 7px 8px;
+ color: var(--muted);
font-size: 11.5px;
- line-height: 1.35;
+ overflow-wrap: anywhere;
+ }
+ .cb-note[data-tone="err"] {
+ color: var(--error);
+ }
+
+ /* The model box, with List models and Test beside it; the test
+ result floats under Test. */
+ .model-row {
+ position: relative;
+ display: flex;
+ gap: 6px;
+ }
+ .model-row > .cb {
+ flex: 1;
+ }
+ .model-row > .change {
+ height: 30px;
}
- .byok-status[data-state="ready"] {
- color: #2b7a3d;
+ .model-row > .list-btn {
+ display: grid;
+ place-items: center;
+ width: 30px;
+ padding: 0;
+ color: var(--muted);
+ }
+ .model-row > .list-btn:hover:not(:disabled) {
+ color: var(--ink);
+ }
+ .list-btn[data-busy="true"] svg {
+ animation: spin 0.9s linear infinite;
+ }
+ .byok-toast {
+ position: absolute;
+ top: calc(100% + 9px);
+ right: 0;
+ z-index: 40;
+ display: grid;
+ grid-template-columns: 16px minmax(0, 1fr) 20px;
+ align-items: start;
+ gap: 8px;
+ width: min(330px, 100%);
+ padding: 10px 8px 10px 12px;
+ border-radius: 10px;
+ background: #1f1f1d;
+ color: #c9c8bf;
+ box-shadow: 0 14px 32px -10px rgba(20, 20, 16, 0.5);
+ font-size: 12px;
+ line-height: 1.45;
+ text-align: left;
+ user-select: text;
+ -webkit-user-select: text;
+ animation: toast-in 180ms var(--ease);
+ }
+ .byok-toast[hidden] {
+ display: none;
}
- .byok-status[data-state="failed"] {
+ .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: toast-out 200ms ease forwards;
+ }
+ @keyframes toast-in {
+ from {
+ opacity: 0;
+ transform: translateY(-4px);
+ }
+ }
+ @keyframes toast-out {
+ to {
+ opacity: 0;
+ transform: translateY(-4px);
+ }
+ }
+ /* Over the setup form's own .choice strong. */
+ .byok-fields .byok-toast strong {
+ display: block;
+ color: #fff;
+ font-size: 12.5px;
+ font-weight: 550;
+ }
+ .byok-toast .url {
+ color: #ecebe3;
+ }
+ .toast-icon {
+ display: grid;
+ margin-top: 1px;
+ }
+ .byok-toast[data-tone="ok"] .toast-icon {
+ color: #74d08b;
+ }
+ .byok-toast[data-tone="err"] .toast-icon {
+ color: #ff9466;
+ }
+ .toast-close {
+ display: grid;
+ place-items: center;
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ border: 0;
+ border-radius: 5px;
+ background: none;
+ color: #8f8e85;
+ }
+ .toast-close:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.08);
+ color: #fff;
+ }
+ .byok-status {
+ color: var(--faint);
+ font-size: 11.5px;
+ line-height: 1.4;
+ overflow-wrap: anywhere;
+ }
+ .byok-status[data-tone="err"] {
color: var(--error);
}
+ .byok-status .url {
+ color: var(--muted);
+ }
+ .byok-status[data-tone] .url {
+ color: inherit;
+ }
+ .byok-fields .url {
+ font-family: var(--mono);
+ font-size: 0.95em;
+ overflow-wrap: anywhere;
+ }
.choice.optional-keys {
display: block;
}
@@ -773,14 +1064,6 @@
margin-bottom: 8px;
color: var(--ink);
}
- .signin-byok {
- display: grid;
- gap: 8px;
- margin-top: 10px;
- padding-top: 10px;
- border-top: 1px solid #ecece7;
- text-align: left;
- }
.choices,
.panel {
border: 1px solid rgba(20, 20, 16, 0.07);
@@ -1277,11 +1560,11 @@
.signin-modal details p {
margin: 8px 0;
}
- .signin-modal form {
+ .signin-modal details form {
display: flex;
gap: 8px;
}
- .signin-modal input {
+ .signin-modal details input {
flex: 1;
min-width: 0;
padding: 5px 10px;
@@ -1291,19 +1574,14 @@
}
.signin-byok {
display: grid;
- gap: 7px;
+ gap: 10px;
margin-top: 8px;
padding-top: 10px;
border-top: 1px solid var(--line);
}
- .signin-byok .seg {
- width: 100%;
- }
- .signin-byok .seg button {
- flex: 1;
- }
- .signin-byok input {
- width: 100%;
+ /* The BYOK fields take the room they have on the setup form. */
+ .signin-modal .sheet:has(.signin-byok:not([hidden])) {
+ width: 448px;
}
.diagnostics {
display: flex;
@@ -1623,11 +1901,11 @@
</div>
<div class="choice byok-box" id="byok-row" hidden>
<div class="byok-row">
- <label>AI runtime</label>
+ <label id="byok-runtime-label">AI runtime</label>
<div
class="seg"
role="radiogroup"
- aria-label="BYOK runtime"
+ aria-labelledby="byok-runtime-label"
data-byok="runtime"
>
<span class="knob"></span>
@@ -1642,40 +1920,7 @@
</button>
</div>
</div>
- <div class="byok-grid">
- <input
- id="byok-url"
- type="url"
- autocomplete="off"
- spellcheck="false"
- aria-label="BYOK endpoint URL"
- placeholder="Endpoint URL (https://… or http://192.168.…)"
- />
- <input
- id="byok-key"
- type="password"
- autocomplete="off"
- spellcheck="false"
- aria-label="BYOK API key"
- placeholder="API key (stored privately on this computer)"
- />
- <input
- id="byok-model"
- type="text"
- autocomplete="off"
- spellcheck="false"
- aria-label="BYOK model ID"
- placeholder="Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)"
- />
- </div>
- <div class="byok-actions">
- <span class="byok-status" id="byok-status">
- Mounted on local Bifrost for all runtimes.
- </span>
- <button type="button" class="change" id="byok-check">
- Check
- </button>
- </div>
+ <div class="byok-fields" id="byok-fields"></div>
</div>
<details class="choice optional-keys" id="optional-keys">
<summary>App integrations (optional)</summary>
@@ -1835,30 +2080,7 @@
</button>
</div>
<form class="signin-byok" id="runtime-signin-byok" hidden>
- <input
- id="signin-byok-url"
- type="url"
- autocomplete="off"
- spellcheck="false"
- aria-label="Sign-in BYOK endpoint URL"
- placeholder="Endpoint URL (https://… or http://192.168.…)"
- />
- <input
- id="signin-byok-key"
- type="password"
- autocomplete="off"
- spellcheck="false"
- aria-label="Sign-in BYOK API key"
- placeholder="API key (stored privately on this computer)"
- />
- <input
- id="signin-byok-model"
- type="text"
- autocomplete="off"
- spellcheck="false"
- aria-label="Sign-in BYOK model ID"
- placeholder="Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)"
- />
+ <div class="byok-fields" id="signin-byok-fields"></div>
<button
class="secondary"
id="runtime-signin-byok-submit"
@@ -2303,33 +2525,617 @@
let picked = false;
let pickedAutoBeforeCheck = false;
let customizing = false;
- const emptyByok = () => ({
- runtime: "claude",
- baseUrl: "",
- apiKey: "",
- modelId: "",
- });
- let byok = emptyByok();
- let signInByokOpen = false;
- let signInByok = {
- baseUrl: "",
- apiKey: "",
- modelId: "",
+ // BYOK. Requests go to the base URL + path + endpoint, used verbatim;
+ // path and endpoint are optional, and a grey value is the default that
+ // is sent. The wire format follows the end of that address, else the
+ // runtime's own, so Bifrost passes the runtime's requests through.
+ // Nothing probes: Test sends one request to that one address.
+ const BYOK_FORMATS = {
+ "openai-chat": {
+ suffix: "/chat/completions",
+ label: "OpenAI Chat Completions",
+ },
+ "openai-responses": { suffix: "/responses", label: "OpenAI Responses" },
+ anthropic: { suffix: "/messages", label: "Anthropic Messages" },
};
- const byokProtocolLabels = {
- anthropic: "Anthropic Messages",
- "openai-chat": "OpenAI Chat Completions",
- "openai-responses": "OpenAI Responses",
+ const RUNTIME_FORMATS = {
+ claude: "anthropic",
+ codex: "openai-responses",
+ pi: "openai-chat",
};
- const trimByok = (value, runtime) => {
- const apiKey = value.apiKey.trim();
- return {
- runtime,
- baseUrl: value.baseUrl.trim(),
- ...(apiKey ? { apiKey } : {}),
- modelId: value.modelId.trim(),
+ const DEFAULT_PATH = "/v1";
+ const PATH_OPTIONS = [
+ { value: "/v1", label: "Most providers" },
+ {
+ 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." },
+ ];
+ const ENDPOINT_OPTIONS = [
+ ...Object.values(BYOK_FORMATS).map((format) => ({
+ value: format.suffix,
+ label: format.label,
+ })),
+ { value: "", label: "No endpoint. The base URL is the full address." },
+ ];
+ // What the installer accepts as a path or endpoint: empty, or whole
+ // segments, so neither can change the base URL's host.
+ const BYOK_URL_PATH = /^(\/[^/?#\s\\]+)*$/;
+ const ICONS = {
+ refresh:
+ '<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" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ chevron:
+ '<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" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ selected:
+ '<svg class="opt-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" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ ok: '<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" stroke-width="1.4"/><path d="m5.2 8.2 1.9 1.9 3.7-4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ err: '<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" stroke-width="1.4"/><path d="M8 4.6v4.2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><circle cx="8" cy="11.2" r="0.9" fill="currentColor"/></svg>',
+ close:
+ '<svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><path d="m2 2 6 6M8 2 2 8" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>',
+ };
+ const esc = (value) =>
+ String(value).replace(
+ /[&<>"]/g,
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c],
+ );
+ const urlHtml = (url) => '<span class="url">' + esc(url) + "</span>";
+ const contextLabel = (tokens) =>
+ tokens >= 1024 ** 2
+ ? Math.round((tokens / 1024 ** 2) * 10) / 10 + "M"
+ : Math.round(tokens / 1024) + "k";
+ // A typed path gains its leading slash and loses trailing ones.
+ const normalizePath = (value) => {
+ const trimmed = value.trim().replace(/\/+$/, "");
+ return trimmed && !trimmed.startsWith("/") ? "/" + trimmed : trimmed;
+ };
+ // An IPC error's own message, without Electron's prefix.
+ const ipcMessage = (error) =>
+ String(error?.message ?? error).replace(
+ /^Error invoking remote method '[^']+': (Error: )?/,
+ "",
+ );
+ // Asks the main process to test or list an endpoint. The answer comes
+ // back in the state the command returns; nothing else waits for it.
+ const byokAsk = async (command, field) => {
+ try {
+ state = await setup.run(command);
+ return (
+ state.localServer[field] ?? {
+ state: "failed",
+ message: "Linger did not answer.",
+ }
+ );
+ } catch (error) {
+ return { state: "failed", message: ipcMessage(error) };
+ }
+ };
+
+ // A combobox: type anything, or pick a suggestion from its list.
+ const combos = [];
+ const closeCombos = () => {
+ for (const combo of combos) combo.open = false;
+ };
+ const combobox = (root, cfg) => {
+ root.classList.add("cb");
+ root.innerHTML = `
+ <input class="cb-input" id="${cfg.id}" role="combobox"
+ aria-autocomplete="none" aria-expanded="false"
+ aria-controls="${cfg.id}-menu" autocomplete="off" spellcheck="false"
+ placeholder="${esc(cfg.placeholder)}" aria-label="${cfg.label}" />
+ <button type="button" class="cb-caret" tabindex="-1"
+ aria-label="Show ${cfg.label} suggestions">${ICONS.chevron}</button>
+ <div class="cb-menu" id="${cfg.id}-menu" role="listbox"
+ aria-label="${cfg.label}" hidden></div>`;
+ const input = root.querySelector(".cb-input");
+ const caret = root.querySelector(".cb-caret");
+ const menu = root.querySelector(".cb-menu");
+ const combo = { root, input, open: false };
+ let menuHtml = "";
+ const openMenu = (focusFirst) => {
+ closeCombos();
+ combo.open = true;
+ render();
+ if (focusFirst)
+ (
+ menu.querySelector('[aria-selected="true"]') ||
+ menu.querySelector("button")
+ )?.focus();
};
+ input.addEventListener("input", () => {
+ cfg.set(input.value);
+ combo.open = false;
+ render();
+ });
+ input.addEventListener("blur", () => {
+ cfg.commit();
+ render();
+ });
+ input.addEventListener("keydown", (event) => {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ openMenu(true);
+ } else if (event.key === "Enter") {
+ // Commits the value; inside a form it does not submit it.
+ event.preventDefault();
+ cfg.commit();
+ closeCombos();
+ render();
+ }
+ });
+ caret.addEventListener("mousedown", (event) => event.preventDefault());
+ caret.addEventListener("click", () => {
+ if (combo.open) {
+ closeCombos();
+ render();
+ } else {
+ openMenu(false);
+ input.focus();
+ }
+ });
+ menu.addEventListener("mousedown", (event) => event.preventDefault());
+ menu.addEventListener("click", (event) => {
+ const option = event.target.closest("[data-value]");
+ if (!option) return;
+ cfg.set(option.dataset.value);
+ cfg.commit();
+ closeCombos();
+ render();
+ input.focus();
+ });
+ menu.addEventListener("keydown", (event) => {
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
+ event.preventDefault();
+ const options = [...menu.querySelectorAll("button")];
+ const at = options.indexOf(document.activeElement);
+ const step = event.key === "ArrowDown" ? 1 : -1;
+ options[(at + step + options.length) % options.length]?.focus();
+ });
+ combo.sync = () => {
+ const value = cfg.get();
+ if (input.value !== value) input.value = value;
+ root.dataset.default = String(Boolean(cfg.isDefault?.()));
+ root.dataset.open = String(combo.open);
+ input.setAttribute("aria-expanded", String(combo.open));
+ menu.hidden = !combo.open;
+ if (!combo.open) {
+ menuHtml = "";
+ return;
+ }
+ const option = (item) => `
+ <button type="button" role="option" data-value="${esc(item.value)}"
+ aria-selected="${item.value === value}">
+ <span class="opt-main">${item.value ? esc(item.value) : "-"}</span>
+ ${
+ item.label || item.tag
+ ? `<span class="opt-label">${esc(item.label || "")}${
+ item.tag ? `<em>${esc(item.tag)}</em>` : ""
+ }</span>`
+ : ""
+ }
+ ${ICONS.selected}
+ </button>`;
+ // Notes are HTML their callers escaped.
+ const html =
+ (cfg.heading ? `<div class="cb-head">${cfg.heading}</div>` : "") +
+ cfg
+ .items()
+ .map((item) =>
+ item.note === undefined
+ ? option(item)
+ : `<div class="cb-note" data-tone="${item.tone || ""}">${item.note}</div>`,
+ )
+ .join("");
+ if (html !== menuHtml) {
+ menu.innerHTML = html;
+ menuHtml = html;
+ }
+ };
+ combos.push(combo);
+ return combo;
};
+
+ // The BYOK fields, built once for the setup form and once for the
+ // sign-in dialog. runtimeOf() names the runtime the endpoint serves,
+ // which picks the default endpoint and format; changed() runs on every
+ // edit.
+ const byokForms = [];
+ const byokFields = (root, prefix, runtimeOf, changed) => {
+ root.innerHTML = `
+ <div class="ep">
+ <span class="ep-base-wrap"><input class="ep-base" id="${prefix}-url"
+ type="url" autocomplete="off" spellcheck="false"
+ aria-label="Base URL" placeholder="Base URL (https://…)" /></span>
+ <div></div>
+ <div></div>
+ </div>
+ <input class="byok-key" id="${prefix}-key" type="password"
+ autocomplete="off" spellcheck="false" aria-label="API key"
+ placeholder="API key (stored privately on this computer)" />
+ <div class="model-row">
+ <div class="standalone"></div>
+ <button type="button" class="change list-btn" id="${prefix}-list"
+ aria-label="List models" title="List models">${ICONS.refresh}</button>
+ <button type="button" class="change test-btn" id="${prefix}-test">Test</button>
+ <div class="byok-toast" id="${prefix}-toast" role="status"
+ aria-live="polite" hidden></div>
+ </div>
+ <div class="byok-status" id="${prefix}-status" aria-live="polite"></div>`;
+ const blank = () => ({
+ baseUrl: "",
+ path: DEFAULT_PATH,
+ // null follows the runtime's default.
+ endpoint: null,
+ apiKey: "",
+ modelId: "",
+ });
+ let f = blank();
+ // The latest test and model listing; each sequence number drops an
+ // answer to a request the fields have changed since.
+ let check = null;
+ let models = null;
+ let checkSeq = 0;
+ let modelSeq = 0;
+ let toast = null;
+ let toastTimer = 0;
+ let toastShown = "";
+
+ const defaultEndpoint = () =>
+ BYOK_FORMATS[RUNTIME_FORMATS[runtimeOf()]].suffix;
+ const endpointValue = () => f.endpoint ?? defaultEndpoint();
+ const baseUrl = () => f.baseUrl.trim().replace(/\/+$/, "");
+ const apiRoot = () => baseUrl() + normalizePath(f.path);
+ const requestUrl = () => apiRoot() + normalizePath(endpointValue());
+ const modelsUrl = () => apiRoot() + "/models";
+ const format = () => {
+ const url = requestUrl();
+ for (const [protocol, { suffix }] of Object.entries(BYOK_FORMATS))
+ if (url.endsWith(suffix)) return { protocol, fromUrl: true };
+ return { protocol: RUNTIME_FORMATS[runtimeOf()], fromUrl: false };
+ };
+ const validParts = () =>
+ [normalizePath(f.path), normalizePath(endpointValue())].every(
+ (part) => part.length <= 256 && BYOK_URL_PATH.test(part),
+ );
+ const addressed = () => baseUrl() !== "" && validParts();
+ const complete = () => addressed() && f.modelId.trim() !== "";
+ const endpoint = () => {
+ const apiKey = f.apiKey.trim();
+ return {
+ baseUrl: baseUrl(),
+ path: normalizePath(f.path),
+ endpoint: normalizePath(endpointValue()),
+ protocol: format().protocol,
+ ...(apiKey ? { apiKey } : {}),
+ };
+ };
+
+ // The test result floats under Test: a success fades on its own, a
+ // failure stays until dismissed or the fields change.
+ const showToast = () => {
+ clearTimeout(toastTimer);
+ toast = { leaving: false };
+ if (check?.state === "ready")
+ toastTimer = setTimeout(hideToast, 3500);
+ };
+ const hideToast = () => {
+ clearTimeout(toastTimer);
+ if (!toast || toast.leaving) return;
+ toast.leaving = true;
+ render();
+ toastTimer = setTimeout(() => {
+ toast = null;
+ render();
+ }, 200);
+ };
+ const resetResults = (all) => {
+ checkSeq += 1;
+ check = null;
+ clearTimeout(toastTimer);
+ toast = null;
+ if (all) {
+ modelSeq += 1;
+ models = null;
+ }
+ };
+ const edit = (next, all) => {
+ f = { ...f, ...next };
+ resetResults(all);
+ changed();
+ };
+
+ const base = root.querySelector(".ep-base");
+ base.addEventListener("input", () => {
+ edit({ baseUrl: base.value }, true);
+ render();
+ });
+ base.addEventListener("blur", () => {
+ if (baseUrl() !== f.baseUrl) f = { ...f, baseUrl: baseUrl() };
+ base.scrollLeft = 0;
+ render();
+ });
+ const [pathBox, endpointBox] = root.querySelectorAll(".ep > div");
+ const path = combobox(pathBox, {
+ id: prefix + "-path",
+ label: "Path",
+ heading: "Path · optional",
+ placeholder: "-",
+ get: () => f.path,
+ set: (value) => edit({ path: value }, true),
+ commit: () => {
+ f = { ...f, path: normalizePath(f.path) };
+ },
+ isDefault: () => f.path === DEFAULT_PATH,
+ items: () =>
+ PATH_OPTIONS.map((option) => ({
+ ...option,
+ tag: option.value === DEFAULT_PATH ? "Default" : "",
+ })),
+ });
+ const endpointCombo = combobox(endpointBox, {
+ id: prefix + "-endpoint",
+ label: "Endpoint",
+ heading: "Endpoint · optional",
+ placeholder: "-",
+ get: endpointValue,
+ set: (value) =>
+ edit(
+ { endpoint: value === defaultEndpoint() ? null : value },
+ false,
+ ),
+ commit: () => {
+ if (f.endpoint === null) return;
+ const value = normalizePath(f.endpoint);
+ f = {
+ ...f,
+ endpoint: value === defaultEndpoint() ? null : value,
+ };
+ },
+ isDefault: () => f.endpoint === null,
+ items: () =>
+ ENDPOINT_OPTIONS.map((option) => ({
+ ...option,
+ tag:
+ option.value === defaultEndpoint()
+ ? RUNTIMES[runtimeOf()] + " default"
+ : "",
+ })),
+ });
+ const modelCombo = combobox(root.querySelector(".model-row > div"), {
+ id: prefix + "-model",
+ label: "Model",
+ placeholder: "Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)",
+ get: () => f.modelId,
+ set: (value) => edit({ modelId: value }, false),
+ commit: () => {
+ f = { ...f, modelId: f.modelId.trim() };
+ },
+ items: () => {
+ if (!models)
+ return [
+ {
+ note: "Use the refresh button to list the endpoint's models, or type an ID.",
+ },
+ ];
+ if (models.state === "loading")
+ return [
+ {
+ note: "Listing models from " + urlHtml(modelsUrl()) + "…",
+ },
+ ];
+ if (models.state === "failed")
+ return [{ note: esc(models.message), tone: "err" }];
+ const count = models.models.length;
+ return [
+ {
+ note:
+ count +
+ (count === 1 ? " model" : " models") +
+ " from " +
+ urlHtml(models.url),
+ },
+ ...models.models.map((model) => ({
+ value: model.id,
+ label: [
+ model.name !== model.id && model.name,
+ model.contextWindow &&
+ contextLabel(model.contextWindow) + " context",
+ ]
+ .filter(Boolean)
+ .join(" · "),
+ })),
+ ];
+ },
+ });
+ const key = root.querySelector(".byok-key");
+ key.addEventListener("input", () => {
+ edit({ apiKey: key.value }, true);
+ render();
+ });
+ const list = root.querySelector(".list-btn");
+ list.addEventListener("click", async () => {
+ if (!addressed()) return;
+ const seq = ++modelSeq;
+ models = { state: "loading" };
+ closeCombos();
+ render();
+ const answer = await byokAsk(
+ { op: "local.byok.models", byok: endpoint() },
+ "byokModels",
+ );
+ if (seq !== modelSeq) return;
+ models = answer;
+ // The list it filled opens; a failure shows on the status line.
+ closeCombos();
+ modelCombo.open = answer.state === "ready";
+ render();
+ });
+ const test = root.querySelector(".test-btn");
+ test.addEventListener("click", async () => {
+ if (!complete()) return;
+ resetResults(false);
+ const seq = checkSeq;
+ check = { state: "checking" };
+ render();
+ const answer = await byokAsk(
+ { op: "local.byok.check", byok: form.config() },
+ "byokCheck",
+ );
+ if (seq !== checkSeq) return;
+ check = answer;
+ showToast();
+ render();
+ });
+ const toastEl = root.querySelector(".byok-toast");
+ toastEl.addEventListener("click", (event) => {
+ if (event.target.closest(".toast-close")) hideToast();
+ });
+ // Hovering keeps a success on screen; leaving lets it fade.
+ toastEl.addEventListener("mouseenter", () => clearTimeout(toastTimer));
+ toastEl.addEventListener("mouseleave", () => {
+ if (check?.state === "ready")
+ toastTimer = setTimeout(hideToast, 1500);
+ });
+ const status = root.querySelector(".byok-status");
+
+ const form = {
+ root,
+ complete,
+ modelId: () => f.modelId.trim(),
+ config: () => ({
+ ...endpoint(),
+ modelId: f.modelId.trim(),
+ runtime: runtimeOf(),
+ }),
+ // The runtime changed: its default endpoint and format may differ.
+ runtimeChanged: () => resetResults(false),
+ clearKey: () => {
+ f = { ...f, apiKey: "" };
+ key.value = "";
+ },
+ reset: () => {
+ f = blank();
+ resetResults(true);
+ },
+ // A click outside the toast and Test dismisses it.
+ dismiss: (target) => {
+ if (toast && !toastEl.contains(target) && !test.contains(target))
+ hideToast();
+ },
+ sync: (busy) => {
+ if (base.value !== f.baseUrl) base.value = f.baseUrl;
+ if (key.value !== f.apiKey) key.value = f.apiKey;
+ path.sync();
+ endpointCombo.sync();
+ modelCombo.sync();
+ const checking = check?.state === "checking";
+ const listing = models?.state === "loading";
+ list.disabled = busy || listing || !addressed();
+ list.dataset.busy = String(listing);
+ list.setAttribute(
+ "aria-label",
+ listing ? "Listing models" : "List models",
+ );
+ test.disabled = busy || checking || !complete();
+ test.textContent = checking ? "Testing…" : "Test";
+ const shown = Boolean(toast && check && !checking);
+ toastEl.hidden = !shown;
+ if (shown) {
+ const ok = check.state === "ready";
+ toastEl.dataset.tone = ok ? "ok" : "err";
+ toastEl.dataset.leaving = String(toast.leaving);
+ const html = `
+ <span class="toast-icon">${ok ? ICONS.ok : ICONS.err}</span>
+ <div>
+ <strong>${ok ? "Connected" : "Couldn't connect"}</strong>
+ <div>${
+ ok
+ ? `${esc(check.modelId)} · ${contextLabel(check.contextWindow)} context · ${BYOK_FORMATS[check.protocol].label}<br />${urlHtml(check.url)}`
+ : esc(check.message)
+ }</div>
+ </div>
+ <button type="button" class="toast-close" aria-label="Dismiss">${ICONS.close}</button>`;
+ if (html !== toastShown) {
+ toastEl.innerHTML = html;
+ toastShown = html;
+ }
+ }
+ let line;
+ if (!validParts())
+ line = {
+ tone: "err",
+ html: "Path and endpoint must be empty or a path such as /v1.",
+ };
+ else if (models?.state === "failed")
+ line = { tone: "err", html: esc(models.message) };
+ else if (listing)
+ line = {
+ html: "Listing models from " + urlHtml(modelsUrl()) + "…",
+ };
+ else if (!baseUrl())
+ line = {
+ html: "Grey values are defaults. Path and endpoint are optional.",
+ };
+ else {
+ const { protocol, fromUrl } = format();
+ line = {
+ html:
+ "Sends " +
+ BYOK_FORMATS[protocol].label +
+ (fromUrl
+ ? ""
+ : " (the " + RUNTIMES[runtimeOf()] + " format)") +
+ " requests to " +
+ urlHtml(requestUrl()),
+ };
+ }
+ if (line.tone) status.dataset.tone = line.tone;
+ else delete status.dataset.tone;
+ if (status.innerHTML !== line.html) status.innerHTML = line.html;
+ },
+ };
+ byokForms.push(form);
+ return form;
+ };
+ document.addEventListener("pointerdown", (event) => {
+ for (const form of byokForms) form.dismiss(event.target);
+ if (
+ combos.some(
+ (combo) => combo.open && !combo.root.contains(event.target),
+ )
+ ) {
+ closeCombos();
+ render();
+ }
+ });
+ document.addEventListener("keydown", (event) => {
+ if (event.key !== "Escape") return;
+ const open = combos.find((combo) => combo.open);
+ if (!open) return;
+ closeCombos();
+ render();
+ open.input.focus();
+ });
+ // The setup form's runtime; the sign-in dialog's endpoint serves the
+ // runtime signing in.
+ let byokRuntime = "claude";
+ let signInByokOpen = false;
+ const mainByok = byokFields(
+ $("byok-fields"),
+ "byok",
+ () => byokRuntime,
+ () => {
+ picked = true;
+ },
+ );
+ const signInByok = byokFields(
+ $("signin-byok-fields"),
+ "signin-byok",
+ () => state.localServer.signIn?.runtime ?? "claude",
+ () => {},
+ );
// Provider keys typed or removed here ("" removes the saved one); kept
// only in the inputs and sent once with Install.
let keys = {};
@@ -2553,8 +3359,9 @@
$("runtime-signin-runtimes").hidden = !otherRuntimes && !pi;
$("runtime-signin-other").hidden = pi;
$("runtime-signin-byok").hidden = !signInByokOpen;
+ signInByok.sync(busy);
$("runtime-signin-byok-submit").disabled =
- busy || !signInByok.baseUrl.trim() || !signInByok.modelId.trim();
+ busy || !signInByok.complete();
for (const option of document.querySelectorAll("[data-switch]")) {
option.hidden = option.dataset.switch === sign.runtime;
option.disabled = busy;
@@ -2692,7 +3499,7 @@
choice.source === "local"
? "Local model + Pi"
: choice.source === "byok"
- ? ["BYOK", RUNTIMES[byok.runtime], byok.modelId.trim()]
+ ? ["BYOK", RUNTIMES[byokRuntime], mainByok.modelId()]
.filter(Boolean)
.join(" · ")
: RUNTIMES[choice.runtime];
@@ -2723,9 +3530,7 @@
$("local-install-label").innerHTML = label;
document.querySelector('[data-step="welcome"]').dataset.customizing =
String(customizing && local.available);
- const byokIncomplete =
- plan.source === "byok" &&
- (!byok.baseUrl.trim() || !byok.modelId.trim());
+ const byokIncomplete = plan.source === "byok" && !mainByok.complete();
const localUnavailable = plan.source === "local" && !model;
$("local-install").disabled ||=
checking || byokIncomplete || localUnavailable;
@@ -2879,36 +3684,16 @@
option.disabled = busy;
}
}
- for (const seg of document.querySelectorAll("[data-byok]"))
- for (const option of seg.querySelectorAll("button")) {
- const field = seg.dataset.byok;
- const value = option.dataset.value;
- option.setAttribute("aria-checked", String(byok[field] === value));
- option.disabled = busy;
- }
- $("byok-check").disabled =
- busy || !byok.baseUrl.trim() || !byok.modelId.trim();
- const byokCheck = local.byokCheck;
- if (byokCheck?.state === "checking") {
- $("byok-status").textContent = "Checking endpoint…";
- $("byok-status").dataset.tone = "";
- } else if (byokCheck?.state === "ready") {
- $("byok-status").textContent =
- "Ready · " +
- byokCheck.modelId +
- " (" +
- Math.round(byokCheck.contextWindow / 1000) +
- "k context) through " +
- byokProtocolLabels[byokCheck.protocol];
- $("byok-status").dataset.tone = "ok";
- } else if (byokCheck?.state === "failed") {
- $("byok-status").textContent = byokCheck.message;
- $("byok-status").dataset.tone = "err";
- } else {
- $("byok-status").textContent =
- "Mounted on local Bifrost for all runtimes.";
- $("byok-status").dataset.tone = "";
+ for (const option of document.querySelectorAll(
+ '[data-byok="runtime"] button',
+ )) {
+ option.setAttribute(
+ "aria-checked",
+ String(byokRuntime === option.dataset.value),
+ );
+ option.disabled = busy;
}
+ mainByok.sync(busy);
requestAnimationFrame(placeKnobs);
// Installing. A restart after a reboot shows here as starting.
@@ -3205,11 +3990,7 @@
state = await setup.run(command);
return true;
} catch (error) {
- const message = String(error?.message ?? error).replace(
- /^Error invoking remote method '[^']+': (Error: )?/,
- "",
- );
- if (errorId) $(errorId).textContent = message;
+ if (errorId) $(errorId).textContent = ipcMessage(error);
return false;
} finally {
pending = null;
@@ -3231,12 +4012,12 @@
// The install runs on its own; this window follows its progress.
const install = async () => {
const byokPayload =
- plan.source === "byok" ? trimByok(byok, byok.runtime) : undefined;
+ plan.source === "byok" ? mainByok.config() : undefined;
const runtime =
plan.source === "local"
? "local"
: plan.source === "byok"
- ? byok.runtime
+ ? byokRuntime
: plan.runtime === "pi"
? "recommended"
: plan.runtime;
@@ -3283,22 +4064,11 @@
signInByokOpen = !signInByokOpen;
render();
});
- for (const [id, field] of [
- ["signin-byok-url", "baseUrl"],
- ["signin-byok-key", "apiKey"],
- ["signin-byok-model", "modelId"],
- ])
- $(id).addEventListener("input", () => {
- signInByok = { ...signInByok, [field]: $(id).value };
- render();
- });
$("runtime-signin-byok").addEventListener("submit", async (event) => {
event.preventDefault();
- const runtime = state.localServer.signIn?.runtime ?? "claude";
- if (!signInByok.baseUrl.trim() || !signInByok.modelId.trim()) return;
- const payload = trimByok(signInByok, runtime);
- $("signin-byok-key").value = "";
- signInByok = { ...signInByok, apiKey: "" };
+ if (!signInByok.complete()) return;
+ const payload = signInByok.config();
+ signInByok.clearKey();
await run(
{ op: "local.signin.byok", byok: payload },
"runtime-signin-error",
@@ -3348,10 +4118,8 @@
);
const clearKeys = () => {
keys = {};
- byok = { ...byok, apiKey: "" };
- $("byok-key").value = "";
- signInByok = { ...signInByok, apiKey: "" };
- $("signin-byok-key").value = "";
+ mainByok.clearKey();
+ signInByok.clearKey();
for (const input of document.querySelectorAll("[data-key]")) {
input.value = "";
input.type = "password";
@@ -3392,9 +4160,8 @@
if (!customizing) {
picked = false;
pickedAutoBeforeCheck = false;
- byok = emptyByok();
- $("byok-url").value = "";
- $("byok-model").value = "";
+ byokRuntime = "claude";
+ mainByok.reset();
clearKeys();
const location = state.localServer.location;
if (location.custom || location.error)
@@ -3437,30 +4204,15 @@
}
render();
});
- for (const seg of document.querySelectorAll("[data-byok]"))
- for (const option of seg.querySelectorAll("button"))
- option.addEventListener("click", () => {
- picked = true;
- byok = { ...byok, [seg.dataset.byok]: option.dataset.value };
- render();
- });
- for (const [id, field] of [
- ["byok-url", "baseUrl"],
- ["byok-key", "apiKey"],
- ["byok-model", "modelId"],
- ])
- $(id).addEventListener("input", () => {
+ for (const option of document.querySelectorAll(
+ '[data-byok="runtime"] button',
+ ))
+ option.addEventListener("click", () => {
picked = true;
- byok = { ...byok, [field]: $(id).value };
+ byokRuntime = option.dataset.value;
+ mainByok.runtimeChanged();
render();
});
- $("byok-check").addEventListener("click", () => {
- if (!byok.baseUrl.trim() || !byok.modelId.trim()) return;
- run(
- { op: "local.byok.check", byok: trimByok(byok, byok.runtime) },
- "local-error",
- );
- });
$("location-change").addEventListener("click", () =>
run({ op: "local.location.pick" }),
);