From 51f52eb1a89f657e9df0858be5f37ff86917e328 Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Tue, 24 Nov 2026 21:20:12 +0800 Subject: [PATCH 1/2] feat(local-models): separate shared Bifrost gateway from model server endpoint --- apps/web/AGENTS.md | 7 +- .../local-models/local-model-details.tsx | 76 +++++++++++++-- .../features/local-models/local-model-row.tsx | 3 + .../local-models/local-models-page.test.tsx | 97 ++++++++++++++++--- .../local-models/local-models-page.tsx | 7 +- .../local-models/local-models-rules.test.ts | 16 +++ .../local-models/local-models-rules.ts | 24 +++++ .../local-models/local-models.messages.ts | 15 ++- apps/web/src/i18n/locales/zh-CN.json | 14 ++- 9 files changed, 226 insertions(+), 33 deletions(-) diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index e89e462e3..da277c020 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -79,8 +79,11 @@ build:assets` to check the initial JS budget. capability/parameter/context badges (never matched against `name` or `description`), state-distinct cards (`loaded`, `recommended`, `failed` with short failure reasons and direct `Remove` for damaged/missing - files, `unavailable`), download speed/ETA, live Bifrost (`Pi`) `Gateway` - readiness, and top diagnostic callouts with a two-column model-card facts + files, `unavailable`), download speed/ETA, live Bifrost (`Pi`) `Shared +gateway` readiness and shared `/v1` endpoint (from `model-source.status.gateway_url`, + also surfaced in Computer `Details`) clearly separated from each model's own + `Model server` address, and top diagnostic callouts with a two-column + model-card facts grid (including `Engine`, `Concurrency`, and hybrid `System memory`) from structured `LocalModel` fields in `local-models-rules.ts`, resolves Sponsor-owned Agent eligibility and `Pi` runtime switch payloads in diff --git a/apps/web/src/features/local-models/local-model-details.tsx b/apps/web/src/features/local-models/local-model-details.tsx index 4665e6cca..f54924312 100644 --- a/apps/web/src/features/local-models/local-model-details.tsx +++ b/apps/web/src/features/local-models/local-model-details.tsx @@ -51,6 +51,7 @@ import { poolOtherBytes, poolUnaccountedBytes, safeModelSourceUrl, + sharedGatewayEndpoint, speedLabel, type ModelEntry, } from "./local-models-rules"; @@ -86,7 +87,17 @@ function Fact({ ); } -function CopyEndpoint({ endpoint, name }: { endpoint: string; name: string }) { +function CopyEndpoint({ + ariaLabel, + copiedAriaLabel, + endpoint, + title, +}: { + ariaLabel: string; + copiedAriaLabel: string; + endpoint: string; + title: string; +}) { const t = useT(); const [copied, setCopied] = useState(false); const timerRef = useRef(undefined); @@ -118,7 +129,7 @@ function CopyEndpoint({ endpoint, name }: { endpoint: string; name: string }) { } return ( - + + ) : null} + + + ) : null} + + + + + {t(loopback ? m.gatewayScopeLocal : m.gatewayScopeNetwork)} + + + {t( + inferenceAuthDisabled + ? m.gatewayInferenceNoAuth + : m.gatewayInferenceKeyRequired, + )} + + + + +

+ {t(m.gatewaySharedNote)} +

+ + ) : ( +
+ {t(m.gatewayNotActive)} +
+ )} + + + {gatewayEndpoint && gatewayModels.length > 0 ? ( +
+

+ {t(m.gatewayLoadedModels)} +

+
+ {gatewayModels.map(({ entry, modelId }) => { + const idKey = `model-id:${entry.model.id}`; + const curlKey = `curl:${entry.model.id}`; + const copiedId = copiedKey === idKey; + const copiedCurl = copiedKey === curlKey; + return ( +
+
+ + {entry.model.name} + +
+ + +
+
+ + {modelId} + +
+ ); + })} +
+
+ ) : null} + +
+

+ {t(m.gatewayAdminCredentials)} +

+ {canUseDesktopGateway ? ( +
+
+ + + + + {desktopGatewayInfo?.hasPassword ? ( + + + {revealedPassword ?? "••••••••••••"} + + + + + ) : ( + + {t(m.gatewayPasswordUnavailable)} + + )} + +
+
+

+ {t(m.gatewayCredentialsLocalOnlyHint)} +

+ +
+ {credentialError ? ( + {credentialError} + ) : null} +
+ ) : ( +
+ {t(m.gatewayCredentialsDesktopOnly, { computer: computerName })} +
+ )} +
+ + ); +} + +function HardwareTabPanel({ view }: { view: LocalModelsView }) { + const t = useT(); + const host = view.computer.host; + type PoolHolder = LocalModelPool["holders"][number]; + const seenHolderIds = new Set(); + const models: PoolHolder[] = []; + const components: PoolHolder[] = []; + let hasOtherApps = false; + let hasUnaccounted = false; + for (const pool of view.pools) { + if (poolOtherBytes(pool) > 0) hasOtherApps = true; + if (poolUnaccountedBytes(pool) > 0) hasUnaccounted = true; + for (const holder of pool.holders) { + if (seenHolderIds.has(holder.id)) continue; + seenHolderIds.add(holder.id); + if (holder.kind === "model") models.push(holder); + else components.push(holder); + } + } + const colorOf = (holderId: string) => { + const index = models.findIndex((holder) => holder.id === holderId); + return index < 0 + ? componentColor + : segmentColors[index % segmentColors.length]!; + }; + + return ( +
+ {view.pools.length ? ( +
+

+ {t(m.factMemory)} +

+
+ {view.pools.map((pool) => ( + + ))} +
+ {seenHolderIds.size > 0 || hasOtherApps || hasUnaccounted ? ( +

+ {[...models, ...components].map((holder) => ( + + + {holder.name} + + ))} + {hasOtherApps ? ( + + + {t(m.otherApps)} + + ) : null} + {hasUnaccounted ? ( + + + {t(m.systemAndEngine)} + + ) : null} +

+ ) : null} +
+ ) : null} + {host ? ( +
+

+ {t(m.hardware)} +

+
+ + {formatGigabytes(host.ram_total_bytes, t)} + + {host.gpus.map((gpu) => ( + + {gpu.name} · {formatGigabytes(gpu.total_bytes, t)} + + ))} + + {formatGigabytes(host.disk_free_bytes, t)} + +
+
+ ) : null} +
+ ); +} + +function DiagnosticsTabPanel({ + computerId, + desktopGatewayInfo, + isLocalDesktop, + loadedEntries, + view, +}: { + computerId: string; + desktopGatewayInfo?: DesktopLocalGatewayInfo; + isLocalDesktop: boolean; + loadedEntries: readonly ModelEntry[]; + view: LocalModelsView; +}) { + const t = useT(); + const [diagnosticsApi] = useState(desktopDiagnostics); + const [localGateway] = useState(desktopLocalGateway); + const [saving, setSaving] = useState(false); + const [actionError, setActionError] = useState(null); + const host = view.computer.host; + const loadedServers = loadedEntries.filter((entry) => + Boolean(entry.model.endpoint?.base_url), + ); + const canOpenFolder = Boolean( + isLocalDesktop && localGateway && desktopGatewayInfo?.available, + ); + + function saveDiagnostics() { + if (!diagnosticsApi) return; + setActionError(null); + setSaving(true); + void diagnosticsApi + .save() + .catch(() => setActionError(t(m.saveDiagnosticsFailed))) + .finally(() => setSaving(false)); + } + + function openDesktopFolder() { + if (!localGateway) return; + setActionError(null); + void localGateway + .openFolder(computerId) + .catch(() => setActionError(t(m.gatewayOpenFolderFailed))); + } + + return ( +
+
+

+ {t(m.diagnosticsRuntime)} +

+
+ {host?.os_label ? ( + {host.os_label} + ) : null} + {host?.engine_label ? ( + {host.engine_label} + ) : null} + {view.tool_version ? ( + + + {view.tool_version} + + + ) : null} + + + + {view.debug ? ( + + + {t(m.debugModeValue, { mode: view.debug.mode })} + + + ) : null} +
+
+ + {loadedServers.length > 0 ? ( +
+

+ {t(m.diagnosticsModelServers)} +

+
+ {loadedServers.map((entry) => ( + + + + ))} +
+
+ ) : null} + + {diagnosticsApi || canOpenFolder ? ( +
+

+ {t(m.diagnosticsActions)} +

+
+ {diagnosticsApi ? ( + + ) : null} + {canOpenFolder && localGateway ? ( + + ) : null} +
+ {actionError ? ( +
+ {actionError} +
+ ) : null} +
+ ) : null} +
+ ); +} + +/** + * Advanced modal for one Computer: shared Bifrost gateway access & local + * desktop credentials, memory/hardware breakdown, and runtime diagnostics. + */ +export function AdvancedDialog({ + gatewayUrl, + isLocalDesktop = false, + onClose, + view, +}: { + gatewayUrl?: string; + isLocalDesktop?: boolean; + onClose: () => void; + view: LocalModelsView; +}) { + const t = useT(); + const host = view.computer.host; + const computerId = view.computer.computer_id; + const gatewayEndpoint = sharedGatewayEndpoint(gatewayUrl); + const adminUrl = gatewayAdminUrl(gatewayUrl); + const [activeTab, setActiveTab] = useState(() => + gatewayEndpoint ? "gateway" : "hardware", + ); + const [desktopGatewayInfo, setDesktopGatewayInfo] = useState< + DesktopLocalGatewayInfo | undefined + >(); + const { indicator, tabRef } = useTabIndicator(activeTab); + + useEffect(() => { + const api = desktopLocalGateway(); + if (!isLocalDesktop || !api) { + setDesktopGatewayInfo(undefined); + return; + } + let active = true; + void api + .getInfo(computerId) + .then((info) => { + if (active) setDesktopGatewayInfo(info); + }) + .catch(() => { + if (active) setDesktopGatewayInfo({ available: false }); + }); + return () => { + active = false; + }; + }, [computerId, isLocalDesktop]); + + const loadedEntries = modelEntries(view).filter( + (entry) => entry.status === "loaded", + ); + + const tabLabels: Record = { + diagnostics: t(m.advancedTabDiagnostics), + gateway: t(m.advancedTabGateway), + hardware: t(m.advancedTabHardware), + }; + + function handleTabKeyDown( + event: KeyboardEvent, + index: number, + ) { + if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return; + event.preventDefault(); + const step = event.key === "ArrowRight" ? 1 : -1; + const nextIndex = + (index + step + advancedTabs.length) % advancedTabs.length; + const nextTab = advancedTabs[nextIndex]; + if (!nextTab) return; + setActiveTab(nextTab); + const tabs = event.currentTarget + .closest('[role="tablist"]') + ?.querySelectorAll('[role="tab"]'); + tabs?.[nextIndex]?.focus(); + } + + return ( + +
+
+ {advancedTabs.map((tab, index) => ( + + ))} + {indicator} +
+
+ +
+ {activeTab === "gateway" ? ( + + ) : activeTab === "hardware" ? ( + + ) : ( + + )} +
+
+ ); +} diff --git a/apps/web/src/features/local-models/local-model-details.tsx b/apps/web/src/features/local-models/local-model-details.tsx index f54924312..7ef9433c8 100644 --- a/apps/web/src/features/local-models/local-model-details.tsx +++ b/apps/web/src/features/local-models/local-model-details.tsx @@ -9,7 +9,6 @@ import { NVIDIA_DRIVER_GUIDE_URL } from "@linger/service-kit/nvidia-driver"; import { Button } from "@/components/ui/button"; import { FormFeedback } from "@/components/ui/form-feedback"; import { Icon } from "@/components/ui/icon"; -import { ModalDialog } from "@/components/ui/modal-dialog"; import { Select, SelectItem } from "@/components/ui/select"; import type { TeamHubLocalComputerPage } from "@/features/teamhub/teamhub-types"; import { commonMessages } from "@/i18n/common.messages"; @@ -33,7 +32,7 @@ import { unavailableCopy, } from "./local-models-copy"; import { localModelsMessages as m } from "./local-models.messages"; -import type { LocalModelPool, LocalModelsView } from "./local-models-queries"; +import type { LocalModelsView } from "./local-models-queries"; import { contextLabel, downloadStopped, @@ -49,19 +48,15 @@ import { poolLabel, poolOf, poolOtherBytes, - poolUnaccountedBytes, safeModelSourceUrl, sharedGatewayEndpoint, speedLabel, type ModelEntry, } from "./local-models-rules"; -/** Category colors from the Nature palette, one per model holding memory. */ -const segmentColors = ["bg-rain-500", "bg-lichen-500", "bg-sun-500"] as const; -/** Foundation components hold memory too, but are not models of the list. */ -const componentColor = "bg-muted-foreground/40"; +export { AdvancedDialog } from "./local-model-advanced-dialog"; -function Fact({ +export function Fact({ children, className, label, @@ -87,7 +82,7 @@ function Fact({ ); } -function CopyEndpoint({ +export function CopyEndpoint({ ariaLabel, copiedAriaLabel, endpoint, @@ -550,227 +545,3 @@ export function ModelFacts({ ); } - -function PoolBar({ - colorOf, - pool, - view, -}: { - colorOf: (holderId: string) => string; - pool: LocalModelPool; - view: LocalModelsView; -}) { - const t = useT(); - const label = poolLabel(view, pool, t); - // used_bytes is the device's real use; on a shared card other processes - // hold memory that no holder accounts for. - const otherBytes = poolOtherBytes(pool); - const unaccountedBytes = poolUnaccountedBytes(pool); - const width = (bytes: number) => - `${pool.total_bytes ? Math.min(100, (bytes / pool.total_bytes) * 100) : 0}%`; - return ( -
- - {pool.kind === "gpu" - ? t(m.gpuIndex, { index: String(pool.gpu_index) }) - : label} - - - {pool.holders - .filter((holder) => holder.bytes > 0) - .map((holder) => ( - - ))} - {otherBytes ? ( - - ) : null} - {unaccountedBytes ? ( - - ) : null} - - - {t(m.memoryFree, { free: formatGigabytes(poolFreeBytes(pool), t) })} - -
- ); -} - -/** Memory, hardware, and shared gateway of one Computer, for people who want the numbers. */ -export function AdvancedDialog({ - gatewayUrl, - onClose, - view, -}: { - gatewayUrl?: string; - onClose: () => void; - view: LocalModelsView; -}) { - const t = useT(); - const host = view.computer.host; - const gatewayEndpoint = sharedGatewayEndpoint(gatewayUrl); - type PoolHolder = LocalModelPool["holders"][number]; - const seenHolderIds = new Set(); - const models: PoolHolder[] = []; - const components: PoolHolder[] = []; - let hasOtherApps = false; - let hasUnaccounted = false; - for (const pool of view.pools) { - if (poolOtherBytes(pool) > 0) hasOtherApps = true; - if (poolUnaccountedBytes(pool) > 0) hasUnaccounted = true; - for (const holder of pool.holders) { - if (seenHolderIds.has(holder.id)) continue; - seenHolderIds.add(holder.id); - if (holder.kind === "model") models.push(holder); - else components.push(holder); - } - } - const colorOf = (holderId: string) => { - const index = models.findIndex((holder) => holder.id === holderId); - return index < 0 - ? componentColor - : segmentColors[index % segmentColors.length]!; - }; - - return ( - -
- {view.pools.length ? ( -
-

- {t(m.factMemory)} -

-
- {view.pools.map((pool) => ( - - ))} -
- {seenHolderIds.size > 0 || hasOtherApps || hasUnaccounted ? ( -

- {[...models, ...components].map((holder) => ( - - - {holder.name} - - ))} - {hasOtherApps ? ( - - - {t(m.otherApps)} - - ) : null} - {hasUnaccounted ? ( - - - {t(m.systemAndEngine)} - - ) : null} -

- ) : null} -
- ) : null} - {host ? ( -
-

- {t(m.hardware)} -

-
- {host.os_label ? ( - {host.os_label} - ) : null} - {host.engine_label ? ( - {host.engine_label} - ) : null} - - {formatGigabytes(host.ram_total_bytes, t)} - - {host.gpus.map((gpu) => ( - - {gpu.name} · {formatGigabytes(gpu.total_bytes, t)} - - ))} - - {formatGigabytes(host.disk_free_bytes, t)} - -
-
- ) : null} - {gatewayEndpoint ? ( -
-

- {t(m.gatewaySection)} -

-
- - - -
-

- {t(m.gatewaySharedNote)} -

-
- ) : null} -
-
- ); -} diff --git a/apps/web/src/features/local-models/local-models-page.test.tsx b/apps/web/src/features/local-models/local-models-page.test.tsx index a9610fd98..79bedc5eb 100644 --- a/apps/web/src/features/local-models/local-models-page.test.tsx +++ b/apps/web/src/features/local-models/local-models-page.test.tsx @@ -389,12 +389,12 @@ describe("LocalModelsPage", () => { ); }); - it("shows the Computer's pools and hardware in Details", async () => { + it("shows the Computer's pools and hardware in Advanced", async () => { await renderPage(setup()); await findModels(); - fireEvent.click(screen.getByRole("button", { name: "Details" })); - const dialog = screen.getByRole("dialog", { name: "lab-118 details" }); + fireEvent.click(screen.getByRole("button", { name: "Advanced" })); + const dialog = screen.getByRole("dialog", { name: "lab-118 · Advanced" }); expect( within(dialog).getByRole("img", { name: "GPU 0 · RTX 4090: 21.4 GB of 24 GB in use", @@ -413,8 +413,8 @@ describe("LocalModelsPage", () => { ); await findModels(); - fireEvent.click(screen.getByRole("button", { name: "Details" })); - const dialog = screen.getByRole("dialog", { name: "lab-118 details" }); + fireEvent.click(screen.getByRole("button", { name: "Advanced" })); + const dialog = screen.getByRole("dialog", { name: "lab-118 · Advanced" }); expect(within(dialog).getByTitle("Other apps · 15 GB")).toHaveStyle({ width: "62.5%", }); @@ -1280,7 +1280,7 @@ describe("LocalModelsPage", () => { screen.queryByRole("region", { name: "Models" }), ).not.toBeInTheDocument(); expect( - screen.queryByRole("button", { name: "Details" }), + screen.queryByRole("button", { name: "Advanced" }), ).not.toBeInTheDocument(); expect( screen.queryByRole("button", { name: "Recheck memory" }), @@ -1687,14 +1687,154 @@ describe("LocalModelsPage", () => { "Model serverhttp://127.0.0.1:18103/v1", ); - // Computer Details modal also surfaces the shared Bifrost gateway instance. - fireEvent.click(screen.getByRole("button", { name: "Details" })); - const dialog = screen.getByRole("dialog", { name: "lab-118 details" }); - expect(dialog).toHaveTextContent("Gateway"); - expect(dialog).toHaveTextContent("Shared gatewayhttp://127.0.0.1:18480/v1"); + // Computer Advanced dialog opens on Gateway & access, lists loaded Gateway + // Model IDs with copyable curl snippets, keeps credentials local-only in a + // browser, and exposes Memory & hardware + Diagnostics tabs. + const writeText = vi.fn(async () => {}); + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + + fireEvent.click(screen.getByRole("button", { name: "Advanced" })); + const dialog = screen.getByRole("dialog", { name: "lab-118 · Advanced" }); + expect( + within(dialog).getByRole("tab", { + name: "Gateway & access", + selected: true, + }), + ).toBeVisible(); + expect(dialog).toHaveTextContent("API endpointhttp://127.0.0.1:18480/v1"); + expect(dialog).toHaveTextContent("Admin consolehttp://127.0.0.1:18480"); + expect(dialog).toHaveTextContent("Local only (127.0.0.1)"); + expect(dialog).toHaveTextContent("qwen3-coder-30b"); + expect(dialog).toHaveTextContent("spark-4b"); expect(dialog).toHaveTextContent( - "All loaded local models on this computer share one Bifrost gateway instance.", + "Bifrost admin credentials stay strictly local on lab-118", + ); + expect( + within(dialog).queryByRole("button", { name: "Show gateway password" }), + ).toBeNull(); + + fireEvent.click( + within(dialog).getByRole("button", { + name: "Copy curl command for Spark 4B", + }), + ); + expect(writeText).toHaveBeenCalledWith( + 'curl http://127.0.0.1:18480/v1/chat/completions -H "Content-Type: application/json" -d \'{"messages":[{"content":"Hello","role":"user"}],"model":"spark-4b"}\'', ); + + // Switch to Diagnostics tab and verify runtime + per-model backend servers. + fireEvent.click(within(dialog).getByRole("tab", { name: "Diagnostics" })); + expect(dialog).toHaveTextContent("0.9.0"); + expect(dialog).toHaveTextContent("computer-lab"); + expect(dialog).toHaveTextContent("http://127.0.0.1:18100/v1"); + expect(dialog).toHaveTextContent("http://127.0.0.1:18103/v1"); + }); + + it("reveals and copies local Bifrost admin credentials in Advanced only on this computer's Linger Desktop", async () => { + const revealPassword = vi.fn(async () => ({ password: "local-admin-pw" })); + const copyPassword = vi.fn(async () => ({ + clearAfterMs: 60_000, + copied: true, + })); + const openAdmin = vi.fn(async () => {}); + const openFolder = vi.fn(async () => {}); + const saveDiagnostics = vi.fn(async () => {}); + const getInfo = vi.fn(async () => ({ + adminUrl: "http://127.0.0.1:18480", + available: true, + hasPassword: true, + inferenceAuthDisabled: true, + username: "admin", + })); + + (window as { lingerDesktop?: unknown }).lingerDesktop = { + computer: { + enroll: vi.fn(), + getStatus: async () => ({ + activeOperations: 0, + bridge: "connected", + computerId: "computer-lab", + runtime: "ready", + }), + onStatus: () => () => {}, + }, + diagnostics: { save: saveDiagnostics }, + localGateway: { + copyPassword, + getInfo, + openAdmin, + openFolder, + revealPassword, + }, + }; + + const fixture = setup([labView()]); + fixture.runtime.server.on("GET", modelSourcePath, ({ params }) => + Response.json({ + computer_id: params.computerId, + online: true, + status: { + byok: { configured: false, key_saved: false }, + gateway_url: "http://127.0.0.1:18480", + mode: "local", + runtime: "pi", + runtime_model: "localmodels-library/qwen3-coder-30b", + }, + viewer_is_owner: true, + }), + ); + + await renderPage(fixture); + await findModels(); + + fireEvent.click(screen.getByRole("button", { name: "Advanced" })); + const dialog = screen.getByRole("dialog", { name: "lab-118 · Advanced" }); + + await waitFor(() => expect(getInfo).toHaveBeenCalledWith("computer-lab")); + expect(await within(dialog).findByText("••••••••••••")).toBeVisible(); + expect(dialog).not.toHaveTextContent("local-admin-pw"); + + // Reveal password on demand. + fireEvent.click( + within(dialog).getByRole("button", { name: "Show gateway password" }), + ); + expect(await within(dialog).findByText("local-admin-pw")).toBeVisible(); + expect(revealPassword).toHaveBeenCalledWith("computer-lab"); + + // Copy password through main process (clears clipboard after 60s). + fireEvent.click( + within(dialog).getByRole("button", { name: "Copy gateway password" }), + ); + await waitFor(() => + expect(copyPassword).toHaveBeenCalledWith("computer-lab"), + ); + expect( + await within(dialog).findByText("Copied · clears in 60s"), + ).toBeVisible(); + + // Open admin console and gateway folder via Desktop IPC. + fireEvent.click(within(dialog).getByRole("button", { name: "Open" })); + expect(openAdmin).toHaveBeenCalledWith("computer-lab"); + fireEvent.click( + within(dialog).getByRole("button", { name: "Open gateway folder" }), + ); + expect(openFolder).toHaveBeenCalledWith("computer-lab"); + + // Switching tabs clears the revealed password and exposes Save diagnostics. + fireEvent.click(within(dialog).getByRole("tab", { name: "Diagnostics" })); + fireEvent.click( + within(dialog).getByRole("button", { name: "Save diagnostics" }), + ); + await waitFor(() => expect(saveDiagnostics).toHaveBeenCalledOnce()); + + fireEvent.click( + within(dialog).getByRole("tab", { name: "Gateway & access" }), + ); + expect(dialog).not.toHaveTextContent("local-admin-pw"); + expect(await within(dialog).findByText("••••••••••••")).toBeVisible(); }); it("reflects Pi runtime setup, catalog registration, and failure states in the Shared gateway row", async () => { @@ -3364,10 +3504,10 @@ describe("Model source", () => { "Research agent uses this model. Load it so it can answer.", ); - // Details modal includes Other apps in the legend when external apps hold memory. - fireEvent.click(screen.getByRole("button", { name: "Details" })); + // Advanced modal includes Other apps in the legend when external apps hold memory. + fireEvent.click(screen.getByRole("button", { name: "Advanced" })); const detailsDialog = screen.getByRole("dialog", { - name: "Workstation details", + name: "Workstation · Advanced", }); expect(detailsDialog).toHaveTextContent("Other apps"); fireEvent.click( @@ -4981,6 +5121,12 @@ describe("Featured Inkling 2 Mini spotlight", () => { expect(inklingCard).toHaveTextContent("2 concurrent requests"); expect(within(inklingCard).queryByText("System memory")).toBeNull(); + // Advanced dialog surfaces both host engines from host.engine_label. + fireEvent.click(screen.getByRole("button", { name: "Advanced" })); + const dialog = screen.getByRole("dialog"); + expect(dialog).toHaveTextContent( + "Ubuntu 24.04 · llama.cpp b11370 · CUDA + PolyStrata 0.2.19-poly.1 · CUDA", + ); // Chinese locale keeps product engine names and translates labels and hints. await reactAct(async () => { await setLanguage("zh-CN"); diff --git a/apps/web/src/features/local-models/local-models-page.tsx b/apps/web/src/features/local-models/local-models-page.tsx index c564c0dc2..218be66c8 100644 --- a/apps/web/src/features/local-models/local-models-page.tsx +++ b/apps/web/src/features/local-models/local-models-page.tsx @@ -4,6 +4,7 @@ import { ArrowDown01Icon, InformationCircleIcon, RefreshIcon, + SlidersHorizontalIcon, } from "@hugeicons/core-free-icons"; import { useMutation, @@ -227,6 +228,10 @@ export function ModelsPage() { ) : null} @@ -747,7 +753,8 @@ function ComputerModels({ onClick={() => setDialog({ kind: "advanced" })} size="compact" > - {t(m.details)} + + {t(m.advanced)} ) : null} @@ -1915,6 +1922,7 @@ function Library({ {dialog?.kind === "advanced" ? ( setDialog(null)} view={view} /> diff --git a/apps/web/src/features/local-models/local-models-rules.test.ts b/apps/web/src/features/local-models/local-models-rules.test.ts index 2adf55b4a..3cff4b49c 100644 --- a/apps/web/src/features/local-models/local-models-rules.test.ts +++ b/apps/web/src/features/local-models/local-models-rules.test.ts @@ -22,7 +22,11 @@ import { downloadStopped, featuredInklingEntry, formatGigabytes, + gatewayAdminUrl, + gatewayCurlSnippet, + gatewayModelId, hostBlocker, + isLoopbackUrl, isModelOnComputer, loadCheck, localSwitchTargets, @@ -704,6 +708,34 @@ describe("local models rules", () => { expect(sharedGatewayEndpoint("ftp://127.0.0.1:18480")).toBeUndefined(); expect(sharedGatewayEndpoint("not a url")).toBeUndefined(); expect(sharedGatewayEndpoint(undefined)).toBeUndefined(); + expect(gatewayAdminUrl("http://127.0.0.1:18480/v1/")).toBe( + "http://127.0.0.1:18480", + ); + expect(gatewayAdminUrl("http://127.0.0.1:18480")).toBe( + "http://127.0.0.1:18480", + ); + expect(gatewayAdminUrl("ftp://127.0.0.1:18480")).toBeUndefined(); + expect(isLoopbackUrl("http://127.0.0.1:18480/v1")).toBe(true); + expect(isLoopbackUrl("http://localhost:18480")).toBe(true); + expect(isLoopbackUrl("http://192.168.1.10:18480")).toBe(false); + expect( + gatewayModelId({ + pi_model: + "localmodels-library/localmodels-lib-inkling-2-mini/Inkling-2-Mini", + }), + ).toBe("localmodels-lib-inkling-2-mini/Inkling-2-Mini"); + expect( + gatewayModelId({ pi_model: "localmodels-library/" }), + ).toBeUndefined(); + expect(gatewayModelId({ pi_model: undefined })).toBeUndefined(); + expect( + gatewayCurlSnippet( + "http://127.0.0.1:18480/v1", + "localmodels-lib-spark/Spark-4B", + ), + ).toBe( + 'curl http://127.0.0.1:18480/v1/chat/completions -H "Content-Type: application/json" -d \'{"messages":[{"content":"Hello","role":"user"}],"model":"localmodels-lib-spark/Spark-4B"}\'', + ); expect( downloadStatusDetail( localModel({ diff --git a/apps/web/src/features/local-models/local-models-rules.ts b/apps/web/src/features/local-models/local-models-rules.ts index dd57833ac..5d1db552a 100644 --- a/apps/web/src/features/local-models/local-models-rules.ts +++ b/apps/web/src/features/local-models/local-models-rules.ts @@ -990,6 +990,74 @@ export function sharedGatewayEndpoint( } } +/** + * Normalizes a Computer's shared Bifrost gateway URL to its root admin console + * address (without a trailing `/v1`). + */ +export function gatewayAdminUrl( + gatewayUrl: string | undefined, +): string | undefined { + if (!gatewayUrl) return undefined; + try { + const parsed = new URL(gatewayUrl); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + return undefined; + } + const trimmedPath = parsed.pathname + .replace(/\/+$/, "") + .replace(/\/v1$/, ""); + return `${parsed.origin}${trimmedPath}`; + } catch { + return undefined; + } +} + +/** Whether a URL targets the local loopback interface. */ +export function isLoopbackUrl(url: string | undefined): boolean { + if (!url) return false; + try { + const host = new URL(url).hostname.toLowerCase(); + return ( + host === "127.0.0.1" || + host === "localhost" || + host === "[::1]" || + host === "::1" + ); + } catch { + return false; + } +} + +const PI_LIBRARY_PROVIDER_PREFIX = "localmodels-library/"; + +/** + * Derives the OpenAI-compatible `model` ID served on the shared Bifrost `/v1` + * endpoint from a loaded model's `pi_model` selector. + */ +export function gatewayModelId( + model: Pick, +): string | undefined { + const selector = model.pi_model?.trim(); + if (!selector) return undefined; + if (selector.startsWith(PI_LIBRARY_PROVIDER_PREFIX)) { + const stripped = selector.slice(PI_LIBRARY_PROVIDER_PREFIX.length).trim(); + return stripped || undefined; + } + return selector; +} + +/** Copy-ready `curl` example targeting a model through the shared Bifrost `/v1` endpoint. */ +export function gatewayCurlSnippet( + gatewayEndpoint: string, + modelId: string, +): string { + const payload = JSON.stringify({ + messages: [{ content: "Hello", role: "user" }], + model: modelId, + }); + return `curl ${gatewayEndpoint}/chat/completions -H "Content-Type: application/json" -d '${payload}'`; +} + /** Candidate local models on disk ordered loaded-first, recommended, then largest. */ export function localSwitchTargets(view: LocalModelsView): LocalModel[] { return view.models diff --git a/apps/web/src/features/local-models/local-models.messages.ts b/apps/web/src/features/local-models/local-models.messages.ts index 202b7ce2b..9255476c9 100644 --- a/apps/web/src/features/local-models/local-models.messages.ts +++ b/apps/web/src/features/local-models/local-models.messages.ts @@ -30,7 +30,11 @@ export const localModelsMessages = defineMessages("localModels", { memoryFree: "{free} free", memoryFreeChecked: "{free} free · Checked {time}", recheckMemory: "Recheck memory", - details: "Details", + advanced: "Advanced", + advancedOf: "{name} · Advanced", + advancedTabGateway: "Gateway & access", + advancedTabHardware: "Memory & hardware", + advancedTabDiagnostics: "Diagnostics", retrying: "Retrying…", switchingComputer: "Switching {computer}. This can take a few minutes the first time.", @@ -167,6 +171,59 @@ export const localModelsMessages = defineMessages("localModels", { gatewaySection: "Gateway", gatewaySharedNote: "All loaded local models on this computer share one Bifrost gateway instance.", + gatewayApiEndpoint: "API endpoint", + gatewayAdminConsole: "Admin console", + gatewayOpenConsole: "Open", + copyGatewayAdminUrl: "Copy admin console address", + copiedGatewayAdminUrl: "Copied admin console address", + gatewayAccessScope: "Access scope", + gatewayScopeLocal: "Local only (127.0.0.1)", + gatewayScopeNetwork: "Network address", + gatewayInferenceNoAuth: "No API key required on localhost", + gatewayInferenceKeyRequired: "API key required", + gatewayNotActive: + "No shared Bifrost gateway is active on this computer yet. Load a local model or save a BYOK endpoint to start it.", + gatewayLoadedModels: "Loaded models (OpenAI-compatible API)", + copyModelId: "Copy ID", + copyGatewayModelId: "Copy {name} gateway model ID", + copiedGatewayModelId: "Copied {name} gateway model ID", + copyCurl: "Copy curl", + copyGatewayCurl: "Copy curl command for {name}", + copiedGatewayCurl: "Copied curl command for {name}", + gatewayAdminCredentials: "Admin credentials", + gatewayUsername: "Username", + copyGatewayUsername: "Copy gateway username", + copiedGatewayUsername: "Copied gateway username", + gatewayPassword: "Password", + showGatewayPassword: "Show gateway password", + hideGatewayPassword: "Hide gateway password", + copyGatewayPassword: "Copy gateway password", + copiedGatewayPassword: "Copied gateway password", + copiedClearsSoon: "Copied · clears in 60s", + gatewayPasswordUnavailable: "Not found on this computer", + gatewayCredentialsLocalOnlyHint: + "Read directly from this computer and never sent over the network.", + gatewayCredentialsDesktopOnly: + "Bifrost admin credentials stay strictly local on {computer} and are never sent over the network. Open Linger Desktop on that computer to view or copy them.", + gatewayOpenFolder: "Open gateway folder", + gatewayCredentialReadFailed: + "Couldn't read the local Bifrost admin password. Check that admin-password is private (chmod 600).", + gatewayOpenAdminFailed: + "Couldn't open the local Bifrost console in your browser.", + gatewayOpenFolderFailed: "Couldn't open the local Bifrost folder.", + diagnosticsRuntime: "Runtime", + factOs: "System", + factLocalModelsTool: "Local models tool", + factComputerId: "Computer ID", + copyComputerId: "Copy computer ID", + copiedComputerId: "Copied computer ID", + factDebugMode: "Debug mode", + debugModeValue: "Active ({mode})", + diagnosticsModelServers: "Backend model servers", + diagnosticsActions: "Local tools", + saveDiagnostics: "Save diagnostics", + saveDiagnosticsFailed: + "Couldn't save diagnostics. Try again from the tray menu.", factLastDownload: "Last download", factLastLoad: "Last load", factWhyNot: "Why not", diff --git a/apps/web/src/features/rooms/chat/voice-mode/voice-risk-markers.test.ts b/apps/web/src/features/rooms/chat/voice-mode/voice-risk-markers.test.ts index e02981422..e6c30fe8f 100644 --- a/apps/web/src/features/rooms/chat/voice-mode/voice-risk-markers.test.ts +++ b/apps/web/src/features/rooms/chat/voice-mode/voice-risk-markers.test.ts @@ -35,6 +35,8 @@ for (const exports of Object.values(messageModules)) const notActions: Record = { "/src/features/auth/teamhub-login-page.tsx: auth.hidePassword": "shows or hides the password in place; it closes nothing", + "/src/features/local-models/local-model-advanced-dialog.tsx: localModels.hideGatewayPassword": + "shows or hides the gateway password in place; it closes nothing", "/src/features/rooms/chat/room-notice-row.tsx: chat.hideChanges": "folds the change list in place; it closes nothing", "/src/features/rooms/task-sidebar/collaboration-panel.tsx: collaboration.hideSource": diff --git a/apps/web/src/i18n/locales/zh-CN.json b/apps/web/src/i18n/locales/zh-CN.json index 6e7add4bc..efd01af41 100644 --- a/apps/web/src/i18n/locales/zh-CN.json +++ b/apps/web/src/i18n/locales/zh-CN.json @@ -1171,7 +1171,11 @@ "memoryFree": "可用 {free}", "memoryFreeChecked": "可用 {free} · {time}检测", "recheckMemory": "重新检测内存", - "details": "详情", + "advanced": "高级选项", + "advancedOf": "{name} · 高级选项", + "advancedTabGateway": "网关与接入", + "advancedTabHardware": "内存与硬件", + "advancedTabDiagnostics": "诊断", "retrying": "正在重试…", "switchingComputer": "正在切换 {computer}。首次切换可能需要几分钟。", "offlineByok": "{name} 已离线。请在电脑设置中重新连接,再测试或更改它的模型来源。", @@ -1289,6 +1293,53 @@ "gatewayPiUnavailable": "Bifrost · Pi 不可用", "gatewaySection": "网关", "gatewaySharedNote": "这台电脑上所有已加载的本地模型共用同一个 Bifrost 网关实例。", + "gatewayApiEndpoint": "API 端点", + "gatewayAdminConsole": "管理控制台", + "gatewayOpenConsole": "打开", + "copyGatewayAdminUrl": "复制管理控制台地址", + "copiedGatewayAdminUrl": "已复制管理控制台地址", + "gatewayAccessScope": "监听范围", + "gatewayScopeLocal": "仅本机(127.0.0.1)", + "gatewayScopeNetwork": "网络地址", + "gatewayInferenceNoAuth": "本机推理无需 API 密钥", + "gatewayInferenceKeyRequired": "需要 API 密钥", + "gatewayNotActive": "这台电脑尚未启动共享 Bifrost 网关。加载本地模型或保存 BYOK 端点后将自动启动。", + "gatewayLoadedModels": "已加载模型(OpenAI 兼容 API)", + "copyModelId": "复制 ID", + "copyGatewayModelId": "复制 {name} 的网关模型 ID", + "copiedGatewayModelId": "已复制 {name} 的网关模型 ID", + "copyCurl": "复制 curl", + "copyGatewayCurl": "复制 {name} 的 curl 命令", + "copiedGatewayCurl": "已复制 {name} 的 curl 命令", + "gatewayAdminCredentials": "管理控制台凭证", + "gatewayUsername": "用户名", + "copyGatewayUsername": "复制网关用户名", + "copiedGatewayUsername": "已复制网关用户名", + "gatewayPassword": "密码", + "showGatewayPassword": "显示网关密码", + "hideGatewayPassword": "隐藏网关密码", + "copyGatewayPassword": "复制网关密码", + "copiedGatewayPassword": "已复制网关密码", + "copiedClearsSoon": "已复制 · 60 秒后清空", + "gatewayPasswordUnavailable": "未在这台电脑上找到", + "gatewayCredentialsLocalOnlyHint": "仅从本机直接读取,不会通过网络传输。", + "gatewayCredentialsDesktopOnly": "Bifrost 管理凭证仅保存在 {computer} 本机,绝不通过网络传输。请在该电脑上打开 Linger 桌面端查看或复制。", + "gatewayOpenFolder": "打开网关目录", + "gatewayCredentialReadFailed": "无法读取本机 Bifrost 管理密码,请检查 admin-password 文件是否为仅当前用户可读(chmod 600)。", + "gatewayOpenAdminFailed": "无法在浏览器中打开本机 Bifrost 管理控制台。", + "gatewayOpenFolderFailed": "无法打开本机 Bifrost 目录。", + "diagnosticsRuntime": "运行环境", + "factOs": "系统", + "factLocalModelsTool": "本地模型工具", + "factComputerId": "电脑 ID", + "copyComputerId": "复制电脑 ID", + "copiedComputerId": "已复制电脑 ID", + "factDebugMode": "调试模式", + "debugModeValue": "已启用({mode})", + "diagnosticsModelServers": "后端模型服务", + "diagnosticsActions": "本机工具", + "saveDiagnostics": "保存诊断包", + "saveDiagnosticsFailed": "保存诊断包失败,请重试或从托盘菜单保存。", "factLastDownload": "上次下载", "factLastLoad": "上次加载", "factWhyNot": "不可用原因", diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md index 4c4add0d6..f56089839 100644 --- a/packages/local-installation/AGENTS.md +++ b/packages/local-installation/AGENTS.md @@ -268,7 +268,10 @@ when present, else `/runtime/localmodels/bifrost-addr`, and on commands that may plan or start Bifrost defaults to `127.0.0.1:18480` when free across loopback and local interfaces or allocates and persists an ephemeral port free across local interfaces when `18480` is held by another process; stop and -read-only calls never probe or allocate a port. +read-only calls never probe or allocate a port. `resolveLocalmodelsBifrostLocation` +exposes the same read-only Bifrost directory and address resolution (reusing +`legacyLocalmodelsTools` without writing a marker and `resolveLocalmodelsBifrostAddr` +with `allocate: false`) for Desktop's local gateway reader. A home whose Quick Install ran before per-home isolation (0.1.6 and earlier) keeps its plan's deployments, Pi profile and Bifrost in localmodels' default `~/.local/share/localmodels/tools`, so it stays there: when the home has no diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.ts index 698db38e4..814dfac3c 100644 --- a/packages/local-installation/src/localmodels-tool.test.ts +++ b/packages/local-installation/src/localmodels-tool.test.ts @@ -37,6 +37,7 @@ import { prefetchLocalmodelsBifrost, readPublishedTool, resolveLocalmodelsBifrostAddr, + resolveLocalmodelsBifrostLocation, runLocalmodels, stopLocalmodels, validateToolSource, @@ -2864,3 +2865,69 @@ print(json.dumps({"ok": True})) }, 120_000, ); + +test("resolveLocalmodelsBifrostLocation stays read-only and never leaks another home's legacy gateway", async () => { + const f = await fixture(); + const otherHome = await mkdtemp(path.join(os.tmpdir(), "linger-other-home-")); + roots.push(otherHome); + await legacyLayout(f.home, "qwen3.8-27b-18100", otherHome); + + // Another home owns the shared legacy deployment, so this home stays isolated. + const isolated = await resolveLocalmodelsBifrostLocation(f.home); + expect(isolated).toEqual({ + bifrostDir: localmodelsBifrostDirectory(f.home), + addr: "127.0.0.1:18480", + }); + await expect(stat(localmodelsBifrostDirectory(f.home))).rejects.toMatchObject( + { code: "ENOENT" }, + ); + await expect(stat(localmodelsBifrostAddrFile(f.home))).rejects.toMatchObject({ + code: "ENOENT", + }); + await expect( + stat(localmodelsLegacyToolsMarkerFile(f.home)), + ).rejects.toMatchObject({ code: "ENOENT" }); + + // Per-home bifrost-addr and owned.json take precedence in the same order as runtime. + await mkdir(path.dirname(localmodelsBifrostAddrFile(f.home)), { + recursive: true, + mode: 0o700, + }); + await writeFile(localmodelsBifrostAddrFile(f.home), "127.0.0.1:49201\n", { + mode: 0o600, + }); + expect(await resolveLocalmodelsBifrostLocation(f.home)).toEqual({ + bifrostDir: localmodelsBifrostDirectory(f.home), + addr: "127.0.0.1:49201", + }); + + await mkdir(localmodelsToolsDirectory(f.home), { + recursive: true, + mode: 0o700, + }); + await writeFile( + path.join(localmodelsToolsDirectory(f.home), "owned.json"), + JSON.stringify({ + schema: "localmodels.owned/v1", + gateway: { bifrost: { addr: "127.0.0.1:49202" } }, + }), + { mode: 0o644 }, + ); + expect(await resolveLocalmodelsBifrostLocation(f.home)).toEqual({ + bifrostDir: localmodelsBifrostDirectory(f.home), + addr: "127.0.0.1:49202", + }); +}); + +test("resolveLocalmodelsBifrostLocation resolves a verified legacy home without writing the marker", async () => { + const f = await fixture(); + const { legacyBifrost } = await legacyLayout(f.home, "qwen3.8-27b-18100"); + const resolved = await resolveLocalmodelsBifrostLocation(f.home); + expect(resolved).toEqual({ + bifrostDir: legacyBifrost, + addr: "127.0.0.1:18480", + }); + await expect( + stat(localmodelsLegacyToolsMarkerFile(f.home)), + ).rejects.toMatchObject({ code: "ENOENT" }); +}); diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts index c40fe2364..401b3934c 100644 --- a/packages/local-installation/src/localmodels-tool.ts +++ b/packages/local-installation/src/localmodels-tool.ts @@ -640,7 +640,7 @@ export function localmodelsBifrostAddrFile(home: string): string { "bifrost-addr", ); } -function parseLoopbackBifrostAddress( +export function parseLoopbackBifrostAddress( raw: unknown, ): LoopbackBifrostAddress | undefined { if (typeof raw !== "string") return undefined; @@ -673,6 +673,13 @@ export function localmodelsLegacyToolsMarkerFile(home: string): string { export function legacyLocalmodelsToolsDirectory(): string { return path.join(os.homedir(), ".local", "share", "localmodels", "tools"); } +/** + * localmodels' own default Bifrost directory (~/.local/share/localmodels/bifrost), + * used only when a legacy home's shared owned.json omits gateway.bifrost.app_dir. + */ +function legacyLocalmodelsBifrostDirectory(): string { + return path.join(os.homedir(), ".local", "share", "localmodels", "bifrost"); +} // owned.json and plan.json are written by localmodels with the process umask // rather than 0600, so this checks for a regular owned file of bounded size. async function readOwnedJson(file: string): Promise { @@ -745,6 +752,7 @@ function planDeploymentNames(plan: unknown): string[] { */ export async function legacyLocalmodelsTools( home: string, + options: { persist?: boolean } = {}, ): Promise { const marker = localmodelsLegacyToolsMarkerFile(home); const recorded = (await readPrivate(marker).catch(() => undefined))?.trim(); @@ -779,8 +787,10 @@ export async function legacyLocalmodelsTools( ); }; if (!names.some(ownsHere)) return undefined; - await privateDirectory(path.dirname(marker)); - await atomicPrivate(marker, `${legacy}\n`); + if (options.persist ?? true) { + await privateDirectory(path.dirname(marker)); + await atomicPrivate(marker, `${legacy}\n`); + } return legacy; } async function readSavedBifrostAddress( @@ -868,6 +878,33 @@ export async function resolveLocalmodelsBifrostAddr( resolvingBifrostAddr.delete(key); } } + +export interface LocalmodelsBifrostLocation { + readonly bifrostDir: string; + readonly addr: string; +} + +/** + * Read-only resolution of the Bifrost app directory and loopback address that + * localmodels runs for this home. Mirrors `localmodelsIsolation` without + * creating directories, writing legacy markers, or allocating ports. + */ +export async function resolveLocalmodelsBifrostLocation( + home: string, +): Promise { + const legacy = await legacyLocalmodelsTools(home, { persist: false }); + if (legacy) { + const owned = await readOwnedBifrost(legacy); + return { + bifrostDir: owned.appDir ?? legacyLocalmodelsBifrostDirectory(), + addr: owned.address?.addr ?? DEFAULT_BIFROST_ADDR, + }; + } + return { + bifrostDir: localmodelsBifrostDirectory(home), + addr: await resolveLocalmodelsBifrostAddr(home, { allocate: false }), + }; +} function formatDownloadedBytes(bytes: number): string { if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;