Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Boat sign-in: the button with Boat's mark above the key field, its states, strings and preview page
milind-sonibb562342ae94
diff --git a/boat-sign-in-preview.html b/boat-sign-in-preview.htmlnew file mode 100644index 0000000000..d33db766fc--- /dev/null+++ b/boat-sign-in-preview.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Boat Sign-in Preview</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/boat-sign-in-preview.tsx"></script>+ </body>+</html>diff --git a/src/boat-sign-in-preview.tsx b/src/boat-sign-in-preview.tsxnew file mode 100644index 0000000000..96adbc5472--- /dev/null+++ b/src/boat-sign-in-preview.tsx@@ -0,0 +1,119 @@+// Dev-only: the Boat row of Settings → AI → Other services (the real Settings) and the computer panel's key card,+// against made-up answers, served at /boat-sign-in-preview.html; not in the packaged app. Every request is answered here.+// ?view=settings|panel&state=none|waiting|connected|both-sign-in|both-key|missing|ended|cancelled|refused|key|hosted|server+// &skin=midnight|daylight&lang=pt-br+// Sign-in is offered only on the desktop app's own ports, so serve this page on one of them to see it+// (pnpm dev --port 18799 --strictPort); on any other port every state shows the key field alone, as a self-hosted server does.+import { StrictMode, useEffect } from "react";+import { createRoot } from "react-dom/client";+import type { BoatSignInStatus } from "../shared/boat-sign-in";+import "./styles.css";++const params = new URLSearchParams(location.search);+const view = params.get("view") ?? "settings";+const state = params.get("state") ?? "none";++const ALL = { available: true, keySaved: false } as const;+const SIGN_IN: Record<string, BoatSignInStatus | undefined> = {+ none: { ...ALL, state: "none" },+ waiting: { ...ALL, state: "none", pending: true },+ connected: { ...ALL, state: "connected", account: "[email protected]", missingScopes: [], used: true, last: { outcome: "connected" } },+ "both-sign-in": { available: true, keySaved: true, state: "connected", account: "[email protected]", missingScopes: [], used: true },+ "both-key": { available: true, keySaved: true, state: "connected", account: "[email protected]", missingScopes: [], used: false },+ missing: { ...ALL, state: "connected", account: "[email protected]", missingScopes: ["sandbox.create", "desktop"], used: true },+ ended: { ...ALL, state: "needs-sign-in", missingScopes: [], used: true },+ cancelled: { ...ALL, state: "none", last: { outcome: "cancelled" } },+ refused: { ...ALL, state: "none", last: { outcome: "refused" } },+ key: { available: true, keySaved: true, state: "none" },+ // A self-hosted server and a hosted Cloud say nothing about sign-in.+ server: undefined,+ hosted: undefined,+};+const signIn = SIGN_IN[state];+const keySaved = signIn?.keySaved === true || state === "server-key";+const box = state === "hosted"+ ? { configured: true, included: true, keySaved: false }+ : { configured: keySaved || signIn?.state === "connected" || signIn?.state === "needs-sign-in", ...(keySaved ? { last4: "c3d4" } : {}), keySaved, ...(signIn ? { signIn } : {}) };++const CONFIG = {+ composio: { configured: false }, box, vps: { configured: false, sshAlias: "" },+ rooms: { turnTimeoutMinutes: 10 }, localVm: { mode: "shared", maxInstances: 1 },+ profile: { name: "Maya Shah", email: "[email protected]" }, features: { savedSteps: false },+ onboarding: { completedAt: "2026-01-01", version: 1, reelSeen: true, hintsSeen: [] },+ edition: { edition: "community", features: [] }, browserProfiles: [], managedPolicy: null,+ signIn: { admins: [], members: [] }, membership: { authority: "local", pairingCodes: true }, cloudHome: state === "hosted",+};+const ANSWERS: Record<string, unknown> = {+ "/api/instances": { instances: [] }, "/api/config": CONFIG,+ "/api/auth/session": { kind: "session", id: "s1", label: "Chrome on Mac", email: "[email protected]", scopes: ["admin", "client"], expiresAt: 0 },+ "/api/auth/sessions": { sessions: [{ id: "s1" }], current: "s1" }, "/api/routines": { routines: [], runs: [] }, "/api/webhooks": { webhooks: [], attempts: [] },+ "/api/bots": { bots: [{ id: "chief", name: "Chief", threadId: "t-chief" }], groups: [] },+};+const realFetch = window.fetch.bind(window);+window.fetch = (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input instanceof Request ? input.url : input), location.href);+ if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return realFetch(input, init);+ // Nothing here signs in: the buttons are answered with a refusal so no browser page is ever opened.+ if (url.pathname.startsWith("/api/boat/sign-in")) return Promise.resolve(new Response(JSON.stringify({ error: "This is a preview." }), { status: 503, headers: { "content-type": "application/json" } }));+ return Promise.resolve(new Response(JSON.stringify(ANSWERS[url.pathname] ?? {}), { headers: { "content-type": "application/json" } }));+};+class QuietEventSource {+ onopen: (() => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string }) => void) | null = null;+ readyState = 1;+ constructor(readonly url: string) { setTimeout(() => this.onmessage?.({ data: JSON.stringify({ kind: "hello", resumed: false, cursor: "run:0" }) }), 50); }+ addEventListener() {} removeEventListener() {} close() {}+}+Object.assign(window, { EventSource: QuietEventSource });+try { localStorage.setItem("omb-advanced-mode", "0"); } catch { /* blocked storage */ }++const [{ StoreProvider }, { useStoreDispatch, useStoreSelector }, { SettingsModal }, { KeyRow }, { requestKeyFocus }, { applySkin, readSkin, SKIN_IDS }, { loadLocale }] = await Promise.all([+ import("@/state/store"), import("@/state/store-select"), import("@/components/SettingsModal"), import("@/components/keys/KeyRow"), import("@/components/keys/key-focus"),+ import("@/lib/skins"), import("@/lib/i18n"),+]);++function SettingsView() {+ const loaded = useStoreSelector((app) => app.config !== null), open = useStoreSelector((app) => app.appSettingsOpen), dispatch = useStoreDispatch();+ useEffect(() => {+ if (!loaded) return;+ dispatch({ type: "toggleAppSettings", open: true, section: "ai" });+ }, [loaded, dispatch]);+ return open ? <SettingsModal /> : null;+}++/** The card the computer panel shows when a cloud desktop has no Boat account yet, at the panel's width. */+function PanelView() {+ const loaded = useStoreSelector((app) => app.config !== null);+ if (!loaded) return <div className="h-screen bg-app" />;+ return (+ <div className="flex min-h-screen justify-center bg-app px-4 py-10 text-ink">+ <div className="w-full max-w-[420px]">+ <div data-boat-key className="mt-3 rounded-xl bg-card py-1.5"><KeyRow id="box" via="computer_panel" /></div>+ </div>+ </div>+ );+}++/** The pictures are taken once the Boat row is in view: in Settings that means opening Other services first, as a person does. */+function markReady() {+ const started = Date.now();+ let asked = false;+ const timer = setInterval(() => {+ const fold = document.querySelector<HTMLButtonElement>("[data-settings-disclosure='ai-other-services'] button[aria-expanded='false']");+ if (fold) fold.click();+ const page = document.querySelector("[data-keys-page]");+ if (page && !asked) { asked = true; requestKeyFocus("box"); }+ const row = document.querySelector<HTMLElement>("[data-key-row='box']");+ const settled = row && !row.hasAttribute("data-key-highlight") && Date.now() - started > 2_500;+ if (settled || Date.now() - started > 9_000) {+ clearInterval(timer);+ row?.scrollIntoView({ block: "center" });+ requestAnimationFrame(() => document.body.setAttribute("data-preview-ready", ""));+ }+ }, 150);+}+markReady();++const asked = params.get("skin");+applySkin((SKIN_IDS as readonly string[]).includes(asked ?? "") ? asked as Parameters<typeof applySkin>[0] : readSkin());+await loadLocale(params.get("lang") ?? "en");+createRoot(document.getElementById("root")!).render(<StrictMode><StoreProvider>{view === "panel" ? <PanelView /> : <SettingsView />}</StoreProvider></StrictMode>);diff --git a/src/components/BoatMark.tsx b/src/components/BoatMark.tsxnew file mode 100644index 0000000000..64a662ba37--- /dev/null+++ b/src/components/BoatMark.tsx@@ -0,0 +1,11 @@+import { cn } from "@/lib/cn";++/** Boat's own mark, taken from boat.dev at the owner's request: one path, its shape and proportions unchanged. It takes+ * the text colour unless a class gives it another (Boat's blue is #263FA9). */+export function BoatMark({ size = 16, className, ...rest }: { size?: number | string; className?: string; "aria-hidden"?: boolean | "true" | "false" }) {+ return (+ <svg width={size} height={size} viewBox="0 0 497.985 462.094" aria-hidden="true" {...rest} className={cn("shrink-0 fill-current", className)}>+ <path d="M490.123 361.461C494.464 361.461 497.985 364.978 497.985 369.323V403.916C497.985 408.256 494.464 411.777 490.123 411.777H473.317C468.941 411.777 465.396 415.327 465.396 419.699V454.232C465.396 458.573 461.875 462.094 457.534 462.094H84.3579C83.1446 462.094 81.9773 461.511 81.2263 460.558C52.4607 424.054 51.9691 423.595 7.86426 411.777C3.67043 410.653 0 408.256 0 403.916V369.323C0 364.978 3.52235 361.461 7.86426 361.461H490.123ZM234.167 4.81756C238.589 -2.56834 249.679 -1.18229 252.148 7.06463L321.938 240.22L244.366 338.334H51.9617C44.2696 338.334 39.5154 329.947 43.4665 323.347L234.167 4.81756ZM453.056 132.260C451.192 124.166 440.791 121.826 435.640 128.341L282.295 322.292C277.163 328.784 281.786 338.334 290.063 338.334H488.080C494.445 338.334 499.157 332.414 497.728 326.210L453.056 132.260Z" />+ </svg>+ );+}diff --git a/src/components/keys/BoatSignIn.dom.test.ts b/src/components/keys/BoatSignIn.dom.test.tsnew file mode 100644index 0000000000..ee7ba9c4eb--- /dev/null+++ b/src/components/keys/BoatSignIn.dom.test.ts@@ -0,0 +1,137 @@+// @vitest-environment happy-dom+// "Sign in with Boat" above the Boat key field: each state it shows, what its buttons ask the server, and where it is+// not offered at all. The server and the browser are stand-ins: nothing here opens a page or reaches Boat.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { BoatSignInStatus } from "../../../shared/boat-sign-in";+import { setLocale } from "@/lib/i18n";++const api = vi.fn(async (path: string, _init?: { method?: string }): Promise<unknown> => (path.endsWith("/start") ? { url: "https://boat.dev/api/boat/oauth2/authorize?client_id=x&state=y" } : { ok: true }));+vi.mock("@/state/api", () => ({ api }));+const openExternalLink = vi.fn(async (_url: string) => {});+vi.mock("@/lib/app-links", () => ({ openExternalLink }));+const { BoatSignIn } = await import("./BoatSignIn");+const { boatSignInShown, isBoatSignInUrl } = await import("@/lib/boat-sign-in");+const { keyEntry, savedState } = await import("./key-catalog");++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let host: HTMLDivElement, root: Root | null = null;+const NONE: BoatSignInStatus = { available: true, state: "none", keySaved: false };+const CONNECTED: BoatSignInStatus = { available: true, state: "connected", account: "[email protected]", missingScopes: [], used: true, keySaved: false };++beforeEach(() => { setLocale("en"); vi.clearAllMocks(); host = document.createElement("div"); document.body.append(host); });+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); });++async function show(status: BoatSignInStatus, more: { fieldShown?: boolean; onConnected?: () => void } = {}) {+ root ??= createRoot(host);+ await act(async () => { root!.render(createElement(BoatSignIn, { status, fieldShown: more.fieldShown ?? true, onConnected: more.onConnected })); });+}+const click = async (element: Element | null) => { expect(element).toBeTruthy(); await act(async () => { (element as HTMLElement).click(); await Promise.resolve(); await Promise.resolve(); }); };+const text = () => host.textContent ?? "";++it("not connected: the button with Boat's mark first, then \"or paste an API key\"", async () => {+ await show(NONE);+ const button = host.querySelector("[data-boat-sign-in]")!;+ expect(button.textContent).toBe("Sign in with Boat");+ expect(button.querySelector("svg path")?.getAttribute("d")).toMatch(/^M490\.123 361\.461/);+ expect(host.querySelector("[data-boat-or]")?.textContent).toBe("or paste an API key");+ expect(host.querySelector("[data-boat-disconnect]")).toBeNull();+ await click(button);+ expect(api).toHaveBeenCalledWith("/api/boat/sign-in/start", { method: "POST" });+ expect(openExternalLink).toHaveBeenCalledWith("https://boat.dev/api/boat/oauth2/authorize?client_id=x&state=y");+});++it("opens nothing but Boat's own sign-in page, whatever the server answers", async () => {+ api.mockResolvedValueOnce({ url: "https://boat.dev.evil.example/api/boat/oauth2/authorize" });+ await show(NONE);+ await click(host.querySelector("[data-boat-sign-in]"));+ expect(openExternalLink).not.toHaveBeenCalled();+ expect(host.querySelector("[role=alert]")?.textContent).toBe("Couldn't open the sign-in page in your browser. Try again.");+ for (const bad of ["https://boat.dev/other", "http://boat.dev/api/boat/oauth2/authorize", "https://[email protected]/api/boat/oauth2/authorize", "javascript:alert(1)", "https://boat.dev:444/api/boat/oauth2/authorize", 7, null]) {+ expect(isBoatSignInUrl(bad), String(bad)).toBe(false);+ }+ expect(isBoatSignInUrl("https://boat.dev/api/boat/oauth2/authorize?state=a")).toBe(true);+});++it("waiting for Boat: says so, and Cancel spends the link", async () => {+ await show({ ...NONE, pending: true });+ expect(host.querySelector("[data-boat-sign-in-state]")?.getAttribute("data-boat-sign-in-state")).toBe("waiting");+ expect(text()).toContain("Finish signing in in your browser");+ expect(host.querySelector("[data-boat-sign-in]")).toBeNull();+ await click(host.querySelector("[data-boat-cancel]"));+ expect(api).toHaveBeenCalledWith("/api/boat/sign-in/cancel", { method: "POST" });+});++it("connected: the account and Disconnect, and the caller hears it once", async () => {+ const onConnected = vi.fn();+ await show({ ...NONE, pending: true }, { onConnected });+ await show(CONNECTED, { onConnected });+ await show(CONNECTED, { onConnected });+ expect(onConnected).toHaveBeenCalledTimes(1);+ expect(host.querySelector("[data-boat-account]")?.textContent).toBe("Signed in to Boat as [email protected]");+ expect(host.querySelector("[data-boat-sign-in]")).toBeNull();+ expect(host.querySelector("[data-boat-used]")).toBeNull();+ await click(host.querySelector("[data-boat-disconnect]"));+ expect(api).toHaveBeenCalledWith("/api/boat/sign-in", { method: "DELETE" });+});++it("a refused Disconnect shows the server's reason", async () => {+ api.mockRejectedValueOnce(new Error("remove this installation's cloud computers before changing or clearing the Boat account"));+ await show(CONNECTED);+ await click(host.querySelector("[data-boat-disconnect]"));+ expect(host.querySelector("[role=alert]")?.textContent).toContain("remove this installation's cloud computers");+});++it("no account name when the person did not allow it, and the scopes they left out are named", async () => {+ await show({ ...CONNECTED, account: undefined, missingScopes: ["account.read", "sandbox.create"] });+ expect(host.querySelector("[data-boat-account]")?.textContent).toBe("Signed in to Boat");+ expect(host.querySelector("[data-boat-missing]")?.textContent).toBe("Not allowed when you signed in: account.read, sandbox.create. Anything that needs one of these will say so. Sign in again to allow them.");+ expect(host.querySelector("[data-boat-sign-in]")?.textContent).toBe("Sign in again");+});++it("with a key saved too, it says which of the two is used", async () => {+ await show({ ...CONNECTED, keySaved: true, used: true }, { fieldShown: false });+ expect(host.querySelector("[data-boat-used]")?.textContent).toContain("use this sign-in");+ expect(host.querySelector("[data-boat-or]")).toBeNull();+ await show({ ...CONNECTED, keySaved: true, used: false }, { fieldShown: false });+ expect(host.querySelector("[data-boat-used]")?.textContent).toContain("use the Boat API key below");+});++it("ended, cancelled and failed each say what happened and offer the button again", async () => {+ await show({ available: true, state: "needs-sign-in", missingScopes: [], used: true, keySaved: false });+ expect(text()).toContain("Your Boat account sign-in has ended. Sign in again.");+ expect(host.querySelector("[data-boat-sign-in]")?.textContent).toBe("Sign in again");+ expect(host.querySelector("[data-boat-disconnect]")).toBeTruthy();+ for (const [outcome, words] of [["cancelled", "Sign-in cancelled. Nothing was connected."], ["failed", "did not complete"], ["refused", "Not signed in."], ["unreachable", "Couldn't reach boat.dev"], ["not-saved", "could not be saved"]] as const) {+ await show({ ...NONE, last: { outcome } });+ expect(host.querySelector(`[data-boat-outcome='${outcome}']`)?.textContent).toContain(words);+ expect(host.querySelector("[data-boat-sign-in]")?.textContent).toBe("Sign in with Boat");+ }+ await show({ ...CONNECTED, last: { outcome: "connected" } });+ expect(host.querySelector("[data-boat-outcome]")).toBeNull();+});++it("is offered only on the desktop app's own local page, and never where cloud desktops are included", () => {+ const config = { box: { configured: false, keySaved: false, signIn: NONE } };+ for (const port of ["8799", "18799", "28799"]) expect(boatSignInShown(config, { hostname: "127.0.0.1", port })).toEqual(NONE);+ expect(boatSignInShown(config, { hostname: "localhost", port: "8799" })).toEqual(NONE);+ for (const page of [{ hostname: "127.0.0.1", port: "5199" }, { hostname: "127.0.0.1", port: "" }, { hostname: "my-server.example", port: "8799" }, { hostname: "192.168.1.20", port: "8799" }]) {+ expect(boatSignInShown(config, page), JSON.stringify(page)).toBeNull();+ }+ const local = { hostname: "127.0.0.1", port: "8799" };+ expect(boatSignInShown({ box: { configured: false } }, local)).toBeNull();+ expect(boatSignInShown({ box: { configured: false, signIn: { ...NONE, available: false } } }, local)).toBeNull();+ expect(boatSignInShown({ box: { configured: true, included: true, signIn: NONE } }, local)).toBeNull();+ expect(boatSignInShown(null, local)).toBeNull();+});++it("the key field under it is the pasted key's alone: a sign-in is not shown as a saved key", () => {+ const entry = keyEntry("box");+ const saved = (box: Record<string, unknown>) => savedState(entry, { box } as never);+ expect(saved({ configured: true, keySaved: false, signIn: CONNECTED })).toEqual({ configured: false });+ expect(saved({ configured: true, keySaved: true, last4: "c3d4", signIn: CONNECTED })).toEqual({ configured: true, last4: "c3d4" });+ // A server that says nothing about sign-in: exactly as before.+ expect(saved({ configured: true, last4: "c3d4" })).toEqual({ configured: true, last4: "c3d4" });+ expect(saved({ configured: true, included: true })).toEqual({ configured: false, included: true });+});diff --git a/src/components/keys/BoatSignIn.tsx b/src/components/keys/BoatSignIn.tsxnew file mode 100644index 0000000000..bd105523dc--- /dev/null+++ b/src/components/keys/BoatSignIn.tsx@@ -0,0 +1,100 @@+import { useEffect, useRef, useState } from "react";+import { Check, CircleAlert, Loader2, TriangleAlert } from "lucide-react";+import type { BoatSignInOutcome, BoatSignInStatus } from "../../../shared/boat-sign-in";+import { cancelBoatSignIn, disconnectBoat, startBoatSignIn } from "@/lib/boat-sign-in";+import { t } from "@/lib/i18n";+import type { LocaleKey } from "@/locales";+import { BoatMark } from "../BoatMark";++const OUTCOME: Partial<Record<BoatSignInOutcome, LocaleKey>> = {+ cancelled: "boatSignIn.cancelled",+ failed: "boatSignIn.failed",+ refused: "boatSignIn.refused",+ unreachable: "boatSignIn.unreachable",+ "not-saved": "boatSignIn.notSaved",+};++const reason = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));++/** The primary way to connect a Boat account, above the key field of the Boat row: a button with Boat's mark, then, once+ * connected, the account, anything the person did not allow, and Disconnect. `keyShown` is the field or saved key below. */+export function BoatSignIn({ status, fieldShown, onConnected }: { status: BoatSignInStatus; fieldShown: boolean; onConnected?: () => void }) {+ const [busy, setBusy] = useState<"starting" | "cancelling" | "disconnecting" | null>(null);+ const [problem, setProblem] = useState<string | null>(null);+ const connected = status.state === "connected";+ const was = useRef(connected);+ useEffect(() => {+ if (connected && !was.current) onConnected?.();+ was.current = connected;+ }, [connected]);++ const run = (what: NonNullable<typeof busy>, action: () => Promise<unknown>, failed: LocaleKey | null) => {+ if (busy) return;+ setBusy(what);+ setProblem(null);+ void action().catch((cause) => setProblem(failed ? t(failed) : reason(cause))).finally(() => setBusy(null));+ };+ const start = () => run("starting", startBoatSignIn, "boatSignIn.openFailed");+ const waiting = status.pending === true || busy === "starting";+ const outcome = !waiting && !problem && status.last ? OUTCOME[status.last.outcome] : undefined;+ const missing = status.missingScopes ?? [];++ const button = (label: string) => (+ <button type="button" data-boat-sign-in className="ui-button ui-button-primary min-h-9 gap-2 self-start px-3.5" disabled={busy !== null} onClick={start}>+ {/* Boat's blue on the light button (Midnight), white on a dark or coloured one. */}+ <BoatMark size={16} className="in-data-[skin=midnight]:fill-[#263FA9]" />+ {label}+ </button>+ );++ return (+ <div data-boat-sign-in-state={waiting ? "waiting" : status.state} className="flex flex-col gap-2">+ {status.state !== "none" && (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span className="flex min-w-0 flex-1 items-center gap-1.5 text-[13px] leading-5 text-ink">+ {connected+ ? <Check size={14} aria-hidden="true" className="shrink-0 text-success" />+ : <CircleAlert size={14} aria-hidden="true" className="shrink-0 text-danger" />}+ <span data-boat-account className="truncate">+ {connected+ ? status.account ? t("boatSignIn.signedInAs", { account: status.account }) : t("boatSignIn.signedIn")+ : t("boatSignIn.ended")}+ </span>+ </span>+ <button type="button" data-boat-disconnect data-danger="" className="settings-quiet shrink-0 cursor-pointer" disabled={busy !== null}+ onClick={() => run("disconnecting", disconnectBoat, null)}>+ {busy === "disconnecting" ? t("boatSignIn.disconnecting") : t("boatSignIn.disconnect")}+ </button>+ </div>+ )}+ {connected && status.keySaved && (+ <p data-boat-used className="text-[12px] leading-4 text-ink-secondary">{t(status.used ? "boatSignIn.usesSignIn" : "boatSignIn.usesKey")}</p>+ )}+ {connected && missing.length > 0 && (+ <p data-boat-missing className="flex gap-1.5 text-[12px] leading-4 text-warning">+ <TriangleAlert size={13} aria-hidden="true" className="mt-px shrink-0" />+ <span>{t("boatSignIn.missing", { scopes: missing.join(", ") })}</span>+ </p>+ )}+ {waiting ? (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[13px] leading-5 text-ink-secondary">+ <span role="status" className="flex items-center gap-1.5">+ <Loader2 size={13} aria-hidden="true" className="animate-spin" />+ {t("boatSignIn.waiting")}+ </span>+ {status.pending && (+ <>+ <button type="button" className="cursor-pointer text-accent-text hover:underline" disabled={busy !== null} onClick={start}>{t("boatSignIn.openAgain")}</button>+ <button type="button" data-boat-cancel className="settings-quiet cursor-pointer" disabled={busy !== null} onClick={() => run("cancelling", cancelBoatSignIn, null)}>{t("common.cancel")}</button>+ </>+ )}+ </div>+ ) : status.state === "none" ? button(t("boatSignIn.button"))+ : (status.state === "needs-sign-in" || missing.length > 0) ? button(t("boatSignIn.again"))+ : null}+ {problem && <p role="alert" className="flex gap-1.5 text-[12px] leading-4 text-danger"><CircleAlert size={13} aria-hidden="true" className="mt-px shrink-0" /><span>{problem}</span></p>}+ {outcome && <p data-boat-outcome={status.last?.outcome} role="status" className="text-[12px] leading-4 text-ink-secondary">{t(outcome)}</p>}+ {fieldShown && <p data-boat-or className="pt-1 text-[12px] leading-4 text-ink-secondary">{t("boatSignIn.orPaste")}</p>}+ </div>+ );+}diff --git a/src/components/keys/KeyRow.tsx b/src/components/keys/KeyRow.tsxindex 38ec67f5a8..8b3168b9f9 100644--- a/src/components/keys/KeyRow.tsx+++ b/src/components/keys/KeyRow.tsx@@ -11,6 +11,8 @@ import { InstanceProviderMark } from "../ProviderIcons";import { FIELD_EDGE, SettingsLook, SettingsMark } from "../SettingsPrimitives";import { keyEntry, keyForInstance, looksLikeOtherKey, savedState, shownKeyEntry, type KeyEntry, type KeyId, type SavedState } from "./key-catalog";import { checkKey, cleanKey, looksLikeKey, saveKey } from "./key-save";+import { boatSignInShown } from "@/lib/boat-sign-in";+import { BoatSignIn } from "./BoatSignIn";export const KEY_FIELD = `h-8 w-full min-w-0 rounded-lg ${FIELD_EDGE} bg-app px-2 text-[13px] leading-5 text-ink placeholder:text-ink-tertiary focus:outline-none focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-focus disabled:opacity-40`;export const KEY_ROW = "group flex scroll-mt-24 flex-col gap-2 px-4 py-3 transition-[background-color,box-shadow] duration-500 data-[key-highlight]:bg-accent/10 data-[key-highlight]:ring-1 data-[key-highlight]:ring-accent/40 motion-reduce:transition-none";@@ -166,12 +168,15 @@ export function KeyRow({const editing = !saved.configured || replacing;const fieldShown = editing && (!saved.included || saved.configured || ownKey);const other = fieldShown && draft ? looksLikeOtherKey(row, draft) : null;+ // The Boat row offers "Sign in with Boat" first, wherever the server and this page allow it; the key field stays beneath.+ const boatSignIn = entry.id === "box" && !pointer ? boatSignInShown(state.config) : null;const status: KeyStatus = busy === "saving" ? { tone: "busy", text: t("keys.row.saving") }: busy === "removing" ? { tone: "busy", text: t("keys.row.removing") }: busy === "checking" ? { tone: "busy", text: t("common.checking") }: failure && (saved.configured || !fieldShown) ? { tone: "bad", text: t("keys.row.didntWork") }: saved.configured ? { tone: "ok", text: target.test || target.verifiedOnSave || works ? t("keys.connected") : t("common.saved") }+ : boatSignIn?.state === "connected" ? { tone: "ok", text: t("keys.connected") }: saved.included ? { tone: "ok", text: t("keys.includedWithCloudPro") }: null;@@ -435,6 +440,7 @@ export function KeyRow({>{bare ? status && <KeyStatusChip status={status} /> : <RowHeading entry={row} status={status} titleId={titleId} />}<div className={cn("flex flex-col gap-2", !bare && KEY_CONTENT)}>+ {boatSignIn && <BoatSignIn status={boatSignIn} fieldShown={fieldShown && !replacing} onConnected={() => onSaved?.(true)} />}{fieldShown ? field : saved.configured ? masked : (<div><button type="button" data-key-own className="ui-button" onClick={() => { setOwnKey(true); focusAfter.current = "input"; }}>{t("keys.row.useOwn")}</button>diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.tsindex f8b1b6392c..1c43898a35 100644--- a/src/components/keys/key-catalog.ts+++ b/src/components/keys/key-catalog.ts@@ -1,4 +1,5 @@-import { AudioLines, Blocks, CalendarClock, Fingerprint, Image, LockKeyhole, Monitor, Phone, Search, Server, Zap, type LucideIcon } from "lucide-react";+import { AudioLines, Blocks, CalendarClock, Fingerprint, Image, LockKeyhole, Phone, Search, Server, Zap, type LucideIcon } from "lucide-react";+import { BoatMark } from "../BoatMark";import type { AppSettingsSection, ConfigStatus } from "@/state/store";import type { SavedKey } from "@/state/config-status";import type { KeyProvider } from "@/lib/analytics-allowlist";@@ -51,7 +52,7 @@ export type KeyId =| "ollama" | "lmStudio" | "openaiCompat" | "liveCalls" | "liveKey" | "elevenlabs" | "fishAudio" | "geminiTts" | "cartesiaTts" | "chatterbox" | "box" | "vps" | "onePassword" | "composio" | "treg" | "postiz"| "jev" | "openrouterHelper" | "workersAi" | "customDecider" | "imageOpenai" | "imageGemini" | "imageCustom";-export type KeyMark = { driverKind: string; preset?: ProviderIconPreset } | { icon: LucideIcon };+export type KeyMark = { driverKind: string; preset?: ProviderIconPreset } | { icon: LucideIcon | typeof BoatMark };export interface KeyEntry {id: KeyId;@@ -166,10 +167,11 @@ export const KEY_CATALOG: readonly KeyEntry[] = [{ id: "chatterbox", section: "voice", labelKey: "voice.chatterboxServer", purposeKey: "voice.chatterboxHelp", name: "Chatterbox", env: [],words: ["chatterbox", "voice", "tts", "speech", "base url", "server", "address", "local"], mark: { icon: AudioLines }, kind: "panel",status: (config) => ({ configured: Boolean(config.tts?.baseUrl?.trim()) }) },- { id: "box", section: "computers", labelKey: "keys.boat.label", purposeKey: "keys.purpose.box", name: "boat.dev", env: ["BOX_TOKEN"],- words: ["boat", "box", "cloud desktop", "cloud computer", "computer", "sandbox"], mark: { icon: Monitor }, kind: "key",+ { id: "box", section: "computers", labelKey: "keys.boat.label", purposeKey: "keys.purpose.box", name: "boat.dev", env: ["BOX_TOKEN", "OMB_BOAT_SIGN_IN"],+ words: ["boat", "box", "cloud desktop", "cloud computer", "computer", "sandbox", "sign in"], mark: { icon: BoatMark }, kind: "key",target: { patch: (value) => ({ box: { token: value } }), slot: "boxToken", verifiedOnSave: true,- saved: (config) => ({ ...flag(config.box?.included ? undefined : config.box), ...(config.box?.included ? { included: true } : {}) }),+ // The row's field is the pasted key's: a "Sign in with Boat" connection alone is not a saved key.+ saved: (config) => ({ ...flag(config.box?.included || config.box?.keySaved === false ? undefined : config.box), ...(config.box?.included ? { included: true } : {}) }),placeholder: "boat_…", href: "https://docs.boat.dev/api-keys", analytics: "boat", shape: /^(boat|box)_/, warningKey: "keys.boat.warning" } },{ id: "vps", section: "computers", labelKey: "keys.vps.ownServer", purposeKey: "keys.purpose.vps", name: "VPS", env: [],words: ["vps", "ssh", "server", "self-hosted", "computer", "docker"], mark: { icon: Server }, kind: "panel",diff --git a/src/lib/boat-sign-in.ts b/src/lib/boat-sign-in.tsnew file mode 100644index 0000000000..568a66c1fa--- /dev/null+++ b/src/lib/boat-sign-in.ts@@ -0,0 +1,39 @@+// "Sign in with Boat" as the page sees it: a status from the server's config and three requests. The page never holds a+// token and never calls Boat; it only opens Boat's own sign-in page in the person's browser.+import { BOAT_SIGN_IN_PORTS, type BoatSignInStatus } from "../../shared/boat-sign-in";+import { openExternalLink } from "@/lib/app-links";+import { api } from "@/state/api";+import type { ConfigStatus } from "@/state/store";++const LOCAL_HOSTS = ["127.0.0.1", "localhost"];++/** Offered only on the desktop app's own page (one of its three local ports) and only where the server offers it; a+ * hosted Cloud, a self-hosted server and a page reached from another device show the key field alone. */+export function boatSignInShown(+ config: Pick<ConfigStatus, "box"> | null | undefined,+ page: Pick<Location, "hostname" | "port"> = window.location,+): BoatSignInStatus | null {+ const status = config?.box?.signIn;+ if (!status?.available || config?.box?.included) return null;+ return LOCAL_HOSTS.includes(page.hostname) && BOAT_SIGN_IN_PORTS.includes(Number(page.port)) ? status : null;+}++/** Only Boat's own authorize page is ever opened (a loopback stand-in in development): anything else the server says is not. */+export function isBoatSignInUrl(value: unknown): value is string {+ if (typeof value !== "string") return false;+ let url: URL;+ try { url = new URL(value); } catch { return false; }+ const boat = url.protocol === "https:" && url.hostname === "boat.dev" && url.port === "";+ const standIn = url.protocol === "http:" && LOCAL_HOSTS.includes(url.hostname);+ return (boat || standIn) && url.username === "" && url.password === "" && url.pathname === "/api/boat/oauth2/authorize" && url.hash === "";+}++export async function startBoatSignIn(): Promise<void> {+ const answer = await api<{ url?: unknown }>("/api/boat/sign-in/start", { method: "POST" });+ if (!isBoatSignInUrl(answer.url)) throw new Error("not the sign-in page");+ await openExternalLink(answer.url);+}++export const cancelBoatSignIn = (): Promise<unknown> => api("/api/boat/sign-in/cancel", { method: "POST" });++export const disconnectBoat = (): Promise<unknown> => api("/api/boat/sign-in", { method: "DELETE" });diff --git a/src/locales/en.json b/src/locales/en.jsonindex a3ca816475..118b82ddfd 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -12463,5 +12463,24 @@"server.github.card.clone": "{bot} couldn't clone {repo}: GitHub isn't connected.","server.github.card.fetch": "{bot} couldn't fetch from {repo}: GitHub isn't connected.","server.github.card.description": "Connect GitHub so {bot} can push its work to your repositories.",- "server.github.card.connectInApps": "Connect GitHub from this card in the app on your computer, or in Apps."+ "server.github.card.connectInApps": "Connect GitHub from this card in the app on your computer, or in Apps.",+ "boatSignIn.button": "Sign in with Boat",+ "boatSignIn.orPaste": "or paste an API key",+ "boatSignIn.waiting": "Finish signing in in your browser…",+ "boatSignIn.openAgain": "Open the page again",+ "boatSignIn.signedInAs": "Signed in to Boat as {account}",+ "boatSignIn.signedIn": "Signed in to Boat",+ "boatSignIn.disconnect": "Disconnect",+ "boatSignIn.disconnecting": "Disconnecting…",+ "boatSignIn.missing": "Not allowed when you signed in: {scopes}. Anything that needs one of these will say so. Sign in again to allow them.",+ "boatSignIn.again": "Sign in again",+ "boatSignIn.ended": "Your Boat account sign-in has ended. Sign in again.",+ "boatSignIn.cancelled": "Sign-in cancelled. Nothing was connected.",+ "boatSignIn.failed": "The Boat account sign-in did not complete. Try again.",+ "boatSignIn.refused": "Not signed in. The Boat account must reach the cloud desktops this app already made, and none of them may be in use. The browser tab says why.",+ "boatSignIn.unreachable": "Couldn't reach boat.dev to finish signing in. Check your connection and try again.",+ "boatSignIn.notSaved": "The Boat account sign-in could not be saved on this computer. Try again.",+ "boatSignIn.openFailed": "Couldn't open the sign-in page in your browser. Try again.",+ "boatSignIn.usesSignIn": "Cloud desktops use this sign-in: it was set after the Boat API key below.",+ "boatSignIn.usesKey": "Cloud desktops use the Boat API key below: it was saved after this sign-in."}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 9d01f2d8df..e4a511df20 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -12463,5 +12463,24 @@"server.github.card.description": "Conecte o GitHub para que {bot} possa enviar o trabalho para os seus repositórios.","server.github.card.connectInApps": "Conecte o GitHub por este cartão no app do seu computador, ou em Apps.","githubSignIn.title": "Login no GitHub",- "githubSignIn.tokenPlaceholder": "github_pat_…"+ "githubSignIn.tokenPlaceholder": "github_pat_…",+ "boatSignIn.button": "Entrar com o Boat",+ "boatSignIn.orPaste": "ou cole uma chave de API",+ "boatSignIn.waiting": "Conclua o login no seu navegador…",+ "boatSignIn.openAgain": "Abrir a página de novo",+ "boatSignIn.signedInAs": "Conectado ao Boat como {account}",+ "boatSignIn.signedIn": "Conectado ao Boat",+ "boatSignIn.disconnect": "Desconectar",+ "boatSignIn.disconnecting": "Desconectando…",+ "boatSignIn.missing": "Não permitido quando você entrou: {scopes}. O que precisar de um deles vai avisar. Entre de novo para permitir.",+ "boatSignIn.again": "Entrar de novo",+ "boatSignIn.ended": "O login na sua conta do Boat terminou. Entre de novo.",+ "boatSignIn.cancelled": "Login cancelado. Nada foi conectado.",+ "boatSignIn.failed": "O login na conta do Boat não foi concluído. Tente de novo.",+ "boatSignIn.refused": "Login não feito. A conta do Boat precisa alcançar os desktops na nuvem que este app já criou, e nenhum deles pode estar em uso. A aba do navegador diz o motivo.",+ "boatSignIn.unreachable": "Não foi possível alcançar boat.dev para concluir o login. Verifique sua conexão e tente de novo.",+ "boatSignIn.notSaved": "Não foi possível salvar o login da conta do Boat neste computador. Tente de novo.",+ "boatSignIn.openFailed": "Não foi possível abrir a página de login no seu navegador. Tente de novo.",+ "boatSignIn.usesSignIn": "Os desktops na nuvem usam este login: ele foi definido depois da chave de API do Boat abaixo.",+ "boatSignIn.usesKey": "Os desktops na nuvem usam a chave de API do Boat abaixo: ela foi salva depois deste login."}diff --git a/src/locales/vocabulary.test.ts b/src/locales/vocabulary.test.tsindex 1c47193951..c7c78dd1fa 100644--- a/src/locales/vocabulary.test.ts+++ b/src/locales/vocabulary.test.ts@@ -43,6 +43,9 @@ const EN_ALLOWED: Record<string, string> = {"botAccess.cloud.boat": "the own-key provider picker names its two providers, Boat and a VPS","botAccess.cloud.hostedBackendDescription": "the own-key provider picker names its two providers, Boat and a VPS","botAccess.cloud.vpsAutoDescription": "the own-key provider picker's VPS line names its Cloud choice",+ "boatSignIn.button": "the owner's wording for signing in with a person's own Boat account",+ "boatSignIn.signedInAs": "names the person's own Boat account, as the key row does",+ "boatSignIn.signedIn": "names the person's own Boat account, as the key row does",};const ROOT = fileURLToPath(new URL("../../", import.meta.url));diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex 87d9c6c7b6..ea4c631ab5 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -60,7 +60,7 @@ export interface ConfigStatus {billing?: { currency?: string; prices?: Record<string, { inputPerMillion: number; outputPerMillion: number; cachedInputPerMillion?: number }> };composio: SavedKey & { mode?: "managed" | "self-hosted" | "unavailable" };/** `included`: cloud computers come with Cloud Pro, no key is saved. */- box: SavedKey & { included?: boolean };+ box: SavedKey & { included?: boolean; /** A pasted API key is saved (`configured` is also true for a sign-in alone). */ keySaved?: boolean; signIn?: import("../../shared/boat-sign-in").BoatSignInStatus };/** `servers`: named servers for the per-bot picker; empty for client sessions, missing from an older server. */vps: { configured: boolean; sshAlias: string; servers?: { name: string; sshAlias: string; memoryGb?: number; cpus?: number }[]; memoryGb?: number; cpus?: number };rooms: { turnTimeoutMinutes: number };