From e47c422dc4b3d27e5a9cbb0eebca6e1694c8b821 Mon Sep 17 00:00:00 2001
From: David McKay
Date: Sun, 15 Nov 2026 12:37:21 -0800
Subject: [PATCH 001/116] Settings for an OpenBot Desktop connected to an
OpenBot that runs elsewhere
Connected, nothing of OpenBot runs on this computer, so Settings, Computer shows where the app is connected, Sign out, and Use OpenBot on this computer instead, in place of the local services, memory and install folder. The app's version, updates and log folder stay. The page holds no sign-in there, so every Sign out asks the desktop app, and a sign-in that stopped working returns to the desktop app's setup. A desktop app from before it could connect is read as OpenBot on this computer, and a browser is unchanged.
---
.../components/app-sidebar/use-sign-out.ts | 5 +-
.../settings/connection-sections.tsx | 211 +++++++++++++
.../settings/this-computer-sections.tsx | 4 +-
app/src/lib/auth/mutations.ts | 41 ++-
app/src/lib/desktop/mutations.ts | 21 ++
app/src/lib/desktop/queries.ts | 40 +++
app/src/routes/_authed.tsx | 13 +
app/src/routes/_authed/settings/computer.tsx | 25 +-
app/tests/desktop-connected-settings.test.tsx | 276 ++++++++++++++++++
9 files changed, 627 insertions(+), 9 deletions(-)
create mode 100644 app/src/components/settings/connection-sections.tsx
create mode 100644 app/tests/desktop-connected-settings.test.tsx
diff --git a/app/src/components/app-sidebar/use-sign-out.ts b/app/src/components/app-sidebar/use-sign-out.ts
index f884450293..cd4ce84238 100644
--- a/app/src/components/app-sidebar/use-sign-out.ts
+++ b/app/src/components/app-sidebar/use-sign-out.ts
@@ -20,9 +20,10 @@ export function useSignOut() {
run: () => {
if (signOut.isPending) return;
signOut.mutate(undefined, {
- onSuccess: () => {
+ onSuccess: ({ leaving }) => {
toast.close(SIGN_OUT_TOAST);
- void navigate({ to: "/sign" });
+ // Inside a connected OpenBot Desktop the app shows its own setup, where sign-in is.
+ if (!leaving) void navigate({ to: "/sign" });
},
onError: (error) =>
toast.add({
diff --git a/app/src/components/settings/connection-sections.tsx b/app/src/components/settings/connection-sections.tsx
new file mode 100644
index 0000000000..d998ede765
--- /dev/null
+++ b/app/src/components/settings/connection-sections.tsx
@@ -0,0 +1,211 @@
+import {
+ IconDeviceLaptop,
+ IconLogout,
+ IconPlugConnected,
+} from "@tabler/icons-react";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+import { PageRows, PageSection } from "@/components/layout/page-shell";
+import { RowMark } from "@/components/layout/row-mark";
+import {
+ LogsRow,
+ VersionRow,
+} from "@/components/settings/this-computer-sections";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemTitle,
+} from "@/components/ui/item";
+import { Separator } from "@/components/ui/separator";
+import {
+ changeConnectionMutationOptions,
+ signOutOfConnectedOpenBotMutationOptions,
+} from "@/lib/desktop/mutations";
+import { desktopStatusQueryOptions } from "@/lib/desktop/queries";
+import { COMPUTER_SECTION } from "@/lib/settings/computer-sections";
+
+/** The address's host, which is how a person names the OpenBot they connect to. */
+function hostOf(address: string): string {
+ try {
+ return new URL(address).host;
+ } catch {
+ return address;
+ }
+}
+
+/**
+ * Settings → Computer inside an OpenBot Desktop that is connected to an OpenBot running somewhere
+ * else: where it is connected, the two ways out, and the app's own details.
+ *
+ * It takes the place of `ThisComputerSections`. Nothing of OpenBot runs on this computer then, so
+ * there are no services to restart or stop, no memory to report and no install folder. The app's
+ * version, its updates and its log folder are about the app, and stay.
+ *
+ * Both ways out end with the window back at setup, so this page goes with them, as it does on Stop.
+ */
+export function ConnectionSections({ address }: { address: string }) {
+ const status = useQuery(desktopStatusQueryOptions({ memory: false }));
+ return (
+ <>
+
+
+
+
+
+
+
+ Connected to
+
+ {address}
+
+
+
+
+
+
+
+
+
+ {status.data && (
+
+
+ {status.data.logFolder && (
+ <>
+
+
+ >
+ )}
+
+
+
+ )}
+ >
+ );
+}
+
+function SignOutRow({ host }: { host: string }) {
+ const [open, setOpen] = useState(false);
+ const signOut = useMutation(signOutOfConnectedOpenBotMutationOptions());
+ // On success the desktop app is showing setup, and this page goes with it.
+ const leaving = signOut.isPending || signOut.isSuccess;
+ return (
+ <>
+
+
+
+
+
+ Sign out
+
+ Sign out of this OpenBot on this computer.
+
+
+
+
+
+
+
+ >
+ );
+}
+
+function UseThisComputerRow({ host }: { host: string }) {
+ const [open, setOpen] = useState(false);
+ const change = useMutation(changeConnectionMutationOptions());
+ // On success the desktop app is showing setup, and this page goes with it.
+ const leaving = change.isPending || change.isSuccess;
+ return (
+ <>
+
+
+
+
+
+ Use OpenBot on this computer instead
+
+ Run every part of OpenBot on this computer.
+
+
+
+
+
+
+
+ >
+ );
+}
diff --git a/app/src/components/settings/this-computer-sections.tsx b/app/src/components/settings/this-computer-sections.tsx
index eef145d54b..730d07a418 100644
--- a/app/src/components/settings/this-computer-sections.tsx
+++ b/app/src/components/settings/this-computer-sections.tsx
@@ -355,7 +355,7 @@ function MachineSection({
* Where the desktop app keeps its log, with Open log folder, so a person can share the file when
* they ask for help. The desktop app opens its own folder; nothing here names a path to open.
*/
-function LogsRow({ folder }: { folder: string }) {
+export function LogsRow({ folder }: { folder: string }) {
const open = useMutation(openLogFolderMutationOptions());
return (
@@ -405,7 +405,7 @@ function LogsRow({ folder }: { folder: string }) {
* A newer version found says how ready it is, as the banner does: downloading in the background
* while this version keeps running, then ready to install in a few minutes.
*/
-function VersionRow({ status }: { status: DesktopStatus }) {
+export function VersionRow({ status }: { status: DesktopStatus }) {
const check = useMutation(checkAppUpdateMutationOptions(queryClient));
const install = useMutation(installAppUpdateMutationOptions(queryClient));
// The download's progress, asked twice a second from the click on, as the banner asks once it
diff --git a/app/src/lib/auth/mutations.ts b/app/src/lib/auth/mutations.ts
index 7672b569d9..c0ff4d0d5f 100644
--- a/app/src/lib/auth/mutations.ts
+++ b/app/src/lib/auth/mutations.ts
@@ -1,6 +1,11 @@
import { mutationOptions, type QueryClient } from "@tanstack/react-query";
import { updatePerson } from "@/lib/api/generated/people/people";
import { idempotencyKey, ORGANIZATION_ID } from "@/lib/api/request";
+import {
+ desktopConnectionQueryOptions,
+ invokeDesktop,
+} from "@/lib/desktop/queries";
+import { desktopShell } from "@/lib/desktop/shell";
import { clearSkin } from "@/skins/store";
import { authClient } from "./client";
import { authKeys } from "./queries";
@@ -17,6 +22,33 @@ async function signOut() {
if (!answered || answered.error) throw new Error(SIGN_OUT_UNFINISHED);
}
+/**
+ * Whether this page is inside an OpenBot Desktop connected to an OpenBot that runs somewhere else.
+ * There the desktop app holds the sign-in and the page holds none, so the desktop app is what signs
+ * out, and it shows its own setup afterwards.
+ */
+export async function connectedThroughDesktop(
+ queryClient: QueryClient,
+): Promise {
+ if (desktopShell() === null) return false;
+ const connection = await queryClient.ensureQueryData(
+ desktopConnectionQueryOptions(),
+ );
+ return connection.mode === "connected";
+}
+
+/** Ask the desktop app to sign out of the OpenBot it is connected to. */
+export async function signOutThroughDesktop() {
+ try {
+ await invokeDesktop("sign_out");
+ } catch {
+ throw new Error(SIGN_OUT_UNFINISHED);
+ }
+}
+
+/** How a sign-out ended: `leaving` when the desktop app is taking the window back to its setup. */
+export type SignedOut = { leaving: boolean };
+
/**
* Every way out of OpenBot signs out through here, the skins' own menus included.
*
@@ -26,7 +58,14 @@ async function signOut() {
*/
export function signOutMutationOptions(queryClient: QueryClient) {
return mutationOptions({
- mutationFn: signOut,
+ mutationFn: async (): Promise => {
+ if (await connectedThroughDesktop(queryClient)) {
+ await signOutThroughDesktop();
+ return { leaving: true };
+ }
+ await signOut();
+ return { leaving: false };
+ },
onSuccess: () => {
clearSkin();
queryClient.removeQueries({ queryKey: authKeys.all });
diff --git a/app/src/lib/desktop/mutations.ts b/app/src/lib/desktop/mutations.ts
index 006b3382b1..2c3c454bd5 100644
--- a/app/src/lib/desktop/mutations.ts
+++ b/app/src/lib/desktop/mutations.ts
@@ -56,6 +56,27 @@ export function changeAiConnectionMutationOptions() {
});
}
+/**
+ * Sign out of the OpenBot this app is connected to. The desktop app ends the sign-in there, forgets
+ * it on this computer and shows setup with the address still filled in. Like Stop, this page goes
+ * with it.
+ */
+export function signOutOfConnectedOpenBotMutationOptions() {
+ return mutationOptions({
+ mutationFn: (): Promise => invokeDesktop("sign_out"),
+ });
+}
+
+/**
+ * Go back to OpenBot on this computer. The desktop app signs out of the OpenBot it is connected to
+ * and shows setup at the choice of where OpenBot runs. Nothing on this computer is changed by it.
+ */
+export function changeConnectionMutationOptions() {
+ return mutationOptions({
+ mutationFn: (): Promise => invokeDesktop("change_connection"),
+ });
+}
+
/**
* Check for updates now. The desktop app reads its update feed and keeps the answer, so the banner
* reads it too. Rejects with the app's own sentence when the feed couldn't be read.
diff --git a/app/src/lib/desktop/queries.ts b/app/src/lib/desktop/queries.ts
index 1e2ba605ca..f878af538a 100644
--- a/app/src/lib/desktop/queries.ts
+++ b/app/src/lib/desktop/queries.ts
@@ -123,8 +123,20 @@ export type DesktopUsageData = {
offByEnvironment: boolean;
};
+/**
+ * Where the OpenBot this window shows runs: on this computer, which the desktop app started itself,
+ * or somewhere else, at an address the person typed and signed in to. Never the sign-in itself: the
+ * desktop app keeps that and the page never holds it.
+ */
+export type DesktopConnection =
+ | { mode: "local"; address: null }
+ | { mode: "connected"; address: string };
+
+const ON_THIS_COMPUTER: DesktopConnection = { mode: "local", address: null };
+
export const desktopKeys = {
all: ["desktop"] as const,
+ connection: ["desktop", "connection"] as const,
aiConnection: ["desktop", "ai-connection"] as const,
usageData: ["desktop", "usage-data"] as const,
status: (memory: boolean) => ["desktop", "status", { memory }] as const,
@@ -144,6 +156,34 @@ export async function invokeDesktop(
return (await shell.invoke(`${PLUGIN}|${command}`, args)) as T;
}
+/**
+ * Whether this window shows an OpenBot on this computer or one it is connected to. In a browser,
+ * and in a desktop app from before it could connect (which refuses the question the same way every
+ * time), the answer is this computer. It does not change while the page shows: changing it sends
+ * the window back to setup.
+ */
+export function desktopConnectionQueryOptions() {
+ return queryOptions({
+ queryKey: desktopKeys.connection,
+ queryFn: async (): Promise => {
+ if (desktopShell() === null) return ON_THIS_COMPUTER;
+ try {
+ const answer = await invokeDesktop<{
+ mode?: string;
+ address?: string | null;
+ }>("connection");
+ return answer?.mode === "connected" && answer.address
+ ? { mode: "connected", address: answer.address }
+ : ON_THIS_COMPUTER;
+ } catch {
+ return ON_THIS_COMPUTER;
+ }
+ },
+ staleTime: Number.POSITIVE_INFINITY,
+ retry: false,
+ });
+}
+
/**
* What runs here, in two reads. Without `memory` it answers in milliseconds, with every container
* listed and none measured, so the page draws at once. With `memory` it takes about two seconds,
diff --git a/app/src/routes/_authed.tsx b/app/src/routes/_authed.tsx
index 8aa969e504..a38b3d4034 100644
--- a/app/src/routes/_authed.tsx
+++ b/app/src/routes/_authed.tsx
@@ -3,6 +3,10 @@ import type { ReactNode } from "react";
import { BotLookProvider } from "../components/agents/bot-look";
import { TeamFeaturesDialog } from "../components/edition/team-features-dialog";
import { CommandMenu } from "../components/navigation/command-menu";
+import {
+ connectedThroughDesktop,
+ signOutThroughDesktop,
+} from "../lib/auth/mutations";
import { currentUserQueryOptions, needsOnboarding } from "../lib/auth/queries";
import { CopilotProvider } from "../lib/copilot/provider";
import { AppHotkeys } from "../lib/hotkeys/app-hotkeys";
@@ -16,6 +20,15 @@ export const Route = createFileRoute("/_authed")({
currentUserQueryOptions(),
);
if (!user) {
+ /*
+ * Inside an OpenBot Desktop connected to an OpenBot that runs somewhere else, the desktop app
+ * holds the sign-in and this page has none to renew: the web sign-in screen would sign in a
+ * window that cannot keep it. The desktop app ends what is left of the sign-in and shows its
+ * own setup, where the person signs in again. If it cannot, the sign-in screen is still there.
+ */
+ if (await connectedThroughDesktop(context.queryClient)) {
+ await signOutThroughDesktop().catch(() => undefined);
+ }
throw redirect({ to: "/sign" });
}
/*
diff --git a/app/src/routes/_authed/settings/computer.tsx b/app/src/routes/_authed/settings/computer.tsx
index aa446d1794..3d540e9be0 100644
--- a/app/src/routes/_authed/settings/computer.tsx
+++ b/app/src/routes/_authed/settings/computer.tsx
@@ -3,8 +3,10 @@ import { createFileRoute } from "@tanstack/react-router";
import { PageShell } from "@/components/layout/page-shell";
import { ComputersPage } from "@/components/manage/computers-page";
import { BrowserSections } from "@/components/settings/browsers/browser-sections";
+import { ConnectionSections } from "@/components/settings/connection-sections";
import { ThisComputerSections } from "@/components/settings/this-computer-sections";
import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries";
+import { desktopConnectionQueryOptions } from "@/lib/desktop/queries";
import { desktopShell } from "@/lib/desktop/shell";
import { editionOf } from "@/lib/edition-guard";
import { useScrollToSection } from "@/lib/settings/computer-sections";
@@ -36,6 +38,15 @@ function ComputerPage() {
const personal =
useQuery(deploymentCapabilitiesQueryOptions()).data?.edition === "personal";
const desktop = desktopShell() !== null;
+ /*
+ * Inside OpenBot Desktop: whether OpenBot runs on this computer or the app is connected to one that
+ * runs somewhere else. Until the app has said which, neither is drawn, so the wrong one never shows.
+ */
+ const connection = useQuery({
+ ...desktopConnectionQueryOptions(),
+ enabled: desktop,
+ }).data;
+ const connected = connection?.mode === "connected";
/*
* Desktop's Status opens `/settings/this-computer` and the extension's popup `/settings/browsers`;
* each redirects here with its section's hash.
@@ -46,14 +57,20 @@ function ComputerPage() {
description={
personal
? "Your Bots share one computer, where each keeps its own browser signed in. A command one Bot runs can still read another Bot's files. Choose folders they can read here, and connect the browsers you teach them in."
- : desktop
- ? "Connect the browsers you teach your Bots in, and see what OpenBot runs on this computer."
- : "Connect the browsers you teach your Bots in."
+ : connected
+ ? "Connect the browsers you teach your Bots in, and see which OpenBot this app is connected to."
+ : desktop
+ ? "Connect the browsers you teach your Bots in, and see what OpenBot runs on this computer."
+ : "Connect the browsers you teach your Bots in."
}
title="Computer"
>
{personal ? : null}
- {desktop ? : null}
+ {!desktop || !connection ? null : connection.mode === "connected" ? (
+
+ ) : (
+
+ )}
);
diff --git a/app/tests/desktop-connected-settings.test.tsx b/app/tests/desktop-connected-settings.test.tsx
new file mode 100644
index 0000000000..bbaa6e5817
--- /dev/null
+++ b/app/tests/desktop-connected-settings.test.tsx
@@ -0,0 +1,276 @@
+/**
+ * OpenBot Desktop can show an OpenBot that runs on this computer, or one it is connected to at an address. Connected,
+ * nothing of OpenBot runs here, so Settings → Computer says where the app is connected and offers the two ways out
+ * (sign out, or go back to OpenBot on this computer) in place of the services, memory and install folder of a local
+ * OpenBot. The app's own version, updates and log folder stay, since those are about the app.
+ *
+ * The page holds no sign-in of its own there: the desktop app keeps it. So signing out, from Settings or from the
+ * account menu, is asked of the desktop app, and a sign-in that stopped working sends the person back to the desktop
+ * app's setup, never to the web sign-in screen.
+ *
+ * A desktop app from before it could connect refuses the question, and is read as OpenBot on this computer.
+ */
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+} from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRouter,
+ RouterProvider,
+} from "@tanstack/react-router";
+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";
+import type { ComponentType } from "react";
+import { signOutMutationOptions } from "@/lib/auth/mutations";
+import { deploymentKeys } from "@/lib/deployment/queries";
+import type { DesktopStatus } from "@/lib/desktop/queries";
+import { Route as AuthedRoute } from "@/routes/_authed";
+import { Route as ComputerRoute } from "@/routes/_authed/settings/computer";
+import { settleReactWork } from "./settle-react-work";
+
+const ADDRESS = "https://openbot.northwind.example";
+
+/** What a connected desktop app answers `status` with: the app's own facts and nothing of a local OpenBot. */
+const CONNECTED_STATUS: DesktopStatus = {
+ openbotRunning: false,
+ openbotHeld: false,
+ processes: [],
+ containers: [],
+ intelligenceStack: null,
+ intelligenceContainers: [],
+ engine: null,
+ root: "",
+ appPort: null,
+ version: "1.1.0",
+ build: "Built 2026-11-15 18:30 UTC from 795f619 on main",
+ logFolder: "/Users/me/Library/Logs/ai.copilotkit.openbot.desktop",
+};
+
+const LOCAL_STATUS: DesktopStatus = {
+ ...CONNECTED_STATUS,
+ openbotRunning: true,
+ openbotHeld: true,
+ engine: "podman",
+ root: "/Users/me/OpenBot",
+ appPort: 3010,
+};
+
+type Shell = "connected" | "local" | "older";
+
+/** Every command the page asked the desktop app, in order. */
+let asked: string[] = [];
+/** Every address the page asked the server. */
+let fetched: string[] = [];
+const originalFetch = globalThis.fetch;
+
+function installShell(kind: Shell) {
+ (window as unknown as Record).__TAURI_INTERNALS__ = {
+ transformCallback: () => 0,
+ invoke: async (command: string) => {
+ const name = command.replace("plugin:openbot-desktop|", "");
+ asked.push(name);
+ if (name === "connection") {
+ if (kind === "older") throw "command connection not found";
+ return kind === "connected"
+ ? { mode: "connected", address: ADDRESS }
+ : { mode: "local", address: null };
+ }
+ if (name === "status")
+ return kind === "connected" ? CONNECTED_STATUS : LOCAL_STATUS;
+ if (name === "update_offer")
+ return { version: null, current: "1.1.0", installing: null };
+ if (name === "sign_out" || name === "change_connection") return null;
+ throw `command ${command} not found`;
+ },
+ };
+}
+
+beforeAll(() => {
+ GlobalRegistrator.register({ url: "http://127.0.0.1:3010/" });
+});
+beforeEach(() => {
+ asked = [];
+ fetched = [];
+ globalThis.fetch = Object.assign(
+ async (input: RequestInfo | URL) => {
+ const url = typeof input === "string" ? input : input.toString();
+ fetched.push(new URL(url, "http://127.0.0.1:3010").pathname);
+ if (url.includes("/api/auth/sign-out"))
+ return Response.json({ success: true });
+ return Response.json({ error: "not served" }, { status: 401 });
+ },
+ { preconnect: originalFetch.preconnect },
+ );
+});
+afterEach(() => {
+ cleanup();
+ globalThis.fetch = originalFetch;
+ delete (window as unknown as Record).__TAURI_INTERNALS__;
+});
+afterAll(async () => {
+ await settleReactWork();
+ GlobalRegistrator.unregister();
+});
+
+function newQueryClient() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ queryClient.setQueryDefaults(deploymentKeys.capabilities(), {
+ staleTime: Number.POSITIVE_INFINITY,
+ });
+ queryClient.setQueryData(deploymentKeys.capabilities(), {
+ generativeUi: true,
+ selfHostBanner: false,
+ localEvaluation: false,
+ edition: "team",
+ });
+ return queryClient;
+}
+
+function renderComputer(kind: Shell) {
+ installShell(kind);
+ const Page = ComputerRoute.options.component as ComponentType;
+ const router = createRouter({
+ routeTree: createRootRoute({ component: () => }),
+ history: createMemoryHistory({ initialEntries: ["/"] }),
+ });
+ return render(
+
+
+ ,
+ );
+}
+
+test("connected, Settings → Computer says where the app is connected and shows nothing of a local OpenBot", async () => {
+ const view = renderComputer("connected");
+ await view.findByRole("heading", { name: "Connection" });
+ expect(view.getByText(ADDRESS)).toBeTruthy();
+ expect(view.getByRole("button", { name: "Sign out" })).toBeTruthy();
+ expect(view.getByRole("button", { name: "Use this computer" })).toBeTruthy();
+ // The app itself: its version and its log folder stay.
+ expect(await view.findByText("Version 1.1.0")).toBeTruthy();
+ expect(view.getByRole("button", { name: "Open log folder" })).toBeTruthy();
+ // Nothing OpenBot runs here: no services, no install folder, no engine.
+ expect(view.queryByRole("heading", { name: "App" })).toBeNull();
+ expect(view.queryByText("Software OpenBot runs on")).toBeNull();
+ expect(view.queryByText("Installed in")).toBeNull();
+ expect(view.queryByRole("button", { name: "Stop" })).toBeNull();
+ expect(view.queryByRole("button", { name: "Restart" })).toBeNull();
+ const header = view
+ .getByRole("heading", { level: 1, name: "Computer" })
+ .closest("header");
+ expect(header?.textContent).toContain(
+ "Connect the browsers you teach your Bots in, and see which OpenBot this app is connected to.",
+ );
+ expect(header?.textContent).not.toContain("runs on this computer");
+});
+
+test("with OpenBot on this computer, the page is as it was: its services, and no Connection section", async () => {
+ const view = renderComputer("local");
+ await view.findByRole("heading", { name: "App" });
+ expect(view.getByText("Installed in")).toBeTruthy();
+ expect(view.queryByRole("heading", { name: "Connection" })).toBeNull();
+});
+
+test("a desktop app from before it could connect is read as OpenBot on this computer", async () => {
+ const view = renderComputer("older");
+ await view.findByRole("heading", { name: "App" });
+ expect(asked).toContain("connection");
+ expect(view.queryByRole("heading", { name: "Connection" })).toBeNull();
+});
+
+test("Sign out asks first, then asks the desktop app to sign out", async () => {
+ const view = renderComputer("connected");
+ fireEvent.click(await view.findByRole("button", { name: "Sign out" }));
+ const dialog = await view.findByRole("dialog");
+ expect(dialog.textContent).toContain(
+ "Sign out of openbot.northwind.example?",
+ );
+ expect(asked).not.toContain("sign_out");
+ fireEvent.click(
+ Array.from(dialog.querySelectorAll("button")).find(
+ (button) => button.textContent === "Sign out",
+ ) as HTMLButtonElement,
+ );
+ await waitFor(() => expect(asked).toContain("sign_out"));
+});
+
+test("Use this computer asks first, saying nothing here is lost, then asks the desktop app to switch", async () => {
+ const view = renderComputer("connected");
+ fireEvent.click(
+ await view.findByRole("button", { name: "Use this computer" }),
+ );
+ const dialog = await view.findByRole("dialog");
+ expect(dialog.textContent).toContain("Use OpenBot on this computer instead?");
+ expect(dialog.textContent).toContain("Nothing on this computer is lost");
+ expect(asked).not.toContain("change_connection");
+ fireEvent.click(
+ Array.from(dialog.querySelectorAll("button")).find(
+ (button) => button.textContent === "Switch to this computer",
+ ) as HTMLButtonElement,
+ );
+ await waitFor(() => expect(asked).toContain("change_connection"));
+ expect(asked).not.toContain("sign_out");
+});
+
+test("connected, the account menu's Sign out is the desktop app's, and the page is told it is leaving", async () => {
+ installShell("connected");
+ const queryClient = newQueryClient();
+ const options = signOutMutationOptions(queryClient);
+ const outcome = await options.mutationFn?.(undefined, {} as never);
+ expect(asked).toContain("sign_out");
+ expect(fetched).not.toContain("/api/auth/sign-out");
+ expect(outcome).toEqual({ leaving: true });
+});
+
+test("with OpenBot on this computer or in a browser, Sign out is the web sign-out as before", async () => {
+ for (const kind of ["local", "browser"] as const) {
+ asked = [];
+ fetched = [];
+ if (kind === "local") installShell("local");
+ const options = signOutMutationOptions(newQueryClient());
+ const outcome = await options.mutationFn?.(undefined, {} as never);
+ expect(asked).not.toContain("sign_out");
+ expect(fetched).toContain("/api/auth/sign-out");
+ expect(outcome).toEqual({ leaving: false });
+ delete (window as unknown as Record).__TAURI_INTERNALS__;
+ }
+});
+
+test("connected, a sign-in that stopped working goes back to the desktop app's setup", async () => {
+ installShell("connected");
+ const guard = AuthedRoute.options.beforeLoad as (input: {
+ context: { queryClient: QueryClient };
+ location: { pathname: string };
+ }) => Promise;
+ await guard({
+ context: { queryClient: newQueryClient() },
+ location: { pathname: "/" },
+ }).catch(() => undefined);
+ expect(fetched).toContain("/api/v2/organizations/default/people/me");
+ expect(asked).toContain("sign_out");
+});
+
+test("in a browser, a visitor who is not signed in goes to the sign-in screen and no desktop app is asked", async () => {
+ const guard = AuthedRoute.options.beforeLoad as (input: {
+ context: { queryClient: QueryClient };
+ location: { pathname: string };
+ }) => Promise;
+ const thrown = await guard({
+ context: { queryClient: newQueryClient() },
+ location: { pathname: "/" },
+ }).then(
+ () => null,
+ (error) => error,
+ );
+ expect(asked).toEqual([]);
+ expect(JSON.stringify(thrown?.options ?? thrown)).toContain("/sign");
+});
From 0fccb7709687e97a5000f6b6706147dfa9a2d2cf Mon Sep 17 00:00:00 2001
From: David McKay
Date: Sun, 15 Nov 2026 12:39:36 -0800
Subject: [PATCH 002/116] Add an API keys page to Settings, and say what OAuth
needs in the spec
A person had no way to make their first API key from the app: the operations were in the spec and nothing called them. Settings now has API keys under You. It lists the person's keys with when each was made, last used and expires, creates one by name and shows it once with Copy, and revokes one after asking.
Two answers from the API read as a sentence, not an error. An OpenBot with no sign-in (503 SIGN_IN_UNAVAILABLE) says it has no keys. A caller that is not signed in on the web (403), which is OpenBot Desktop connected to an OpenBot elsewhere, is told to create keys from OpenBot in the browser, with a button that opens the page there.
The spec's description and its appOAuth and apiKey schemes now state what a developer needs: the public client ids, loopback redirect addresses, the metadata, authorize, token and revocation endpoints, token prefixes and lifetimes, consent, and how to get a first key. Text only, so the generated clients are unchanged.
---
CHANGELOG.md | 5 +
api/openapi.yaml | 21 +-
api/openapi/common.yaml | 57 ++-
app/src/components/settings/api-keys.tsx | 405 ++++++++++++++++++
.../components/settings/settings-sidebar.tsx | 10 +-
app/src/lib/api-keys/mutations.ts | 74 ++++
app/src/lib/api-keys/queries.ts | 85 ++++
app/src/lib/desktop/open-in-browser.ts | 18 +
app/src/routeTree.gen.ts | 21 +
app/src/routes/_authed/settings/api-keys.tsx | 6 +
app/tests/api-keys-screen.test.tsx | 339 +++++++++++++++
app/tests/settings-sidebar.test.ts | 9 +
12 files changed, 1046 insertions(+), 4 deletions(-)
create mode 100644 app/src/components/settings/api-keys.tsx
create mode 100644 app/src/lib/api-keys/mutations.ts
create mode 100644 app/src/lib/api-keys/queries.ts
create mode 100644 app/src/lib/desktop/open-in-browser.ts
create mode 100644 app/src/routes/_authed/settings/api-keys.tsx
create mode 100644 app/tests/api-keys-screen.test.tsx
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 56df252441..3c7a53d441 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -350,6 +350,11 @@ earlier release's is one top-level line in it, `x-openbot-scheduled-work: server
person, is sent as `Authorization: Bearer` or `x-api-key`, and works on `/api/v2` only. The
server also issues access tokens through OAuth 2.1 with PKCE, which work on `/api/v2` only too.
Both end when the person is removed.
+- **Settings has an API keys page.** Under You, a signed-in person lists their keys, creates one
+ by name and revokes one. A new key is shown once, with Copy. OpenBot on one computer for one
+ person has no sign-in and says it has no keys, and OpenBot Desktop connected to an OpenBot
+ elsewhere opens the page in your browser. The spec now lists what an app needs for OAuth: the
+ client ids, redirect addresses, endpoints and how long tokens last.
- **The web app calls the new addresses**, through a client generated from the spec, for Bots,
the audit trail, accounts, admin settings, model connections, notifications, routines,
conversations and approvals, and opens its sockets there. Apps, connections, a Bot's grants,
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 8a9222a3b9..5ae6a41537 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -10,6 +10,10 @@ info:
Until multi-organization lands, an OpenBot install has exactly one organization, and organizationId is that organization. Clients address it as `default`; the server treats any other value as an organization that does not exist.
+ A program of your own signs its requests in one of two ways, and both work on /api/v2 only. An API key acts as the person who made it. Keys start `obk_` and are sent as `Authorization: Bearer ` or in an `x-api-key` header. To get a first key, sign in to OpenBot's web app, open Settings, then API keys, and create one. The key is shown once. Only a person signed in to the web app can make or delete keys: a key or an app's sign-in cannot. An app that signs people in uses OAuth 2.1 instead, described under the appOAuth security scheme: its client ids, redirect addresses, endpoints and how long tokens last.
+
+ An install for one person on one computer has no sign-in. It signs nobody in, so it has neither OAuth nor API keys, and the operations that manage keys and sessions answer 503 with the code SIGN_IN_UNAVAILABLE.
+
This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request.
servers:
- url: http://127.0.0.1:3001
@@ -18295,7 +18299,20 @@ components:
description: The web app's server-side session, so no token ever reaches the browser. Served over HTTPS the cookie is __Secure-better-auth.session_token. A single-user install signs its one person in without a cookie.
appOAuth:
type: oauth2
- description: Desktop and mobile. OAuth 2.1 authorization code with PKCE (RFC 7636, S256 only); the access token is sent as a bearer token.
+ description: |-
+ Desktop and mobile. OAuth 2.1 authorization code with PKCE (RFC 7636, S256 only); the access token is sent as a bearer token.
+
+ Clients. Three public clients are registered: `openbot-desktop-oauth`, `openbot-mobile` and `openbot-cli`. A public client has no secret and must use PKCE with S256. Dynamic client registration is off, so an app uses one of these ids.
+
+ Redirect addresses. A client on the person's own computer listens on a loopback address and any port: `http://127.0.0.1:/callback` or `http://[::1]:/callback`. `localhost` is not accepted.
+
+ Endpoints. The authorization server's metadata (RFC 8414) is at `/.well-known/oauth-authorization-server/api/auth`. The person is sent to `/api/auth/oauth2/authorize`. The code is exchanged, and a token refreshed, at `/api/auth/oauth2/token`, with a form-encoded body (`application/x-www-form-urlencoded`) that carries `client_id`. A token is revoked (RFC 7009) at `/api/auth/oauth2/revoke`.
+
+ Tokens. An access token starts `oba_` and lasts one hour. A refresh token starts `obr_`, is issued only when the `offline_access` scope is asked for, and rotates on every use: each refresh answers a new refresh token and ends the one it was given. Access tokens work on /api/v2 only.
+
+ Consent. The person is asked once for each app, and not again for scopes they already allowed it.
+
+ An install for one person on one computer has no sign-in, so it has no OAuth: there is nobody to authorize an app as.
flows:
authorizationCode:
authorizationUrl: /api/auth/oauth2/authorize
@@ -18383,7 +18400,7 @@ components:
type: http
scheme: bearer
bearerFormat: OpenBot API key
- description: Automation. An API key acts as the person who created it, inside one organization.
+ description: 'Automation. An API key acts as the person who created it, inside one organization. A key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 only. A person makes one in the web app, signed in, under Settings, then API keys (createApiKey).'
recorderConnection:
type: http
scheme: bearer
diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml
index 4adf35fbec..39892df718 100644
--- a/api/openapi/common.yaml
+++ b/api/openapi/common.yaml
@@ -32,6 +32,23 @@ info:
does not exist.
+ A program of your own signs its requests in one of two ways, and both
+ work on /api/v2 only. An API key acts as the person who made it. Keys
+ start `obk_` and are sent as `Authorization: Bearer ` or in an
+ `x-api-key` header. To get a first key, sign in to OpenBot's web app, open
+ Settings, then API keys, and create one. The key is shown once. Only a
+ person signed in to the web app can make or delete keys: a key or an
+ app's sign-in cannot. An app that signs people in uses OAuth 2.1
+ instead, described under the appOAuth security scheme: its client ids,
+ redirect addresses, endpoints and how long tokens last.
+
+
+ An install for one person on one computer has no sign-in. It signs
+ nobody in, so it has neither OAuth nor API keys, and the operations
+ that manage keys and sessions answer 503 with the code
+ SIGN_IN_UNAVAILABLE.
+
+
This file is the single source of truth: the clients, the server's types,
the docs and the contract tests are all generated from it or checked
against it. A change that breaks an existing client fails the pull request.
@@ -420,6 +437,41 @@ components:
description: >-
Desktop and mobile. OAuth 2.1 authorization code with PKCE
(RFC 7636, S256 only); the access token is sent as a bearer token.
+
+
+ Clients. Three public clients are registered: `openbot-desktop-oauth`,
+ `openbot-mobile` and `openbot-cli`. A public client has no secret and
+ must use PKCE with S256. Dynamic client registration is off, so an
+ app uses one of these ids.
+
+
+ Redirect addresses. A client on the person's own computer listens on
+ a loopback address and any port:
+ `http://127.0.0.1:/callback` or
+ `http://[::1]:/callback`. `localhost` is not accepted.
+
+
+ Endpoints. The authorization server's metadata (RFC 8414) is at
+ `/.well-known/oauth-authorization-server/api/auth`. The person is
+ sent to `/api/auth/oauth2/authorize`. The code is exchanged, and a
+ token refreshed, at `/api/auth/oauth2/token`, with a form-encoded
+ body (`application/x-www-form-urlencoded`) that carries `client_id`.
+ A token is revoked (RFC 7009) at `/api/auth/oauth2/revoke`.
+
+
+ Tokens. An access token starts `oba_` and lasts one hour. A refresh
+ token starts `obr_`, is issued only when the `offline_access` scope
+ is asked for, and rotates on every use: each refresh answers a new
+ refresh token and ends the one it was given. Access tokens work on
+ /api/v2 only.
+
+
+ Consent. The person is asked once for each app, and not again for
+ scopes they already allowed it.
+
+
+ An install for one person on one computer has no sign-in, so it has
+ no OAuth: there is nobody to authorize an app as.
flows:
authorizationCode:
authorizationUrl: /api/auth/oauth2/authorize
@@ -509,7 +561,10 @@ components:
bearerFormat: OpenBot API key
description: >-
Automation. An API key acts as the person who created it, inside one
- organization.
+ organization. A key starts `obk_` and is sent as
+ `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2
+ only. A person makes one in the web app, signed in, under Settings,
+ then API keys (createApiKey).
recorderConnection:
type: http
scheme: bearer
diff --git a/app/src/components/settings/api-keys.tsx b/app/src/components/settings/api-keys.tsx
new file mode 100644
index 0000000000..495031925a
--- /dev/null
+++ b/app/src/components/settings/api-keys.tsx
@@ -0,0 +1,405 @@
+import { IconExternalLink, IconKey, IconPlus } from "@tabler/icons-react";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { Fragment, useState } from "react";
+import {
+ PageEmpty,
+ PageRows,
+ PageSection,
+ PageShell,
+} from "@/components/layout/page-shell";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
+import { Input } from "@/components/ui/input";
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemMedia,
+ ItemTitle,
+} from "@/components/ui/item";
+import { Separator } from "@/components/ui/separator";
+import {
+ createApiKeyMutationOptions,
+ type NewApiKey,
+ revokeApiKeyMutationOptions,
+} from "@/lib/api-keys/mutations";
+import { type ApiKey, apiKeyListQueryOptions } from "@/lib/api-keys/queries";
+import { openInSystemBrowser } from "@/lib/desktop/open-in-browser";
+import { desktopShell } from "@/lib/desktop/shell";
+import { relativeTime } from "@/lib/relative-time";
+import { queryClient } from "@/query-client";
+import { copyText } from "./linked-accounts";
+
+/** The longest name the API takes (`CreateApiKeyRequest.name`). */
+const NAME_LIMIT = 32;
+
+const day = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
+
+/** What a key is called on screen. The API allows a key with no name; the screen never makes one. */
+function keyName(apiKey: ApiKey): string {
+ return apiKey.name?.trim() || "Unnamed key";
+}
+
+/** A key's row, under its name: how it starts, when it was made, its last use, and its end if it has one. */
+export function apiKeyDescription(apiKey: ApiKey, now = Date.now()): string {
+ const parts = [
+ ...(apiKey.start ? [`${apiKey.start}…`] : []),
+ `Created ${day.format(new Date(apiKey.createdAt))}`,
+ apiKey.lastUsedAt
+ ? `Last used ${relativeTime(apiKey.lastUsedAt)}`
+ : "Never used",
+ ];
+ if (apiKey.expiresAt) {
+ const expires = new Date(apiKey.expiresAt);
+ parts.push(
+ `${expires.getTime() <= now ? "Expired" : "Expires"} ${day.format(expires)}`,
+ );
+ }
+ return parts.join(" · ");
+}
+
+/**
+ * Settings → API keys: the keys a person made for their own scripts and programs, with Create and
+ * Revoke.
+ *
+ * A key is shown whole once, when it is made, and is kept nowhere in the app after that dialog
+ * closes. Two answers from the API are not failures and read as a sentence: an OpenBot with no
+ * sign-in has no keys, and OpenBot Desktop connected to an OpenBot elsewhere is sent to the browser,
+ * because only a person signed in on the web can manage keys.
+ */
+export function ApiKeysPage() {
+ const list = useQuery(apiKeyListQueryOptions());
+ const [creating, setCreating] = useState(false);
+ const [made, setMade] = useState(null);
+ const ready = list.data?.state === "ready";
+ const createButton = (size: "sm" | "lg", variant: "default" | "outline") => (
+
+ );
+ return (
+
+ {/* One section, so it carries no heading: the page title already names it. */}
+
+ {list.isPending ? null : list.error ? (
+
+ Couldn't load your API keys. Reload the page.
+
+ ) : list.data.state === "unavailable" ? (
+
+ This OpenBot runs on one computer for one person and has no sign-in,
+ so it has no API keys.
+
+ ) : list.data.state === "browser-only" ? (
+
+ ) : list.data.apiKeys.length === 0 ? (
+
+ A key lets a script or another program use OpenBot as you.
+
+ ) : (
+
+ {list.data.apiKeys.map((apiKey, index) => (
+
+ {index > 0 ? : null}
+
+
+ ))}
+
+ )}
+
+ {
+ setCreating(false);
+ setMade(key);
+ }}
+ onOpenChange={setCreating}
+ open={creating}
+ />
+ setMade(null)} />
+
+ );
+}
+
+/**
+ * Where keys are managed when this window can't: OpenBot in a browser. In OpenBot Desktop a button
+ * opens this page there; anywhere else there is nothing to press, so it is only said.
+ */
+function BrowserOnly() {
+ const [failed, setFailed] = useState(false);
+ const address = `${window.location.origin}/settings/api-keys`;
+ return (
+
+ setFailed(!(await openInSystemBrowser(address)))
+ }
+ size="sm"
+ variant="outline"
+ >
+
+ Open in browser
+
+ ) : undefined
+ }
+ icon={IconKey}
+ title="API keys are managed in your browser"
+ >
+ {failed ? (
+
+ Couldn't open your browser. Go to {address} there.
+
+ ) : (
+ "Create API keys from OpenBot in your browser."
+ )}
+
+ );
+}
+
+/**
+ * One key, with its own Revoke: asked first in a dialog, because whatever uses the key stops working
+ * at once, and pending for this row alone. A refusal is said in the dialog, where the person asked.
+ */
+function ApiKeyRow({ apiKey }: { apiKey: ApiKey }) {
+ const [asking, setAsking] = useState(false);
+ const revoke = useMutation(revokeApiKeyMutationOptions(queryClient));
+ const name = keyName(apiKey);
+ return (
+ <>
+
+
+
+
+
+ {name}
+ {apiKeyDescription(apiKey)}
+
+
+
+
+
+
+ >
+ );
+}
+
+/** The one thing a key needs from a person: a name. One field, so a dialog and not a screen of its own. */
+function CreateApiKeyDialog({
+ onMade,
+ onOpenChange,
+ open,
+}: {
+ onMade: (made: NewApiKey) => void;
+ onOpenChange: (open: boolean) => void;
+ open: boolean;
+}) {
+ const [name, setName] = useState("");
+ const create = useMutation(createApiKeyMutationOptions(queryClient));
+ const trimmed = name.trim();
+ const close = (next: boolean) => {
+ if (!next) {
+ setName("");
+ create.reset();
+ }
+ onOpenChange(next);
+ };
+ return (
+
+ );
+}
+
+/** The key itself, this once. Closing the dialog drops it: the API never gives it again. */
+function NewApiKeyDialog({
+ made,
+ onClose,
+}: {
+ made: NewApiKey | null;
+ onClose: () => void;
+}) {
+ const [copied, setCopied] = useState(false);
+ const [copyFailed, setCopyFailed] = useState(false);
+ const close = () => {
+ setCopied(false);
+ setCopyFailed(false);
+ onClose();
+ };
+ return (
+
+ );
+}
diff --git a/app/src/components/settings/settings-sidebar.tsx b/app/src/components/settings/settings-sidebar.tsx
index 49dad6383a..1c671e4348 100644
--- a/app/src/components/settings/settings-sidebar.tsx
+++ b/app/src/components/settings/settings-sidebar.tsx
@@ -1,6 +1,7 @@
import {
IconArrowLeft,
IconBell,
+ IconKey,
IconLayoutGrid,
IconListCheck,
IconSettings,
@@ -58,7 +59,7 @@ type SettingsSidebarItem = {
/**
* Settings, for every Bot at once (`docs/how-openbot-works.md`), in three groups:
*
- * - You: your account, where updates reach you, and your Vault.
+ * - You: your account, where updates reach you, your Vault, and your API keys.
* - Every Bot: what is set once for all of them, in the fixed order of `lib/primitives.ts`.
* Conversations is not here: it is where work happens, not something to set. Routines, Memory,
* Skills and Apps (Connections) are things you make and come back to, so they are in the main
@@ -91,6 +92,13 @@ export const SETTINGS_SIDEBAR_ITEMS: SettingsSidebarItem[] = [
icon: VAULT.icon,
linkOptions: { to: "/settings/vault" },
},
+ {
+ /* The keys you make for your own scripts and programs, which use OpenBot as you. */
+ group: "you",
+ title: "API keys",
+ icon: IconKey,
+ linkOptions: { to: "/settings/api-keys" },
+ },
{
/* The computer Bots work on, folders, what OpenBot runs here, and your Recorder browsers. */
group: "every-bot",
diff --git a/app/src/lib/api-keys/mutations.ts b/app/src/lib/api-keys/mutations.ts
new file mode 100644
index 0000000000..551da28331
--- /dev/null
+++ b/app/src/lib/api-keys/mutations.ts
@@ -0,0 +1,74 @@
+import { mutationOptions, type QueryClient } from "@tanstack/react-query";
+import {
+ createApiKey,
+ deleteApiKey,
+} from "@/lib/api/generated/api-keys/api-keys";
+import { idempotencyKey, ORGANIZATION_ID } from "@/lib/api/request";
+import { ClientError } from "@/lib/client";
+import { type ApiKey, apiKeyKeys } from "./queries";
+
+const CREATE_FALLBACK = "Couldn't create the API key. Try again.";
+const REVOKE_FALLBACK = "Couldn't revoke the API key. Try again.";
+
+/** What a person gives to make a key: what it is for. */
+export type ApiKeyInput = { name: string };
+
+/** A key just made. `key` is the key itself, which the API answers this once and never again. */
+export type NewApiKey = { apiKey: ApiKey; key: string };
+
+/** The API's code for "no such key". */
+export const API_KEY_NOT_FOUND = "API_KEY_NOT_FOUND";
+
+/**
+ * Whether a refusal says the key is already gone: the API's own 404, `API_KEY_NOT_FOUND`. Revoked in
+ * another tab, which is what the person asked for, so it is success. Any other 404 (a proxy, a
+ * missing route) says nothing about the key and is a failure: the key may still work.
+ */
+export function alreadyRevoked(error: unknown): boolean {
+ return (
+ error instanceof ClientError &&
+ error.status === 404 &&
+ error.code === API_KEY_NOT_FOUND
+ );
+}
+
+function invalidateApiKeys(queryClient: QueryClient) {
+ return queryClient.invalidateQueries({ queryKey: apiKeyKeys.all });
+}
+
+export function createApiKeyMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: (input: ApiKeyInput): Promise =>
+ createApiKey(
+ ORGANIZATION_ID,
+ "me",
+ input,
+ { "Idempotency-Key": idempotencyKey() },
+ { fallback: CREATE_FALLBACK },
+ ),
+ // The key itself is handed to whoever asked and kept nowhere: it can't be read again, so a
+ // copy left in the mutation cache would be the one place it outlived the dialog that showed it.
+ gcTime: 0,
+ onSuccess: () => invalidateApiKeys(queryClient),
+ });
+}
+
+export function revokeApiKeyMutationOptions(queryClient: QueryClient) {
+ return mutationOptions({
+ mutationFn: async (apiKeyId: string): Promise => {
+ try {
+ await deleteApiKey(
+ ORGANIZATION_ID,
+ "me",
+ apiKeyId,
+ { "Idempotency-Key": idempotencyKey() },
+ { fallback: REVOKE_FALLBACK },
+ );
+ } catch (error) {
+ if (alreadyRevoked(error)) return;
+ throw error;
+ }
+ },
+ onSettled: () => invalidateApiKeys(queryClient),
+ });
+}
diff --git a/app/src/lib/api-keys/queries.ts b/app/src/lib/api-keys/queries.ts
new file mode 100644
index 0000000000..92b9e03d1d
--- /dev/null
+++ b/app/src/lib/api-keys/queries.ts
@@ -0,0 +1,85 @@
+import { queryOptions } from "@tanstack/react-query";
+import { everyPage } from "@/lib/api/every-page";
+import { listApiKeys } from "@/lib/api/generated/api-keys/api-keys";
+import type { ApiKey as ApiKeyRecord } from "@/lib/api/generated/model";
+import { ORGANIZATION_ID } from "@/lib/api/request";
+import { ClientError } from "@/lib/client";
+
+/** An API key the person made, as the API lists it. Never the key itself: `start` is its first characters. */
+export type ApiKey = ApiKeyRecord;
+
+export const apiKeyKeys = {
+ all: ["api-keys"] as const,
+ list: () => ["api-keys", "list"] as const,
+};
+
+const LOAD_FALLBACK = "Couldn't load your API keys.";
+
+/** The API's code for "this OpenBot signs nobody in", which is OpenBot on one computer for one person. */
+export const SIGN_IN_UNAVAILABLE = "SIGN_IN_UNAVAILABLE";
+
+/** The API's code for a refusal by who is asking. */
+export const PERMISSION_DENIED = "PERMISSION_DENIED";
+
+/**
+ * Whether a refusal is this OpenBot saying it has no sign-in, and so no API keys: the API's 503 with
+ * `SIGN_IN_UNAVAILABLE`. That is the feature being absent, not the server breaking. Any other
+ * failure, a 503 from a proxy included, is shown as a failure.
+ */
+export function apiKeysAbsent(error: unknown): boolean {
+ return (
+ error instanceof ClientError &&
+ error.status === 503 &&
+ error.code === SIGN_IN_UNAVAILABLE
+ );
+}
+
+/**
+ * Whether a refusal is the API saying keys are managed only by a person signed in to OpenBot on the
+ * web: its 403 with `PERMISSION_DENIED`. The list is always the person's own (`me`), so the only way
+ * to be refused is to have signed in as an app, which is what OpenBot Desktop connected to an OpenBot
+ * elsewhere does.
+ */
+export function apiKeysNeedBrowser(error: unknown): boolean {
+ return (
+ error instanceof ClientError &&
+ error.status === 403 &&
+ error.code === PERMISSION_DENIED
+ );
+}
+
+/**
+ * What the screen has to show: the person's keys, or one of the two reasons there is no list. Both
+ * reasons are answers, not failures, so the screen says them in a sentence.
+ */
+export type ApiKeyList =
+ | { state: "ready"; apiKeys: ApiKey[] }
+ /** This OpenBot has no sign-in, so it has no keys. */
+ | { state: "unavailable" }
+ /** Keys are managed from OpenBot in a browser, not from here. */
+ | { state: "browser-only" };
+
+/** Every page of the person's API keys, newest first. A handful at most, so the screen reads them all. */
+export function apiKeyListQueryOptions() {
+ return queryOptions({
+ queryKey: apiKeyKeys.list(),
+ queryFn: async ({ signal }): Promise => {
+ try {
+ const apiKeys = await everyPage(async (cursor) => {
+ const page = await listApiKeys(
+ ORGANIZATION_ID,
+ "me",
+ { limit: 100, ...(cursor ? { cursor } : {}) },
+ { signal, fallback: LOAD_FALLBACK },
+ );
+ return { items: page.apiKeys, nextCursor: page.nextCursor };
+ });
+ return { state: "ready", apiKeys };
+ } catch (error) {
+ if (apiKeysAbsent(error)) return { state: "unavailable" };
+ if (apiKeysNeedBrowser(error)) return { state: "browser-only" };
+ throw error;
+ }
+ },
+ });
+}
diff --git a/app/src/lib/desktop/open-in-browser.ts b/app/src/lib/desktop/open-in-browser.ts
new file mode 100644
index 0000000000..bab16634bf
--- /dev/null
+++ b/app/src/lib/desktop/open-in-browser.ts
@@ -0,0 +1,18 @@
+import { desktopShell } from "./shell";
+
+/**
+ * Open an address in the person's own browser from the OpenBot Desktop window, answering whether it
+ * was handed over. The window is a webview, so a link to one of OpenBot's own pages would open
+ * inside it; this is the opener plugin's command, which leaves the window where it is. False in a
+ * plain browser, and when the window refuses the command.
+ */
+export async function openInSystemBrowser(url: string): Promise {
+ const shell = desktopShell();
+ if (!shell) return false;
+ try {
+ await shell.invoke("plugin:opener|open_url", { url });
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.ts
index 4610113495..ba2fdfac1a 100644
--- a/app/src/routeTree.gen.ts
+++ b/app/src/routeTree.gen.ts
@@ -44,6 +44,7 @@ import { Route as AuthedAdminSkillsRouteImport } from './routes/_authed/admin/sk
import { Route as AuthedAdminWhatIfRouteImport } from './routes/_authed/admin/what-if'
import { Route as AuthedSettingsIndexRouteImport } from './routes/_authed/settings/index'
import { Route as AuthedSettingsPersonalRouteImport } from './routes/_authed/settings/_personal'
+import { Route as AuthedSettingsApiKeysRouteImport } from './routes/_authed/settings/api-keys'
import { Route as AuthedSettingsApprovalsRouteImport } from './routes/_authed/settings/approvals'
import { Route as AuthedSettingsBrowsersRouteImport } from './routes/_authed/settings/browsers'
import { Route as AuthedSettingsComputerRouteImport } from './routes/_authed/settings/computer'
@@ -295,6 +296,11 @@ const AuthedSettingsPersonalRoute = AuthedSettingsPersonalRouteImport.update({
id: '/_personal',
getParentRoute: () => AuthedSettingsRouteRoute,
} as any)
+const AuthedSettingsApiKeysRoute = AuthedSettingsApiKeysRouteImport.update({
+ id: '/api-keys',
+ path: '/api-keys',
+ getParentRoute: () => AuthedSettingsRouteRoute,
+} as any)
const AuthedSettingsApprovalsRoute = AuthedSettingsApprovalsRouteImport.update({
id: '/approvals',
path: '/approvals',
@@ -757,6 +763,7 @@ export interface FileRoutesByFullPath {
'/admin/providers': typeof AuthedAdminProvidersRoute
'/admin/skills': typeof AuthedAdminSkillsRoute
'/admin/what-if': typeof AuthedAdminWhatIfRoute
+ '/settings/api-keys': typeof AuthedSettingsApiKeysRoute
'/settings/approvals': typeof AuthedSettingsApprovalsRoute
'/settings/browsers': typeof AuthedSettingsBrowsersRoute
'/settings/computer': typeof AuthedSettingsComputerRoute
@@ -866,6 +873,7 @@ export interface FileRoutesByTo {
'/admin/skills': typeof AuthedAdminSkillsRoute
'/admin/what-if': typeof AuthedAdminWhatIfRoute
'/settings': typeof AuthedSettingsIndexRoute
+ '/settings/api-keys': typeof AuthedSettingsApiKeysRoute
'/settings/approvals': typeof AuthedSettingsApprovalsRoute
'/settings/browsers': typeof AuthedSettingsBrowsersRoute
'/settings/computer': typeof AuthedSettingsComputerRoute
@@ -978,6 +986,7 @@ export interface FileRoutesById {
'/_authed/admin/skills': typeof AuthedAdminSkillsRoute
'/_authed/admin/what-if': typeof AuthedAdminWhatIfRoute
'/_authed/settings/_personal': typeof AuthedSettingsPersonalRouteWithChildren
+ '/_authed/settings/api-keys': typeof AuthedSettingsApiKeysRoute
'/_authed/settings/approvals': typeof AuthedSettingsApprovalsRoute
'/_authed/settings/browsers': typeof AuthedSettingsBrowsersRoute
'/_authed/settings/computer': typeof AuthedSettingsComputerRoute
@@ -1091,6 +1100,7 @@ export interface FileRouteTypes {
| '/admin/providers'
| '/admin/skills'
| '/admin/what-if'
+ | '/settings/api-keys'
| '/settings/approvals'
| '/settings/browsers'
| '/settings/computer'
@@ -1200,6 +1210,7 @@ export interface FileRouteTypes {
| '/admin/skills'
| '/admin/what-if'
| '/settings'
+ | '/settings/api-keys'
| '/settings/approvals'
| '/settings/browsers'
| '/settings/computer'
@@ -1311,6 +1322,7 @@ export interface FileRouteTypes {
| '/_authed/admin/skills'
| '/_authed/admin/what-if'
| '/_authed/settings/_personal'
+ | '/_authed/settings/api-keys'
| '/_authed/settings/approvals'
| '/_authed/settings/browsers'
| '/_authed/settings/computer'
@@ -1644,6 +1656,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthedSettingsPersonalRouteImport
parentRoute: typeof AuthedSettingsRouteRoute
}
+ '/_authed/settings/api-keys': {
+ id: '/_authed/settings/api-keys'
+ path: '/api-keys'
+ fullPath: '/settings/api-keys'
+ preLoaderRoute: typeof AuthedSettingsApiKeysRouteImport
+ parentRoute: typeof AuthedSettingsRouteRoute
+ }
'/_authed/settings/approvals': {
id: '/_authed/settings/approvals'
path: '/approvals'
@@ -2278,6 +2297,7 @@ const AuthedSettingsPersonalRouteWithChildren =
interface AuthedSettingsRouteRouteChildren {
AuthedSettingsPersonalRoute: typeof AuthedSettingsPersonalRouteWithChildren
+ AuthedSettingsApiKeysRoute: typeof AuthedSettingsApiKeysRoute
AuthedSettingsApprovalsRoute: typeof AuthedSettingsApprovalsRoute
AuthedSettingsBrowsersRoute: typeof AuthedSettingsBrowsersRoute
AuthedSettingsComputerRoute: typeof AuthedSettingsComputerRoute
@@ -2300,6 +2320,7 @@ interface AuthedSettingsRouteRouteChildren {
const AuthedSettingsRouteRouteChildren: AuthedSettingsRouteRouteChildren = {
AuthedSettingsPersonalRoute: AuthedSettingsPersonalRouteWithChildren,
+ AuthedSettingsApiKeysRoute: AuthedSettingsApiKeysRoute,
AuthedSettingsApprovalsRoute: AuthedSettingsApprovalsRoute,
AuthedSettingsBrowsersRoute: AuthedSettingsBrowsersRoute,
AuthedSettingsComputerRoute: AuthedSettingsComputerRoute,
diff --git a/app/src/routes/_authed/settings/api-keys.tsx b/app/src/routes/_authed/settings/api-keys.tsx
new file mode 100644
index 0000000000..43dbaca5f3
--- /dev/null
+++ b/app/src/routes/_authed/settings/api-keys.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { ApiKeysPage } from "@/components/settings/api-keys";
+
+export const Route = createFileRoute("/_authed/settings/api-keys")({
+ component: ApiKeysPage,
+});
diff --git a/app/tests/api-keys-screen.test.tsx b/app/tests/api-keys-screen.test.tsx
new file mode 100644
index 0000000000..9e4b461fd0
--- /dev/null
+++ b/app/tests/api-keys-screen.test.tsx
@@ -0,0 +1,339 @@
+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+import { QueryClientProvider } from "@tanstack/react-query";
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRoute,
+ createRouter,
+ RouterProvider,
+} from "@tanstack/react-router";
+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { HttpResponse, http } from "msw";
+import { setupServer } from "msw/node";
+import { ApiKeysPage } from "@/components/settings/api-keys";
+import {
+ getApiKeysMock,
+ getCreateApiKeyMockHandler,
+ getCreateApiKeyResponseMock,
+ getDeleteApiKeyMockHandler,
+ getListApiKeysMockHandler,
+ getListApiKeysResponseMock,
+} from "@/lib/api/generated/api-keys/api-keys.msw";
+import type { ApiKey } from "@/lib/api/generated/model";
+import { queryClient as appQueryClient } from "@/query-client";
+import { settleReactWork } from "./settle-react-work";
+
+/**
+ * Settings → API keys, against the spec's own server.
+ *
+ * The MSW handlers are the ones Orval generates beside the client, answering at the API's addresses
+ * with the spec's examples, and the screen is the real one. A request anywhere else is not found, so
+ * a hand-written address cannot pass.
+ */
+
+const requests: string[] = [];
+const server = setupServer(
+ ...getApiKeysMock(),
+ http.all("*", () => new HttpResponse(null, { status: 404 })),
+);
+server.events.on("request:start", ({ request }) => {
+ const url = new URL(request.url);
+ requests.push(`${request.method} ${url.pathname}${url.search}`);
+});
+
+const KEYS = "/api/v2/organizations/default/people/me/api-keys";
+
+beforeAll(() => {
+ GlobalRegistrator.register({ url: "http://openbot.invalid/" });
+ server.listen({ onUnhandledRequest: "error" });
+});
+afterEach(() => {
+ cleanup();
+ server.resetHandlers();
+ requests.length = 0;
+ // The screen's writes invalidate through the app's one client; nothing is left in it for the next test.
+ appQueryClient.clear();
+ delete (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
+});
+afterAll(async () => {
+ server.close();
+ await settleReactWork();
+ GlobalRegistrator.unregister();
+});
+
+function draw() {
+ const rootRoute = createRootRoute();
+ const router = createRouter({
+ routeTree: rootRoute.addChildren([
+ createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/settings/api-keys",
+ component: ApiKeysPage,
+ }),
+ ]),
+ history: createMemoryHistory({ initialEntries: ["/settings/api-keys"] }),
+ });
+ return render(
+
+
+ ,
+ );
+}
+
+/** A problem answer, as the API writes one. */
+function problem(status: number, code: string, detail: string) {
+ return HttpResponse.json(
+ {
+ type: "https://open.bot/errors/example",
+ title: detail,
+ status,
+ detail,
+ code,
+ category: "permission",
+ retryable: false,
+ requestId: "req_example",
+ traceId: "trace_example",
+ },
+ { status, headers: { "content-type": "application/problem+json" } },
+ );
+}
+
+test("lists the person's keys with when each was made, last used and expires", async () => {
+ const [example] = getListApiKeysResponseMock().apiKeys;
+ const never: ApiKey = {
+ id: "9f8e7d6c5b4a3210",
+ name: "Laptop script",
+ start: "obk_Qr",
+ createdAt: "2026-11-01T10:00:00.000Z",
+ expiresAt: null,
+ lastUsedAt: null,
+ };
+ server.use(
+ getListApiKeysMockHandler({ apiKeys: [example, never], nextCursor: null }),
+ );
+ const view = draw();
+
+ const used = (await view.findByText("Nightly report")).closest(
+ '[data-slot="item"]',
+ );
+ expect(used?.textContent).toContain("obk_Xy");
+ expect(used?.textContent).toContain("Created Nov 14, 2026");
+ expect(used?.textContent).toMatch(/Last used .+ ago|Last used/);
+ expect(used?.textContent).toContain("Expires Feb 12, 2027");
+
+ const unused = view.getByText("Laptop script").closest('[data-slot="item"]');
+ expect(unused?.textContent).toContain("Never used");
+ expect(unused?.textContent).not.toContain("Expires");
+
+ expect(requests).toContain(`GET ${KEYS}?limit=100`);
+});
+
+test("reads every page of the list", async () => {
+ const [example] = getListApiKeysResponseMock().apiKeys;
+ server.use(
+ getListApiKeysMockHandler(({ request }) =>
+ new URL(request.url).searchParams.get("cursor") === "bmV4dA"
+ ? {
+ apiKeys: [{ ...example, id: "second", name: "Second page key" }],
+ nextCursor: null,
+ }
+ : { apiKeys: [example], nextCursor: "bmV4dA" },
+ ),
+ );
+ const view = draw();
+
+ await view.findByText("Second page key");
+ expect(view.getByText("Nightly report")).toBeTruthy();
+ expect(requests).toContain(`GET ${KEYS}?limit=100&cursor=bmV4dA`);
+});
+
+test("with no keys it says so and offers to create one", async () => {
+ server.use(getListApiKeysMockHandler({ apiKeys: [], nextCursor: null }));
+ const view = draw();
+
+ await view.findByText("No API keys yet");
+ expect(
+ view.getAllByRole("button", { name: "Create key" }).length,
+ ).toBeGreaterThan(0);
+});
+
+test("creating a key sends its name with an Idempotency-Key, shows the key once with Copy, and it is gone after Done", async () => {
+ const sent: { key: string; body: unknown }[] = [];
+ const copied: string[] = [];
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: {
+ writeText: async (text: string) => {
+ copied.push(text);
+ },
+ },
+ });
+ server.use(
+ getCreateApiKeyMockHandler(async ({ request }) => {
+ sent.push({
+ key: request.headers.get("idempotency-key") ?? "",
+ body: await request.json(),
+ });
+ return getCreateApiKeyResponseMock();
+ }),
+ );
+ const secret = getCreateApiKeyResponseMock().key;
+ const view = draw();
+ await view.findByText("Nightly report");
+
+ fireEvent.click(view.getByRole("button", { name: "Create key" }));
+ const name = await view.findByLabelText("Name");
+ // Typed, not set: the box is a Base UI input, which reads keystrokes and not a `change` event.
+ await userEvent.type(name, " Deploy script ");
+ fireEvent.submit(name.closest("form") as HTMLFormElement);
+
+ // The key, whole, once.
+ await view.findByText(secret);
+ expect(view.getByText(/can't see it again/)).toBeTruthy();
+ expect(sent).toHaveLength(1);
+ expect(sent[0].body).toEqual({ name: "Deploy script" });
+ expect(sent[0].key).toMatch(/^[0-9a-f]{32}$/);
+ expect(requests).toContain(`POST ${KEYS}`);
+
+ fireEvent.click(view.getByRole("button", { name: "Copy" }));
+ await view.findByRole("button", { name: "Copied" });
+ expect(copied).toEqual([secret]);
+
+ fireEvent.click(view.getByRole("button", { name: "Done" }));
+ await waitFor(() => expect(view.queryByText(secret)).toBeNull());
+ expect(document.body.textContent).not.toContain(secret);
+ // Nothing the app keeps holds it either.
+ expect(JSON.stringify(appQueryClient.getQueryCache().getAll())).not.toContain(
+ secret,
+ );
+ expect(
+ JSON.stringify(
+ appQueryClient
+ .getMutationCache()
+ .getAll()
+ .map((mutation) => mutation.state),
+ ),
+ ).not.toContain(secret);
+});
+
+test("a name is needed before a key is made", async () => {
+ const view = draw();
+ await view.findByText("Nightly report");
+
+ fireEvent.click(view.getByRole("button", { name: "Create key" }));
+ const name = await view.findByLabelText("Name");
+ fireEvent.submit(name.closest("form") as HTMLFormElement);
+
+ await settleReactWork();
+ expect(requests.filter((line) => line.startsWith("POST"))).toEqual([]);
+});
+
+test("revoking asks first, then deletes the key and its row goes", async () => {
+ let keys = getListApiKeysResponseMock().apiKeys;
+ const deleted: { id: string; key: string }[] = [];
+ server.use(
+ getListApiKeysMockHandler(() => ({ apiKeys: keys, nextCursor: null })),
+ getDeleteApiKeyMockHandler(({ request, params }) => {
+ deleted.push({
+ id: String(params.apiKeyId),
+ key: request.headers.get("idempotency-key") ?? "",
+ });
+ keys = keys.filter((key) => key.id !== params.apiKeyId);
+ }),
+ );
+ const view = draw();
+ await view.findByText("Nightly report");
+
+ fireEvent.click(view.getByRole("button", { name: "Revoke Nightly report" }));
+ // Asked first: nothing is deleted by the row's button.
+ await view.findByText("Revoke Nightly report?");
+ expect(deleted).toEqual([]);
+
+ fireEvent.click(view.getByRole("button", { name: "Revoke" }));
+ await waitFor(() => expect(view.queryByText("Nightly report")).toBeNull());
+ expect(deleted).toHaveLength(1);
+ expect(deleted[0].id).toBe("4b2c9e71d0a84f6b");
+ expect(deleted[0].key).toMatch(/^[0-9a-f]{32}$/);
+ expect(requests).toContain(`DELETE ${KEYS}/4b2c9e71d0a84f6b`);
+ await view.findByText("No API keys yet");
+});
+
+test("an OpenBot with no sign-in says it has no API keys, in a sentence and not as an error", async () => {
+ server.use(
+ http.get(`*${KEYS}`, () =>
+ problem(
+ 503,
+ "SIGN_IN_UNAVAILABLE",
+ "This OpenBot signs nobody in, so it has no API keys.",
+ ),
+ ),
+ );
+ const view = draw();
+
+ await view.findByText("API keys aren't available on this OpenBot");
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(view.queryByRole("button", { name: "Create key" })).toBeNull();
+});
+
+test("any other 503 is a failure to load, not the missing feature", async () => {
+ server.use(
+ http.get(
+ `*${KEYS}`,
+ () => new HttpResponse("bad gateway", { status: 503 }),
+ ),
+ );
+ const view = draw();
+
+ // The app's client tries a failed read once more before it says so.
+ const alert = await view.findByRole("alert", {}, { timeout: 4000 });
+ expect(alert.textContent).toContain("Couldn't load your API keys.");
+});
+
+test("refused for not being signed in on the web, in a browser it says where to create keys", async () => {
+ server.use(
+ http.get(`*${KEYS}`, () =>
+ problem(
+ 403,
+ "PERMISSION_DENIED",
+ "An API key or an app can't manage API keys or sessions. Sign in to OpenBot to do this.",
+ ),
+ ),
+ );
+ const view = draw();
+
+ await view.findByText("Create API keys from OpenBot in your browser.");
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(view.queryByRole("button", { name: "Create key" })).toBeNull();
+ expect(view.queryByRole("button", { name: "Open in browser" })).toBeNull();
+});
+
+test("refused in OpenBot Desktop, a button opens this page in the system browser", async () => {
+ const invoked: { command: string; args: unknown }[] = [];
+ (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__ = {
+ transformCallback: () => 0,
+ invoke: async (command: string, args: unknown) => {
+ invoked.push({ command, args });
+ return null;
+ },
+ };
+ server.use(
+ http.get(`*${KEYS}`, () =>
+ problem(
+ 403,
+ "PERMISSION_DENIED",
+ "An API key or an app can't manage API keys or sessions. Sign in to OpenBot to do this.",
+ ),
+ ),
+ );
+ const view = draw();
+
+ await view.findByText("Create API keys from OpenBot in your browser.");
+ fireEvent.click(view.getByRole("button", { name: "Open in browser" }));
+ await waitFor(() => expect(invoked).toHaveLength(1));
+ expect(invoked[0]).toEqual({
+ command: "plugin:opener|open_url",
+ args: { url: "http://openbot.invalid/settings/api-keys" },
+ });
+});
diff --git a/app/tests/settings-sidebar.test.ts b/app/tests/settings-sidebar.test.ts
index 76034033a7..092911fafa 100644
--- a/app/tests/settings-sidebar.test.ts
+++ b/app/tests/settings-sidebar.test.ts
@@ -31,6 +31,15 @@ describe("settings sidebar", () => {
expect(groups).toEqual([...groups].sort((a, b) => a - b));
});
+ test("API keys is the person's own, last of You, in both editions", () => {
+ const you = SETTINGS_SIDEBAR_ITEMS.filter((item) => item.group === "you");
+ const apiKeys = you[you.length - 1];
+
+ expect(apiKeys?.title).toBe("API keys");
+ expect(apiKeys?.linkOptions).toEqual({ to: "/settings/api-keys" });
+ expect(apiKeys?.personalOnly).toBeUndefined();
+ });
+
test("Routines, Memory, Skills and Learning are not in Settings: the first three are in the main menu", () => {
const titles = SETTINGS_SIDEBAR_ITEMS.map((item) => item.title);
for (const moved of ["Routines", "Memory", "Skills", "Learning"])
From 8ca2f9549bc7737f6cb1a13c9e42f144ed733eab Mon Sep 17 00:00:00 2001
From: David McKay
Date: Sun, 15 Nov 2026 12:51:20 -0800
Subject: [PATCH 003/116] Let Desktop's setup connect to an OpenBot that runs
elsewhere
The first screen's OpenBot for Business choice can now be picked. It asks
for the address of the OpenBot a company runs in place of what this
computer needs and Install, then signs in through the browser. Nothing is
installed or started on this computer for it. The booking link moves to
that screen, for a company that has no OpenBot yet. OpenBot Cloud is still
shown as coming soon, and Self-hosted is unchanged.
Setup asks the shell where OpenBot runs before anything else. A saved
connection opens that OpenBot, or shows the first screen with the address
filled in and the reason the sign-in ended, and none of the checks,
downloads or starts of an install on this computer run. A shell that does
not know the question is an install on this computer, as before.
What goes wrong is said in the shell's own sentence. The screen reads only
its kind to choose what to offer: the field to fix, Try again, Sign in
again, or opening that OpenBot in the browser. Use OpenBot on this computer
instead goes back, and switches a saved connection first.
---
desktop/src/App.test.tsx | 470 +++++++++++++++++++++++-
desktop/src/App.tsx | 139 ++++++-
desktop/src/ConnectToOpenBot.tsx | 322 ++++++++++++++++
desktop/src/Problem.tsx | 11 +-
desktop/src/Welcome.tsx | 110 ++++--
desktop/src/setupLayout.browser.test.ts | 13 +
desktop/src/styles.css | 82 ++++-
desktop/src/telemetry.ts | 13 +-
8 files changed, 1114 insertions(+), 46 deletions(-)
create mode 100644 desktop/src/ConnectToOpenBot.tsx
diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx
index f3ee14f680..92ea038392 100644
--- a/desktop/src/App.test.tsx
+++ b/desktop/src/App.test.tsx
@@ -602,14 +602,15 @@ async function chooseOpenAi(view: Awaited>) {
await userEvent.click(view.getByRole("button", { name: "Continue" }));
}
-test("the first screen offers Self-hosted, shows Cloud and Business greyed, and says what this computer needs and why", async () => {
+test("the first screen offers Self-hosted and OpenBot for Business, shows Cloud greyed, and says what this computer needs and why", async () => {
setupRootConfiguration("/tmp/local-eval-welcome", async () =>
emptyConfiguration(),
);
withLocalCli({});
const view = await renderApp();
expect(view.getByRole("heading", { name: "Set up OpenBot" })).toBeTruthy();
- // Three ways to run OpenBot. This app sets up the first; the other two are there to be seen.
+ // Three ways to run OpenBot. This app sets up the first and connects to the third; OpenBot Cloud
+ // is there to be seen.
const self = view.getByRole("radio", {
name: /^Self-hosted/,
}) as HTMLInputElement;
@@ -621,7 +622,10 @@ test("the first screen offers Self-hosted, shows Cloud and Business greyed, and
}) as HTMLInputElement;
expect([self.checked, self.disabled]).toEqual([true, false]);
expect([cloud.checked, cloud.disabled]).toEqual([false, true]);
- expect([business.checked, business.disabled]).toEqual([false, true]);
+ expect([business.checked, business.disabled]).toEqual([false, false]);
+ expect(business.closest("label")?.textContent).toContain(
+ "For your whole team. Connect to the OpenBot your company runs.",
+ );
// What Self-hosted asks of this computer, and why: every part of OpenBot runs on it.
expect(
view.getByRole("heading", { name: "What this computer needs" }),
@@ -642,13 +646,467 @@ test("the first screen offers Self-hosted, shows Cloud and Business greyed, and
"4 CPU cores or more",
"40 GB of free disk space",
]);
- // The one booking link, never a scheduling page of its own, still live on the greyed row.
+ expect(buttons(view)).toEqual(["Install"]);
+ expectPlain(view);
+ expect(localCliCalls()).toEqual([]);
+});
+
+/*
+ * An OpenBot that runs elsewhere. The shell's commands, what they answer and the sentence for each
+ * thing that can go wrong are faked here exactly as the shell gives them: the window shows the
+ * sentence as given, and reads only its `kind` to choose what to offer.
+ */
+const ELSEWHERE = "https://openbot.example.com";
+const THIS_COMPUTER = { mode: "local", address: null, signedIn: false };
+
+const CONNECT_PROBLEMS: Array<{
+ kind: string;
+ said: string;
+ at: "check" | "connect";
+ offer: "field" | "Try again" | "Sign in again" | "Open in browser";
+}> = [
+ {
+ kind: "address-invalid",
+ at: "check",
+ offer: "field",
+ said: "That isn't an address OpenBot can connect to. Use one that starts with https://, such as https://openbot.example.com.",
+ },
+ {
+ kind: "unreachable",
+ at: "check",
+ offer: "Try again",
+ said: "OpenBot couldn't reach openbot.example.com. Check the address and your network, then try again.",
+ },
+ {
+ kind: "not-openbot",
+ at: "check",
+ offer: "field",
+ said: "There's no OpenBot at openbot.example.com. Check the address with whoever runs your OpenBot.",
+ },
+ {
+ kind: "single-person",
+ at: "check",
+ offer: "field",
+ said: "The OpenBot at openbot.example.com is set up for one person on its own computer, so the app can't connect to it.",
+ },
+ {
+ kind: "too-old",
+ at: "check",
+ offer: "Open in browser",
+ said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser.",
+ },
+ {
+ kind: "sign-in-cancelled",
+ at: "connect",
+ offer: "Sign in again",
+ said: "Sign-in didn't finish. Try again when you're ready.",
+ },
+ {
+ kind: "sign-in-failed",
+ at: "connect",
+ offer: "Sign in again",
+ said: "OpenBot couldn't sign you in at openbot.example.com. Try again, or ask whoever runs your OpenBot.",
+ },
+ {
+ kind: "session-ended",
+ at: "connect",
+ offer: "Sign in again",
+ said: "Your sign-in to openbot.example.com has ended. Sign in again to keep going.",
+ },
+ {
+ kind: "credential-store",
+ at: "connect",
+ offer: "Try again",
+ said: "OpenBot couldn't save your sign-in on this computer. Unlock your keychain, then try again.",
+ },
+];
+
+/** A first run on which the person picks OpenBot for Business: the connect screen. */
+async function chooseConnect(shell: Record = {}) {
+ setupRootConfiguration("/tmp/connect-elsewhere", async () =>
+ emptyConfiguration(),
+ );
+ withLocalCli({
+ connection: THIS_COMPUTER,
+ record_setup_event: null,
+ ...shell,
+ });
+ const view = await renderApp();
+ await userEvent.click(
+ view.getByRole("radio", { name: /^OpenBot for Business/ }),
+ );
+ return view;
+}
+
+/** What the window asked the shell for, in order, leaving out what it counts for usage data. */
+function asked(from = 0) {
+ return invokeCalls
+ .slice(from)
+ .filter((call) => call.command !== "record_setup_event");
+}
+
+/**
+ * The shell of an app whose saved choice is an OpenBot that runs elsewhere. It answers `answers`,
+ * and anything else the window asks for, which is every command of an install on this computer, is
+ * a stray: the test fails on one.
+ */
+function connectedShell(answers: Record) {
+ const strays: string[] = [];
+ invokeHandler = async (command, args) => {
+ if (command in answers) {
+ const answer = answers[command];
+ return typeof answer === "function" ? answer(args) : answer;
+ }
+ if (command === "record_setup_event") return null;
+ strays.push(command);
+ throw new Error(`a connected app asked for ${command}`);
+ };
+ return strays;
+}
+
+test("choosing OpenBot for Business asks for an address in place of Install, and going back brings Install back", async () => {
+ const view = await chooseConnect();
+ const business = view.getByRole("radio", {
+ name: /^OpenBot for Business/,
+ }) as HTMLInputElement;
+ expect(business.checked).toBe(true);
+ const field = view.getByLabelText("OpenBot address") as HTMLInputElement;
+ expect(field.placeholder).toBe("https://openbot.example.com");
+ expect(field.value).toBe("");
+ expect(
+ view.getByText(
+ "You'll sign in to it in your browser. Nothing is installed on this computer.",
+ ),
+ ).toBeTruthy();
+ // What Self-hosted asks of this computer, and its Install, are not this choice's.
+ expect(buttons(view)).toEqual([
+ "Connect",
+ "Use OpenBot on this computer instead",
+ ]);
+ expect(
+ view.queryByRole("heading", { name: "What this computer needs" }),
+ ).toBeNull();
+ expect(view.queryByText(/Setup takes/)).toBeNull();
+ // Nothing to connect to until an address is typed.
+ expect(view.getByRole("button", { name: "Connect" })).toHaveProperty(
+ "disabled",
+ true,
+ );
+ // The one booking link, for somebody whose company has no OpenBot yet.
+ expect(view.getByText(/Don't have one yet\?/)).toBeTruthy();
expect(
view.getByRole("link", { name: "Book a demo" }).getAttribute("href"),
).toBe("https://open.bot/business");
- expect(buttons(view)).toEqual(["Install"]);
+ // OpenBot Cloud is still to come.
+ expect(view.getByRole("radio", { name: /^OpenBot Cloud/ })).toHaveProperty(
+ "disabled",
+ true,
+ );
expectPlain(view);
- expect(localCliCalls()).toEqual([]);
+ // Back, by the control that says so, and by the row itself.
+ await userEvent.type(field, "openbot.example.com");
+ await userEvent.click(
+ view.getByRole("button", { name: "Use OpenBot on this computer instead" }),
+ );
+ expect(buttons(view)).toEqual(["Install"]);
+ await userEvent.click(business);
+ // What was typed is still there.
+ expect(
+ (view.getByLabelText("OpenBot address") as HTMLInputElement).value,
+ ).toBe("openbot.example.com");
+ await userEvent.click(view.getByRole("radio", { name: /^Self-hosted/ }));
+ expect(buttons(view)).toEqual(["Install"]);
+ expect(
+ view.getByRole("heading", { name: "What this computer needs" }),
+ ).toBeTruthy();
+ // The saved choice was this computer all along: there was nothing to switch back from.
+ expect(asked().map((call) => call.command)).not.toContain(
+ "use_this_computer",
+ );
+});
+
+test("a good address signs in through the browser, and nothing on this computer is asked for", async () => {
+ const signIn = deferred();
+ const view = await chooseConnect({
+ check_openbot_address: { address: ELSEWHERE },
+ connect_to_openbot: () => signIn.promise,
+ });
+ const from = invokeCalls.length;
+ const field = view.getByLabelText("OpenBot address") as HTMLInputElement;
+ // No scheme: the shell takes it as https, and the window does not refuse it first.
+ await userEvent.type(field, "openbot.example.com{Enter}");
+ expect(
+ await view.findByText("Finish signing in in your browser."),
+ ).toBeTruthy();
+ // The address as the shell understood it, and Cancel as the only control while it waits.
+ expect(field.value).toBe(ELSEWHERE);
+ expect(buttons(view)).toEqual(["Cancel"]);
+ await act(async () => signIn.resolve(null));
+ expect(view.getByText("Opening OpenBot…")).toBeTruthy();
+ expect(view.queryAllByRole("button")).toEqual([]);
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(asked(from)).toEqual([
+ {
+ command: "check_openbot_address",
+ args: { address: "openbot.example.com" },
+ },
+ { command: "connect_to_openbot", args: { address: ELSEWHERE } },
+ ]);
+ // The screen is counted, and the address never is.
+ expect(setupEvents()).toContainEqual({
+ event: { kind: "step_viewed", step: "connect_openbot" },
+ });
+ expect(JSON.stringify(setupEvents())).not.toContain("openbot.example.com");
+});
+
+for (const { kind, said, at, offer } of CONNECT_PROBLEMS) {
+ test(`${kind}: the screen says the shell's sentence and offers ${offer === "field" ? "the field to fix" : offer}`, async () => {
+ let checks = 0;
+ let signIns = 0;
+ const view = await chooseConnect({
+ check_openbot_address: () => {
+ checks += 1;
+ if (at === "check") throw { said, kind };
+ return { address: ELSEWHERE };
+ },
+ connect_to_openbot: () => {
+ signIns += 1;
+ throw { said, kind };
+ },
+ "plugin:opener|open_url": null,
+ });
+ const field = view.getByLabelText("OpenBot address") as HTMLInputElement;
+ await userEvent.type(field, `${ELSEWHERE}{Enter}`);
+ const alert = await view.findByRole("alert");
+ expect(alert.textContent).toContain(said);
+ // The address is still there, to fix or to try again with.
+ expect(field.value).toBe(ELSEWHERE);
+ if (offer === "field") {
+ expect(alert.textContent).toBe(said);
+ expect(document.activeElement).toBe(field);
+ expect(field.getAttribute("aria-invalid")).toBe("true");
+ expect(buttons(view)).toEqual([
+ "Connect",
+ "Use OpenBot on this computer instead",
+ ]);
+ // A sentence about the address goes once the address changes.
+ await userEvent.type(field, "x");
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(field.getAttribute("aria-invalid")).toBeNull();
+ } else if (offer === "Open in browser") {
+ const link = view.getByRole("link", { name: "Open in browser" });
+ expect(link.getAttribute("href")).toBe(ELSEWHERE);
+ await userEvent.click(link);
+ expect(invokeCalls).toContainEqual({
+ command: "plugin:opener|open_url",
+ args: { url: ELSEWHERE },
+ });
+ expect(view.getByRole("button", { name: "Connect" })).toBeTruthy();
+ } else {
+ // One way on, and it says what it does.
+ expect(view.queryByRole("button", { name: "Connect" })).toBeNull();
+ await userEvent.click(view.getByRole("button", { name: offer }));
+ await waitFor(() => expect(at === "check" ? checks : signIns).toBe(2));
+ }
+ });
+}
+
+test("Cancel while the browser is waited on stops the sign-in and gives the form back", async () => {
+ const signIn = deferred();
+ const view = await chooseConnect({
+ check_openbot_address: { address: ELSEWHERE },
+ connect_to_openbot: () => signIn.promise,
+ cancel_connect: null,
+ });
+ const field = view.getByLabelText("OpenBot address") as HTMLInputElement;
+ await userEvent.type(field, `${ELSEWHERE}{Enter}`);
+ await view.findByText("Finish signing in in your browser.");
+ await userEvent.click(view.getByRole("button", { name: "Cancel" }));
+ expect(
+ invokeCalls.filter((call) => call.command === "cancel_connect"),
+ ).toHaveLength(1);
+ expect(view.queryByText("Finish signing in in your browser.")).toBeNull();
+ expect(view.getByRole("button", { name: "Connect" })).toHaveProperty(
+ "disabled",
+ false,
+ );
+ expect(field.value).toBe(ELSEWHERE);
+ // The shell then ends the sign-in it was asked to stop. The person chose that: nothing is
+ // announced, and the field is where they are.
+ await act(async () =>
+ signIn.reject({
+ said: "Sign-in didn't finish. Try again when you're ready.",
+ kind: "sign-in-cancelled",
+ }),
+ );
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(document.activeElement).toBe(field);
+});
+
+test("a launch that is connected and signed in opens OpenBot and asks nothing of this computer", async () => {
+ const strays = connectedShell({
+ connection: { mode: "connected", address: ELSEWHERE, signedIn: true },
+ show_connected: null,
+ });
+ // The development double mount included: OpenBot is opened once.
+ const view = await renderApp(true);
+ expect(invokeCalls.map((call) => call.command)).toEqual([
+ "connection",
+ "show_connected",
+ ]);
+ expect(view.getByRole("status").textContent).toBe("Opening OpenBot…");
+ expect(view.queryAllByRole("button")).toEqual([]);
+ expect(strays).toEqual([]);
+});
+
+test("a launch after the sign-in ended says so once, with the address filled in and Sign in again", async () => {
+ const said =
+ "Your sign-in to openbot.example.com has ended. Sign in again to keep going.";
+ let notices = 0;
+ const strays = connectedShell({
+ connection: { mode: "connected", address: ELSEWHERE, signedIn: false },
+ // Answered once, as the shell does.
+ take_connection_notice: () => {
+ notices += 1;
+ return notices === 1 ? { kind: "session-ended", message: said } : null;
+ },
+ check_openbot_address: { address: ELSEWHERE },
+ connect_to_openbot: () => new Promise(() => {}),
+ });
+ const view = await renderApp(true);
+ expect(view.getByRole("heading", { name: "Set up OpenBot" })).toBeTruthy();
+ expect(
+ view.getByRole("radio", { name: /^OpenBot for Business/ }),
+ ).toHaveProperty("checked", true);
+ expect(
+ (view.getByLabelText("OpenBot address") as HTMLInputElement).value,
+ ).toBe(ELSEWHERE);
+ expect(view.getByRole("alert").textContent).toBe(said);
+ expect(notices).toBe(1);
+ expect(view.queryByRole("button", { name: "Install" })).toBeNull();
+ expect(view.queryByRole("button", { name: "Connect" })).toBeNull();
+ await userEvent.click(view.getByRole("button", { name: "Sign in again" }));
+ await view.findByText("Finish signing in in your browser.");
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(asked().map((call) => call.command)).toEqual([
+ "connection",
+ "take_connection_notice",
+ "check_openbot_address",
+ "connect_to_openbot",
+ ]);
+ expect(setupEvents()).toEqual([
+ { event: { kind: "step_viewed", step: "connect_openbot" } },
+ ]);
+ expect(strays).toEqual([]);
+});
+
+test("asked from Settings to choose where OpenBot runs, the first screen opens on the connect choice with the address and no failure", async () => {
+ setupRootConfiguration("/tmp/choose-again", async () => emptyConfiguration());
+ withLocalCli({
+ connection: { mode: "connected", address: ELSEWHERE, signedIn: false },
+ take_connection_notice: { kind: "choose", message: null },
+ use_this_computer: null,
+ record_setup_event: null,
+ });
+ const view = await renderApp();
+ expect(view.getByRole("heading", { name: "Set up OpenBot" })).toBeTruthy();
+ expect(
+ view.getByRole("radio", { name: /^OpenBot for Business/ }),
+ ).toHaveProperty("checked", true);
+ expect(
+ (view.getByLabelText("OpenBot address") as HTMLInputElement).value,
+ ).toBe(ELSEWHERE);
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(buttons(view)).toEqual([
+ "Connect",
+ "Use OpenBot on this computer instead",
+ ]);
+ // Nothing of an install on this computer has been asked for yet.
+ expect(asked().map((call) => call.command)).toEqual([
+ "connection",
+ "take_connection_notice",
+ ]);
+ // Picking Self-hosted switches the saved choice, then setup carries on as it does today.
+ await userEvent.click(view.getByRole("radio", { name: /^Self-hosted/ }));
+ await view.findByRole("button", { name: "Install" });
+ const commands = asked().map((call) => call.command);
+ expect(commands.indexOf("use_this_computer")).toBe(2);
+ expect(commands).toContain("already_configured");
+});
+
+test("a saved sign-in that can't open OpenBot says why on the connect screen, and Try again opens it without signing in again", async () => {
+ const said =
+ "OpenBot couldn't reach openbot.example.com. Check the address and your network, then try again.";
+ let shows = 0;
+ const strays = connectedShell({
+ connection: { mode: "connected", address: ELSEWHERE, signedIn: true },
+ show_connected: () => {
+ shows += 1;
+ if (shows === 1) throw { said, kind: "unreachable" };
+ return new Promise(() => {});
+ },
+ });
+ const view = await renderApp();
+ expect((await view.findByRole("alert")).textContent).toContain(said);
+ expect(
+ (view.getByLabelText("OpenBot address") as HTMLInputElement).value,
+ ).toBe(ELSEWHERE);
+ await userEvent.click(view.getByRole("button", { name: "Try again" }));
+ await view.findByText("Opening OpenBot…");
+ expect(asked().map((call) => call.command)).toEqual([
+ "connection",
+ "show_connected",
+ "show_connected",
+ ]);
+ expect(strays).toEqual([]);
+});
+
+test("Use OpenBot on this computer instead switches a saved connection back, and setup carries on as a first run", async () => {
+ setupRootConfiguration("/tmp/back-to-this-computer", async () =>
+ emptyConfiguration(),
+ );
+ withLocalCli({
+ connection: { mode: "connected", address: ELSEWHERE, signedIn: false },
+ take_connection_notice: null,
+ use_this_computer: null,
+ record_setup_event: null,
+ });
+ const view = await renderApp();
+ // Connected: nothing of an install on this computer has been asked for.
+ expect(asked().map((call) => call.command)).toEqual([
+ "connection",
+ "take_connection_notice",
+ ]);
+ await userEvent.click(
+ view.getByRole("button", { name: "Use OpenBot on this computer instead" }),
+ );
+ await view.findByRole("button", { name: "Install" });
+ const commands = asked().map((call) => call.command);
+ expect(commands.indexOf("use_this_computer")).toBe(2);
+ expect(commands.indexOf("default_root")).toBeGreaterThan(2);
+ expect(view.getByRole("radio", { name: /^Self-hosted/ })).toHaveProperty(
+ "checked",
+ true,
+ );
+ expect(
+ view.getByRole("heading", { name: "What this computer needs" }),
+ ).toBeTruthy();
+ // The address is still there for somebody who changes their mind.
+ await userEvent.click(
+ view.getByRole("radio", { name: /^OpenBot for Business/ }),
+ );
+ expect(
+ (view.getByLabelText("OpenBot address") as HTMLInputElement).value,
+ ).toBe(ELSEWHERE);
+});
+
+test("a person who went back to this computer finds the address they connected to if they pick connect again", async () => {
+ const view = await chooseConnect({
+ connection: { mode: "local", address: ELSEWHERE, signedIn: false },
+ });
+ expect(
+ (view.getByLabelText("OpenBot address") as HTMLInputElement).value,
+ ).toBe(ELSEWHERE);
});
test("the first screen says nothing about usage data: that is the last screen's choice", async () => {
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 7dbcdf8836..efd68b81f1 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -113,7 +113,139 @@ export function App() {
return ;
}
+/** Where OpenBot runs, as the shell has it saved (`connection`). */
+type Connection = {
+ mode: "local" | "connected";
+ address: string | null;
+ /** A sign-in for that address is kept on this computer. */
+ signedIn: boolean;
+};
+
+/** Said once by the shell when it put this window back: why, or `choose` to pick again. */
+type ConnectionNotice = { kind: string; message: string | null };
+
+type Launch =
+ | { at: "asking" }
+ /** OpenBot on this computer: setup as it has always been. */
+ | { at: "local"; address: string }
+ /** Signed in to an OpenBot that runs elsewhere, which the shell is opening. */
+ | { at: "opening" }
+ /** The first screen with that OpenBot's address, to sign in to it again or choose otherwise. */
+ | {
+ at: "connect";
+ address: string;
+ problem: Problem | null;
+ reopen: boolean;
+ };
+
+/**
+ * Asks where OpenBot runs before anything else. On this computer, setup carries on exactly as it
+ * did (`LocalSetup`). Connected to an OpenBot that runs elsewhere, none of that is mounted, so
+ * nothing about an install on this computer is asked for, downloaded or started: the shell opens
+ * that OpenBot, or the first screen shows its address to sign in to again.
+ *
+ * A shell from before this choice does not know `connection`: that is OpenBot on this computer.
+ */
function Setup() {
+ const [launch, setLaunch] = useState({ at: "asking" });
+ // Asked once, the development double mount included: the shell answers its notice only once.
+ const asked = useRef(false);
+ const alive = useRef(true);
+ useEffect(() => {
+ alive.current = true;
+ if (!asked.current) {
+ asked.current = true;
+ void (async () => {
+ const found = await invoke("connection").catch(() => null);
+ if (!alive.current) return;
+ const address = found?.address ?? "";
+ if (found?.mode !== "connected") {
+ setLaunch({ at: "local", address });
+ return;
+ }
+ if (found.signedIn) {
+ setLaunch({ at: "opening" });
+ try {
+ await invoke("show_connected");
+ } catch (error) {
+ if (alive.current)
+ setLaunch({
+ at: "connect",
+ address,
+ problem: asProblem(error),
+ reopen: true,
+ });
+ }
+ return;
+ }
+ const notice = await invoke(
+ "take_connection_notice",
+ ).catch(() => null);
+ if (!alive.current) return;
+ setLaunch({
+ at: "connect",
+ address,
+ // `choose` is the person asking to pick again from Settings: nothing went wrong.
+ problem: notice?.message
+ ? { said: notice.message, kind: notice.kind }
+ : null,
+ reopen: false,
+ });
+ })();
+ }
+ return () => {
+ alive.current = false;
+ };
+ }, []);
+ const connecting = launch.at === "connect";
+ useEffect(() => {
+ if (connecting)
+ recordSetupEvent({ kind: "step_viewed", step: "connect_openbot" });
+ }, [connecting]);
+
+ if (launch.at === "local") return ;
+ if (launch.at === "connect") {
+ const { address } = launch;
+ return (
+
+ {}}
+ // The saved choice goes back to this computer, then setup carries on as a first run.
+ onThisComputer={async () => {
+ await invoke("use_this_computer");
+ setLaunch({ at: "local", address });
+ }}
+ saved={{
+ address,
+ problem: launch.problem,
+ reopen: launch.reopen
+ ? () => invoke("show_connected")
+ : undefined,
+ }}
+ onInstall={() => {}}
+ />
+
+ );
+ }
+ return (
+
+
+
+ );
+}
+
+/** Setup of OpenBot on this computer. `address`: an OpenBot connected to before, if any. */
+function LocalSetup({ address }: { address: string }) {
const [blocker, setBlocker] = useState(null);
// A Windows fix made earlier that only counts once Windows has restarted, and it has not.
const [restartPending, setRestartPending] = useState(false);
@@ -937,10 +1069,15 @@ function Setup() {
* Skipped entirely when a stack is already up: somebody returning to a running OpenBot is not
* setting one up.
*/
- if (!running && step === "welcome") {
+ if (!running && (step === "welcome" || step === "connect_openbot")) {
return (
setStep("connect_openbot")}
+ onThisComputer={() => setStep("welcome")}
+ saved={{ address }}
onInstall={() => {
// The default Bot, recorded as a choice of it would be.
recordSetupEvent(harnessChoiceEvent(DEFAULT_HARNESS));
diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx
new file mode 100644
index 0000000000..89623cc7f5
--- /dev/null
+++ b/desktop/src/ConnectToOpenBot.tsx
@@ -0,0 +1,322 @@
+import { invoke } from "@tauri-apps/api/core";
+import { useEffect, useId, useRef, useState } from "react";
+import { ExternalLink } from "./ExternalLink";
+import { asProblem, Failure, type Problem } from "./Problem";
+import { StatusLine } from "./SetupProgress";
+
+/** OpenBot's one booking link. */
+export const BOOK_A_DEMO = "https://open.bot/business";
+
+/**
+ * What the screen offers after something went wrong, chosen by the problem's `kind`. The sentence
+ * is the shell's, shown as given.
+ *
+ * `field`: the address is what to fix, so the sentence sits under the field and the field has the
+ * focus. `sign-in` and `retry`: the screen's one button says Sign in again or Try again. `browser`:
+ * this app can't connect to that OpenBot, and a link opens it in the browser. A kind this app does
+ * not know is offered Try again.
+ */
+type Offer = "field" | "retry" | "sign-in" | "browser";
+
+function offerFor(kind: string | null | undefined): Offer {
+ switch (kind) {
+ case "address-invalid":
+ case "not-openbot":
+ case "single-person":
+ return "field";
+ case "too-old":
+ return "browser";
+ case "sign-in-cancelled":
+ case "sign-in-failed":
+ case "session-ended":
+ return "sign-in";
+ default:
+ return "retry";
+ }
+}
+
+/** Nothing failed: the sign-in stopped or ended, and signing in again is all there is to do. */
+function isNotice(kind: string | null | undefined) {
+ return kind === "sign-in-cancelled" || kind === "session-ended";
+}
+
+/** The typed address as a link the browser can open. The shell takes no scheme as https too. */
+function browserAddress(address: string) {
+ const typed = address.trim();
+ return /^https?:\/\//i.test(typed) ? typed : `https://${typed}`;
+}
+
+type Phase = "idle" | "checking" | "waiting" | "opening" | "leaving";
+
+/** What went wrong, and what the screen offers for it. `null` offers nothing of its own. */
+type Trouble = { problem: Problem; offer: Offer | null };
+
+export type Connecting = ReturnType;
+
+/**
+ * Connecting this app to an OpenBot that runs elsewhere: the address, the sign-in in the person's
+ * browser, and what went wrong. Held by the first screen, above the choice of where OpenBot runs,
+ * so an address typed is still there after a look at the other choice.
+ *
+ * The shell does the work. `check_openbot_address` says whether there is an OpenBot this app can
+ * connect to at the address, and gives it back as it understood it. `connect_to_openbot` opens the
+ * browser, waits for the sign-in and then shows that OpenBot in this window. Nothing is installed
+ * or started on this computer.
+ */
+export function useConnectToOpenBot({
+ address: remembered = "",
+ problem: found = null,
+ reopen,
+ onThisComputer,
+}: {
+ /** The address connected to before, when there is one. */
+ address?: string;
+ /** What the launch found: a sign-in that ended, or an OpenBot it could not open. */
+ problem?: Problem | null;
+ /**
+ * Opens OpenBot with the sign-in this computer already has. Given when the launch tried that and
+ * it failed: Try again does it again, without a new sign-in, while the address is the same.
+ */
+ reopen?: () => Promise;
+ /** Back to OpenBot on this computer. May fail, when a saved connection has to be switched. */
+ onThisComputer: () => void | Promise;
+}) {
+ const [address, setAddress] = useState(remembered);
+ const [phase, setPhase] = useState("idle");
+ const [trouble, setTrouble] = useState(
+ found ? { problem: found, offer: offerFor(found.kind) } : null,
+ );
+ const [reopens, setReopens] = useState(Boolean(reopen));
+ // Each go at connecting: one that was cancelled or left behind says nothing when it ends.
+ const attempt = useRef(0);
+ const waiting = useRef(false);
+ const alive = useRef(true);
+ const field = useRef(null);
+ const action = useRef(null);
+ // Where the focus goes once the form is back: it was on a control that was disabled meanwhile.
+ const [focus, setFocus] = useState<{ on: "field" | "action" } | null>(null);
+ useEffect(() => {
+ if (!focus) return;
+ (focus.on === "field" ? field : action).current?.focus();
+ }, [focus]);
+
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ // Leaving the screen while the browser is waited on stops that sign-in.
+ if (waiting.current) {
+ waiting.current = false;
+ invoke("cancel_connect").catch(() => {});
+ }
+ };
+ }, []);
+
+ async function submit() {
+ const typed = address.trim();
+ if (!typed || phase !== "idle") return;
+ attempt.current += 1;
+ const mine = attempt.current;
+ const current = () => alive.current && attempt.current === mine;
+ setTrouble(null);
+ try {
+ if (reopens && reopen) {
+ setPhase("opening");
+ await reopen();
+ return;
+ }
+ setPhase("checking");
+ const checked = await invoke<{ address: string }>(
+ "check_openbot_address",
+ { address: typed },
+ );
+ if (!current()) return;
+ setAddress(checked.address);
+ setPhase("waiting");
+ waiting.current = true;
+ await invoke("connect_to_openbot", { address: checked.address });
+ if (!current()) return;
+ waiting.current = false;
+ // Signed in: the shell is showing that OpenBot in this window.
+ setPhase("opening");
+ } catch (error) {
+ if (!current()) return;
+ waiting.current = false;
+ const problem = asProblem(error);
+ const offer = offerFor(problem.kind);
+ setTrouble({ problem, offer });
+ // Only Try again opens it with the sign-in this computer has: any other way on signs in anew.
+ if (offer !== "retry") setReopens(false);
+ setPhase("idle");
+ // To the field when the address is what to fix, to the button when it is the way on.
+ if (offer !== "browser")
+ setFocus({ on: offer === "field" ? "field" : "action" });
+ }
+ }
+
+ /** Stops the sign-in the browser is waited on for. The person chose it, so nothing is said. */
+ async function cancel() {
+ attempt.current += 1;
+ waiting.current = false;
+ setPhase("idle");
+ setFocus({ on: "field" });
+ await invoke("cancel_connect").catch(() => {});
+ }
+
+ async function leave() {
+ if (phase !== "idle") return;
+ setTrouble(null);
+ setPhase("leaving");
+ try {
+ await onThisComputer();
+ } catch (error) {
+ if (alive.current) setTrouble({ problem: asProblem(error), offer: null });
+ } finally {
+ if (alive.current) setPhase("idle");
+ }
+ }
+
+ return {
+ address,
+ phase,
+ trouble,
+ busy: phase !== "idle",
+ field,
+ action,
+ /** A sentence about the address, or about opening it, is not about the next one typed. */
+ change(next: string) {
+ setAddress(next);
+ setTrouble(null);
+ setReopens(false);
+ },
+ submit,
+ cancel,
+ leave,
+ };
+}
+
+/**
+ * The first screen's lower half when OpenBot runs elsewhere: one field for its address, what
+ * happens next, and Connect. While the browser is waited on, Cancel is the only control.
+ */
+export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) {
+ const id = useId();
+ const { address, phase, trouble, busy } = connecting;
+ const underField = trouble?.offer === "field";
+ return (
+
+ );
+}
+
+/** The sentence, in the card: a notice when nothing failed, the window's failure when it did. */
+function Trouble({ trouble, address }: { trouble: Trouble; address: string }) {
+ const { problem, offer } = trouble;
+ if (isNotice(problem.kind)) {
+ return (
+
+
{problem.said}
+
+ );
+ }
+ return (
+
+ {offer === "browser" && address.trim() && (
+
+ Open in browser
+
+ )}
+
+ );
+}
diff --git a/desktop/src/Problem.tsx b/desktop/src/Problem.tsx
index 2268095043..53318136ae 100644
--- a/desktop/src/Problem.tsx
+++ b/desktop/src/Problem.tsx
@@ -1,5 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
-import { useState } from "react";
+import { type ReactNode, useState } from "react";
import { ExternalLink } from "./ExternalLink";
/**
@@ -21,6 +21,11 @@ export type Problem = {
leftover_containers?: string[] | null;
/** Only a Windows restart fixes this: the window offers one instead of Try again. */
restart_windows?: boolean | null;
+ /**
+ * Which thing went wrong while connecting to an OpenBot that runs elsewhere. The window reads it
+ * only to choose what to offer next (`ConnectToOpenBot`); the sentence is still `said`.
+ */
+ kind?: string | null;
};
/** Anything thrown, as a problem. A bare string keeps working and reads as it always did. */
@@ -158,13 +163,16 @@ export function TroubleshootingLogs({
/**
* `onRetry`, where the screen has no other way to run what failed again: Try again, in the card.
* The install behind the account step had none, and its failure sat there with nothing to press.
+ * `children`, where the way on is something other than Try again: it takes that button's place.
*/
export function Failure({
problem,
onRetry,
+ children,
}: {
problem: Problem;
onRetry?: () => void;
+ children?: ReactNode;
}) {
return (
@@ -177,6 +185,7 @@ export function Failure({
)}
+ {children &&
{children}
}
{/* The real output, kept but not the headline. Whoever is debugging opens this; the person
reading the sentence above never has to. */}
{problem.detail && (
diff --git a/desktop/src/Welcome.tsx b/desktop/src/Welcome.tsx
index a702ff5ff2..566872faf3 100644
--- a/desktop/src/Welcome.tsx
+++ b/desktop/src/Welcome.tsx
@@ -1,14 +1,14 @@
import { IconBuilding, IconCloud, IconDeviceLaptop } from "@tabler/icons-react";
import { type ReactNode, useState } from "react";
+import { ConnectToOpenBot, useConnectToOpenBot } from "./ConnectToOpenBot";
import {
EarlyDownloadsLine,
earlyDownloadsMeasured,
useEarlyDownloads,
} from "./EarlyDownloads";
-import { ExternalLink } from "./ExternalLink";
+import type { Problem } from "./Problem";
-/** OpenBot's one booking link. */
-export const BOOK_A_DEMO = "https://open.bot/business";
+export { BOOK_A_DEMO } from "./ConnectToOpenBot";
/**
* The least a computer needs to run every part of OpenBot itself.
@@ -25,19 +25,24 @@ export const SELF_HOSTED_NEEDS = [
"40 GB of free disk space",
] as const;
+/** Where OpenBot runs: on this computer, or at an address this app connects to. */
+export type Hosting = "self-hosted" | "connect";
+
/**
* Where OpenBot runs, and what that asks of this computer, before it asks for anything else.
*
- * In this order: the three ways to run OpenBot, of which only Self-hosted can be chosen here
- * (OpenBot Cloud and OpenBot for Business are shown greyed, Business with the one booking link);
- * all of it fits the window's default size (1000×800, less a title bar) with no scrollbar;
- * what this computer needs for Self-hosted and why, which is that every part of OpenBot runs on it;
- * then how long setup takes. Usage data is not said here: it is the last screen's choice
- * (`UsageDataChoice`).
+ * First the three ways to run OpenBot, of which two can be chosen here: Self-hosted runs
+ * everything on this computer, and OpenBot for Business connects this app to the OpenBot a company
+ * runs, at its address. OpenBot Cloud is shown greyed. Then what the choice needs. For Self-hosted
+ * that is what this computer needs and why, which is that every part of OpenBot runs on it, how
+ * long setup takes, and Install. For OpenBot for Business it is the address and Connect
+ * (`ConnectToOpenBot`), with the one booking link for a company that has no OpenBot yet. Either
+ * way it fits the window's default size (1000×800, less a title bar) with no scrollbar. Usage data
+ * is not said here: it is the last screen's choice (`UsageDataChoice`).
*
- * The big downloads start while this screen shows, before Install is clicked, and its line says how
- * far they are (`EarlyDownloadsLine`). Once they are done it says nothing: Install is the next step
- * either way.
+ * The big downloads start while this screen shows with Self-hosted chosen, before Install is
+ * clicked, and its line says how far they are (`EarlyDownloadsLine`). Once they are done it says
+ * nothing: Install is the next step either way.
*
* On a disk too full for OpenBot, Install waits with the line that says so, and is there once the
* download starts by itself. On Windows F it was pressable at 15 GB free: it built OpenBot's machine,
@@ -45,23 +50,30 @@ export const SELF_HOSTED_NEEDS = [
* downloads have looked at the disk asks them first (`earlyDownloadsMeasured`).
*/
export function Welcome({
+ hosting,
+ onConnect,
+ onThisComputer,
+ saved,
onInstall,
failure,
}: {
+ hosting: Hosting;
+ /** OpenBot for Business was picked. */
+ onConnect: () => void;
+ /** Self-hosted was picked again. May fail, when a saved connection has to be switched first. */
+ onThisComputer: () => void | Promise;
+ /** What is known of an OpenBot connected to before (`useConnectToOpenBot`). */
+ saved?: {
+ address?: string;
+ problem?: Problem | null;
+ reopen?: () => Promise;
+ };
onInstall: () => void;
- /** A failure from setup itself, shown inside this card rather than under it. */
+ /** A failure from setup on this computer, shown inside this card rather than under it. */
failure?: ReactNode;
}) {
- const downloads = useEarlyDownloads();
- const [checking, setChecking] = useState(false);
- const short = downloads?.state === "short";
- const install = () => {
- setChecking(true);
- void earlyDownloadsMeasured().then((now) => {
- setChecking(false);
- if (now?.state !== "short") onInstall();
- });
- };
+ const connecting = useConnectToOpenBot({ ...saved, onThisComputer });
+ const connect = hosting === "connect";
return (
@@ -76,14 +88,20 @@ export function Welcome({
Set up OpenBot
+ {connect ? (
+
+ ) : (
+
+ )}
+
+ );
+}
+
+/** What Self-hosted asks of this computer and why, how long setup takes, and Install. */
+function SelfHosted({
+ onInstall,
+ failure,
+}: {
+ onInstall: () => void;
+ failure?: ReactNode;
+}) {
+ const downloads = useEarlyDownloads();
+ const [checking, setChecking] = useState(false);
+ const short = downloads?.state === "short";
+ const install = () => {
+ setChecking(true);
+ void earlyDownloadsMeasured().then((now) => {
+ setChecking(false);
+ if (now?.state !== "short") onInstall();
+ });
+ };
+ return (
+ <>
What this computer needs
@@ -149,7 +195,7 @@ export function Welcome({
{failure}
-
+ >
);
}
diff --git a/desktop/src/setupLayout.browser.test.ts b/desktop/src/setupLayout.browser.test.ts
index 855669c223..0ff436134a 100644
--- a/desktop/src/setupLayout.browser.test.ts
+++ b/desktop/src/setupLayout.browser.test.ts
@@ -739,6 +739,19 @@ describe.skipIf(!asked)("the first screen at the window's default size", () => {
return card.scrollHeight - card.clientHeight;
});
expect(overflow).toBeLessThanOrEqual(0);
+ // And with the other choice picked, OpenBot for Business: its address field and Connect.
+ await page.getByText("OpenBot for Business").click();
+ await page.getByLabel("OpenBot address", { exact: true }).waitFor();
+ await page.waitForTimeout(400);
+ expect(
+ await page.evaluate(() => {
+ const card = document.querySelector("main > .sheet") as HTMLElement;
+ return card.scrollHeight - card.clientHeight;
+ }),
+ ).toBeLessThanOrEqual(0);
+ expect(await page.getByRole("button", { name: "Connect" }).count()).toBe(
+ 1,
+ );
} finally {
await page.close();
}
diff --git a/desktop/src/styles.css b/desktop/src/styles.css
index 9ba21523f4..87c6e6e410 100644
--- a/desktop/src/styles.css
+++ b/desktop/src/styles.css
@@ -732,9 +732,9 @@ button.text-link.change-provider {
}
/*
- * The ways to run OpenBot, on the first screen. Self-hosted is the one this app sets up; OpenBot
- * Cloud and OpenBot for Business are shown so a person knows they exist, greyed and not choosable.
- * Business's booking link stays live, and keeps the pointer every link has.
+ * The ways to run OpenBot, on the first screen. Self-hosted is the one this app sets up, and
+ * OpenBot for Business is the one it connects to. OpenBot Cloud is shown so a person knows it
+ * exists, greyed and not choosable.
*/
fieldset.picker.hosting {
max-height: none;
@@ -766,6 +766,76 @@ fieldset.picker.hosting .tile.unavailable .mark-tile {
opacity: 0.45;
}
+/* Not choosable for now, while an address is checked or the browser is waited on: Cancel is. */
+fieldset.picker.hosting .tile.held,
+fieldset.picker.hosting .tile.held:hover,
+fieldset.picker.hosting .tile.held:active {
+ cursor: default;
+ background: var(--card);
+}
+
+/*
+ * OpenBot for Business, under the choices: the address of the OpenBot to connect to, what happens
+ * next under the field, then Connect. What went wrong with the address is said under the field,
+ * in the destructive colour; anything else is said in a card between the field and the button.
+ */
+.connect-to-openbot .field {
+ margin: 8px 0 0;
+}
+
+/* Held while it is checked or signed in to: still readable, on the ground of a field at rest. */
+.connect-to-openbot .field input:read-only {
+ background: var(--muted);
+}
+
+.address-problem {
+ margin: 6px 0 0;
+ font-size: var(--text-sm);
+ line-height: 20px;
+ overflow-wrap: anywhere;
+}
+
+.connect-to-openbot .footnote {
+ margin-top: 8px;
+}
+
+/* A sign-in that stopped or ended: the card that waits on the person, with the sentence in ink. */
+.connect-to-openbot .local-alert {
+ margin: 16px 0 0;
+}
+
+.connect-to-openbot .local-alert p {
+ color: var(--text-primary);
+}
+
+.connect-to-openbot .blocker p,
+.connect-to-openbot .local-alert p {
+ overflow-wrap: anywhere;
+}
+
+/* A link that is the way on, drawn as the app's `outline` button. */
+a.button-link {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 40px;
+ padding: 0 14px;
+ border-radius: var(--r-card);
+ border: 1px solid var(--border);
+ background: var(--background);
+ color: var(--text-primary);
+ font-size: var(--text-sm);
+ line-height: 1;
+ font-weight: 500;
+ text-decoration: none;
+ white-space: nowrap;
+ transition: background-color 150ms ease-out;
+}
+
+a.button-link:hover {
+ background: var(--muted);
+}
+
/* What Self-hosted asks of this computer: the reason, then the four needs, two to a line. */
.needs .lede {
margin-bottom: 6px;
@@ -1871,13 +1941,15 @@ a:hover {
/* The app's dark `outline` button: `dark:bg-input/30`, a shade above the card. */
button.quiet,
- button.another-question {
+ button.another-question,
+ a.button-link {
background: color-mix(in srgb, var(--input) 30%, transparent);
border-color: var(--input);
}
button.quiet:hover:not(:disabled),
- button.another-question:hover:not(:disabled) {
+ button.another-question:hover:not(:disabled),
+ a.button-link:hover {
background: color-mix(in srgb, var(--input) 50%, transparent);
}
diff --git a/desktop/src/telemetry.ts b/desktop/src/telemetry.ts
index 07d201805c..96882cc984 100644
--- a/desktop/src/telemetry.ts
+++ b/desktop/src/telemetry.ts
@@ -1,7 +1,18 @@
import { invoke } from "@tauri-apps/api/core";
import type { ModelChoice } from "./ProviderPicker";
-export type SetupStep = "welcome" | "install" | "account" | "model" | "connect";
+/**
+ * `connect` is the Start step, where OpenBot on this computer starts. `connect_openbot` is the
+ * first screen with an OpenBot that runs elsewhere chosen: the address field. The address itself is
+ * never part of an event.
+ */
+export type SetupStep =
+ | "welcome"
+ | "install"
+ | "account"
+ | "model"
+ | "connect"
+ | "connect_openbot";
const HARNESSES = {
crewai: "crewai",
From 124cae7b978834b8d79bba74641950e55e628fdc Mon Sep 17 00:00:00 2001
From: David McKay
Date: Sun, 15 Nov 2026 12:54:40 -0800
Subject: [PATCH 004/116] Offer connecting to an OpenBot from Settings when
OpenBot runs on this computer
A person who already runs OpenBot here had no way back to the choice of where it runs. Settings, Computer now has a Connection row that, after a confirm, stops OpenBot here and opens setup at that choice. It is drawn only by a desktop app that can connect.
---
.../settings/connection-sections.tsx | 67 +++++++++++++++++++
app/src/lib/desktop/queries.ts | 11 ++-
app/src/routes/_authed/settings/computer.tsx | 10 ++-
app/tests/desktop-connected-settings.test.tsx | 28 +++++++-
4 files changed, 109 insertions(+), 7 deletions(-)
diff --git a/app/src/components/settings/connection-sections.tsx b/app/src/components/settings/connection-sections.tsx
index d998ede765..c750db595a 100644
--- a/app/src/components/settings/connection-sections.tsx
+++ b/app/src/components/settings/connection-sections.tsx
@@ -152,6 +152,73 @@ function SignOutRow({ host }: { host: string }) {
);
}
+/**
+ * Settings → Computer inside an OpenBot Desktop that runs OpenBot on this computer: the way to
+ * connect to an OpenBot that runs somewhere else instead. Drawn under `ThisComputerSections`, and
+ * only by a desktop app that can connect.
+ *
+ * It stops OpenBot here, as Stop does, and the window shows setup at the choice of where OpenBot
+ * runs. This page goes with it.
+ */
+export function ConnectInsteadSection() {
+ const [open, setOpen] = useState(false);
+ const change = useMutation(changeConnectionMutationOptions());
+ const leaving = change.isPending || change.isSuccess;
+ return (
+
+
+
+
+
+
+
+ OpenBot runs on this computer
+
+ You can connect to an OpenBot your company runs instead.
+
+
+
+
+
+
+
+
+
+ );
+}
+
function UseThisComputerRow({ host }: { host: string }) {
const [open, setOpen] = useState(false);
const change = useMutation(changeConnectionMutationOptions());
diff --git a/app/src/lib/desktop/queries.ts b/app/src/lib/desktop/queries.ts
index f878af538a..a0ccd71c3d 100644
--- a/app/src/lib/desktop/queries.ts
+++ b/app/src/lib/desktop/queries.ts
@@ -129,10 +129,15 @@ export type DesktopUsageData = {
* desktop app keeps that and the page never holds it.
*/
export type DesktopConnection =
- | { mode: "local"; address: null }
+ /** `canConnect`: the desktop app is one that can connect to an OpenBot elsewhere. */
+ | { mode: "local"; address: null; canConnect: boolean }
| { mode: "connected"; address: string };
-const ON_THIS_COMPUTER: DesktopConnection = { mode: "local", address: null };
+const ON_THIS_COMPUTER: DesktopConnection = {
+ mode: "local",
+ address: null,
+ canConnect: false,
+};
export const desktopKeys = {
all: ["desktop"] as const,
@@ -174,7 +179,7 @@ export function desktopConnectionQueryOptions() {
}>("connection");
return answer?.mode === "connected" && answer.address
? { mode: "connected", address: answer.address }
- : ON_THIS_COMPUTER;
+ : { mode: "local", address: null, canConnect: true };
} catch {
return ON_THIS_COMPUTER;
}
diff --git a/app/src/routes/_authed/settings/computer.tsx b/app/src/routes/_authed/settings/computer.tsx
index 3d540e9be0..356d2bd0db 100644
--- a/app/src/routes/_authed/settings/computer.tsx
+++ b/app/src/routes/_authed/settings/computer.tsx
@@ -3,7 +3,10 @@ import { createFileRoute } from "@tanstack/react-router";
import { PageShell } from "@/components/layout/page-shell";
import { ComputersPage } from "@/components/manage/computers-page";
import { BrowserSections } from "@/components/settings/browsers/browser-sections";
-import { ConnectionSections } from "@/components/settings/connection-sections";
+import {
+ ConnectInsteadSection,
+ ConnectionSections,
+} from "@/components/settings/connection-sections";
import { ThisComputerSections } from "@/components/settings/this-computer-sections";
import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries";
import { desktopConnectionQueryOptions } from "@/lib/desktop/queries";
@@ -69,7 +72,10 @@ function ComputerPage() {
{!desktop || !connection ? null : connection.mode === "connected" ? (
) : (
-
+ <>
+
+ {connection.canConnect ? : null}
+ >
)}
diff --git a/app/tests/desktop-connected-settings.test.tsx b/app/tests/desktop-connected-settings.test.tsx
index bbaa6e5817..7b3806261e 100644
--- a/app/tests/desktop-connected-settings.test.tsx
+++ b/app/tests/desktop-connected-settings.test.tsx
@@ -173,18 +173,42 @@ test("connected, Settings → Computer says where the app is connected and shows
expect(header?.textContent).not.toContain("runs on this computer");
});
-test("with OpenBot on this computer, the page is as it was: its services, and no Connection section", async () => {
+test("with OpenBot on this computer, its services are as they were, and the way to connect to an OpenBot instead is offered", async () => {
const view = renderComputer("local");
await view.findByRole("heading", { name: "App" });
expect(view.getByText("Installed in")).toBeTruthy();
- expect(view.queryByRole("heading", { name: "Connection" })).toBeNull();
+ expect(view.queryByText("Connected to")).toBeNull();
+ await view.findByRole("heading", { name: "Connection" });
+ expect(view.getByText("OpenBot runs on this computer")).toBeTruthy();
+});
+
+test("Connect to an OpenBot asks first, saying OpenBot stops here and nothing is lost, then asks the desktop app", async () => {
+ const view = renderComputer("local");
+ fireEvent.click(
+ await view.findByRole("button", { name: "Connect to an OpenBot" }),
+ );
+ const dialog = await view.findByRole("dialog");
+ expect(dialog.textContent).toContain("Connect to an OpenBot instead?");
+ expect(dialog.textContent).toContain("OpenBot stops on this computer");
+ expect(dialog.textContent).toContain("Nothing on this computer is lost");
+ expect(asked).not.toContain("change_connection");
+ fireEvent.click(
+ Array.from(dialog.querySelectorAll("button")).find(
+ (button) => button.textContent === "Stop and open setup",
+ ) as HTMLButtonElement,
+ );
+ await waitFor(() => expect(asked).toContain("change_connection"));
});
test("a desktop app from before it could connect is read as OpenBot on this computer", async () => {
const view = renderComputer("older");
await view.findByRole("heading", { name: "App" });
expect(asked).toContain("connection");
+ // It cannot connect, so it is not offered.
expect(view.queryByRole("heading", { name: "Connection" })).toBeNull();
+ expect(
+ view.queryByRole("button", { name: "Connect to an OpenBot" }),
+ ).toBeNull();
});
test("Sign out asks first, then asks the desktop app to sign out", async () => {
From 97648317c96509867fabfe3b89fdddbdb6e9d100 Mon Sep 17 00:00:00 2001
From: David McKay
Date: Sun, 15 Nov 2026 13:03:53 -0800
Subject: [PATCH 005/116] Say connection problems calmly, and offer the choice
to an install on this computer
A connection that didn't work is not a failed install. Every connection
problem that is not about the address itself now shows the shell's
sentence in the calm notice, with no failure heading and no
troubleshooting logs, and the way on is the screen's button: Try again,
Sign in again, or Open in browser beside Connect. The connect screen no
longer scrolls at the window's default size. The failure card is as it was
for setup on this computer.
Setup also asks the shell whether the person chose, in Settings, to pick
where OpenBot runs. When they did, the first screen shows whichever way
OpenBot runs today. On a computer that already runs OpenBot, nothing
starts while the choice shows, and Continue goes on as any relaunch does.
---
desktop/src/App.test.tsx | 77 +++++++++++++++++++++++++++++-
desktop/src/App.tsx | 81 ++++++++++++++++++++++++++------
desktop/src/ConnectToOpenBot.tsx | 46 ++++++++----------
desktop/src/Problem.tsx | 6 +--
desktop/src/Welcome.tsx | 52 +++++++++++++++-----
desktop/src/styles.css | 9 ++--
6 files changed, 207 insertions(+), 64 deletions(-)
diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx
index 92ea038392..160d101d3a 100644
--- a/desktop/src/App.test.tsx
+++ b/desktop/src/App.test.tsx
@@ -893,7 +893,15 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) {
await userEvent.type(field, "x");
expect(view.queryByRole("alert")).toBeNull();
expect(field.getAttribute("aria-invalid")).toBeNull();
- } else if (offer === "Open in browser") {
+ return;
+ }
+ // A connection that didn't work is not a failed install: a calm notice with the sentence,
+ // not the failure card with its heading and troubleshooting logs.
+ expect(alert.classList.contains("blocker")).toBe(false);
+ expect(view.queryByText("That didn’t finish")).toBeNull();
+ expect(view.queryByRole("button", { name: "Copy logs" })).toBeNull();
+ expect(view.queryByRole("link", { name: "Get setup help" })).toBeNull();
+ if (offer === "Open in browser") {
const link = view.getByRole("link", { name: "Open in browser" });
expect(link.getAttribute("href")).toBe(ELSEWHERE);
await userEvent.click(link);
@@ -904,6 +912,7 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) {
expect(view.getByRole("button", { name: "Connect" })).toBeTruthy();
} else {
// One way on, and it says what it does.
+ expect(alert.textContent).toBe(said);
expect(view.queryByRole("button", { name: "Connect" })).toBeNull();
await userEvent.click(view.getByRole("button", { name: offer }));
await waitFor(() => expect(at === "check" ? checks : signIns).toBe(2));
@@ -1034,6 +1043,72 @@ test("asked from Settings to choose where OpenBot runs, the first screen opens o
expect(commands).toContain("already_configured");
});
+/*
+ * Settings' choice of where OpenBot runs, for a person who already runs it on this computer: the
+ * shell stops OpenBot, puts setup back and says `choose` once. The first screen shows in place of
+ * the start that a relaunch does by itself, and nothing starts until the person continues.
+ */
+test("asked from Settings on an install on this computer, the first screen shows the choice and starts nothing until Continue, which starts it as a relaunch does", async () => {
+ setupConnectedLocalStack(
+ "/tmp/choose-on-this-computer",
+ localStatus("ready", "valid"),
+ );
+ let notices = 0;
+ withLocalCli({
+ connection: { mode: "local", address: ELSEWHERE, signedIn: false },
+ take_connection_notice: () => {
+ notices += 1;
+ return notices === 1 ? { kind: "choose", message: null } : null;
+ },
+ record_setup_event: null,
+ });
+ const view = await renderApp();
+ expect(
+ await view.findByRole("heading", { name: "Set up OpenBot" }),
+ ).toBeTruthy();
+ expect(view.getByRole("radio", { name: /^Self-hosted/ })).toHaveProperty(
+ "checked",
+ true,
+ );
+ // OpenBot is already installed here: the way on is Continue, not Install.
+ expect(buttons(view)).toEqual(["Continue"]);
+ expect(view.queryByText(/Setup takes/)).toBeNull();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ const started = () =>
+ invokeCalls
+ .map((call) => call.command)
+ .filter((command) =>
+ [
+ "run_local_eval",
+ "set_up_local_eval",
+ "connect_local_eval",
+ "start_stack",
+ "show_openbot",
+ "prepare_installation",
+ "start_early_downloads",
+ "use_this_computer",
+ ].includes(command),
+ );
+ expect(started()).toEqual([]);
+ // The other choice, with the address connected to before, and back.
+ await userEvent.click(
+ view.getByRole("radio", { name: /^OpenBot for Business/ }),
+ );
+ expect(
+ (view.getByLabelText("OpenBot address") as HTMLInputElement).value,
+ ).toBe(ELSEWHERE);
+ await userEvent.click(view.getByRole("radio", { name: /^Self-hosted/ }));
+ expect(started()).toEqual([]);
+ // Continue: today's relaunch, which starts the saved installation and opens OpenBot.
+ await userEvent.click(view.getByRole("button", { name: "Continue" }));
+ await view.findByRole("heading", { name: "OpenBot is running" });
+ expect(started()).toEqual(["run_local_eval", "start_stack", "show_openbot"]);
+ expect(getStartStackPayload()).toMatchObject({
+ root: "/tmp/choose-on-this-computer",
+ ...LOCAL_ADDRESSES,
+ });
+});
+
test("a saved sign-in that can't open OpenBot says why on the connect screen, and Try again opens it without signing in again", async () => {
const said =
"OpenBot couldn't reach openbot.example.com. Check the address and your network, then try again.";
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index efd68b81f1..7e4295220b 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -54,7 +54,7 @@ import {
type SetupStep,
} from "./telemetry";
import { UsageDataChoice } from "./UsageDataChoice";
-import { Welcome } from "./Welcome";
+import { type Hosting, Welcome } from "./Welcome";
import { type Blocker, WindowsBlocker, WindowsRestart } from "./WindowsBlocker";
type AlreadyConfigured = {
@@ -126,8 +126,11 @@ type ConnectionNotice = { kind: string; message: string | null };
type Launch =
| { at: "asking" }
- /** OpenBot on this computer: setup as it has always been. */
- | { at: "local"; address: string }
+ /**
+ * OpenBot on this computer: setup as it has always been. `choose`: the person asked from
+ * Settings to choose where OpenBot runs, so the first screen shows before anything starts.
+ */
+ | { at: "local"; address: string; choose: boolean }
/** Signed in to an OpenBot that runs elsewhere, which the shell is opening. */
| { at: "opening" }
/** The first screen with that OpenBot's address, to sign in to it again or choose otherwise. */
@@ -159,11 +162,12 @@ function Setup() {
const found = await invoke("connection").catch(() => null);
if (!alive.current) return;
const address = found?.address ?? "";
- if (found?.mode !== "connected") {
- setLaunch({ at: "local", address });
+ // An older shell knows neither question: OpenBot on this computer, with nothing to say.
+ if (!found) {
+ setLaunch({ at: "local", address, choose: false });
return;
}
- if (found.signedIn) {
+ if (found.mode === "connected" && found.signedIn) {
setLaunch({ at: "opening" });
try {
await invoke("show_connected");
@@ -182,6 +186,14 @@ function Setup() {
"take_connection_notice",
).catch(() => null);
if (!alive.current) return;
+ if (found.mode !== "connected") {
+ setLaunch({
+ at: "local",
+ address,
+ choose: notice?.kind === "choose",
+ });
+ return;
+ }
setLaunch({
at: "connect",
address,
@@ -203,7 +215,8 @@ function Setup() {
recordSetupEvent({ kind: "step_viewed", step: "connect_openbot" });
}, [connecting]);
- if (launch.at === "local") return ;
+ if (launch.at === "local")
+ return ;
if (launch.at === "connect") {
const { address } = launch;
return (
@@ -214,7 +227,7 @@ function Setup() {
// The saved choice goes back to this computer, then setup carries on as a first run.
onThisComputer={async () => {
await invoke("use_this_computer");
- setLaunch({ at: "local", address });
+ setLaunch({ at: "local", address, choose: false });
}}
saved={{
address,
@@ -244,8 +257,20 @@ function Setup() {
);
}
-/** Setup of OpenBot on this computer. `address`: an OpenBot connected to before, if any. */
-function LocalSetup({ address }: { address: string }) {
+/**
+ * Setup of OpenBot on this computer. `address`: an OpenBot connected to before, if any. `choose`:
+ * open at the first screen, the choice of where OpenBot runs, whatever is already installed.
+ */
+function LocalSetup({ address, choose }: { address: string; choose: boolean }) {
+ /*
+ * The choice the person asked for from Settings, shown over wherever setup would have resumed:
+ * nothing starts by itself while it shows. Continue with Self-hosted drops it, and setup goes on
+ * as this launch would have without it; an installation that is already set up starts as it does
+ * on any relaunch.
+ */
+ const [choosing, setChoosing] = useState(
+ choose ? "self-hosted" : null,
+ );
const [blocker, setBlocker] = useState(null);
// A Windows fix made earlier that only counts once Windows has restarted, and it has not.
const [restartPending, setRestartPending] = useState(false);
@@ -291,11 +316,15 @@ function LocalSetup({ address }: { address: string }) {
// The back end is ready on the release it had, and its update did not finish.
const [backEndNotice, setBackEndNotice] = useState(null);
const [step, setStep] = useState("welcome");
+ const [checkingResume, setCheckingResume] = useState(true);
+ // With nothing set up yet, setup opens at the first screen anyway: it is the choice.
+ useEffect(() => {
+ if (!checkingResume && choosing && step === "welcome") setChoosing(null);
+ }, [checkingResume, choosing, step]);
const [steps, setSteps] = useState
{phase === "checking" && (
Checking the address…
@@ -300,23 +301,16 @@ export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) {
);
}
-/** The sentence, in the card: a notice when nothing failed, the window's failure when it did. */
-function Trouble({ trouble, address }: { trouble: Trouble; address: string }) {
- const { problem, offer } = trouble;
- if (isNotice(problem.kind)) {
- return (
-
-
{problem.said}
-
- );
- }
+/**
+ * The sentence, in a calm notice: the card that waits on the person. A connection that didn't work
+ * is not a failed install, so it is not drawn as one: no failure heading and no troubleshooting
+ * logs, which are about OpenBot on this computer. The way on is the screen's button, or the link
+ * beside it when that OpenBot can only be opened in the browser.
+ */
+function Trouble({ trouble }: { trouble: Trouble }) {
return (
-
- {offer === "browser" && address.trim() && (
-
- Open in browser
-
- )}
-
+
+
{trouble.problem.said}
+
);
}
diff --git a/desktop/src/Problem.tsx b/desktop/src/Problem.tsx
index 53318136ae..c238e74902 100644
--- a/desktop/src/Problem.tsx
+++ b/desktop/src/Problem.tsx
@@ -1,5 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
-import { type ReactNode, useState } from "react";
+import { useState } from "react";
import { ExternalLink } from "./ExternalLink";
/**
@@ -163,16 +163,13 @@ export function TroubleshootingLogs({
/**
* `onRetry`, where the screen has no other way to run what failed again: Try again, in the card.
* The install behind the account step had none, and its failure sat there with nothing to press.
- * `children`, where the way on is something other than Try again: it takes that button's place.
*/
export function Failure({
problem,
onRetry,
- children,
}: {
problem: Problem;
onRetry?: () => void;
- children?: ReactNode;
}) {
return (
@@ -185,7 +182,6 @@ export function Failure({
)}
- {children &&
{children}
}
{/* The real output, kept but not the headline. Whoever is debugging opens this; the person
reading the sentence above never has to. */}
{problem.detail && (
diff --git a/desktop/src/Welcome.tsx b/desktop/src/Welcome.tsx
index 566872faf3..56b0f034b1 100644
--- a/desktop/src/Welcome.tsx
+++ b/desktop/src/Welcome.tsx
@@ -54,10 +54,17 @@ export function Welcome({
onConnect,
onThisComputer,
saved,
+ resumes = false,
onInstall,
failure,
}: {
hosting: Hosting;
+ /**
+ * OpenBot is already set up on this computer, and the person asked from Settings to choose where
+ * it runs. Self-hosted's way on is Continue, which goes on with that setup; there is nothing to
+ * install or download first.
+ */
+ resumes?: boolean;
/** OpenBot for Business was picked. */
onConnect: () => void;
/** Self-hosted was picked again. May fail, when a saved connection has to be switched first. */
@@ -146,30 +153,22 @@ export function Welcome({
{connect ? (
) : (
-
+
)}
);
}
-/** What Self-hosted asks of this computer and why, how long setup takes, and Install. */
+/** What Self-hosted asks of this computer and why, then the way on. */
function SelfHosted({
onInstall,
failure,
+ resumes,
}: {
onInstall: () => void;
failure?: ReactNode;
+ resumes: boolean;
}) {
- const downloads = useEarlyDownloads();
- const [checking, setChecking] = useState(false);
- const short = downloads?.state === "short";
- const install = () => {
- setChecking(true);
- void earlyDownloadsMeasured().then((now) => {
- setChecking(false);
- if (now?.state !== "short") onInstall();
- });
- };
return (
<>
@@ -185,6 +184,34 @@ function SelfHosted({
))}
+ {resumes ? (
+
Setup takes 1 to 10 minutes, depending on your internet speed.
@@ -194,7 +221,6 @@ function SelfHosted({
- {failure}
>
);
}
diff --git a/desktop/src/styles.css b/desktop/src/styles.css
index 87c6e6e410..939a8a07b5 100644
--- a/desktop/src/styles.css
+++ b/desktop/src/styles.css
@@ -799,17 +799,16 @@ fieldset.picker.hosting .tile.held:active {
margin-top: 8px;
}
-/* A sign-in that stopped or ended: the card that waits on the person, with the sentence in ink. */
+/*
+ * A connection that didn't work, or a sign-in that stopped or ended: the card that waits on the
+ * person, with the shell's sentence in ink. Not the failure card: nothing on this computer failed.
+ */
.connect-to-openbot .local-alert {
margin: 16px 0 0;
}
.connect-to-openbot .local-alert p {
color: var(--text-primary);
-}
-
-.connect-to-openbot .blocker p,
-.connect-to-openbot .local-alert p {
overflow-wrap: anywhere;
}
From 9c9ce151c950ff5fba04f22768707e34b91e0c67 Mon Sep 17 00:00:00 2001
From: David McKay
Date: Sun, 15 Nov 2026 13:07:47 -0800
Subject: [PATCH 006/116] Sign in to an OpenBot at an address and relay the
window to it
OpenBot Desktop could only run OpenBot on the computer it is installed on. This adds what it
takes to show an OpenBot that runs somewhere else instead, as a library module of its own
(desktop/src-tauri/src/connected) that nothing calls yet.
choice: which of the two the person chose, in connection.json in the app's configuration folder,
with the address and the organisation picked there. No file means on this computer.
address: a typed address kept as scheme and host (https, or http for 127.0.0.1 and [::1]; no
scheme is taken as https), and two public questions asked of it: what it offers and how an app
signs in to it (RFC 8414). Each way that can go wrong is one kind with its own sentence: not an
address, unreachable, not an OpenBot, one person's OpenBot on its own computer, a release from
before apps could sign in. A redirect to another host is not followed, and metadata that names
another host is refused.
sign_in: OAuth 2.1 authorization code with PKCE (S256) as the public client
openbot-desktop-oauth, with a listener on 127.0.0.1 at a port the system picks and a redirect of
exactly /callback. The verifier, the state and the callback's first line use what
provider_oauth already has (its random and its challenge are now shared, unchanged). The wait
ends on the code, a refusal, Cancel or ten minutes. After the exchange the OpenBot is asked
/api/me with the new token; a 401 there means it cannot serve the app. Refresh tokens rotate, so
one refresh runs at a time and the new token is stored before the old one is let go. Sign-out
revokes both tokens (RFC 7009) and forgets the sign-in.
credentials: the refresh token in the system's credential store through keyring 4.2 (Keychain,
Credential Manager, the Secret Service), under the app's identifier and the address. The access
token stays in memory. Nothing token-shaped is written to a file or a log, and the log's
redaction now also covers OpenBot's own token prefixes and the relay's cookie.
relay: an HTTP/1 server on 127.0.0.1 only, at a port the system picks, that passes each request
and WebSocket upgrade on to the one typed address with the access token added. It answers only
its own Host, only requests that carry the secret made for that run (given to the window as an
HttpOnly, SameSite=Strict cookie at an entry address that is never forwarded), and no request
from another site. Absolute request targets and CONNECT are refused and redirects are handed
back, rewritten onto the relay when they point at the typed address. Origin, Cookie, Referer,
Forwarded and X-Forwarded-* are dropped on the way out and Set-Cookie on the way back. Bodies
stream both ways. The organisation the person picked is named in a header on every request, set
by the shell and never taken from the page. A 401 to a request with no body leads to one refresh
and the request again; a refused refresh says the session ended, once, and the relay stops.
The tests run against a stand-in OpenBot that answers the same addresses the same way: the
metadata document, a form-encoded token endpoint with the client's id in the body, the verifier
really checked, a code that burns on a wrong verifier, rotating refresh tokens where a replayed
one answers invalid_grant, revocation, and a redirect that must be http://127.0.0.1:/callback.
The credential store in tests is keyring's own in-memory one.
New crates: keyring and keyring-core; tokio, hyper, hyper-util, http-body-util, bytes and
futures-util, which reqwest and Tauri already build; tokio-tungstenite for the tests' WebSocket.
---
desktop/src-tauri/Cargo.lock | 305 ++++-
desktop/src-tauri/Cargo.toml | 20 +-
desktop/src-tauri/src/connected/address.rs | 334 +++++
desktop/src-tauri/src/connected/choice.rs | 183 +++
.../src-tauri/src/connected/credentials.rs | 146 ++
.../src-tauri/src/connected/fake_openbot.rs | 775 +++++++++++
desktop/src-tauri/src/connected/mod.rs | 215 +++
desktop/src-tauri/src/connected/relay.rs | 1171 +++++++++++++++++
desktop/src-tauri/src/connected/sign_in.rs | 1019 ++++++++++++++
desktop/src-tauri/src/lib.rs | 1 +
desktop/src-tauri/src/logging.rs | 8 +
desktop/src-tauri/src/logging_file_tests.rs | 52 +
desktop/src-tauri/src/problem.rs | 6 +
desktop/src-tauri/src/provider_oauth.rs | 9 +-
14 files changed, 4240 insertions(+), 4 deletions(-)
create mode 100644 desktop/src-tauri/src/connected/address.rs
create mode 100644 desktop/src-tauri/src/connected/choice.rs
create mode 100644 desktop/src-tauri/src/connected/credentials.rs
create mode 100644 desktop/src-tauri/src/connected/fake_openbot.rs
create mode 100644 desktop/src-tauri/src/connected/mod.rs
create mode 100644 desktop/src-tauri/src/connected/relay.rs
create mode 100644 desktop/src-tauri/src/connected/sign_in.rs
diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock
index e66a092079..80a22fc204 100644
--- a/desktop/src-tauri/Cargo.lock
+++ b/desktop/src-tauri/Cargo.lock
@@ -8,6 +8,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aes"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
+dependencies = [
+ "cipher",
+ "cpubits",
+ "cpufeatures 0.3.1",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -64,6 +75,17 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "apple-native-keyring-store"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a"
+dependencies = [
+ "keyring-core",
+ "log",
+ "security-framework",
+]
+
[[package]]
name = "arbitrary"
version = "1.4.2"
@@ -305,6 +327,15 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "block-padding"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "block2"
version = "0.6.2"
@@ -458,6 +489,15 @@ dependencies = [
"toml 1.1.5+spec-1.1.0",
]
+[[package]]
+name = "cbc"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cc"
version = "1.4.5"
@@ -538,6 +578,22 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "crypto-common 0.2.2",
+ "inout",
+]
+
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
[[package]]
name = "combine"
version = "4.6.8"
@@ -664,6 +720,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpubits"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
+
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -760,6 +822,15 @@ version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
+[[package]]
+name = "ctutils"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
+dependencies = [
+ "cmov",
+]
+
[[package]]
name = "darling"
version = "0.20.11"
@@ -829,6 +900,12 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "data-encoding"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
+
[[package]]
name = "dbus"
version = "0.9.12"
@@ -962,6 +1039,7 @@ dependencies = [
"block-buffer 0.12.1",
"const-oid",
"crypto-common 0.2.2",
+ "ctutils",
]
[[package]]
@@ -1764,6 +1842,24 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hkdf"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
+dependencies = [
+ "digest 0.11.3",
+]
+
[[package]]
name = "html5ever"
version = "0.39.0"
@@ -1822,6 +1918,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
[[package]]
name = "hybrid-array"
version = "0.4.15"
@@ -1844,6 +1946,7 @@ dependencies = [
"http",
"http-body",
"httparse",
+ "httpdate",
"itoa",
"pin-project-lite",
"smallvec",
@@ -2081,6 +2184,16 @@ dependencies = [
"cfb",
]
+[[package]]
+name = "inout"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
+dependencies = [
+ "block-padding",
+ "hybrid-array",
+]
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -2305,6 +2418,27 @@ dependencies = [
"serde",
]
+[[package]]
+name = "keyring"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627"
+dependencies = [
+ "apple-native-keyring-store",
+ "keyring-core",
+ "windows-native-keyring-store",
+ "zbus-secret-service-keyring-store",
+]
+
+[[package]]
+name = "keyring-core"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "konst"
version = "0.2.20"
@@ -2605,12 +2739,75 @@ dependencies = [
"zbus",
]
+[[package]]
+name = "num"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
+dependencies = [
+ "num-bigint",
+ "num-complex",
+ "num-integer",
+ "num-iter",
+ "num-rational",
+ "num-traits",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-iter"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2972,8 +3169,15 @@ version = "1.0.3"
dependencies = [
"base64 0.22.1",
"block2",
+ "bytes",
"dirs",
"flate2",
+ "futures-util",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "keyring",
+ "keyring-core",
"libc",
"log",
"objc2",
@@ -3006,6 +3210,8 @@ dependencies = [
"tauri-plugin-updater",
"tauri-plugin-window-state",
"time",
+ "tokio",
+ "tokio-tungstenite",
"windows 0.62.2",
"windows-registry",
"zip 2.4.2",
@@ -3623,12 +3829,14 @@ dependencies = [
"sync_wrapper",
"tokio",
"tokio-rustls",
+ "tokio-util",
"tower",
"tower-http",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
+ "wasm-streams 0.4.2",
"web-sys",
"webpki-roots",
]
@@ -3669,7 +3877,7 @@ dependencies = [
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
- "wasm-streams",
+ "wasm-streams 0.5.0",
"web-sys",
]
@@ -3910,6 +4118,25 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "secret-service"
+version = "5.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8"
+dependencies = [
+ "aes",
+ "cbc",
+ "futures-util",
+ "getrandom 0.4.3",
+ "hkdf",
+ "hybrid-array",
+ "num",
+ "once_cell",
+ "serde",
+ "sha2 0.11.1",
+ "zbus",
+]
+
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -4144,6 +4371,17 @@ dependencies = [
"stable_deref_trait",
]
+[[package]]
+name = "sha1"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "digest 0.11.3",
+]
+
[[package]]
name = "sha2"
version = "0.10.9"
@@ -5178,6 +5416,18 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "tokio-tungstenite"
+version = "0.30.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71"
+dependencies = [
+ "futures-util",
+ "log",
+ "tokio",
+ "tungstenite",
+]
+
[[package]]
name = "tokio-util"
version = "0.7.19"
@@ -5392,6 +5642,22 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "tungstenite"
+version = "0.30.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"
+dependencies = [
+ "bytes",
+ "data-encoding",
+ "http",
+ "httparse",
+ "log",
+ "rand 0.10.2",
+ "sha1",
+ "thiserror 2.0.20",
+]
+
[[package]]
name = "typed-path"
version = "0.13.0"
@@ -5624,6 +5890,19 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "wasm-streams"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
[[package]]
name = "wasm-streams"
version = "0.5.0"
@@ -5937,6 +6216,19 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+[[package]]
+name = "windows-native-keyring-store"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8"
+dependencies = [
+ "byteorder",
+ "keyring-core",
+ "regex",
+ "windows-sys 0.61.2",
+ "zeroize",
+]
+
[[package]]
name = "windows-numerics"
version = "0.2.0"
@@ -6443,6 +6735,17 @@ dependencies = [
"zvariant",
]
+[[package]]
+name = "zbus-secret-service-keyring-store"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a"
+dependencies = [
+ "keyring-core",
+ "secret-service",
+ "zbus",
+]
+
[[package]]
name = "zbus_macros"
version = "5.19.0"
diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml
index dbee71939f..7ff29a2297 100644
--- a/desktop/src-tauri/Cargo.toml
+++ b/desktop/src-tauri/Cargo.toml
@@ -34,7 +34,8 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
rand = "0.9"
base64 = "0.22"
-reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "blocking", "json"] }
+# `stream`: the relay hands a request's and a response's body on as it arrives. See `connected/relay.rs`.
+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "blocking", "json", "stream"] }
flate2 = "1"
# Checking the digest of an installer before running it. See `install.rs`.
sha2 = "0.10"
@@ -79,6 +80,20 @@ log = "0.4"
regex = "1"
# The log's UTC timestamps, and the local offset its first line says. The version Tauri already uses.
time = { version = "0.3", features = ["formatting", "macros", "local-offset"] }
+# The sign-in to an OpenBot that runs elsewhere, kept in the system's own credential store: Keychain
+# on macOS, Credential Manager on Windows, the Secret Service on Linux. See `connected/credentials.rs`.
+keyring = "4.2"
+# The entry type `keyring` hands back, and the in-memory store its own tests use, which this
+# crate's tests use in place of the real keychain. The version `keyring` already builds.
+keyring-core = "1"
+# The loopback relay between the window and that OpenBot: an HTTP/1 server on 127.0.0.1, with the
+# runtime, bodies and streams reqwest and Tauri already build. See `connected/relay.rs`.
+tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "sync", "time", "macros"] }
+hyper = { version = "1", features = ["server", "http1"] }
+hyper-util = { version = "0.1", features = ["tokio"] }
+http-body-util = "0.1"
+bytes = "1"
+futures-util = { version = "0.3", default-features = false, features = ["std"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
@@ -118,6 +133,9 @@ harness = false
[dev-dependencies]
tauri = { version = "2", features = ["test"] }
+# A real WebSocket client and server at each end of the relay in its tests.
+tokio-tungstenite = "0.30"
+futures-util = { version = "0.3", default-features = false, features = ["std", "sink"] }
# Every local evaluation CLI call checks the pinned runtime and script against their digests,
# about 150 MB. Unoptimized, that hash alone took 4.9 s per call in a debug build; optimized, 0.3 s.
diff --git a/desktop/src-tauri/src/connected/address.rs b/desktop/src-tauri/src/connected/address.rs
new file mode 100644
index 0000000000..0782f5542d
--- /dev/null
+++ b/desktop/src-tauri/src/connected/address.rs
@@ -0,0 +1,334 @@
+//! The address a person types, made into one the app can use, and checked to be an OpenBot this
+//! app can connect to.
+//!
+//! Two questions are asked of the address, both public: what it offers
+//! (`/api/v2/organizations/default/deployment`, which every OpenBot answers before sign-in) and
+//! how an app signs in to it (its authorization server metadata, RFC 8414). Each way that can go
+//! wrong is one `Kind`, so the window can say what to do next.
+
+use super::{host_of, http, transport, Kind};
+use crate::problem::Problem;
+
+const DEPLOYMENT: &str = "/api/v2/organizations/default/deployment";
+const METADATA: &str = "/.well-known/oauth-authorization-server/api/auth";
+/// What keeps a sign-in going after its first hour: a refresh token.
+const OFFLINE_ACCESS: &str = "offline_access";
+
+/// How this app signs in to an OpenBot, as that OpenBot publishes it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Metadata {
+ pub authorization_endpoint: String,
+ pub token_endpoint: String,
+ pub revocation_endpoint: Option,
+ /// Every scope it lists. The app's screens use the whole API, so all of them are asked for.
+ pub scopes: Vec,
+}
+
+/// `typed` as the app keeps it: scheme and host (and a port that is not the scheme's own), with
+/// no path and no trailing slash. An address with no scheme is taken as `https://`. Only `https`,
+/// except for this computer's own `127.0.0.1` and `[::1]`, where `http` is allowed.
+pub fn normalise(typed: &str) -> Result {
+ let typed = typed.trim();
+ let invalid = |why: &str| Kind::AddressInvalid.problem("", why.to_owned());
+ if typed.is_empty() || typed.contains(char::is_whitespace) {
+ return Err(invalid("no address, or one with a space in it"));
+ }
+ let with_scheme = if typed.contains("://") {
+ typed.to_owned()
+ } else {
+ format!("https://{typed}")
+ };
+ let url = reqwest::Url::parse(&with_scheme).map_err(|error| invalid(&error.to_string()))?;
+ let host = url.host_str().filter(|host| !host.is_empty());
+ let Some(host) = host else {
+ return Err(invalid("no host"));
+ };
+ if !url.username().is_empty() || url.password().is_some() {
+ return Err(invalid("a name or password in the address"));
+ }
+ match url.scheme() {
+ "https" => {}
+ "http" if matches!(host, "127.0.0.1" | "[::1]") => {}
+ "http" => return Err(invalid("http is only for 127.0.0.1 and [::1]")),
+ other => return Err(invalid(&format!("the scheme {other}"))),
+ }
+ // A name needs a dot or to be an IP address: "openbot" alone is a word, not an address.
+ let named = host.contains('.') || host.starts_with('[');
+ if !named {
+ return Err(invalid("a host with no dot in it"));
+ }
+ Ok(match url.port() {
+ Some(port) => format!("{}://{host}:{port}", url.scheme()),
+ None => format!("{}://{host}", url.scheme()),
+ })
+}
+
+/// Normalise `typed`, then ask the OpenBot there whether this app can connect to it. The answer is
+/// the normalised address and how to sign in.
+pub fn check(typed: &str) -> Result<(String, Metadata), Problem> {
+ let address = normalise(typed)?;
+ let metadata = probe(&address)?;
+ Ok((address, metadata))
+}
+
+/// Ask a normalised `address` what it is and how an app signs in to it.
+pub fn probe(address: &str) -> Result {
+ let host = host_of(address);
+ let client = http().map_err(|error| Kind::Unreachable.problem(&host, error))?;
+ let get = |path: &str| {
+ client
+ .get(format!("{address}{path}"))
+ .header(reqwest::header::ACCEPT, "application/json")
+ .send()
+ .map_err(|error| Kind::Unreachable.problem(&host, transport(error)))
+ };
+
+ let answered = get(DEPLOYMENT)?;
+ let status = answered.status();
+ let deployment = json_object(answered).filter(|_| status.is_success());
+ let edition = deployment
+ .as_ref()
+ .and_then(|deployment| deployment.get("edition"))
+ .and_then(serde_json::Value::as_str);
+ let Some(edition) = edition else {
+ return Err(Kind::NotOpenBot.problem(
+ &host,
+ format!("GET {DEPLOYMENT} answered {status}, not as an OpenBot does"),
+ ));
+ };
+ let on_its_own_computer = deployment
+ .as_ref()
+ .and_then(|deployment| deployment.get("localEvaluation"))
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false);
+ if on_its_own_computer {
+ return Err(Kind::SinglePerson.problem(&host, "the deployment says localEvaluation"));
+ }
+
+ let answered = get(METADATA)?;
+ let status = answered.status();
+ let Some(document) = json_object(answered).filter(|_| status.is_success()) else {
+ // No sign-in for apps. A personal OpenBot has no sign-in at all; any other is a release
+ // from before apps could sign in.
+ let kind = if edition == "personal" {
+ Kind::SinglePerson
+ } else {
+ Kind::TooOld
+ };
+ return Err(kind.problem(
+ &host,
+ format!("GET {METADATA} answered {status}; edition {edition}"),
+ ));
+ };
+ metadata_from(address, &document).map_err(|why| Kind::TooOld.problem(&host, why))
+}
+
+fn json_object(
+ response: reqwest::blocking::Response,
+) -> Option> {
+ match response.json::().ok()? {
+ serde_json::Value::Object(object) => Some(object),
+ _ => None,
+ }
+}
+
+/// The endpoints and scopes of a metadata document. Each endpoint has to be on the address itself:
+/// the browser is sent to one and a code is posted to another, and neither goes anywhere but the
+/// OpenBot the person typed.
+fn metadata_from(
+ address: &str,
+ document: &serde_json::Map,
+) -> Result {
+ let home = reqwest::Url::parse(address).map_err(|error| error.to_string())?;
+ let endpoint = |name: &str| -> Result