diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index dd0ac4746..a5f66c896 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -591,11 +591,23 @@ Gateway and runs Agents. The daemon exits with the app. RTX DCH WHQL downloads (allowlisted CDN, Windows Authenticode check, elevated `-s -noreboot -noeula` install, `PowerGuard` sleep block, and `config.json` `pendingDriverUpdate` post-reboot resume) with `getInstallState` / - `onInstallState` / `startInstall` / `clearInstallState`; and + `onInstallState` / `startInstall` / `clearInstallState`; `localServer.owned()` reports whether the window points at this app's own local installation regardless of startup/resume readiness, so the SPA can hide CLI daemon download entry points even during hot start or install-time - preload. + preload; and `localGateway` + (`src/main/local-gateway.ts`) resolves this home's Bifrost gateway through + `resolveLocalmodelsBifrostLocation` in `@linger/local-installation` and gives + Settings › Models Advanced local-only metadata (`username`, loopback + `adminUrl`, `hasPassword`, `inferenceAuthDisabled`), explicit-action password + reveal, 60 s auto-clearing clipboard copy (shared with `SetupAccount` via + `src/main/secret-clipboard.ts`), loopback admin console launch, and gateway + folder reveal. The `serverUrl` origin check in `DesktopIpcModule` is the + security boundary — any script running on the configured TeamHub origin can + read the enrolled `computerId` from `computer.status` and invoke + `revealPassword`; the `computerId` check only routes the UI to this desktop's + enrolled computer. Passwords never cross TeamHub APIs and are read fresh from + the private `0600` `admin-password` file in the main process. - `src/shared/api.ts`, `src/shared/shell.ts`: preload contract types and IPC channel names. - `src/main/computer-daemon.ts`: ComputerDaemon. While the computer is diff --git a/apps/desktop/src/main/desktop-ipc.test.ts b/apps/desktop/src/main/desktop-ipc.test.ts index 83a389c0e..603632478 100644 --- a/apps/desktop/src/main/desktop-ipc.test.ts +++ b/apps/desktop/src/main/desktop-ipc.test.ts @@ -32,6 +32,20 @@ const fixture = async ( servesWindow?: () => Promise; signInWithAccount?: () => Promise; } = {}, + options: { + computerId?: string; + localGateway?: { + getInfo?: () => Promise; + revealPassword?: () => Promise<{ readonly password: string }>; + copyPassword?: () => Promise<{ + readonly copied: boolean; + readonly clearAfterMs: number; + }>; + openAdmin?: () => Promise; + openFolder?: () => Promise; + dispose?: () => void; + }; + } = {}, ) => { const local = { ...stubModule("LocalServer"), @@ -82,6 +96,24 @@ const fixture = async ( })), clearInstallState: vi.fn(), }; + const gateway = options.localGateway + ? { + getInfo: vi.fn( + options.localGateway.getInfo ?? (async () => ({ available: false })), + ), + revealPassword: vi.fn( + options.localGateway.revealPassword ?? + (async () => ({ password: PASSWORD })), + ), + copyPassword: vi.fn( + options.localGateway.copyPassword ?? + (async () => ({ copied: true, clearAfterMs: 60_000 })), + ), + openAdmin: vi.fn(options.localGateway.openAdmin ?? (async () => {})), + openFolder: vi.fn(options.localGateway.openFolder ?? (async () => {})), + dispose: vi.fn(options.localGateway.dispose ?? (() => {})), + } + : undefined; const send = vi.fn(); const windows = { ...stubModule("WindowManager"), @@ -102,9 +134,16 @@ const fixture = async ( stubModule("WorkspaceGrants"), updater as never, local as never, - new DesktopIpcModule({ defaultDisplayName: "Desk", driverUpdater }), + new DesktopIpcModule({ + defaultDisplayName: "Desk", + driverUpdater, + ...(gateway ? { localGateway: gateway as never } : {}), + }), ], - { serverUrl: SERVER }, + { + serverUrl: SERVER, + ...(options.computerId ? { computerId: options.computerId } : {}), + }, bus, ); await host.start(); @@ -119,6 +158,7 @@ const fixture = async ( bus, diagnostics, driverUpdater, + gateway, language, local, power, @@ -429,3 +469,63 @@ describe("DesktopIpcModule driverUpdate", () => { await f.host.stop("quit"); }); }); + +describe("DesktopIpcModule local gateway", () => { + it("serves local Bifrost metadata and secret actions only for this desktop's enrolled computer and server origin", async () => { + const f = await fixture( + {}, + { + computerId: "computer-this-mac", + localGateway: { + getInfo: async () => ({ + available: true, + adminUrl: "http://127.0.0.1:18480", + username: "admin", + hasPassword: true, + inferenceAuthDisabled: true, + }), + }, + }, + ); + + expect( + await f.invoke(IPC.localGatewayInfo, SERVER, "computer-this-mac"), + ).toEqual({ + available: true, + adminUrl: "http://127.0.0.1:18480", + username: "admin", + hasPassword: true, + inferenceAuthDisabled: true, + }); + expect( + await f.invoke(IPC.localGatewayInfo, SERVER, "computer-other"), + ).toEqual({ available: false }); + expect(() => + f.invoke(IPC.localGatewayRevealPassword, SERVER, "computer-other"), + ).toThrow("Not allowed"); + expect(() => + f.invoke( + IPC.localGatewayRevealPassword, + "https://evil.example.com", + "computer-this-mac", + ), + ).toThrow("Not allowed"); + + expect( + await f.invoke( + IPC.localGatewayRevealPassword, + SERVER, + "computer-this-mac", + ), + ).toEqual({ password: PASSWORD }); + expect( + await f.invoke(IPC.localGatewayCopyPassword, SERVER, "computer-this-mac"), + ).toEqual({ copied: true, clearAfterMs: 60_000 }); + await f.invoke(IPC.localGatewayOpenAdmin, SERVER, "computer-this-mac"); + await f.invoke(IPC.localGatewayOpenFolder, SERVER, "computer-this-mac"); + expect(f.gateway!.openAdmin).toHaveBeenCalledOnce(); + expect(f.gateway!.openFolder).toHaveBeenCalledOnce(); + await f.host.stop("quit"); + expect(f.gateway!.dispose).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/desktop/src/main/desktop-ipc.ts b/apps/desktop/src/main/desktop-ipc.ts index f8879ea7c..b4bed49c2 100644 --- a/apps/desktop/src/main/desktop-ipc.ts +++ b/apps/desktop/src/main/desktop-ipc.ts @@ -4,6 +4,7 @@ import { z } from "zod"; import { IPC, type ComputerStatus, + type DesktopLocalGatewayInfo, type DesktopSettings, type DesktopUpdateState, type LocalAccountSignIn, @@ -17,6 +18,7 @@ import type { DiagnosticsModule } from "./diagnostics.js"; import type { DriverUpdaterHost } from "./driver-updater.js"; import type { EnrollmentModule } from "./enrollment.js"; import type { LanguageModule } from "./language.js"; +import type { LocalGatewayService } from "./local-gateway.js"; import type { LocalServerModule } from "./local-server.js"; import type { Module, ModuleContext } from "./modules.js"; import { sameOrigin } from "./navigation.js"; @@ -30,6 +32,7 @@ import type { WindowManagerModule } from "./window-manager.js"; import type { WorkspaceGrantsModule } from "./workspace-grants.js"; const grantIdInput = z.string().min(1).max(128); +const computerIdInput = z.string().min(1).max(128); const languageInput = z.enum(LANGUAGES); // The server address is not settable from the SPA: a page served by one // server must not be able to repoint the app. It changes on app://offline. @@ -105,16 +108,19 @@ export class DesktopIpcModule implements Module { // Set on macOS only. readonly #permissions: DesktopPermissionHost | undefined; readonly #driverUpdater: DriverUpdaterHost | undefined; + readonly #localGateway: LocalGatewayService | undefined; readonly #unsubscribe: (() => void)[] = []; constructor(options: { defaultDisplayName: string; permissions?: DesktopPermissionHost; driverUpdater?: DriverUpdaterHost; + localGateway?: LocalGatewayService; }) { this.#defaultDisplayName = options.defaultDisplayName; this.#permissions = options.permissions; this.#driverUpdater = options.driverUpdater; + this.#localGateway = options.localGateway; } async start(ctx: ModuleContext): Promise { @@ -258,6 +264,43 @@ export class DesktopIpcModule implements Module { handle(IPC.updateInstall, () => updater.install()); handle(IPC.updateCheck, () => updater.check()); + const localGateway = this.#localGateway; + // Security boundary is `handle()`'s `serverUrl` origin check; `isOwnComputer` + // is a UI-routing guard so calls only target this desktop's enrolled computer. + const isOwnComputer = (computerId: unknown): boolean => { + const requested = computerIdInput.parse(computerId); + const enrolled = ctx.config.get().computerId; + return Boolean(enrolled && requested === enrolled); + }; + const requireOwnGateway = (computerId: unknown): LocalGatewayService => { + if (!localGateway || !isOwnComputer(computerId)) { + throw new Error("Not allowed"); + } + return localGateway; + }; + handle( + IPC.localGatewayInfo, + async (computerId): Promise => { + if (!localGateway || !isOwnComputer(computerId)) { + return { available: false }; + } + return localGateway.getInfo(); + }, + ); + handle(IPC.localGatewayRevealPassword, (computerId) => + requireOwnGateway(computerId).revealPassword(), + ); + handle(IPC.localGatewayCopyPassword, (computerId) => + requireOwnGateway(computerId).copyPassword(), + ); + handle(IPC.localGatewayOpenAdmin, (computerId) => + requireOwnGateway(computerId).openAdmin(), + ); + handle(IPC.localGatewayOpenFolder, (computerId) => + requireOwnGateway(computerId).openFolder(), + ); + this.#unsubscribe.push(() => localGateway?.dispose()); + const permissions = this.#permissions; if (permissions) handle(IPC.permissionAct, (step) => diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 4c653cf53..37b295d72 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url"; import { Notification, app, + clipboard, desktopCapturer, dialog, powerMonitor, @@ -36,6 +37,7 @@ import { } from "./windows-driver-platform.js"; import { EnrollmentModule } from "./enrollment.js"; import { LanguageModule } from "./language.js"; +import { LocalGatewayService } from "./local-gateway.js"; import { LocalServerModule, signInWithPassword, @@ -395,6 +397,19 @@ async function main(): Promise { new TrayModule({ quit: () => void quit() }), new DesktopIpcModule({ defaultDisplayName, + localGateway: new LocalGatewayService({ + home: () => home, + clipboard: { + writeText: async (text) => clipboard.writeText(text), + readText: async () => clipboard.readText(), + clear: () => clipboard.clear(), + }, + openExternal: (url) => + process.platform === "linux" + ? openWithXdg(url) + : shell.openExternal(url), + showFile: (file) => shell.showItemInFolder(file), + }), ...(desktopPermissions ? { permissions: desktopPermissions } : {}), driverUpdater, }), diff --git a/apps/desktop/src/main/local-gateway.test.ts b/apps/desktop/src/main/local-gateway.test.ts new file mode 100644 index 000000000..4cc80d207 --- /dev/null +++ b/apps/desktop/src/main/local-gateway.test.ts @@ -0,0 +1,328 @@ +import { + chmod, + mkdir, + mkdtemp, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { LocalGatewayService, parseLoopbackAdminUrl } from "./local-gateway.js"; + +describe("parseLoopbackAdminUrl", () => { + it("accepts only loopback 127.0.0.1: addresses", () => { + expect(parseLoopbackAdminUrl("127.0.0.1:18480")).toBe( + "http://127.0.0.1:18480", + ); + expect(parseLoopbackAdminUrl("http://127.0.0.1:18481/")).toBe( + "http://127.0.0.1:18481", + ); + expect(parseLoopbackAdminUrl("0.0.0.0:18480")).toBeUndefined(); + expect( + parseLoopbackAdminUrl("https://evil.example.com:443"), + ).toBeUndefined(); + expect(parseLoopbackAdminUrl("127.0.0.1:0")).toBeUndefined(); + expect(parseLoopbackAdminUrl("127.0.0.1:99999")).toBeUndefined(); + expect(parseLoopbackAdminUrl(undefined)).toBeUndefined(); + }); +}); + +describe("LocalGatewayService", () => { + const dirs: string[] = []; + + async function tempDir(): Promise { + const dir = await mkdtemp(path.join(os.tmpdir(), "linger-local-gw-")); + dirs.push(dir); + return dir; + } + + afterEach(async () => { + vi.useRealTimers(); + vi.unstubAllEnvs(); + for (const dir of dirs.splice(0)) { + await rm(dir, { recursive: true, force: true }); + } + }); + + function fakeClipboard() { + let text = ""; + return { + get current() { + return text; + }, + writeText: vi.fn(async (next: string) => { + text = next; + }), + readText: vi.fn(async () => text), + clear: vi.fn(() => { + text = ""; + }), + }; + } + + it("reads gateway metadata without returning the password, reveals on demand, and auto-clears clipboard after 60s", async () => { + vi.useFakeTimers(); + const root = await tempDir(); + const fakeUserHome = path.join(root, "fake-user-home"); + vi.stubEnv("HOME", fakeUserHome); + vi.stubEnv("USERPROFILE", fakeUserHome); + const home = path.join(root, "linger-home"); + const toolsDir = path.join(home, "runtime", "localmodels", "tools"); + const bifrostDir = path.join(home, "runtime", "localmodels", "bifrost"); + await mkdir(toolsDir, { recursive: true }); + await mkdir(bifrostDir, { recursive: true }); + + await writeFile( + path.join(toolsDir, "owned.json"), + JSON.stringify({ + gateway: { + bifrost: { + addr: "127.0.0.1:18480", + app_dir: bifrostDir, + }, + }, + }), + ); + await writeFile( + path.join(bifrostDir, "config.json"), + JSON.stringify({ + governance: { + auth_config: { + admin_username: "admin", + disable_auth_on_inference: true, + }, + }, + }), + ); + const pwFile = path.join(bifrostDir, "admin-password"); + await writeFile(pwFile, "super-secret-bifrost-pw\n", { mode: 0o600 }); + if (process.platform !== "win32") await chmod(pwFile, 0o600); + + const clipboard = fakeClipboard(); + const openExternal = vi.fn(async () => {}); + const showFile = vi.fn(); + const service = new LocalGatewayService({ + home: () => home, + clipboard, + openExternal, + showFile, + }); + + const info = await service.getInfo(); + expect(info).toEqual({ + available: true, + adminUrl: "http://127.0.0.1:18480", + username: "admin", + hasPassword: true, + inferenceAuthDisabled: true, + }); + expect(JSON.stringify(info)).not.toContain("super-secret-bifrost-pw"); + + expect(await service.revealPassword()).toEqual({ + password: "super-secret-bifrost-pw", + }); + + const copied = await service.copyPassword(); + expect(copied).toEqual({ copied: true, clearAfterMs: 60_000 }); + expect(clipboard.current).toBe("super-secret-bifrost-pw"); + + await vi.advanceTimersByTimeAsync(60_000); + expect(clipboard.clear).toHaveBeenCalledOnce(); + expect(clipboard.current).toBe(""); + + // Does not clear clipboard if the user copied something else meanwhile. + await service.copyPassword(); + await clipboard.writeText("something-else"); + await vi.advanceTimersByTimeAsync(60_000); + expect(clipboard.clear).toHaveBeenCalledOnce(); + + await service.openAdmin(); + expect(openExternal).toHaveBeenCalledExactlyOnceWith( + "http://127.0.0.1:18480", + ); + + await service.openFolder(); + expect(showFile).toHaveBeenCalledExactlyOnceWith(pwFile); + service.dispose(); + }); + + it("refuses world-readable or symlinked admin-password files on POSIX", async () => { + if (process.platform === "win32") return; + const root = await tempDir(); + const fakeUserHome = path.join(root, "fake-user-home"); + vi.stubEnv("HOME", fakeUserHome); + vi.stubEnv("USERPROFILE", fakeUserHome); + const home = path.join(root, "linger-home"); + const bifrostDir = path.join(home, "runtime", "localmodels", "bifrost"); + await mkdir(bifrostDir, { recursive: true }); + await writeFile(path.join(bifrostDir, "config.json"), "{}"); + const pwFile = path.join(bifrostDir, "admin-password"); + await writeFile(pwFile, "too-open-pw\n", { mode: 0o644 }); + await chmod(pwFile, 0o644); + + const service = new LocalGatewayService({ + home: () => home, + clipboard: fakeClipboard(), + openExternal: vi.fn(async () => {}), + showFile: vi.fn(), + }); + + expect(await service.getInfo()).toMatchObject({ + available: true, + hasPassword: false, + }); + await expect(service.revealPassword()).rejects.toThrow( + /missing or not private/, + ); + + // Symlinked password file is also rejected. + const realTarget = path.join(root, "target-pw"); + await writeFile(realTarget, "symlink-pw\n", { mode: 0o600 }); + await chmod(realTarget, 0o600); + await rm(pwFile); + await symlink(realTarget, pwFile); + + await expect(service.revealPassword()).rejects.toThrow( + /missing or not private/, + ); + service.dispose(); + }); + + it("never falls back to another installation's shared legacy gateway when this home is isolated", async () => { + const root = await tempDir(); + const fakeUserHome = path.join(root, "fake-user-home"); + vi.stubEnv("HOME", fakeUserHome); + vi.stubEnv("USERPROFILE", fakeUserHome); + + const sharedTools = path.join( + fakeUserHome, + ".local", + "share", + "localmodels", + "tools", + ); + const sharedBifrost = path.join( + fakeUserHome, + ".local", + "share", + "localmodels", + "bifrost", + ); + await mkdir(sharedTools, { recursive: true }); + await mkdir(sharedBifrost, { recursive: true }); + await writeFile( + path.join(sharedTools, "owned.json"), + JSON.stringify({ + schema: "localmodels.owned/v1", + gateway: { + bifrost: { + addr: "127.0.0.1:18499", + app_dir: sharedBifrost, + }, + }, + }), + ); + const foreignPw = path.join(sharedBifrost, "admin-password"); + await writeFile(foreignPw, "other-install-secret\n", { mode: 0o600 }); + if (process.platform !== "win32") await chmod(foreignPw, 0o600); + await writeFile(path.join(sharedBifrost, "config.json"), "{}"); + + const isolatedHome = path.join(root, "fresh-linger-home"); + const service = new LocalGatewayService({ + home: () => isolatedHome, + clipboard: fakeClipboard(), + openExternal: vi.fn(async () => {}), + showFile: vi.fn(), + }); + + expect(await service.getInfo()).toEqual({ available: false }); + await expect(service.revealPassword()).rejects.toThrow(/not configured/); + await expect(service.openAdmin()).rejects.toThrow(/not available/); + service.dispose(); + }); + + it("reads a legacy home's shared Bifrost gateway when its tools-dir marker points there", async () => { + const root = await tempDir(); + const fakeUserHome = path.join(root, "fake-user-home"); + vi.stubEnv("HOME", fakeUserHome); + vi.stubEnv("USERPROFILE", fakeUserHome); + + const legacyTools = path.join( + fakeUserHome, + ".local", + "share", + "localmodels", + "tools", + ); + const legacyBifrost = path.join( + fakeUserHome, + ".local", + "share", + "localmodels", + "bifrost", + ); + await mkdir(legacyTools, { recursive: true }); + await mkdir(legacyBifrost, { recursive: true }); + await writeFile( + path.join(legacyTools, "owned.json"), + JSON.stringify({ + schema: "localmodels.owned/v1", + gateway: { + bifrost: { + addr: "127.0.0.1:18482", + app_dir: legacyBifrost, + }, + }, + }), + ); + const legacyPw = path.join(legacyBifrost, "admin-password"); + await writeFile(legacyPw, "legacy-secret\n", { mode: 0o600 }); + if (process.platform !== "win32") await chmod(legacyPw, 0o600); + + const legacyHome = path.join(root, "legacy-linger-home"); + const markerDir = path.join(legacyHome, "runtime", "localmodels"); + await mkdir(markerDir, { recursive: true }); + const markerFile = path.join(markerDir, "tools-dir"); + await writeFile(markerFile, `${legacyTools}\n`, { mode: 0o600 }); + if (process.platform !== "win32") await chmod(markerFile, 0o600); + + const service = new LocalGatewayService({ + home: () => legacyHome, + clipboard: fakeClipboard(), + openExternal: vi.fn(async () => {}), + showFile: vi.fn(), + }); + + expect(await service.getInfo()).toEqual({ + available: true, + adminUrl: "http://127.0.0.1:18482", + username: "localmodels", + hasPassword: true, + inferenceAuthDisabled: true, + }); + expect(await service.revealPassword()).toEqual({ + password: "legacy-secret", + }); + service.dispose(); + }); + + it("returns available: false when no local Bifrost gateway exists", async () => { + const root = await tempDir(); + const fakeUserHome = path.join(root, "fake-user-home"); + vi.stubEnv("HOME", fakeUserHome); + vi.stubEnv("USERPROFILE", fakeUserHome); + const service = new LocalGatewayService({ + home: () => path.join(root, "empty-home"), + clipboard: fakeClipboard(), + openExternal: vi.fn(async () => {}), + showFile: vi.fn(), + }); + expect(await service.getInfo()).toEqual({ available: false }); + await expect(service.openAdmin()).rejects.toThrow(/not available/); + service.dispose(); + }); +}); diff --git a/apps/desktop/src/main/local-gateway.ts b/apps/desktop/src/main/local-gateway.ts new file mode 100644 index 000000000..17b57dd06 --- /dev/null +++ b/apps/desktop/src/main/local-gateway.ts @@ -0,0 +1,243 @@ +import { lstat, readFile } from "node:fs/promises"; +import path from "node:path"; + +import { + parseLoopbackBifrostAddress, + resolveLocalmodelsBifrostLocation, +} from "@linger/local-installation/localmodels-tool"; + +import type { DesktopLocalGatewayInfo } from "../shared/api.js"; +import { + SecretClipboard, + type SecretClipboardTarget, +} from "./secret-clipboard.js"; + +const MAX_CONFIG_BYTES = 2 * 1024 * 1024; +const MAX_PASSWORD_BYTES = 4096; +const DEFAULT_ADMIN_USER = "localmodels"; + +export type LocalGatewayClipboard = SecretClipboardTarget; + +export interface LocalGatewayOptions { + /** Returns the current installation's Linger home directory. */ + readonly home: () => string; + readonly clipboard: LocalGatewayClipboard; + readonly openExternal: (url: string) => Promise; + readonly showFile: (file: string) => void; + readonly clearAfterMs?: number; +} + +interface ResolvedGateway { + readonly appDir: string; + readonly adminUrl?: string; + readonly passwordPath: string; + readonly configPath: string; +} + +/** Parses a loopback `127.0.0.1:` address into `http://127.0.0.1:`. */ +export function parseLoopbackAdminUrl(raw: unknown): string | undefined { + if (typeof raw !== "string") return undefined; + const trimmed = raw + .trim() + .replace(/^http:\/\//, "") + .replace(/\/+$/, ""); + const parsed = parseLoopbackBifrostAddress(trimmed); + return parsed ? `http://${parsed.addr}` : undefined; +} + +async function readOwnedRegularFile( + file: string, + maxBytes: number, + options: { requirePrivateMode?: boolean } = {}, +): Promise { + try { + const info = await lstat(file); + if (!info.isFile() || info.isSymbolicLink() || info.size > maxBytes) { + return undefined; + } + if (process.platform !== "win32") { + if (info.uid !== process.getuid?.()) return undefined; + if (options.requirePrivateMode && (info.mode & 0o077) !== 0) { + return undefined; + } + } + return await readFile(file, "utf8"); + } catch { + return undefined; + } +} + +async function isRegularOwnedFile( + file: string, + maxBytes: number, +): Promise { + try { + const info = await lstat(file); + if (!info.isFile() || info.isSymbolicLink() || info.size > maxBytes) { + return false; + } + if (process.platform !== "win32" && info.uid !== process.getuid?.()) { + return false; + } + return true; + } catch { + return false; + } +} + +function field(value: unknown, key: string): unknown { + return value && typeof value === "object" && key in value + ? (value as Record)[key] + : undefined; +} + +async function readJsonObject( + file: string, + maxBytes: number, +): Promise | undefined> { + const raw = await readOwnedRegularFile(file, maxBytes); + if (raw === undefined) return undefined; + try { + const parsed: unknown = JSON.parse(raw); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Record) + : undefined; + } catch { + return undefined; + } +} + +/** + * Local-only reader and helper for this computer's managed Bifrost gateway. + * Passwords are never cached and never cross TeamHub APIs; they are read on + * demand from the owner-only `admin-password` file in the Electron main process. + */ +export class LocalGatewayService { + readonly #options: LocalGatewayOptions; + readonly #clipboard: SecretClipboard; + + constructor(options: LocalGatewayOptions) { + this.#options = options; + this.#clipboard = new SecretClipboard( + options.clipboard, + options.clearAfterMs, + ); + } + + async getInfo(): Promise { + const resolved = await this.#resolve(); + if (!resolved) return { available: false }; + + const config = await readJsonObject(resolved.configPath, MAX_CONFIG_BYTES); + const authConfig = field(field(config, "governance"), "auth_config"); + const rawUsername = field(authConfig, "admin_username"); + const username = + typeof rawUsername === "string" && rawUsername.trim() + ? rawUsername.trim() + : DEFAULT_ADMIN_USER; + const rawDisableInferenceAuth = field( + authConfig, + "disable_auth_on_inference", + ); + const inferenceAuthDisabled = + typeof rawDisableInferenceAuth === "boolean" + ? rawDisableInferenceAuth + : true; + const hasPassword = + (await this.#readPassword(resolved.passwordPath)) !== undefined; + + return { + available: true, + ...(resolved.adminUrl ? { adminUrl: resolved.adminUrl } : {}), + username, + hasPassword, + inferenceAuthDisabled, + }; + } + + async revealPassword(): Promise<{ readonly password: string }> { + const resolved = await this.#resolve(); + if (!resolved) { + throw new Error( + "Local Bifrost gateway is not configured on this computer.", + ); + } + const password = await this.#readPassword(resolved.passwordPath); + if (!password) { + throw new Error( + "The local Bifrost admin password file is missing or not private.", + ); + } + return { password }; + } + + async copyPassword(): Promise<{ + readonly copied: boolean; + readonly clearAfterMs: number; + }> { + const { password } = await this.revealPassword(); + const clearAfterMs = await this.#clipboard.copy(password); + return { copied: true, clearAfterMs }; + } + + async openAdmin(): Promise { + const resolved = await this.#resolve(); + if (!resolved?.adminUrl) { + throw new Error("Local Bifrost gateway address is not available."); + } + await this.#options.openExternal(resolved.adminUrl); + } + + async openFolder(): Promise { + const resolved = await this.#resolve(); + if (!resolved) { + throw new Error("Local Bifrost gateway folder is not available."); + } + const target = (await isRegularOwnedFile( + resolved.passwordPath, + MAX_PASSWORD_BYTES, + )) + ? resolved.passwordPath + : (await isRegularOwnedFile(resolved.configPath, MAX_CONFIG_BYTES)) + ? resolved.configPath + : resolved.appDir; + this.#options.showFile(target); + } + + dispose(): void { + this.#clipboard.dispose(); + } + + async #readPassword(passwordPath: string): Promise { + const raw = await readOwnedRegularFile(passwordPath, MAX_PASSWORD_BYTES, { + requirePrivateMode: true, + }); + const trimmed = raw?.trim(); + return trimmed ? trimmed : undefined; + } + + async #resolve(): Promise { + const { bifrostDir, addr } = await resolveLocalmodelsBifrostLocation( + this.#options.home(), + ); + const passwordPath = path.join(bifrostDir, "admin-password"); + const configPath = path.join(bifrostDir, "config.json"); + const hasPasswordFile = await isRegularOwnedFile( + passwordPath, + MAX_PASSWORD_BYTES, + ); + const hasConfigFile = await isRegularOwnedFile( + configPath, + MAX_CONFIG_BYTES, + ); + if (!hasPasswordFile && !hasConfigFile) return undefined; + + const adminUrl = parseLoopbackAdminUrl(addr); + return { + appDir: bifrostDir, + ...(adminUrl ? { adminUrl } : {}), + passwordPath, + configPath, + }; + } +} diff --git a/apps/desktop/src/main/secret-clipboard.ts b/apps/desktop/src/main/secret-clipboard.ts new file mode 100644 index 000000000..d00e8515c --- /dev/null +++ b/apps/desktop/src/main/secret-clipboard.ts @@ -0,0 +1,48 @@ +// How long a copied secret may stay on the clipboard. +export const CLIPBOARD_CLEAR_MS = 60_000; + +export interface SecretClipboardTarget { + writeText(text: string): Promise; + readText(): Promise; + clear(): void; +} + +/** + * Writes a secret to the clipboard and clears it after `clearAfterMs` only if + * the clipboard still holds that exact value. Re-copying resets the timer. + */ +export class SecretClipboard { + readonly #clipboard: SecretClipboardTarget; + readonly #clearAfterMs: number; + #timer: ReturnType | undefined; + + constructor( + clipboard: SecretClipboardTarget, + clearAfterMs = CLIPBOARD_CLEAR_MS, + ) { + this.#clipboard = clipboard; + this.#clearAfterMs = clearAfterMs; + } + + async copy(secret: string): Promise { + await this.#clipboard.writeText(secret); + clearTimeout(this.#timer); + this.#timer = setTimeout(() => { + this.#timer = undefined; + // Something copied since is left alone. + void this.#clipboard + .readText() + .then((current) => { + if (current === secret) this.#clipboard.clear(); + }) + .catch(() => undefined); + }, this.#clearAfterMs); + this.#timer.unref?.(); + return this.#clearAfterMs; + } + + dispose(): void { + clearTimeout(this.#timer); + this.#timer = undefined; + } +} diff --git a/apps/desktop/src/main/setup-account.ts b/apps/desktop/src/main/setup-account.ts index 9666a7607..e2a70acbb 100644 --- a/apps/desktop/src/main/setup-account.ts +++ b/apps/desktop/src/main/setup-account.ts @@ -1,17 +1,17 @@ import type { SetupLocalAccount } from "../shared/setup.js"; import type { LocalAccount } from "./local-server.js"; +import { + CLIPBOARD_CLEAR_MS, + SecretClipboard, + type SecretClipboardTarget, +} from "./secret-clipboard.js"; -// How long a copied password may stay on the clipboard. -export const CLIPBOARD_CLEAR_MS = 60_000; +export { CLIPBOARD_CLEAR_MS }; export interface SetupAccountOptions { // Reads the installation's local-account.json. readonly read: () => Promise; - readonly clipboard: { - writeText(text: string): Promise; - readText(): Promise; - clear(): void; - }; + readonly clipboard: SecretClipboardTarget; readonly showFile: (file: string) => void; } @@ -22,12 +22,13 @@ type Cached = Pick | { readonly error: string }; // person shows or copies it, and is held only while it is shown. export class SetupAccount { readonly #options: SetupAccountOptions; + readonly #clipboard: SecretClipboard; #account: Cached | undefined; #shown: string | undefined; - #clear: ReturnType | undefined; constructor(options: SetupAccountOptions) { this.#options = options; + this.#clipboard = new SecretClipboard(options.clipboard); } async refresh(): Promise { @@ -56,20 +57,7 @@ export class SetupAccount { async copy(): Promise { const password = (await this.#read())?.password; if (password === undefined) return; - const clipboard = this.#options.clipboard; - await clipboard.writeText(password); - clearTimeout(this.#clear); - this.#clear = setTimeout(() => { - this.#clear = undefined; - // Something copied since is left alone. - void clipboard - .readText() - .then((text) => { - if (text === password) clipboard.clear(); - }) - .catch(() => undefined); - }, CLIPBOARD_CLEAR_MS); - this.#clear.unref?.(); + await this.#clipboard.copy(password); } reveal(): void { diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index 67264a7cb..2bcdf675a 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -130,6 +130,18 @@ const api: LingerDesktopApi = { ipcRenderer.invoke(IPC.driverUpdateStartInstall, request), clearInstallState: () => ipcRenderer.invoke(IPC.driverUpdateClearState), }, + localGateway: { + getInfo: (computerId) => + ipcRenderer.invoke(IPC.localGatewayInfo, computerId), + revealPassword: (computerId) => + ipcRenderer.invoke(IPC.localGatewayRevealPassword, computerId), + copyPassword: (computerId) => + ipcRenderer.invoke(IPC.localGatewayCopyPassword, computerId), + openAdmin: (computerId) => + ipcRenderer.invoke(IPC.localGatewayOpenAdmin, computerId), + openFolder: (computerId) => + ipcRenderer.invoke(IPC.localGatewayOpenFolder, computerId), + }, ...(process.platform === "darwin" ? { permissions: { diff --git a/apps/desktop/src/shared/api.ts b/apps/desktop/src/shared/api.ts index b6f4dcbf3..336ce814c 100644 --- a/apps/desktop/src/shared/api.ts +++ b/apps/desktop/src/shared/api.ts @@ -68,6 +68,16 @@ export type DesktopPermissionStep = } | { readonly action: "relaunch"; readonly subject: "linger" }; +// Metadata about this computer's locally managed Bifrost gateway. Passwords +// are never included here; revealing or copying requires an explicit action. +export interface DesktopLocalGatewayInfo { + readonly available: boolean; + readonly adminUrl?: string; + readonly username?: string; + readonly hasPassword?: boolean; + readonly inferenceAuthDisabled?: boolean; +} + // The updater's progress as the page sees it; the same states the tray shows. export type DesktopUpdateState = | { readonly kind: "idle" } @@ -191,6 +201,20 @@ export interface LingerDesktopApi { readonly diagnostics: { save(): Promise; }; + // Local-only access to this computer's managed Bifrost gateway credentials + // and folder. Absent in a browser and in older desktop builds. The + // configured serverUrl origin check is the IPC security boundary; matching + // computerId only routes the UI to this desktop's enrolled computer. + readonly localGateway?: { + getInfo(computerId: string): Promise; + revealPassword(computerId: string): Promise<{ readonly password: string }>; + copyPassword(computerId: string): Promise<{ + readonly copied: boolean; + readonly clearAfterMs: number; + }>; + openAdmin(computerId: string): Promise; + openFolder(computerId: string): Promise; + }; // macOS only. readonly permissions?: { act(step: DesktopPermissionStep): Promise; @@ -252,4 +276,9 @@ export const IPC = { voiceWindowShowMain: "voice-window.show-main", languageSet: "language.set", diagnosticsSave: "diagnostics.save", + localGatewayInfo: "local-gateway.info", + localGatewayRevealPassword: "local-gateway.reveal-password", + localGatewayCopyPassword: "local-gateway.copy-password", + localGatewayOpenAdmin: "local-gateway.open-admin", + localGatewayOpenFolder: "local-gateway.open-folder", } as const; diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index e89e462e3..57b36e57a 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -79,8 +79,18 @@ 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`) clearly separated from each model's own + `Model server` address, a tabbed `Advanced` dialog + (`local-model-advanced-dialog.tsx`) grouping `Gateway & access` (shared `/v1` + endpoint, admin console address, loaded Gateway Model IDs with copyable + `curl` snippets, and Linger Desktop local-only Bifrost admin credentials via + `window.lingerDesktop.localGateway`, where the Desktop `serverUrl` origin is + the IPC boundary and `computerId` routes the UI to this computer), + `Memory & hardware`, and `Diagnostics` (runtime versions, per-model backend + servers, and Desktop `Save diagnostics`), 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/desktop-local-gateway.ts b/apps/web/src/features/local-models/desktop-local-gateway.ts new file mode 100644 index 000000000..d34a26614 --- /dev/null +++ b/apps/web/src/features/local-models/desktop-local-gateway.ts @@ -0,0 +1,42 @@ +// Local-only desktop shell bridge (`window.lingerDesktop.localGateway` and +// `window.lingerDesktop.diagnostics`) used by the Models Advanced dialog. +// Absent in a browser and in older desktop builds. + +export interface DesktopLocalGatewayInfo { + readonly available: boolean; + readonly adminUrl?: string; + readonly username?: string; + readonly hasPassword?: boolean; + readonly inferenceAuthDisabled?: boolean; +} + +export interface DesktopLocalGatewayApi { + getInfo(computerId: string): Promise; + revealPassword(computerId: string): Promise<{ readonly password: string }>; + copyPassword(computerId: string): Promise<{ + readonly copied: boolean; + readonly clearAfterMs: number; + }>; + openAdmin(computerId: string): Promise; + openFolder(computerId: string): Promise; +} + +export interface DesktopDiagnosticsApi { + save(): Promise; +} + +export function desktopLocalGateway(): DesktopLocalGatewayApi | undefined { + if (typeof window === "undefined") return undefined; + const api = ( + window as { lingerDesktop?: { localGateway?: DesktopLocalGatewayApi } } + ).lingerDesktop?.localGateway; + return typeof api?.getInfo === "function" ? api : undefined; +} + +export function desktopDiagnostics(): DesktopDiagnosticsApi | undefined { + if (typeof window === "undefined") return undefined; + const api = ( + window as { lingerDesktop?: { diagnostics?: DesktopDiagnosticsApi } } + ).lingerDesktop?.diagnostics; + return typeof api?.save === "function" ? api : undefined; +} diff --git a/apps/web/src/features/local-models/local-model-advanced-dialog.tsx b/apps/web/src/features/local-models/local-model-advanced-dialog.tsx new file mode 100644 index 000000000..623b5d1fb --- /dev/null +++ b/apps/web/src/features/local-models/local-model-advanced-dialog.tsx @@ -0,0 +1,900 @@ +import { + CommandLineIcon, + Copy01Icon, + Download04Icon, + Folder01Icon, + LinkSquare02Icon, + Tick02Icon, + ViewIcon, + ViewOffSlashIcon, +} from "@hugeicons/core-free-icons"; +import { type KeyboardEvent, useEffect, useRef, useState } from "react"; + +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 { useTabIndicator } from "@/components/ui/tab-indicator"; +import { commonMessages } from "@/i18n/common.messages"; +import { useT } from "@/i18n/use-translation"; +import { cn } from "@/lib/cn"; + +import { + desktopDiagnostics, + desktopLocalGateway, + type DesktopLocalGatewayInfo, +} from "./desktop-local-gateway"; +import { CopyEndpoint, Fact } from "./local-model-details"; +import { localModelsMessages as m } from "./local-models.messages"; +import type { LocalModelPool, LocalModelsView } from "./local-models-queries"; +import { + formatGigabytes, + gatewayAdminUrl, + gatewayCurlSnippet, + gatewayModelId, + isLoopbackUrl, + modelEntries, + poolFreeBytes, + poolLabel, + poolOtherBytes, + poolUnaccountedBytes, + sharedGatewayEndpoint, + 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"; + +type AdvancedTab = "gateway" | "hardware" | "diagnostics"; +const advancedTabs: readonly AdvancedTab[] = [ + "gateway", + "hardware", + "diagnostics", +]; + +function useCopiedFlag(durationMs = 1_500) { + const [copiedKey, setCopiedKey] = useState(null); + const timerRef = useRef(undefined); + + useEffect( + () => () => { + window.clearTimeout(timerRef.current); + }, + [], + ); + + function mark(key: string) { + window.clearTimeout(timerRef.current); + setCopiedKey(key); + timerRef.current = window.setTimeout(() => setCopiedKey(null), durationMs); + } + + function copyText(key: string, text: string) { + const clipboard = navigator.clipboard; + if (clipboard?.writeText) { + void clipboard.writeText(text).then( + () => mark(key), + () => undefined, + ); + } + } + + return { copiedKey, copyText, mark }; +} + +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) })} + +
+ ); +} + +function GatewayTabPanel({ + computerId, + computerName, + desktopGatewayInfo, + gatewayEndpoint, + adminUrl, + isLocalDesktop, + loadedEntries, +}: { + adminUrl?: string; + computerId: string; + computerName: string; + desktopGatewayInfo?: DesktopLocalGatewayInfo; + gatewayEndpoint?: string; + isLocalDesktop: boolean; + loadedEntries: readonly ModelEntry[]; +}) { + const t = useT(); + const [localGateway] = useState(desktopLocalGateway); + const [revealedPassword, setRevealedPassword] = useState(null); + const [revealing, setRevealing] = useState(false); + const [copyingPassword, setCopyingPassword] = useState(false); + const [credentialError, setCredentialError] = useState(null); + const { copiedKey, copyText, mark } = useCopiedFlag(2_000); + + // Clear revealed secrets when switching computers or unmounting this tab. + useEffect(() => { + setRevealedPassword(null); + setCredentialError(null); + return () => setRevealedPassword(null); + }, [computerId]); + + const effectiveAdminUrl = adminUrl ?? desktopGatewayInfo?.adminUrl; + const loopback = isLoopbackUrl(gatewayEndpoint ?? effectiveAdminUrl); + const inferenceAuthDisabled = + desktopGatewayInfo?.inferenceAuthDisabled ?? true; + const gatewayModels = loadedEntries + .map((entry) => ({ + entry, + modelId: gatewayModelId(entry.model), + })) + .filter((item): item is { entry: ModelEntry; modelId: string } => + Boolean(item.modelId), + ); + const canUseDesktopGateway = Boolean( + isLocalDesktop && localGateway && desktopGatewayInfo?.available, + ); + const canOpenDesktopAdmin = Boolean( + canUseDesktopGateway && desktopGatewayInfo?.adminUrl, + ); + + function toggleRevealPassword() { + if (!localGateway) return; + if (revealedPassword !== null) { + setRevealedPassword(null); + return; + } + setCredentialError(null); + setRevealing(true); + void localGateway + .revealPassword(computerId) + .then((result) => setRevealedPassword(result.password)) + .catch(() => setCredentialError(t(m.gatewayCredentialReadFailed))) + .finally(() => setRevealing(false)); + } + + function copyDesktopPassword() { + if (!localGateway) return; + setCredentialError(null); + setCopyingPassword(true); + void localGateway + .copyPassword(computerId) + .then(() => mark("password")) + .catch(() => setCredentialError(t(m.gatewayCredentialReadFailed))) + .finally(() => setCopyingPassword(false)); + } + + function openDesktopAdmin() { + if (!localGateway) return; + setCredentialError(null); + void localGateway + .openAdmin(computerId) + .catch(() => setCredentialError(t(m.gatewayOpenAdminFailed))); + } + + function openDesktopFolder() { + if (!localGateway) return; + setCredentialError(null); + void localGateway + .openFolder(computerId) + .catch(() => setCredentialError(t(m.gatewayOpenFolderFailed))); + } + + return ( +
+
+

+ {t(m.gatewaySection)} +

+ {gatewayEndpoint || effectiveAdminUrl ? ( + <> +
+ {gatewayEndpoint ? ( + + + + ) : null} + {effectiveAdminUrl ? ( + + + + {canOpenDesktopAdmin ? ( + + ) : 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 4665e6cca..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,18 +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, @@ -86,7 +82,17 @@ function Fact({ ); } -function CopyEndpoint({ endpoint, name }: { endpoint: string; name: string }) { +export 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 +124,7 @@ function CopyEndpoint({ endpoint, name }: { endpoint: string; name: string }) { } return ( - + @@ -747,7 +753,8 @@ function ComputerModels({ onClick={() => setDialog({ kind: "advanced" })} size="compact" > - {t(m.details)} + + {t(m.advanced)} ) : null} @@ -1495,6 +1502,7 @@ function Library({ disabled={offline || readOnly || switching || busy(modelId)} entry={entry} expanded={expandedKey === group.key} + gatewayUrl={status?.gateway_url} inSpotlight={inSpotlight} key={group.key} onAssignAgent={ @@ -1912,7 +1920,12 @@ function Library({ )} {dialog?.kind === "advanced" ? ( - setDialog(null)} view={view} /> + setDialog(null)} + view={view} + /> ) : null} {dialog?.kind === "updateDriver" ? ( { expect(safeModelSourceUrl("http://example.com/model")).toBeUndefined(); const safe = safeModelSourceUrl("https://huggingface.co/Qwen/Qwen3-4B/"); expect(safe).toBe("https://huggingface.co/Qwen/Qwen3-4B/"); + expect(sharedGatewayEndpoint("http://127.0.0.1:18480")).toBe( + "http://127.0.0.1:18480/v1", + ); + expect(sharedGatewayEndpoint("http://127.0.0.1:18480/")).toBe( + "http://127.0.0.1:18480/v1", + ); + expect(sharedGatewayEndpoint("http://127.0.0.1:18480/v1/")).toBe( + "http://127.0.0.1:18480/v1", + ); + expect(sharedGatewayEndpoint("https://gw.local/proxy")).toBe( + "https://gw.local/proxy/v1", + ); + 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 98a205db5..5d1db552a 100644 --- a/apps/web/src/features/local-models/local-models-rules.ts +++ b/apps/web/src/features/local-models/local-models-rules.ts @@ -966,6 +966,98 @@ export function modelSourceLabel(url: string) { return `${parsed.host}${parsed.pathname.replace(/\/+$/, "")}`; } +/** + * Normalizes a Computer's shared Bifrost gateway base URL into the + * OpenAI-compatible `/v1` endpoint shown alongside each loaded model's own + * inference server address. + */ +export function sharedGatewayEndpoint( + 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(/\/+$/, ""); + const apiPath = trimmedPath.endsWith("/v1") + ? trimmedPath + : `${trimmedPath}/v1`; + return `${parsed.origin}${apiPath}`; + } catch { + return undefined; + } +} + +/** + * 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 acfed69f3..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.", @@ -154,14 +158,72 @@ export const localModelsMessages = defineMessages("localModels", { discardDownload: "Discard download", // The details of a model and of a Computer. - copyEndpointOf: "Copy {name} endpoint", - copiedEndpointOf: "Copied {name} endpoint", - copyEndpoint: "Copy endpoint", + copyEndpointOf: "Copy {name} model server endpoint", + copiedEndpointOf: "Copied {name} model server endpoint", + copyEndpoint: "Copy model server endpoint", + copyGatewayEndpoint: "Copy shared gateway endpoint", + copiedGatewayEndpoint: "Copied shared gateway endpoint", gatewayPiNotInstalled: "Bifrost · Pi not installed", gatewayReady: "Ready · Bifrost (Pi)", gatewayRegistering: "Bifrost · Registering with Pi…", gatewaySettingUp: "Bifrost · Setting up Pi…", gatewayPiUnavailable: "Bifrost · Pi unavailable", + 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", @@ -182,8 +244,8 @@ export const localModelsMessages = defineMessages("localModels", { factLicense: "License", factUsedBy: "Used by", factSource: "Source", - factGateway: "Gateway", - factEndpoint: "Endpoint", + factGateway: "Shared gateway", + factEndpoint: "Model server", factFreeDisk: "Free disk", memoryOn: "{size} on {place}", idleUsedWarning: { 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 b7fe19842..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} 已离线。请在电脑设置中重新连接,再测试或更改它的模型来源。", @@ -1277,14 +1281,65 @@ "detailsOf": "{name} 详情", "removeFromComputer": "从电脑中移除", "discardDownload": "放弃下载", - "copyEndpointOf": "复制 {name} 的端点", - "copiedEndpointOf": "已复制 {name} 的端点", - "copyEndpoint": "复制端点", + "copyEndpointOf": "复制 {name} 的模型服务端点", + "copiedEndpointOf": "已复制 {name} 的模型服务端点", + "copyEndpoint": "复制模型服务端点", + "copyGatewayEndpoint": "复制共享网关端点", + "copiedGatewayEndpoint": "已复制共享网关端点", "gatewayPiNotInstalled": "Bifrost · 未安装 Pi", "gatewayReady": "就绪 · Bifrost(Pi)", "gatewayRegistering": "Bifrost · 正在向 Pi 注册…", "gatewaySettingUp": "Bifrost · 正在设置 Pi…", "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": "不可用原因", @@ -1304,8 +1359,8 @@ "factLicense": "许可证", "factUsedBy": "使用者", "factSource": "来源", - "factGateway": "网关", - "factEndpoint": "端点", + "factGateway": "共享网关", + "factEndpoint": "模型服务", "factFreeDisk": "可用磁盘空间", "memoryOn": "{size}({place})", "idleUsedWarning": { 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`;