Skip to content

Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.

Fix fresh desktop setup and Mac sign-in (#591)

David McKay2e43afd61afd
diff --git a/app/src/components/layout/detail-panel.tsx b/app/src/components/layout/detail-panel.tsx
index 38d7ba3a..2d326c82 100644
--- a/app/src/components/layout/detail-panel.tsx
+++ b/app/src/components/layout/detail-panel.tsx
@@ -1,11 +1,12 @@
import { IconX } from "@tabler/icons-react";
import { motion, useReducedMotion } from "motion/react";
-import type { ReactNode } from "react";
+import { type ReactNode, useLayoutEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
+import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { EASE_OUT } from "@/lib/motion";
/**
- * A main pane with a detail pane that slides in beside it.
+ * A main pane with details beside it when there is room, or in a sheet on narrow windows.
*
* The open/closed state belongs to the caller, in practice a search parameter, so opening a detail
* is a real navigation: it survives a reload, it can be linked to, and Back closes it.
@@ -16,6 +17,7 @@ import { EASE_OUT } from "@/lib/motion";
const ANIMATION_DURATION_SECONDS = 0.3;
const DEFAULT_DETAIL_WIDTH = 400;
+const MIN_MAIN_WIDTH = 400;
/**
* The content overlaps the tail of the pane rather than following it.
@@ -45,59 +47,101 @@ export function DetailPanel({
}) {
// Reduced motion keeps the fade, which explains the change, and drops the movement.
const shouldReduceMotion = useReducedMotion();
+ const container = useRef<HTMLDivElement>(null);
+ const [overlay, setOverlay] = useState(true);
+ useLayoutEffect(() => {
+ const element = container.current;
+ if (!element) return;
+ const measure = (width: number) =>
+ setOverlay(width < detailWidth + MIN_MAIN_WIDTH);
+ measure(element.getBoundingClientRect().width);
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) measure(entry.contentRect.width);
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [detailWidth]);
return (
- <div className="flex h-full min-h-0">
+ <div ref={container} className="flex h-full min-h-0">
<div className="flex flex-1 min-w-0 flex-col">{children}</div>
- <motion.div
- animate={{ width: open ? detailWidth : 0 }}
- className="shrink-0 overflow-hidden"
- // No entry animation on first paint: URL-opened panels should appear as initial state.
- initial={false}
- transition={{
- duration: shouldReduceMotion ? 0 : ANIMATION_DURATION_SECONDS,
- ease: EASE_OUT,
- }}
- >
- <div
- className="flex h-full flex-col bg-sidebar border-l border-border"
- style={{ width: detailWidth }}
+ {overlay ? (
+ <Sheet
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
>
- {/* Rendered for the whole animation, so the way out is available immediately. */}
- <div className="h-12 shrink-0 sticky top-0 flex flex-row items-center justify-between px-2 gap-2">
- <div className="flex min-w-0 w-full items-center gap-1.5">
- {title}
+ <SheetContent
+ className="gap-0"
+ style={{ width: `min(${detailWidth}px, 100vw)`, maxWidth: "100vw" }}
+ >
+ <SheetTitle className="h-12 shrink-0 px-4 pr-12 flex items-center">
+ {title ?? "Details"}
+ </SheetTitle>
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ {open ? detail : null}
</div>
- <div className="flex flex-row gap-1.5">
- <Button onClick={onClose} variant="ghost" size="icon">
- <IconX className="size-4.5" />
- </Button>
+ </SheetContent>
+ </Sheet>
+ ) : (
+ <motion.div
+ animate={{ width: open ? detailWidth : 0 }}
+ className="shrink-0 overflow-hidden"
+ // No entry animation on first paint: URL-opened panels should appear as initial state.
+ initial={false}
+ transition={{
+ duration: shouldReduceMotion ? 0 : ANIMATION_DURATION_SECONDS,
+ ease: EASE_OUT,
+ }}
+ >
+ <div
+ className="flex h-full flex-col bg-sidebar border-l border-border"
+ style={{ width: detailWidth }}
+ >
+ {/* Rendered for the whole animation, so the way out is available immediately. */}
+ <div className="h-12 shrink-0 sticky top-0 flex flex-row items-center justify-between px-2 gap-2">
+ <div className="flex min-w-0 w-full items-center gap-1.5">
+ {title}
+ </div>
+ <div className="flex flex-row gap-1.5">
+ <Button
+ aria-label="Close details"
+ onClick={onClose}
+ variant="ghost"
+ size="icon"
+ >
+ <IconX className="size-4.5" />
+ </Button>
+ </div>
</div>
+ {/*
+ * Unmount while closed so dismissed form state and detail queries do not remain active.
+ */}
+ {open ? (
+ <motion.div
+ animate={{ opacity: 1, transform: "translateY(0px)" }}
+ className="flex-1 min-h-0 overflow-y-auto"
+ initial={{
+ opacity: 0,
+ transform: shouldReduceMotion
+ ? "none"
+ : CONTENT_ENTRANCE_OFFSET,
+ }}
+ transition={{
+ delay: shouldReduceMotion
+ ? 0
+ : CONTENT_ENTRANCE_DELAY_SECONDS,
+ duration: CONTENT_ENTRANCE_SECONDS,
+ ease: EASE_OUT,
+ }}
+ >
+ {detail}
+ </motion.div>
+ ) : null}
</div>
- {/*
- * Unmount while closed so dismissed form state and detail queries do not remain active.
- */}
- {open ? (
- <motion.div
- animate={{ opacity: 1, transform: "translateY(0px)" }}
- className="flex-1 min-h-0 overflow-y-auto"
- initial={{
- opacity: 0,
- transform: shouldReduceMotion
- ? "none"
- : CONTENT_ENTRANCE_OFFSET,
- }}
- transition={{
- delay: shouldReduceMotion ? 0 : CONTENT_ENTRANCE_DELAY_SECONDS,
- duration: CONTENT_ENTRANCE_SECONDS,
- ease: EASE_OUT,
- }}
- >
- {detail}
- </motion.div>
- ) : null}
- </div>
- </motion.div>
+ </motion.div>
+ )}
</div>
);
}
diff --git a/app/src/routes/_authed/admin/boundaries.tsx b/app/src/routes/_authed/admin/boundaries.tsx
index 1511713a..b792dc0e 100644
--- a/app/src/routes/_authed/admin/boundaries.tsx
+++ b/app/src/routes/_authed/admin/boundaries.tsx
@@ -225,6 +225,9 @@ function BoundariesPage() {
<div className="mt-3 flex gap-2">
<Input
aria-label="A rule, written in CEL"
+ autoCapitalize="off"
+ autoCorrect="off"
+ spellCheck={false}
className="min-w-0 flex-1 font-mono text-xs"
onChange={(event) => {
setDraft(event.target.value);
diff --git a/app/tests/composing-enter.test.tsx b/app/tests/composing-enter.test.tsx
index b0ea8fba..75a4f359 100644
--- a/app/tests/composing-enter.test.tsx
+++ b/app/tests/composing-enter.test.tsx
@@ -192,6 +192,9 @@ test("a boundary rule is not saved by the Enter that confirms a composed charact
);
const field = await view.findByLabelText("A rule, written in CEL");
+ expect(field.getAttribute("spellcheck")).toBe("false");
+ expect(field.getAttribute("autocorrect")).toBe("off");
+ expect(field.getAttribute("autocapitalize")).toBe("off");
const rule = 'contains(element.name, "送信")';
await type(field, rule);
diff --git a/app/tests/detail-panel.test.tsx b/app/tests/detail-panel.test.tsx
new file mode 100644
index 00000000..cf887a65
--- /dev/null
+++ b/app/tests/detail-panel.test.tsx
@@ -0,0 +1,112 @@
+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ waitFor,
+} from "@testing-library/react";
+import { useEffect } from "react";
+import { DetailPanel } from "@/components/layout/detail-panel";
+
+class Observer implements ResizeObserver {
+ static targets = new Map<Element, Observer>();
+ constructor(private readonly callback: ResizeObserverCallback) {}
+ observe(target: Element) {
+ Observer.targets.set(target, this);
+ }
+ unobserve(target: Element) {
+ Observer.targets.delete(target);
+ }
+ disconnect() {
+ for (const [target, observer] of Observer.targets) {
+ if (observer === this) Observer.targets.delete(target);
+ }
+ }
+ resize(target: Element, width: number) {
+ this.callback(
+ [
+ {
+ target,
+ contentRect: new DOMRect(0, 0, width, 640),
+ borderBoxSize: [],
+ contentBoxSize: [],
+ devicePixelContentBoxSize: [],
+ },
+ ],
+ this,
+ );
+ }
+}
+let originalObserver: typeof ResizeObserver;
+beforeAll(() => {
+ GlobalRegistrator.register();
+ originalObserver = globalThis.ResizeObserver;
+ globalThis.ResizeObserver = Observer;
+});
+afterEach(() => {
+ cleanup();
+ Observer.targets.clear();
+});
+afterAll(() => {
+ globalThis.ResizeObserver = originalObserver;
+ GlobalRegistrator.unregister();
+});
+
+async function resize(container: HTMLElement, width: number) {
+ const target = container.firstElementChild;
+ if (!target) throw new Error("Panel root missing");
+ await act(async () => {
+ Observer.targets.get(target)?.resize(target, width);
+ });
+}
+
+test("narrow container overlays details without remounting the chat draft", async () => {
+ let mounts = 0;
+ function Chat() {
+ useEffect(() => {
+ mounts += 1;
+ }, []);
+ return <textarea aria-label="Draft" defaultValue="Keep this draft" />;
+ }
+ const view = render(
+ <DetailPanel
+ open
+ title="Computer"
+ onClose={() => {}}
+ detail={<p>Browser preview</p>}
+ >
+ <Chat />
+ </DetailPanel>,
+ );
+ await resize(view.container, 560);
+ expect(await view.findByRole("dialog", { name: "Computer" })).toBeTruthy();
+ const draft = view.getByDisplayValue("Keep this draft");
+ await resize(view.container, 1000);
+ await waitFor(() => expect(view.queryByRole("dialog")).toBeNull());
+ expect(view.getByText("Browser preview")).toBeTruthy();
+ expect(view.getByDisplayValue("Keep this draft")).toBe(draft);
+ await resize(view.container, 560);
+ expect(await view.findByRole("dialog", { name: "Computer" })).toBeTruthy();
+ expect(mounts).toBe(1);
+});
+
+test("closing narrow details invokes the owner and unmounts detail work", async () => {
+ let closed = 0;
+ const props = {
+ title: "Computer",
+ onClose: () => {
+ closed += 1;
+ },
+ detail: <p>Browser preview</p>,
+ children: <p>Chat</p>,
+ };
+ const view = render(<DetailPanel {...props} open />);
+ await resize(view.container, 380);
+ expect(await view.findByRole("dialog", { name: "Computer" })).toBeTruthy();
+ fireEvent.click(view.getByRole("button", { name: "Close" }));
+ expect(closed).toBe(1);
+ view.rerender(<DetailPanel {...props} open={false} />);
+ await waitFor(() => expect(view.queryByText("Browser preview")).toBeNull());
+});
diff --git a/desktop/src-tauri/src/install.rs b/desktop/src-tauri/src/install.rs
index 9a138627..c3f46def 100644
--- a/desktop/src-tauri/src/install.rs
+++ b/desktop/src-tauri/src/install.rs
@@ -204,7 +204,7 @@ fn digest_of(bytes: &[u8]) -> String {
.collect()
}
-/// A fresh Windows account has no developer tools. Acquire the host runtime as that user,
+/// A fresh Mac or Windows account has no developer tools. Acquire the host runtime as that user,
/// without changing PATH or requiring an administrator. Existing installations remain usable.
pub fn ensure_bun(cache: &Path, existing: Option<PathBuf>) -> Result<PathBuf, Problem> {
ensure_bun_with(existing, || install_bun(cache))
@@ -220,22 +220,30 @@ fn ensure_bun_with(
}
}
-#[cfg(any(windows, test))]
-fn bun_download(arch: &str) -> Result<Download, Problem> {
+#[cfg(any(windows, target_os = "macos", test))]
+fn bun_download(os: &str, arch: &str) -> Result<Download, Problem> {
// Official bun-v1.3.14/SHASUMS256.txt. The baseline x64 build also supports older CPUs.
- let (file, sha256) = match arch {
- "x86_64" => (
+ let (file, sha256) = match (os, arch) {
+ ("windows", "x86_64") => (
"bun-windows-x64-baseline.zip",
"538f9c846355d9e847b2671bc00c47da4229a0befb24df3282b739770f3b475f",
),
- "aarch64" => (
+ ("windows", "aarch64") => (
"bun-windows-aarch64.zip",
"89841f5a57f2348b67ec0839b718f4bf4ea7d07c371c9ba4b77b6c790f918953",
),
+ ("macos", "x86_64") => (
+ "bun-darwin-x64-baseline.zip",
+ "3e35ad6f53971a9834bf9e6786e2adf72b5f1921cc9a9c5fde073d2972944076",
+ ),
+ ("macos", "aarch64") => (
+ "bun-darwin-aarch64.zip",
+ "d8b96221828ad6f97ac7ac0ab7e95872341af763001e8803e8267652c2652620",
+ ),
_ => {
return Err(Problem::with(
"OpenBot cannot install its app runtime on this kind of computer.",
- format!("no Bun {BUN} Windows build for {arch}"),
+ format!("no Bun {BUN} build for {os} on {arch}"),
))
}
};
@@ -246,10 +254,14 @@ fn bun_download(arch: &str) -> Result<Download, Problem> {
})
}
-#[cfg(windows)]
+#[cfg(any(windows, target_os = "macos"))]
fn install_bun(cache: &Path) -> Result<PathBuf, Problem> {
- let download = bun_download(std::env::consts::ARCH)?;
- let entry = format!("{}/bun.exe", download.file.trim_end_matches(".zip"));
+ let download = bun_download(std::env::consts::OS, std::env::consts::ARCH)?;
+ let entry = format!(
+ "{}/bun{}",
+ download.file.trim_end_matches(".zip"),
+ std::env::consts::EXE_SUFFIX,
+ );
let into = crate::acquire::download_dir(cache).join(format!("bun-{BUN}"));
install_bun_with(
&into,
@@ -259,27 +271,27 @@ fn install_bun(cache: &Path) -> Result<PathBuf, Problem> {
)
}
-#[cfg(not(windows))]
+#[cfg(not(any(windows, target_os = "macos")))]
fn install_bun(_cache: &Path) -> Result<PathBuf, Problem> {
Err(Problem::plain(
"bun was not found, so the API server cannot be started",
))
}
-#[cfg(any(windows, test))]
+#[cfg(any(windows, target_os = "macos", test))]
fn install_bun_with(
into: &Path,
download: &Download,
extract: impl FnOnce(&Path, &Path) -> Result<(), Problem>,
verify: impl Fn(&Path) -> Result<(), Problem>,
) -> Result<PathBuf, Problem> {
- let binary = into.join("bun.exe");
+ let binary = into.join(format!("bun{}", std::env::consts::EXE_SUFFIX));
if binary.is_file() {
verify(&binary)?;
return Ok(binary);
}
let archive = fetch_verified(download, into)?;
- let staged = into.join("bun.download.exe");
+ let staged = into.join(format!("bun.download{}", std::env::consts::EXE_SUFFIX));
extract(&archive, &staged)?;
verify(&staged)?;
std::fs::rename(&staged, &binary).map_err(|error| unwritable(&binary, &error.to_string()))?;
@@ -326,7 +338,42 @@ try {
Ok(())
}
-#[cfg(windows)]
+#[cfg(target_os = "macos")]
+fn extract_bun(archive: &Path, target: &Path, entry: &str) -> Result<(), Problem> {
+ use std::os::unix::fs::PermissionsExt;
+
+ // unzip ships with macOS itself. Use its absolute path and extract only the expected file;
+ // neither Xcode's command-line tools, Homebrew, nor a configured shell PATH is needed.
+ let file =
+ std::fs::File::create(target).map_err(|error| unwritable(target, &error.to_string()))?;
+ let output = crate::quiet::command("/usr/bin/unzip")
+ .arg("-p")
+ .arg(archive)
+ .arg(entry)
+ .stdout(file)
+ .output()
+ .map_err(|error| {
+ Problem::with(
+ "OpenBot could not unpack its app runtime. Try again.",
+ error.to_string(),
+ )
+ })?;
+ if !output.status.success() {
+ return Err(Problem::with(
+ "OpenBot could not unpack its app runtime. Try again.",
+ format!(
+ "unzip {}: {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ ),
+ ));
+ }
+ std::fs::set_permissions(target, std::fs::Permissions::from_mode(0o755))
+ .map_err(|error| unwritable(target, &error.to_string()))?;
+ Ok(())
+}
+
+#[cfg(any(windows, target_os = "macos"))]
fn verify_bun(binary: &Path) -> Result<(), Problem> {
let output = crate::quiet::command(binary)
.arg("--version")
@@ -729,8 +776,10 @@ mod tests {
for download in [
compose_download(),
podman_download(),
- bun_download("x86_64"),
- bun_download("aarch64"),
+ bun_download("windows", "x86_64"),
+ bun_download("windows", "aarch64"),
+ bun_download("macos", "x86_64"),
+ bun_download("macos", "aarch64"),
]
.into_iter()
.flatten()
@@ -806,6 +855,83 @@ mod tests {
(dir, download)
}
+ #[cfg(target_os = "macos")]
+ fn macos_bun_zip_fixture(name: &str) -> (PathBuf, Download) {
+ use base64::Engine as _;
+
+ // A real ZIP containing only bun-fixture/bun: a /bin/sh script printing 1.3.14.
+ // Fixed bytes keep both digest verification and extraction in this offline regression.
+ let bytes = base64::engine::general_purpose::STANDARD.decode(
+ "UEsDBBQAAAAAAAAAIVwlsF+1HAAAABwAAAAPAAAAYnVuLWZpeHR1cmUvYnVuIyEvYmluL3NoCnByaW50ZiAnMS4zLjE0XG4nClBLAQIUAxQAAAAAAAAAIVwlsF+1HAAAABwAAAAPAAAAAAAAAAAAAACAAQAAAABidW4tZml4dHVyZS9idW5QSwUGAAAAAAEAAQA9AAAASQAAAAAA",
+ ).unwrap();
+ let root = temp_root(name);
+ std::fs::create_dir_all(&root).unwrap();
+ let download = Download {
+ url: "http://127.0.0.1:1/never-reached".into(),
+ sha256: "15be25bd806770f73afe7d2bab41ae26b2a380645e3100c60f391dc97ac0126e",
+ file: "bun-fixture.zip",
+ };
+ std::fs::write(root.join(download.file), bytes).unwrap();
+ (root, download)
+ }
+
+ #[test]
+ fn macos_runtime_downloads_are_pinned_for_both_supported_architectures() {
+ for (arch, file) in [
+ ("aarch64", "bun-darwin-aarch64.zip"),
+ ("x86_64", "bun-darwin-x64-baseline.zip"),
+ ] {
+ let download = bun_download("macos", arch).unwrap();
+ assert_eq!(download.file, file);
+ assert_eq!(
+ download.url,
+ format!("https://github.com/oven-sh/bun/releases/download/bun-v{BUN}/{file}")
+ );
+ }
+ assert!(bun_download("macos", "unsupported").is_err());
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn macos_bun_installation_works_without_developer_tools() {
+ if crate::test_support::isolated_process(
+ "install::tests::macos_bun_installation_works_without_developer_tools",
+ ) {
+ return;
+ }
+ std::env::set_var("PATH", "/openbot-no-developer-tools");
+ let (root, download) = macos_bun_zip_fixture("bun Mac's fresh account");
+ let binary = ensure_bun_with(None, || {
+ install_bun_with(
+ &root,
+ &download,
+ |archive, target| extract_bun(archive, target, "bun-fixture/bun"),
+ verify_bun,
+ )
+ })
+ .unwrap();
+ assert_eq!(binary, root.join("bun"));
+ verify_bun(&binary).unwrap();
+ assert!(!root.join("bun.download").exists());
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn macos_missing_bun_archive_entry_is_not_published_or_run() {
+ let (root, download) = macos_bun_zip_fixture("bun Mac missing entry");
+ let failure = install_bun_with(
+ &root,
+ &download,
+ |archive, target| extract_bun(archive, target, "missing/bun"),
+ |_| panic!("a missing archive entry must not be run"),
+ )
+ .unwrap_err();
+ assert!(failure.detail.unwrap().contains("unzip"));
+ assert!(!root.join("bun").exists());
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
#[test]
fn a_fresh_account_acquires_bun_before_returning_its_executable() {
let (dir, download) = cached_bun_archive("bun-fresh-account");
@@ -815,21 +941,32 @@ mod tests {
&download,
|archive, target| {
assert_eq!(std::fs::read(archive).unwrap(), b"abc");
- assert!(!dir.join("bun.exe").exists());
+ assert!(!dir
+ .join(format!("bun{}", std::env::consts::EXE_SUFFIX))
+ .exists());
std::fs::write(target, b"executable").unwrap();
Ok(())
},
|target| {
assert_eq!(std::fs::read(target).unwrap(), b"executable");
- assert!(!dir.join("bun.exe").exists(), "verify before publishing");
+ assert!(
+ !dir.join(format!("bun{}", std::env::consts::EXE_SUFFIX))
+ .exists(),
+ "verify before publishing"
+ );
Ok(())
},
)
})
.unwrap();
- assert_eq!(binary, dir.join("bun.exe"));
+ assert_eq!(
+ binary,
+ dir.join(format!("bun{}", std::env::consts::EXE_SUFFIX))
+ );
assert_eq!(std::fs::read(binary).unwrap(), b"executable");
- assert!(!dir.join("bun.download.exe").exists());
+ assert!(!dir
+ .join(format!("bun.download{}", std::env::consts::EXE_SUFFIX))
+ .exists());
let _ = std::fs::remove_dir_all(dir);
}
@@ -845,7 +982,7 @@ mod tests {
#[test]
fn an_acquired_bun_is_checked_and_reused_without_extracting_again() {
let (dir, download) = cached_bun_archive("bun-reuse");
- let binary = dir.join("bun.exe");
+ let binary = dir.join(format!("bun{}", std::env::consts::EXE_SUFFIX));
std::fs::write(&binary, b"installed").unwrap();
std::fs::remove_file(dir.join(download.file)).unwrap();
let result = install_bun_with(
@@ -872,7 +1009,9 @@ mod tests {
|_| panic!("failed extraction must not be executed"),
);
assert_eq!(result, Err(failure));
- assert!(!dir.join("bun.exe").exists());
+ assert!(!dir
+ .join(format!("bun{}", std::env::consts::EXE_SUFFIX))
+ .exists());
let _ = std::fs::remove_dir_all(dir);
}
@@ -892,7 +1031,9 @@ mod tests {
)
});
assert_eq!(result, Err(failure));
- assert!(!dir.join("bun.exe").exists());
+ assert!(!dir
+ .join(format!("bun{}", std::env::consts::EXE_SUFFIX))
+ .exists());
let _ = std::fs::remove_dir_all(dir);
}
@@ -907,7 +1048,9 @@ mod tests {
|_| panic!("an unverified runtime must not be run"),
);
assert!(result.unwrap_err().detail.is_some());
- assert!(!dir.join("bun.exe").exists());
+ assert!(!dir
+ .join(format!("bun{}", std::env::consts::EXE_SUFFIX))
+ .exists());
let _ = std::fs::remove_dir_all(dir);
}
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 5d5409e1..ebb63ddb 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -10,6 +10,7 @@ pub mod host_access;
pub mod install;
pub mod intelligence;
pub mod plan;
+pub mod preparation;
pub mod problem;
pub mod provider;
pub mod pull_metrics;
diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs
index 31a6ef14..f7c6bbf8 100644
--- a/desktop/src-tauri/src/main.rs
+++ b/desktop/src-tauri/src/main.rs
@@ -12,8 +12,8 @@ mod test_support;
use openbot_desktop_lib::{
acquire, deployment, deployment_release, engine, env as openbot_env, harness, host_access,
- install, problem::Problem, provider, pull_metrics, quiet, stack, supervise, telemetry, tray,
- windows as win,
+ install, preparation, problem::Problem, provider, pull_metrics, quiet, stack, supervise,
+ telemetry, tray, windows as win,
};
const QUIT_CLEANUP_NOTICE_FILE: &str = ".openbot-quit-cleanup-notice";
@@ -41,6 +41,8 @@ struct Shell {
startup: Mutex<()>,
/// A cancelled attempt must finish returning its unpublished children before another starts.
starting: std::sync::atomic::AtomicBool,
+ /// An explicit Stop must survive setup navigation; a new app session may resume again.
+ stopped_in_session: std::sync::atomic::AtomicBool,
/// Quit keeps the event loop alive until one background cleanup attempt finishes.
quit: std::sync::Arc<QuitState>,
/// Why the stack stopped, kept for the screen that has not loaded yet.
@@ -214,6 +216,8 @@ struct SavedConfiguration {
struct AlreadyConfigured {
values: std::collections::BTreeMap<String, String>,
saved: SavedConfiguration,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ launch: Option<preparation::Launch>,
}
struct ReadyRespondingEngine {
@@ -367,12 +371,114 @@ async fn prepare_engine(app: tauri::AppHandle) -> Result<engine::EngineStatus, P
Ok(engine::detect())
}
+/// Complete all local software acquisition before either authentication screen is available.
+#[tauri::command]
+async fn prepare_installation(
+ app: tauri::AppHandle,
+ root: String,
+ harness: Option<harness::HarnessChoice>,
+) -> Result<(), Problem> {
+ let root = stack::root_from(&root);
+ tauri::async_runtime::spawn_blocking(move || {
+ let shell = app.state::<Shell>();
+ let attempt = StartAttempt::begin(&shell)?;
+ {
+ let shell = app.state::<Shell>();
+ let _startup = attempt.lock_current()?;
+ if shell.containers.lock().unwrap().is_some() || shell.root.lock().unwrap().is_some() {
+ return Err(Problem::plain(
+ "Stop OpenBot before changing its local installation.",
+ ));
+ }
+ remember_selected_root(&shell, &root);
+ }
+ let address = tauri::async_runtime::block_on(engine_ready(&app))?.pin()?;
+ attempt.require_current()?;
+ tauri::async_runtime::block_on(deployment_ready(&app, &root))?;
+ let picked = harness::picked(harness.as_ref(), &root).map_err(Problem::from)?;
+ let handle = app.clone();
+ let _startup = attempt.lock_current()?;
+ if preparation::require(&root, Some(&harness), &address).is_ok() {
+ report(
+ &handle,
+ "installation",
+ true,
+ "Local software is already installed.",
+ );
+ return Ok(());
+ }
+ preparation::invalidate(&root)?;
+ if let Some(problem) = stack::deployment_problem(&root) {
+ return Err(Problem::from(problem));
+ }
+ report(
+ &handle,
+ "dependencies",
+ true,
+ "Preparing the app's dependencies.",
+ );
+ preparation::install_dependencies_if_needed(&root, || {
+ install::ensure_bun(&root, which_bun())
+ })?;
+ report(
+ &handle,
+ "dependencies",
+ true,
+ "The app's dependencies are installed.",
+ );
+ let settings = preparation::image_settings(&root, picked.as_ref())?;
+ let installed = picked
+ .as_ref()
+ .and_then(|picked| picked.installed_port())
+ .is_some();
+ let mut images = stack::installation_images(&address, &root, installed, &settings)?;
+ for published in [
+ openbot_desktop_lib::plan::SIGN_IN_IMAGE,
+ openbot_desktop_lib::plan::CHATGPT_SIGN_IN_IMAGE,
+ ] {
+ images.push(deployment::reference(&root, published)?);
+ }
+ images.sort();
+ images.dedup();
+ for (index, image) in images.iter().enumerate() {
+ attempt.require_current()?;
+ report(
+ &handle,
+ "images",
+ true,
+ format!(
+ "Downloading local software ({}/{}).",
+ index + 1,
+ images.len()
+ ),
+ );
+ pull_metrics::pull_image(&address, image, |metrics| {
+ desktop_telemetry::pull_completed(&handle, metrics)
+ })?;
+ }
+ attempt.require_current()?;
+ preparation::complete(&root, harness.as_ref(), images, &address)?;
+ report(
+ &handle,
+ "installation",
+ true,
+ "Local software is installed. Continue to sign in.",
+ );
+ Ok::<(), Problem>(())
+ })
+ .await
+ .map_err(|error| {
+ Problem::with(
+ "The local installation did not finish. Try again.",
+ error.to_string(),
+ )
+ })?
+}
+
/// An engine that can run a container: installed, its machine up, and answering.
///
-/// ONE function, because three screens need it and they used to disagree. Start installed and
-/// created; both plan sign-ins only looked, and answered "No container engine is answering, so the
-/// sign-in cannot run" on a machine whose whole setup exists to put one there. That sentence named
-/// an obstacle and no way past it, on a screen where the way past it is ours to take.
+/// Called only by local installation. Authentication and launch check the prepared assets and
+/// never invoke acquisition or repair from inside a sign-in operation.
///
/// Reported step by step rather than as one result, because these take minutes and a window with
/// nothing moving in it reads as a hang.
@@ -492,9 +598,8 @@ async fn engine_ready(app: &tauri::AppHandle) -> Result<engine::Address, Problem
/// Install the latest published deployment on first use, then keep its recorded version.
///
-/// Extracted from `start_stack` because Start is no longer the only thing that needs it: a plan
-/// sign-in runs a published image, and the reference for that image is read from the manifest this
-/// lays down. An installed deployment keeps its exact tag without consulting GitHub again.
+/// Local preparation fetches the manifest needed by both launch and plan sign-in images.
+/// An installed deployment keeps its exact tag without consulting GitHub again.
async fn deployment_ready<R: tauri::Runtime>(
app: &tauri::AppHandle<R>,
root: &Path,
@@ -533,36 +638,18 @@ async fn deployment_ready<R: tauri::Runtime>(
/// The reference for an image the shell runs directly, rather than through Compose.
///
-/// The deployment first, because the manifest that names the image is part of it. A sign-in on a
-/// machine that has never started the stack has no manifest yet, and building a name instead is
-/// what sent Podman to Docker Hub.
-async fn sign_in_image(
- app: &tauri::AppHandle,
- root: &Path,
- published: &str,
-) -> Result<String, Problem> {
- sign_in_image_with(
- root,
- published,
- |ready_root| async move { deployment_ready(app, &ready_root).await },
- deployment::reference,
- )
- .await
-}
-
-async fn sign_in_image_with<Ready, ReadyFuture, Reference>(
- root: &Path,
- published: &str,
- deployment_ready: Ready,
- reference: Reference,
-) -> Result<String, Problem>
-where
- Ready: FnOnce(PathBuf) -> ReadyFuture,
- ReadyFuture: std::future::Future<Output = Result<(), Problem>>,
- Reference: FnOnce(&Path, &str) -> Result<String, String>,
-{
- deployment_ready(root.to_path_buf()).await?;
- sign_in_reference(root, published, reference)
+/// Require completed local installation before starting an authentication container.
+fn prepared_sign_in(root: &Path, published: &str) -> Result<(engine::Address, String), Problem> {
+ let status = engine::detect();
+ let address = status
+ .address
+ .filter(|_| status.responding)
+ .ok_or_else(|| preparation::required(status.detail))?
+ .pin()?;
+ preparation::require(root, None, &address)?;
+ let image = sign_in_reference(root, published, deployment::reference)?;
+ preparation::require_images(&address, std::slice::from_ref(&image))?;
+ Ok((address, image))
}
fn sign_in_reference(
@@ -851,6 +938,7 @@ async fn start_stack_inner<R: tauri::Runtime>(
* Nobody is asked to know this, which is the audience rule. The plan re-points the Bot, and
* the window says which Bot it will be while there is still a screen to say it on.
*/
+ let requested_harness = harness.clone();
let harness =
match &credential {
openbot_env::ModelCredential::ClaudePlan { .. } => harness::speaking_for("anthropic")
@@ -865,24 +953,19 @@ async fn start_stack_inner<R: tauri::Runtime>(
}),
_ => harness,
};
- let picked = harness::picked_after_deployment_ready(&root, harness.as_ref(), || async {
- deployment_ready(&app, &root).await
- })
- .await
- .map_err(|error| match error {
- harness::PickedAfterDeploymentError::Deployment(problem) => problem,
+ let picked = harness::picked(harness.as_ref(), &root).map_err(|error| {
// Two registers, because one of these refusals is about a release and the other is
// about a pick. "OpenBot v0.0.8 does not include agent-langgraph-agui" is the
// evidence, not the sentence: it names a published image, which is not a thing the
// person chose or can change.
- harness::PickedAfterDeploymentError::Harness(error) => Problem::with(
+ Problem::with(
"This version of OpenBot does not include the Bot you picked. Go back and choose \
another, or update OpenBot.",
error,
- ),
+ )
})?;
- let (logs, existing_bun, mut secrets) = {
+ let (logs, bun, mut secrets) = {
let _startup = attempt.lock_current()?;
// Belt and braces: a fetch that reported success and left something out is still not a
@@ -907,6 +990,7 @@ async fn start_stack_inner<R: tauri::Runtime>(
};
let found = found.pin()?;
acquire::prepare_for_compose(&found)?;
+ let bun = preparation::require(&root, Some(&requested_harness), &found)?;
// Checked here as well as in the health gate, because the gate only runs when an engine had to
// be installed. A machine that already had Podman skips all of that and arrives at Compose,
@@ -977,15 +1061,9 @@ async fn start_stack_inner<R: tauri::Runtime>(
// Set before Bun imports the runtime, and retained for supervised restarts.
secrets.extend(desktop_telemetry::runtime_env(&app));
- // Said before rather than after. On a machine that has never run OpenBot this pulls five
- // images, and a person watching a button that says "Working" has no way to tell a download
- // from a hang.
- report(
- &app,
- "services",
- true,
- "pulling images and starting containers",
- );
+ // Installation already verified these images. Start only raises the local containers;
+ // its no-pull policy sends missing assets back to the installation step.
+ report(&app, "services", true, "starting installed containers");
/*
* The harness's port, before the containers rather than after.
*
@@ -1027,17 +1105,6 @@ async fn start_stack_inner<R: tauri::Runtime>(
*/
let bundled_bots = stack::BundledBots::for_credential(&credential);
attempt.require_current()?;
- stack::pull(
- &found,
- &root,
- installed_harness,
- bundled_bots,
- &secrets,
- |metrics| {
- desktop_telemetry::pull_completed(&app, metrics);
- },
- )?;
- attempt.require_current()?;
// Even a failed up can have started some services. Keep their root until down succeeds.
*shell.containers.lock().unwrap() = Some(ContainerDeployment {
root: root.clone(),
@@ -1087,27 +1154,9 @@ async fn start_stack_inner<R: tauri::Runtime>(
}
let logs = root.join(".logs");
- let bun = which_bun();
-
(logs, bun, secrets)
};
- // The source alone will not run: without this the server stops at a package it cannot resolve
- // and the app at a missing `vite`, neither of which mentions dependencies.
- report(&app, "dependencies", true, "installing");
- let bun = {
- let target = root.clone();
- tauri::async_runtime::spawn_blocking(move || {
- let bun = install::ensure_bun(&target, existing_bun)?;
- stack::install_dependencies(&target, &bun).map_err(Problem::plain)?;
- Ok::<_, Problem>(bun)
- })
- .await
- .map_err(|error| format!("the install did not run: {error}"))?
- .inspect_err(|error| report(&app, "dependencies", false, problem_detail(error.clone())))?
- };
- report(&app, "dependencies", true, "installed");
-
// Never persisted or passed to Compose. Only the server process receives this credential;
// model workers and frontend processes cannot impersonate the native approval transport.
use base64::Engine as _;
@@ -1160,6 +1209,14 @@ async fn start_stack_inner<R: tauri::Runtime>(
)
.map_err(|error| Problem::with("Local folder access could not start.", error.to_string()))?;
*shell.host_access.lock().unwrap() = Some(broker);
+ preparation::record_launch(&root, requested_harness.as_ref())?;
+ let config = app.path().app_config_dir().map_err(|error| {
+ Problem::with(
+ "OpenBot could not remember this installation for next time.",
+ error.to_string(),
+ )
+ })?;
+ preparation::save_selected_root(&config, &root)?;
supervise_host_processes(app.clone(), root, logs, bun, secrets, generation);
report(&app, "answering", true, "the API and the app are answering");
@@ -1227,6 +1284,9 @@ where
C: FnOnce(&Path) -> Result<usize, openbot_desktop_lib::problem::Problem>,
D: FnOnce(&Path) -> Result<(), String>,
{
+ shell
+ .stopped_in_session
+ .store(true, std::sync::atomic::Ordering::SeqCst);
shell
.start_generation
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
@@ -2291,7 +2351,22 @@ same person: reading their own file back to them is not a disclosure. The key is
anywhere, and only the settings the wizard asks about are read.
*/
#[tauri::command]
-fn already_configured(root: String) -> AlreadyConfigured {
+fn already_configured<R: tauri::Runtime>(
+ app: tauri::AppHandle<R>,
+ root: String,
+) -> AlreadyConfigured {
+ let mut configured = already_configured_for_root(root);
+ if app
+ .state::<Shell>()
+ .stopped_in_session
+ .load(std::sync::atomic::Ordering::SeqCst)
+ {
+ configured.launch = None;
+ }
+ configured
+}
+
+fn already_configured_for_root(root: String) -> AlreadyConfigured {
let root = stack::root_from(&root);
let env_file = root.join(".env");
let mut values = openbot_desktop_lib::vault::already_given_file_only(
@@ -2324,6 +2399,7 @@ fn already_configured(root: String) -> AlreadyConfigured {
};
let claude_plan = values.remove("CLAUDE_CODE_OAUTH_TOKEN").is_some();
AlreadyConfigured {
+ launch: preparation::launch(&root),
saved: SavedConfiguration {
intelligence_api_key: hint(
Category::Intelligence,
@@ -2376,16 +2452,8 @@ async fn begin_claude_sign_in(app: tauri::AppHandle, root: String) -> Result<Str
* carry Anthropic's bundled CLI, which is what does the OAuth. Letting the screen name an image
* would make the sign-in depend on a choice that has nothing to do with it.
*/
- // Set up rather than refused. The sign-in runs in a container, so it needs the same engine
- // Start needs and the same deployment Start needs, and on a first run nothing has fetched or
- // installed either yet.
- let address = engine_ready(&app).await?;
- let image = sign_in_image(&app, &root, openbot_desktop_lib::plan::SIGN_IN_IMAGE).await?;
- let telemetry_app = app.clone();
let (signing, url) = tauri::async_runtime::spawn_blocking(move || {
- pull_metrics::pull_image(&address, &image, |metrics| {
- desktop_telemetry::pull_completed(&telemetry_app, metrics);
- })?;
+ let (address, image) = prepared_sign_in(&root, openbot_desktop_lib::plan::SIGN_IN_IMAGE)?;
openbot_desktop_lib::plan::SigningIn::begin(&address, &image).map_err(Problem::from)
})
.await
@@ -2438,19 +2506,9 @@ async fn begin_chatgpt_sign_in(
) -> Result<String, openbot_desktop_lib::problem::Problem> {
let root = stack::root_from(&root);
remember_selected_root(&app.state::<Shell>(), &root);
- // Set up rather than refused: see `engine_ready`.
- let address = engine_ready(&app).await?;
- let image = sign_in_image(
- &app,
- &root,
- openbot_desktop_lib::plan::CHATGPT_SIGN_IN_IMAGE,
- )
- .await?;
- let telemetry_app = app.clone();
let (signing, url) = tauri::async_runtime::spawn_blocking(move || {
- pull_metrics::pull_image(&address, &image, |metrics| {
- desktop_telemetry::pull_completed(&telemetry_app, metrics);
- })?;
+ let (address, image) =
+ prepared_sign_in(&root, openbot_desktop_lib::plan::CHATGPT_SIGN_IN_IMAGE)?;
openbot_desktop_lib::plan::SigningInToChatGpt::begin(&address, &image)
})
.await
@@ -2567,7 +2625,13 @@ fn which_bun() -> Option<PathBuf> {
.map(|o| o.status.success())
.unwrap_or(false)
{
- return Some(PathBuf::from("bun"));
+ if let Some(path) = std::env::var_os("PATH").and_then(|path| {
+ std::env::split_paths(&path)
+ .map(|directory| directory.join(if cfg!(windows) { "bun.exe" } else { "bun" }))
+ .find(|path| path.is_file())
+ }) {
+ return Some(path);
+ }
}
let home = std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
@@ -2900,6 +2964,7 @@ fn main() {
windows_blocker,
windows_blocker_instruction,
prepare_engine,
+ prepare_installation,
start_stack,
stop_stack,
show_openbot,
@@ -2942,6 +3007,14 @@ fn main() {
})
.setup(|app| {
desktop_telemetry::initialize(app.handle());
+ if let Some(root) = app
+ .path()
+ .app_config_dir()
+ .ok()
+ .and_then(|config| preparation::selected_root(&config))
+ {
+ remember_selected_root(&app.state::<Shell>(), &root);
+ }
// Where the Compose provider OpenBot installs itself lives, told once so every engine
// command can put it on the child's PATH. Before anything asks for an engine.
engine::tools_live_in(engine::tools_dir_under(&acquire::download_dir(
@@ -3463,7 +3536,7 @@ mod tests {
}
for legacy in ["", "INTELLIGENCE_API_KEY=synthetic-cpk\nOPENAI_API_KEY=synthetic-openai\nANTHROPIC_API_KEY=synthetic-anthropic\nCLAUDE_CODE_OAUTH_TOKEN=synthetic-claude\n"] {
std::fs::write(root.join(".env"), format!("INTELLIGENCE_API_URL=https://synthetic.example\n{legacy}")).unwrap();
- let configured = already_configured(root.to_string_lossy().into_owned());
+ let configured = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(configured.values["INTELLIGENCE_API_URL"], "https://synthetic.example");
assert!(!configured.values.contains_key("CLAUDE_CODE_OAUTH_TOKEN"));
}
@@ -3471,6 +3544,23 @@ mod tests {
std::fs::remove_dir_all(root).unwrap();
}
+ #[test]
+ fn launch_never_downloads_missing_images() {
+ if test_support::isolated_process("tests::launch_never_downloads_missing_images") {
+ return;
+ }
+ let _path = SerializedPath::set_only_with("docker", "installation-boundary");
+ let root = temp_root("launch-without-installation");
+ std::fs::create_dir_all(&root).unwrap();
+ let address = engine::Address::new(engine::Engine::Docker, None);
+ let secrets = stack::Secrets::new();
+ let up = stack::up(&address, &root, false, stack::BundledBots::none(), &secrets);
+ let migrate = stack::migrate(&address, &root, &secrets);
+ std::fs::remove_dir_all(root).unwrap();
+ assert!(up.is_ok(), "{up:?}");
+ assert!(migrate.is_ok(), "{migrate:?}");
+ }
+
#[test]
fn deployment_ready_preserves_the_installed_release() {
let root = temp_root("deployment-ready-pinned");
@@ -3492,30 +3582,24 @@ mod tests {
}
#[test]
- fn plan_sign_in_boundary_uses_selected_root_for_deploy_and_reference() {
+ fn plan_sign_in_boundary_uses_selected_root_for_reference_without_acquisition() {
let default = temp_root("signin-default-root");
let selected = temp_root("signin-selected-root");
std::fs::create_dir_all(&default).unwrap();
std::fs::create_dir_all(&selected).unwrap();
std::fs::write(default.join("manifest.json"), "poisoned-default").unwrap();
- let ready_root = std::cell::RefCell::new(None);
let reference_root = std::cell::RefCell::new(None);
- let image = tauri::async_runtime::block_on(sign_in_image_with(
+ let image = sign_in_reference(
&selected,
openbot_desktop_lib::plan::CHATGPT_SIGN_IN_IMAGE,
- |root| {
- *ready_root.borrow_mut() = Some(root);
- async { Ok(()) }
- },
|root, published| {
*reference_root.borrow_mut() = Some((root.to_path_buf(), published.to_string()));
Ok(format!("{}@{}", published, root.display()))
},
- ))
+ )
.unwrap();
- assert_eq!(ready_root.into_inner(), Some(selected.clone()));
assert_eq!(
reference_root.into_inner(),
Some((
@@ -3582,8 +3666,8 @@ mod tests {
)
.unwrap();
let typed = format!(" \n{}\t ", root.display());
- let configured = already_configured(typed);
- let normal = already_configured(root.to_string_lossy().into_owned());
+ let configured = already_configured_for_root(typed);
+ let normal = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(configured.values, normal.values);
assert_eq!(
configured.values.get("INTELLIGENCE_API_URL"),
@@ -3608,7 +3692,7 @@ mod tests {
)
.unwrap();
- let configured = already_configured(root.to_string_lossy().into_owned());
+ let configured = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(
configured.values.get("INTELLIGENCE_API_KEY"),
@@ -3635,7 +3719,7 @@ mod tests {
"CLAUDE_CODE_OAUTH_TOKEN=synthetic-legacy-plan\n",
)
.unwrap();
- let configured = already_configured(root.to_string_lossy().into_owned());
+ let configured = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(configured.saved.model_sessions.anthropic, Some(true));
assert!(!configured.values.contains_key("CLAUDE_CODE_OAUTH_TOKEN"));
@@ -3688,7 +3772,7 @@ mod tests {
if let Some(input) = input {
std::fs::write(root.join(openbot_desktop_lib::saved_intent::FILE), input).unwrap();
}
- let unknown = already_configured(root.to_string_lossy().into_owned());
+ let unknown = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(unknown.saved.intelligence_api_key, None);
assert_eq!(unknown.saved.model_sessions.anthropic, None);
}
@@ -3697,13 +3781,13 @@ mod tests {
r#"{"version":1,"categories":["intelligence","claude-plan"],"model":"claude-plan"}"#,
)
.unwrap();
- let recorded = already_configured(root.to_string_lossy().into_owned());
+ let recorded = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(recorded.saved.intelligence_api_key, Some(true));
assert_eq!(recorded.saved.model_sessions.anthropic, Some(true));
assert_eq!(recorded.saved.model_api_keys.anthropic, None);
assert_eq!(recorded.saved.model_sessions.openai, None);
assert!(recorded.values.is_empty());
- let fresh = already_configured(
+ let fresh = already_configured_for_root(
temp_root("different-public-root")
.to_string_lossy()
.into_owned(),
@@ -3714,7 +3798,7 @@ mod tests {
"ANTHROPIC_API_KEY=synthetic-legacy-anthropic\n",
)
.unwrap();
- let legacy = already_configured(root.to_string_lossy().into_owned());
+ let legacy = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(legacy.saved.model_api_keys.anthropic, Some(true));
std::fs::remove_dir_all(root).unwrap();
}
@@ -4117,7 +4201,7 @@ mod tests {
chosen.api_key = Some("synthetic-endpoint-key".into());
let credential = chosen.into_credential(&root).unwrap();
persist_endpoint_fixture(&root, &credential);
- let configured = already_configured(root.to_string_lossy().into_owned());
+ let configured = already_configured_for_root(root.to_string_lossy().into_owned());
assert_eq!(
configured.values.get("BOT_MODEL").map(String::as_str),
Some("local-model")
@@ -4730,6 +4814,7 @@ fn main() {
if words.first()==Some(&"machine") { println!("[]"); return; }
if !base.join(format!("{engine}-ready")).exists() { eprintln!("synthetic original runtime unavailable"); std::process::exit(74); }
match words.as_slice() {
+ ["image", "inspect", _] => (),
["version","--format",_] => println!("1.44"),
["info","--format","{{.Host.ServiceIsRemote}}"] => println!("false"),
["compose","version"] => println!("Synthetic Compose"),
@@ -4738,7 +4823,7 @@ fn main() {
fs::write(cwd.join("fixture-containers-running"),&identity).unwrap();
if cwd.join("fail-up").exists() { eprintln!("synthetic partial up failure");std::process::exit(71); }
}
- ["compose","run","--rm","migrate"] => { eprintln!("synthetic migration barrier");std::process::exit(72); }
+ ["compose","run","--rm","--pull","never","migrate"] => { eprintln!("synthetic migration barrier");std::process::exit(72); }
["compose","-f","docker-compose.yml","config","--format","json"] => println!("{{\"services\":{{\"supervisor\":{{\"environment\":{{\"COMPUTER_NAMESPACE\":\"fixture\"}}}}}}}}"),
["compose","-f","docker-compose.yml","stop","supervisor"] => (),
["ps","--quiet","--filter",_,"--filter",_] => (),
@@ -5611,33 +5696,33 @@ fn main() {
let mut choice = serde_json::json!({"id":"byo-url", "agentUrl":remote});
let (expected_up, expected_image) = match case {
"remote" | "remote-stale-image" => (
- "compose up -d --no-build postgres supervisor agent-computer agent-bot agent-langgraph",
+ "compose up -d --no-build --pull never postgres supervisor agent-computer agent-bot agent-langgraph",
None,
),
"anthropic-api" => {
model = serde_json::json!({"provider":"anthropic", "login":"api-key", "apiKey":"synthetic-anthropic-key"});
choice = serde_json::json!({"id":"langgraph"});
- ("compose --profile harness up -d --no-build postgres supervisor agent-computer agent-langgraph agent-harness", Some("agent-langgraph-agui"))
+ ("compose --profile harness up -d --no-build --pull never postgres supervisor agent-computer agent-langgraph agent-harness", Some("agent-langgraph-agui"))
}
"compatible" => {
model = serde_json::json!({"provider":"openai-compatible", "login":"endpoint", "baseUrl":"http://127.0.0.1:11434/v1", "model":"synthetic-model", "apiKey":""});
- ("compose up -d --no-build postgres supervisor agent-computer agent-bot agent-langgraph", None)
+ ("compose up -d --no-build --pull never postgres supervisor agent-computer agent-bot agent-langgraph", None)
}
"installed" => {
choice = serde_json::json!({"id":"langgraph"});
- ("compose --profile harness up -d --no-build postgres supervisor agent-computer agent-bot agent-langgraph agent-harness", Some("agent-langgraph-agui"))
+ ("compose --profile harness up -d --no-build --pull never postgres supervisor agent-computer agent-bot agent-langgraph agent-harness", Some("agent-langgraph-agui"))
}
"none" => {
choice = serde_json::Value::Null;
- ("compose up -d --no-build postgres supervisor agent-computer agent-bot agent-langgraph", None)
+ ("compose up -d --no-build --pull never postgres supervisor agent-computer agent-bot agent-langgraph", None)
}
"chatgpt-plan" => {
model = serde_json::json!({"provider":"openai", "login":"plan", "token":"{\"refresh_token\":\"synthetic-plan\"}"});
- ("compose --profile harness up -d --no-build postgres supervisor agent-computer agent-harness", Some("agent-langgraph-agui"))
+ ("compose --profile harness up -d --no-build --pull never postgres supervisor agent-computer agent-harness", Some("agent-langgraph-agui"))
}
"claude-plan" => {
model = serde_json::json!({"provider":"anthropic", "login":"plan", "token":"synthetic-claude-plan"});
- ("compose --profile harness up -d --no-build postgres supervisor agent-computer agent-harness", Some("agent-claude-sdk"))
+ ("compose --profile harness up -d --no-build --pull never postgres supervisor agent-computer agent-harness", Some("agent-claude-sdk"))
}
_ => panic!("unknown test case"),
};
@@ -5684,6 +5769,14 @@ fn main() {
)
.map(|body| body.deserialize::<serde_json::Value>().unwrap())
};
+ let prepared_choice: Option<harness::HarnessChoice> =
+ serde_json::from_value(choice.clone()).unwrap();
+ preparation::record(
+ &root,
+ prepared_choice.as_ref(),
+ vec!["fixture-image".into()],
+ )
+ .unwrap();
let problem = invoke("start_stack", serde_json::json!({
"root":root, "apiUrl":"https://intelligence.example.test", "gatewayWsUrl":"wss://gateway.example.test",
"apiKey":"synthetic-intelligence-key", "model":model, "harness":choice,
@@ -5708,7 +5801,7 @@ fn main() {
vec![expected_up],
"case={case}, actual Start IPC commands:\n{commands}"
);
- assert!(commands.contains("\tcompose run --rm migrate\n"));
+ assert!(commands.contains("\tcompose run --rm --pull never migrate\n"));
assert!(!root.join(".logs").exists(), "no host runtime was launched");
let settings = openbot_env::read_already_set(
&root.join(".env"),
@@ -5916,9 +6009,9 @@ fn main() {
"{commands}"
);
assert!(commands.contains("\tcompose version\n"), "{commands}");
- assert!(commands.contains("\tcompose up -d --no-build postgres supervisor agent-computer agent-bot agent-langgraph\n"), "{commands}");
+ assert!(commands.contains("\tcompose up -d --no-build --pull never postgres supervisor agent-computer agent-bot agent-langgraph\n"), "{commands}");
assert!(
- commands.contains("\tcompose run --rm migrate\n"),
+ commands.contains("\tcompose run --rm --pull never migrate\n"),
"{commands}"
);
assert!(
@@ -5982,13 +6075,13 @@ fn main() {
let commands = std::fs::read_to_string(&record).expect("command record");
assert!(
commands.contains(
- "\tcompose up -d --no-build postgres supervisor agent-computer agent-langgraph\n"
+ "\tcompose up -d --no-build --pull never postgres supervisor agent-computer agent-langgraph\n"
),
"{commands}"
);
assert!(
!commands
- .contains("compose up -d --no-build postgres supervisor agent-computer agent-bot"),
+ .contains("compose up -d --no-build --pull never postgres supervisor agent-computer agent-bot"),
"Anthropic Start must not target the OpenAI-only agent-bot: {commands}"
);
assert_eq!(problem.said, "Part of OpenBot stopped during startup.");
@@ -6531,6 +6624,12 @@ fn main() {
)
.unwrap();
deployment::record(root, DEPLOYMENT_VERSION).unwrap();
+ for package in ["", "server", "worker"] {
+ std::fs::write(root.join(package).join("package.json"), "{}").unwrap();
+ }
+ std::fs::write(root.join("bun.lock"), "synthetic-lock").unwrap();
+ preparation::record_dependencies(root, Path::new("bun")).unwrap();
+ preparation::record(root, None, vec!["fixture-image".into()]).unwrap();
}
struct TestRequest {
@@ -8041,6 +8140,7 @@ fn main() {
let bin = temp_root("openbot-fake-engine-bin");
std::fs::create_dir_all(&bin).unwrap();
Self::write_binary_under(&bin, binary, scenario);
+ Self::write_binary_under(&bin, "bun", "runtime");
let mut path = std::ffi::OsString::from(bin.clone());
if inherit_path {
if let Some(previous) = previous.as_ref().filter(|previous| !previous.is_empty()) {
diff --git a/desktop/src-tauri/src/plan.rs b/desktop/src-tauri/src/plan.rs
index 3d6c2321..ef96a8d0 100644
--- a/desktop/src-tauri/src/plan.rs
+++ b/desktop/src-tauri/src/plan.rs
@@ -268,6 +268,7 @@ impl SigningIn {
command.arg(argument);
}
command.arg("run");
+ command.arg("--pull=never");
command.arg("--rm");
command.arg("-i");
command.arg("-t");
@@ -486,18 +487,20 @@ const CHATGPT_RELAY: u16 = 1456;
fn publish_chatgpt_callback(
command: &mut std::process::Command,
engine: crate::engine::Engine,
- windows: bool,
+ os: &str,
) {
- // Windows Podman's IPv6 forward accepts TCP but closes the callback without an HTTP
- // response. That prevents localhost clients from trying the working IPv4 address:
- // Happy Eyeballs stops at the first successful TCP handshake (RFC 8305, sections 5/9.2).
- // Publish only IPv4 there so localhost falls back after IPv6 connection refusal.
- // Keep the registered localhost redirect URI and the other runtimes' bindings unchanged.
- let hosts: &[&str] = if windows && engine == crate::engine::Engine::Podman {
- &["127.0.0.1"]
- } else {
- &["127.0.0.1", "[::1]"]
- };
+ // macOS Podman clears HostIP inside its VM, so dual loopback publishes become duplicate
+ // mappings and rootlessport rejects them with "conflict with ID 1". See Podman's
+ // libpod/networking_common.go::convertPortMappings. Windows Podman's IPv6 forward instead
+ // accepts TCP but drops HTTP, preventing localhost from trying IPv4 (RFC 8305, sections 5/9.2).
+ // Publish IPv4 only on these hosts: IPv6 refuses, allowing the registered localhost callback
+ // to reach IPv4. Docker and native Linux Podman retain both loopback bindings.
+ let hosts: &[&str] =
+ if matches!(os, "windows" | "macos") && engine == crate::engine::Engine::Podman {
+ &["127.0.0.1"]
+ } else {
+ &["127.0.0.1", "[::1]"]
+ };
for host in hosts {
command.arg("-p");
command.arg(format!("{host}:{CHATGPT_LOOPBACK}:{CHATGPT_RELAY}"));
@@ -615,15 +618,16 @@ impl SigningInToChatGpt {
let mut command = crate::quiet::command(binary);
command.args(arguments);
command.arg("run");
+ command.arg("--pull=never");
command.arg("--rm");
/*
* Published on loopback only, and on the number the vendor's login advertises.
*
* The container's relay listens on `CHATGPT_RELAY` and forwards to the login's own
* loopback bind; the browser is sent to `CHATGPT_LOOPBACK` on this machine.
- * publish_chatgpt_callback handles the Windows Podman IPv6 forwarding limitation.
+ * publish_chatgpt_callback handles the macOS and Windows Podman forwarding limitations.
*/
- publish_chatgpt_callback(&mut command, engine.engine, cfg!(windows));
+ publish_chatgpt_callback(&mut command, engine.engine, std::env::consts::OS);
command.arg(image);
command.arg("python");
command.arg("-u");
@@ -772,6 +776,43 @@ mod tests {
use super::*;
use crate::engine::Engine;
+ #[test]
+ fn subscription_containers_never_download_software() {
+ if crate::test_support::isolated_process(
+ "plan::tests::subscription_containers_never_download_software",
+ ) {
+ return;
+ }
+ let root = crate::test_support::temp_root("subscription-without-downloads");
+ std::fs::create_dir_all(&root).unwrap();
+ let source = root.join("docker.rs");
+ std::fs::write(&source, r#"
+use std::io::Write;
+fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ assert_eq!(args.first().map(String::as_str), Some("run"));
+ assert!(args.iter().any(|arg| arg == "--pull=never"), "subscription login must refuse missing images");
+ print!("\x1b]8;;https://claude.ai/oauth/authorize?synthetic=prepared\x1b\\Sign in\x1b]8;;\x1b\\\r\n");
+ println!("https://auth.openai.com/oauth/authorize?synthetic=prepared");
+ std::io::stdout().flush().unwrap();
+ std::thread::sleep(std::time::Duration::from_secs(30));
+}
+"#).unwrap();
+ crate::test_support::compile_fixture(
+ &source,
+ &root.join(format!("docker{}", std::env::consts::EXE_SUFFIX)),
+ );
+ std::env::set_var("PATH", &root);
+ let address = crate::engine::Address::new(Engine::Docker, None);
+ let (mut claude, url) = SigningIn::begin(&address, "synthetic-claude").unwrap();
+ assert!(url.contains("synthetic=prepared"));
+ claude.stop();
+ let (mut chatgpt, url) = SigningInToChatGpt::begin(&address, "synthetic-chatgpt").unwrap();
+ assert!(url.contains("synthetic=prepared"));
+ chatgpt.stop();
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
#[test]
#[cfg(windows)]
fn windows_claude_sign_in_keeps_its_terminal_until_the_flow_finishes() {
@@ -845,15 +886,17 @@ mod tests {
}
#[test]
- fn chatgpt_callback_uses_ipv4_only_for_windows_podman() {
- for (engine, windows, hosts) in [
- (Engine::Podman, true, vec!["127.0.0.1"]),
- (Engine::Podman, false, vec!["127.0.0.1", "[::1]"]),
- (Engine::Docker, true, vec!["127.0.0.1", "[::1]"]),
- (Engine::Docker, false, vec!["127.0.0.1", "[::1]"]),
+ fn chatgpt_callback_uses_one_loopback_mapping_for_macos_and_windows_podman() {
+ for (engine, os, hosts) in [
+ (Engine::Podman, "windows", vec!["127.0.0.1"]),
+ (Engine::Podman, "macos", vec!["127.0.0.1"]),
+ (Engine::Podman, "linux", vec!["127.0.0.1", "[::1]"]),
+ (Engine::Docker, "windows", vec!["127.0.0.1", "[::1]"]),
+ (Engine::Docker, "macos", vec!["127.0.0.1", "[::1]"]),
+ (Engine::Docker, "linux", vec!["127.0.0.1", "[::1]"]),
] {
let mut command = crate::quiet::command(engine.binary());
- publish_chatgpt_callback(&mut command, engine, windows);
+ publish_chatgpt_callback(&mut command, engine, os);
let args: Vec<_> = command
.get_args()
.map(|arg| arg.to_str().unwrap())
@@ -862,7 +905,7 @@ mod tests {
.into_iter()
.flat_map(|host| ["-p".into(), format!("{host}:1455:1456")])
.collect();
- assert_eq!(args, expected, "{engine:?}, Windows={windows}");
+ assert_eq!(args, expected, "{engine:?}, OS={os}");
}
}
diff --git a/desktop/src-tauri/src/preparation.rs b/desktop/src-tauri/src/preparation.rs
new file mode 100644
index 00000000..354535c5
--- /dev/null
+++ b/desktop/src-tauri/src/preparation.rs
@@ -0,0 +1,507 @@
+//! Local installation checkpoints. These contain no credentials and never grant runtime ownership.
+use std::collections::BTreeSet;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+use crate::{deployment, engine::Address, harness::HarnessChoice, problem::Problem, quiet, stack};
+
+pub const REQUIRED: &str = "Finish installing OpenBot's local software before signing in or starting. Return to Install and try again.";
+pub const FILE: &str = ".openbot-prepared.json";
+const DEPENDENCIES: &str = ".openbot-dependencies.json";
+const LAUNCH: &str = ".openbot-launched.json";
+const PACKAGES: [&str; 4] = ["", "server", "app", "worker"];
+
+#[derive(Serialize, Deserialize)]
+struct Dependencies {
+ fingerprint: String,
+ bun: PathBuf,
+ package_files: Vec<PathBuf>,
+}
+
+#[derive(Serialize, Deserialize)]
+struct Prepared {
+ fingerprint: String,
+ harness: Option<HarnessChoice>,
+ images: Vec<String>,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+pub struct Launch {
+ pub harness: Option<HarnessChoice>,
+}
+
+#[derive(Serialize, Deserialize)]
+struct Launched {
+ preparation: String,
+ launch: Launch,
+}
+
+fn prepared_digest(root: &Path) -> Option<String> {
+ std::fs::read(root.join(FILE))
+ .ok()
+ .map(|bytes| format!("{:x}", Sha256::digest(bytes)))
+}
+
+pub fn record_launch(root: &Path, harness: Option<&HarnessChoice>) -> Result<(), Problem> {
+ let preparation = prepared_digest(root)
+ .ok_or_else(|| required("The completed installation record is unavailable."))?;
+ write_record(
+ root,
+ LAUNCH,
+ &Launched {
+ preparation,
+ launch: Launch {
+ harness: harness.cloned(),
+ },
+ },
+ )
+}
+
+/// Passive resume intent. Runtime and credential validity are checked by the normal Start path.
+pub fn launch(root: &Path) -> Option<Launch> {
+ let record: Launched = serde_json::from_slice(&std::fs::read(root.join(LAUNCH)).ok()?).ok()?;
+ (prepared_digest(root).as_deref() == Some(&record.preparation)).then_some(record.launch)
+}
+
+pub fn save_selected_root(config: &Path, root: &Path) -> Result<(), Problem> {
+ let root = std::fs::canonicalize(root).map_err(|e| {
+ Problem::with(
+ "OpenBot could not remember this installation for next time.",
+ e.to_string(),
+ )
+ })?;
+ std::fs::create_dir_all(config).map_err(|e| {
+ Problem::with(
+ "OpenBot could not remember this installation for next time.",
+ e.to_string(),
+ )
+ })?;
+ write_record(config, "last-launched-root.json", &root)
+}
+
+pub fn selected_root(config: &Path) -> Option<PathBuf> {
+ let root: PathBuf =
+ serde_json::from_slice(&std::fs::read(config.join("last-launched-root.json")).ok()?)
+ .ok()?;
+ root.is_absolute().then_some(root)
+}
+
+pub fn required(detail: impl Into<String>) -> Problem {
+ Problem::with(REQUIRED, detail)
+}
+
+fn hash_files(root: &Path, files: impl IntoIterator<Item = PathBuf>) -> Result<String, Problem> {
+ let mut hash = Sha256::new();
+ hash.update(b"openbot-preparation-v1\0");
+ hash.update(
+ std::fs::canonicalize(root)
+ .map_err(|e| required(e.to_string()))?
+ .to_string_lossy()
+ .as_bytes(),
+ );
+ for file in files {
+ hash.update(file.to_string_lossy().as_bytes());
+ let bytes = std::fs::read(root.join(&file))
+ .map_err(|e| required(format!("{}: {e}", file.display())))?;
+ hash.update((bytes.len() as u64).to_le_bytes());
+ hash.update(bytes);
+ }
+ Ok(format!("{:x}", hash.finalize()))
+}
+
+fn dependency_fingerprint(root: &Path) -> Result<String, Problem> {
+ hash_files(
+ root,
+ std::iter::once(PathBuf::from("bun.lock"))
+ .chain(PACKAGES.map(|path| Path::new(path).join("package.json"))),
+ )
+}
+
+fn fingerprint(root: &Path) -> Result<String, Problem> {
+ hash_files(
+ root,
+ [
+ PathBuf::from(".openbot-deployment"),
+ PathBuf::from("container-images.json"),
+ PathBuf::from("docker-compose.yml"),
+ PathBuf::from(DEPENDENCIES),
+ ],
+ )
+}
+
+fn write_record(root: &Path, name: &str, value: &impl Serialize) -> Result<(), Problem> {
+ let target = root.join(name);
+ let temporary = root.join(format!("{name}.tmp"));
+ let bytes = serde_json::to_vec(value).map_err(|e| required(e.to_string()))?;
+ std::fs::write(&temporary, bytes).map_err(|e| required(e.to_string()))?;
+ // Windows rename does not replace an existing file. A missing checkpoint is safe on interruption.
+ match std::fs::remove_file(&target) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => return Err(required(e.to_string())),
+ }
+ std::fs::rename(temporary, target).map_err(|e| required(e.to_string()))
+}
+
+pub fn invalidate(root: &Path) -> Result<(), Problem> {
+ match std::fs::remove_file(root.join(FILE)) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(required(e.to_string())),
+ }
+}
+
+/// Record resolved package manifests, not just the existence of a partial node_modules directory.
+fn package_files(root: &Path) -> Result<Vec<PathBuf>, Problem> {
+ let mut files = BTreeSet::new();
+ for package in PACKAGES {
+ let directory = root.join(package);
+ let manifest: serde_json::Value = serde_json::from_slice(
+ &std::fs::read(directory.join("package.json")).map_err(|e| required(e.to_string()))?,
+ )
+ .map_err(|e| required(e.to_string()))?;
+ for group in ["dependencies", "devDependencies"] {
+ for name in manifest
+ .get(group)
+ .and_then(serde_json::Value::as_object)
+ .into_iter()
+ .flat_map(|entries| entries.keys())
+ {
+ let relative = Path::new("node_modules").join(name).join("package.json");
+ let file = [directory.join(&relative), root.join(&relative)]
+ .into_iter()
+ .find(|path| path.is_file())
+ .ok_or_else(|| {
+ required(format!(
+ "The installed package {name} is missing from {package}."
+ ))
+ })?;
+ files.insert(std::fs::canonicalize(file).map_err(|e| required(e.to_string()))?);
+ }
+ }
+ }
+ Ok(files.into_iter().collect())
+}
+
+pub fn record_dependencies(root: &Path, bun: &Path) -> Result<(), Problem> {
+ let record = Dependencies {
+ fingerprint: dependency_fingerprint(root)?,
+ bun: bun.to_path_buf(),
+ package_files: package_files(root)?,
+ };
+ write_record(root, DEPENDENCIES, &record)
+}
+
+pub fn install_dependencies_if_needed(
+ root: &Path,
+ acquire_runtime: impl FnOnce() -> Result<PathBuf, Problem>,
+) -> Result<PathBuf, Problem> {
+ if let Ok(bun) = dependencies_ready(root) {
+ return Ok(bun);
+ }
+ let bun = acquire_runtime()?;
+ stack::install_dependencies(root, &bun)?;
+ record_dependencies(root, &bun)?;
+ Ok(bun)
+}
+
+pub fn dependencies_ready(root: &Path) -> Result<PathBuf, Problem> {
+ let bytes = std::fs::read(root.join(DEPENDENCIES)).map_err(|e| required(e.to_string()))?;
+ let record: Dependencies =
+ serde_json::from_slice(&bytes).map_err(|e| required(e.to_string()))?;
+ if record.fingerprint != dependency_fingerprint(root)?
+ || record.package_files.iter().any(|file| !file.is_file())
+ {
+ return Err(required(
+ "The installed dependencies are incomplete or the lockfile changed.",
+ ));
+ }
+ // This executes only the installed runtime's version probe; it cannot install packages.
+ if !quiet::command(&record.bun)
+ .arg("--version")
+ .output()
+ .map_err(|e| required(e.to_string()))?
+ .status
+ .success()
+ {
+ return Err(required("The installed app runtime is unavailable."));
+ }
+ Ok(record.bun)
+}
+
+pub fn image_present(address: &Address, image: &str) -> Result<bool, Problem> {
+ address
+ .command()
+ .args(["image", "inspect", image])
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .map(|status| status.success())
+ .map_err(|e| required(format!("Could not check an installed image: {e}")))
+}
+
+pub fn require_images(address: &Address, images: &[String]) -> Result<(), Problem> {
+ for image in images {
+ if !image_present(address, image)? {
+ return Err(required(format!(
+ "The selected container engine does not have {image}."
+ )));
+ }
+ }
+ Ok(())
+}
+
+/// Written only after dependencies and every image have finished successfully.
+pub fn record(
+ root: &Path,
+ harness: Option<&HarnessChoice>,
+ images: Vec<String>,
+) -> Result<(), Problem> {
+ write_record(
+ root,
+ FILE,
+ &Prepared {
+ fingerprint: fingerprint(root)?,
+ harness: harness.cloned(),
+ images,
+ },
+ )
+}
+
+pub fn complete(
+ root: &Path,
+ harness: Option<&HarnessChoice>,
+ images: Vec<String>,
+ address: &Address,
+) -> Result<(), Problem> {
+ complete_with(root, harness, images, |images| {
+ require_images(address, images)
+ })
+}
+
+fn complete_with(
+ root: &Path,
+ harness: Option<&HarnessChoice>,
+ images: Vec<String>,
+ verify: impl FnOnce(&[String]) -> Result<(), Problem>,
+) -> Result<(), Problem> {
+ dependencies_ready(root)?;
+ verify(&images)?;
+ record(root, harness, images)
+}
+
+/// `selection=None` is the auth check, which has no authority to change the Bot selection.
+pub fn require(
+ root: &Path,
+ selection: Option<&Option<HarnessChoice>>,
+ address: &Address,
+) -> Result<PathBuf, Problem> {
+ require_with(root, selection, |images| require_images(address, images))
+}
+
+fn require_with(
+ root: &Path,
+ selection: Option<&Option<HarnessChoice>>,
+ verify: impl FnOnce(&[String]) -> Result<(), Problem>,
+) -> Result<PathBuf, Problem> {
+ let record: Prepared = serde_json::from_slice(
+ &std::fs::read(root.join(FILE)).map_err(|e| required(e.to_string()))?,
+ )
+ .map_err(|e| required(e.to_string()))?;
+ if record.fingerprint != fingerprint(root)?
+ || selection.is_some_and(|selection| selection != &record.harness)
+ {
+ return Err(required(
+ "The deployment folder or Bot selection changed after installation.",
+ ));
+ }
+ if let Some(problem) = stack::deployment_problem(root) {
+ return Err(required(problem));
+ }
+ let bun = dependencies_ready(root)?;
+ verify(&record.images)?;
+ Ok(bun)
+}
+
+/// Public Compose overrides suffice to identify and download software before authentication.
+pub fn image_settings(
+ root: &Path,
+ picked: Option<&crate::env::PickedHarness>,
+) -> Result<stack::Secrets, Problem> {
+ let mut settings: stack::Secrets = deployment::image_variables(root)?.into_iter().collect();
+ settings.insert("IMAGE_PULL_POLICY".into(), "missing".into());
+ if let Some(crate::env::PickedHarness::Installed { image, port, .. }) = picked {
+ settings.insert("PICKED_HARNESS_IMAGE".into(), image.clone());
+ settings.insert("PICKED_HARNESS_PORT".into(), port.to_string());
+ }
+ Ok(settings)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct Fixture {
+ root: PathBuf,
+ bun: PathBuf,
+ }
+
+ impl Fixture {
+ fn new() -> Self {
+ let root = crate::test_support::temp_root("preparation");
+ for package in PACKAGES {
+ std::fs::create_dir_all(root.join(package)).unwrap();
+ std::fs::write(
+ root.join(package).join("package.json"),
+ r#"{"scripts":{"serve":"bun serve.ts"}}"#,
+ )
+ .unwrap();
+ }
+ let root = std::fs::canonicalize(root).unwrap();
+ std::fs::write(
+ root.join("package.json"),
+ r#"{"dependencies":{"synthetic-package":"1"}}"#,
+ )
+ .unwrap();
+ std::fs::write(root.join("bun.lock"), "synthetic-lock").unwrap();
+ std::fs::write(root.join("docker-compose.yml"), "services: {}\n").unwrap();
+ std::fs::write(root.join("container-images.json"), "{}").unwrap();
+ deployment::record(&root, "v-test").unwrap();
+ let source = root.join("runtime.rs");
+ std::fs::write(&source, r#"
+use std::io::Write;
+fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ if args == ["--version"] { println!("1.3.14"); return; }
+ assert_eq!(args, ["install", "--frozen-lockfile", "--ignore-scripts"]);
+ let previous = std::fs::read_to_string("installs").unwrap_or_default();
+ writeln!(std::fs::OpenOptions::new().create(true).append(true).open("installs").unwrap(), "install").unwrap();
+ std::fs::create_dir_all("node_modules/synthetic-package").unwrap();
+ if previous.is_empty() { std::process::exit(71); }
+ std::fs::write("node_modules/synthetic-package/package.json", "{}").unwrap();
+}
+"#).unwrap();
+ let bun = root.join(format!("runtime{}", std::env::consts::EXE_SUFFIX));
+ crate::test_support::compile_fixture(&source, &bun);
+ Self { root, bun }
+ }
+
+ fn dependencies(&self) {
+ std::fs::create_dir_all(self.root.join("node_modules/synthetic-package")).unwrap();
+ std::fs::write(
+ self.root
+ .join("node_modules/synthetic-package/package.json"),
+ "{}",
+ )
+ .unwrap();
+ record_dependencies(&self.root, &self.bun).unwrap();
+ }
+
+ fn prepared(&self, harness: Option<&HarnessChoice>) {
+ self.dependencies();
+ complete_with(&self.root, harness, vec!["synthetic-image".into()], |_| {
+ Ok(())
+ })
+ .unwrap();
+ }
+ }
+
+ impl Drop for Fixture {
+ fn drop(&mut self) {
+ std::fs::remove_dir_all(&self.root).unwrap();
+ }
+ }
+
+ #[test]
+ fn failed_dependencies_retry_then_auth_reuses_success_without_installing() {
+ let f = Fixture::new();
+ std::fs::write(f.root.join(".env"), "KEEP_THIS_PUBLIC_SETTING=yes\n").unwrap();
+ let install = || install_dependencies_if_needed(&f.root, || Ok(f.bun.clone()));
+ assert!(install().is_err());
+ assert!(!f.root.join(DEPENDENCIES).exists());
+ assert!(f.root.join("node_modules").is_dir());
+ install().unwrap();
+ install_dependencies_if_needed(&f.root, || panic!("cached runtime must be reused"))
+ .unwrap();
+ f.prepared(None);
+ for _ in 0..2 {
+ require_with(&f.root, None, |images| {
+ assert_eq!(images, ["synthetic-image"]);
+ Ok(())
+ })
+ .unwrap();
+ }
+ assert_eq!(
+ std::fs::read_to_string(f.root.join("installs")).unwrap(),
+ "install\ninstall\n"
+ );
+ assert_eq!(
+ std::fs::read_to_string(f.root.join(".env")).unwrap(),
+ "KEEP_THIS_PUBLIC_SETTING=yes\n"
+ );
+ }
+
+ #[test]
+ fn failed_image_preparation_cannot_publish_completion() {
+ let f = Fixture::new();
+ f.dependencies();
+ let result = complete_with(&f.root, None, vec!["missing-image".into()], |_| {
+ Err(required("missing image"))
+ });
+ assert!(result.is_err());
+ assert!(!f.root.join(FILE).exists());
+ complete_with(&f.root, None, vec!["now-present".into()], |_| Ok(())).unwrap();
+ assert!(f.root.join(FILE).is_file());
+ }
+
+ #[test]
+ fn changed_bot_lockfile_or_deleted_package_requires_installation() {
+ let f = Fixture::new();
+ let chosen = Some(HarnessChoice {
+ id: "langgraph".into(),
+ agent_url: None,
+ });
+ f.prepared(chosen.as_ref());
+ require_with(&f.root, Some(&chosen), |_| Ok(())).unwrap();
+ assert!(require_with(&f.root, Some(&None), |_| panic!(
+ "wrong selection must stop first"
+ ))
+ .is_err());
+ std::fs::remove_file(f.root.join("node_modules/synthetic-package/package.json")).unwrap();
+ assert!(require_with(&f.root, Some(&chosen), |_| Ok(())).is_err());
+ f.dependencies();
+ f.prepared(chosen.as_ref());
+ std::fs::write(f.root.join("bun.lock"), "changed-lock").unwrap();
+ assert!(require_with(&f.root, Some(&chosen), |_| Ok(())).is_err());
+ }
+
+ #[test]
+ fn successful_launch_remembers_exact_root_and_bot_without_credentials() {
+ let f = Fixture::new();
+ let chosen = HarnessChoice {
+ id: "byo-url".into(),
+ agent_url: Some("https://agent.example/ag-ui".into()),
+ };
+ f.prepared(Some(&chosen));
+ let config = f.root.join("app-config");
+ assert!(launch(&f.root).is_none());
+ record_launch(&f.root, Some(&chosen)).unwrap();
+ save_selected_root(&config, &f.root).unwrap();
+ assert_eq!(selected_root(&config), Some(f.root.clone()));
+ assert_eq!(launch(&f.root).unwrap().harness, Some(chosen));
+ std::fs::remove_file(f.root.join("node_modules/synthetic-package/package.json")).unwrap();
+ assert!(
+ launch(&f.root).is_some(),
+ "resume intent survives missing assets for explicit install recovery"
+ );
+ invalidate(&f.root).unwrap();
+ assert!(launch(&f.root).is_none());
+ assert_eq!(
+ selected_root(&config),
+ Some(f.root.clone()),
+ "repair must not forget the last successful folder"
+ );
+ }
+}
diff --git a/desktop/src-tauri/src/pull_metrics.rs b/desktop/src-tauri/src/pull_metrics.rs
index 899e078e..a7408744 100644
--- a/desktop/src-tauri/src/pull_metrics.rs
+++ b/desktop/src-tauri/src/pull_metrics.rs
@@ -112,14 +112,19 @@ fn download_bytes(stdout: &[u8], stderr: &[u8]) -> Option<u64> {
/// Pull a provider sign-in image without starting its CLI or creating a container.
/// A tiny stdin Compose project gives the same missing-only policy and JSON progress as setup.
-/// Providers without `pull --policy missing` retain their implicit pull and emit no metric.
+/// Older Compose providers use an explicit native pull after a local presence check.
pub fn pull_image(
engine: &Address,
image: &str,
on_complete: impl FnOnce(PullMetrics),
) -> Result<(), Problem> {
- let Some(json_progress) = compose_pull_progress(engine) else {
+ if crate::preparation::image_present(engine, image)? {
return Ok(());
+ }
+ let Some(json_progress) = compose_pull_progress(engine) else {
+ let mut command = engine.command();
+ command.args(["pull", image]);
+ return run(command, None, false, on_complete);
};
let mut command = engine.command();
command.arg("compose");
@@ -214,6 +219,48 @@ pub(crate) fn run(
mod tests {
use super::*;
+ #[test]
+ fn older_compose_explicitly_downloads_missing_images_and_reuses_cached_images() {
+ if crate::test_support::isolated_process("pull_metrics::tests::older_compose_explicitly_downloads_missing_images_and_reuses_cached_images") { return; }
+ let root = crate::test_support::temp_root("explicit-image-install");
+ std::fs::create_dir_all(&root).unwrap();
+ let source = root.join("docker.rs");
+ std::fs::write(&source, r#"
+fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ let executable = std::env::current_exe().unwrap();
+ let root = executable.parent().unwrap();
+ match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
+ ["image", "inspect", image] => std::process::exit(if root.join(image).is_file() {0} else {1}),
+ ["compose", "pull", "--help"] => println!("--include-deps"),
+ ["pull", "synthetic-image"] => { std::fs::write(root.join("synthetic-image"), "installed").unwrap(); },
+ ["pull", "missing-image"] => { eprintln!("synthetic download failure"); std::process::exit(71); },
+ _ => panic!("no services or authentication may start while installing: {args:?}"),
+ }
+}
+"#).unwrap();
+ crate::test_support::compile_fixture(
+ &source,
+ &root.join(format!("docker{}", std::env::consts::EXE_SUFFIX)),
+ );
+ std::env::set_var("PATH", &root);
+ let address = Address::new(crate::engine::Engine::Docker, None);
+ let mut outcomes = Vec::new();
+ pull_image(&address, "synthetic-image", |metric| {
+ outcomes.push(metric.outcome)
+ })
+ .unwrap();
+ pull_image(&address, "synthetic-image", |_| {
+ panic!("cached image must not be downloaded again")
+ })
+ .unwrap();
+ assert!(pull_image(&address, "missing-image", |metric| outcomes
+ .push(metric.outcome))
+ .is_err());
+ assert_eq!(outcomes, [Outcome::Success, Outcome::Failure]);
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
#[test]
fn counts_each_shared_layer_once_and_ignores_extraction() {
let output = br#"
diff --git a/desktop/src-tauri/src/stack.rs b/desktop/src-tauri/src/stack.rs
index 56a4cff2..d8fd7131 100644
--- a/desktop/src-tauri/src/stack.rs
+++ b/desktop/src-tauri/src/stack.rs
@@ -179,10 +179,53 @@ fn compose_command(engine: &Address, root: &Path, secrets: &Secrets) -> Command
command
}
+/// Resolve only image references, using public installation overrides before credentials exist.
+pub fn installation_images(
+ engine: &Address,
+ root: &Path,
+ harness: bool,
+ settings: &Secrets,
+) -> Result<Vec<String>, Problem> {
+ let mut requested = selected_services(harness, BundledBots::openai_compatible());
+ requested.push("migrate");
+ let mut command = compose_command(engine, root, settings);
+ if harness {
+ command.args(["--profile", "harness"]);
+ }
+ let output = command
+ .args(["config", "--images"])
+ .args(requested)
+ .output()
+ .map_err(|e| {
+ Problem::with(
+ "OpenBot could not check which software to install.",
+ e.to_string(),
+ )
+ })?;
+ if !output.status.success() {
+ return Err(Problem::with(
+ "OpenBot could not check which software to install.",
+ command_said(&output.stderr),
+ ));
+ }
+ let images: std::collections::BTreeSet<String> = String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.is_empty())
+ .map(str::to_string)
+ .collect();
+ if images.is_empty() {
+ return Err(Problem::plain(
+ "This deployment does not identify the software OpenBot needs to install.",
+ ));
+ }
+ Ok(images.into_iter().collect())
+}
+
/// Pull the selected stack before `up`, including the one-shot migration and service dependencies.
/// Keep this separate from `up`: image transfer must not include container startup or migrations.
-/// Older providers without a missing-only pull policy retain the existing implicit pull in `up`;
-/// no pull metric is reported for that unmeasurable path.
+/// Legacy batch helper for providers with a missing-only pull policy. The desktop installation
+/// step uses `pull_image` for explicit acquisition on every provider; `up` never pulls.
pub fn pull(
engine: &Address,
root: &Path,
@@ -236,7 +279,7 @@ pub fn up(
command.args(["--profile", "harness"]);
}
let output = command
- .args(["up", "-d", "--no-build"])
+ .args(["up", "-d", "--no-build", "--pull", "never"])
.args(&requested)
.output()
.map_err(|error| format!("could not run {} compose: {error}", engine.engine.binary()))?;
@@ -263,11 +306,10 @@ pub fn migrate(
root: &Path,
secrets: &Secrets,
) -> Result<(), crate::problem::Problem> {
- // No `--no-build` here: `compose run` does not take it, and passing it fails on the flag rather
- // than on anything to do with migrations. Building is prevented the other way, by
- // `IMAGE_PULL_POLICY=missing` in the environment, which makes the service pull instead.
+ // The installation step supplies this image. `run` does not accept `--no-build`, and its
+ // explicit no-pull policy must report a missing image without starting another download.
let output = compose_command(engine, root, secrets)
- .args(["run", "--rm", "migrate"])
+ .args(["run", "--rm", "--pull", "never", "migrate"])
.output()
.map_err(|error| format!("could not run migrations: {error}"))?;
diff --git a/desktop/src-tauri/src/stop_ipc_tests.rs b/desktop/src-tauri/src/stop_ipc_tests.rs
index 56be383d..fa441ce9 100644
--- a/desktop/src-tauri/src/stop_ipc_tests.rs
+++ b/desktop/src-tauri/src/stop_ipc_tests.rs
@@ -340,6 +340,19 @@ mod stop_ipc {
return;
}
let fixture = Fixture::new();
+ std::fs::write(
+ fixture.root.join(".openbot-prepared.json"),
+ "completed preparation",
+ )
+ .unwrap();
+ preparation::record_launch(&fixture.root, None).unwrap();
+ let configured = || {
+ already_configured(
+ fixture.app.handle().clone(),
+ fixture.root.to_string_lossy().into_owned(),
+ )
+ };
+ assert!(configured().launch.is_some());
let setup = "tauri://localhost/menu-stop-success";
*fixture.app.state::<Shell>().setup_url.lock().unwrap() = Some(setup.into());
let compose = fixture.compose_barrier();
@@ -351,6 +364,23 @@ mod stop_ipc {
let shell = fixture.app.state::<Shell>();
assert!(last_failure(fixture.app.handle().clone()).is_none());
assert!(!recovery_required(&shell, &fixture.root));
+ assert!(
+ configured().launch.is_none(),
+ "Stop must survive setup reloading"
+ );
+ let reopened = tauri::test::mock_builder()
+ .manage(Shell::default())
+ .build(tauri::test::mock_context(tauri::test::noop_assets()))
+ .unwrap();
+ assert!(
+ already_configured(
+ reopened.handle().clone(),
+ fixture.root.to_string_lossy().into_owned(),
+ )
+ .launch
+ .is_some(),
+ "a fresh app session may resume the saved installation"
+ );
}
#[test]
diff --git a/desktop/src-tauri/src/telemetry.rs b/desktop/src-tauri/src/telemetry.rs
index aa57f29b..3a6d9b2f 100644
--- a/desktop/src-tauri/src/telemetry.rs
+++ b/desktop/src-tauri/src/telemetry.rs
@@ -686,8 +686,9 @@ impl Architecture {
pub enum Step {
Welcome,
Harness,
- Model,
Install,
+ Model,
+ Connect,
Ask,
}
@@ -798,16 +799,16 @@ pub fn schema_json() -> serde_json::Value {
"runtime_env": ["development", "production", "test"]
},
"events": {
- "step_viewed": { "step": ["welcome", "harness", "model", "install", "ask"] },
+ "step_viewed": { "step": ["welcome", "harness", "install", "model", "connect", "ask"] },
"harness_chosen": { "harness": ["crewai", "llamaindex", "agno", "langgraph", "google_adk", "pydantic_ai", "microsoft_agent_framework", "claude_agent_sdk", "strands", "ag2", "langroid", "mastra", "byo_url"] },
"model_chosen": { "provider": ["openai", "anthropic", "compatible", "none"], "credential_path": ["subscription", "api_key", "none"], "custom_base_url": "bool" },
"engine_detected": { "engine": ["docker", "podman", "none"], "responding": "bool" },
"engine_installed": { "engine": ["docker", "podman", "none"], "outcome": ["success", "failure"] },
"windows_stage": { "outcome": ["ready", "wsl_absent", "wsl_one", "wsl_no_kernel", "virtual_machine_platform_disabled", "virtualization_disabled", "not_administrator", "check_failed"] },
"image_pull": { "outcome": ["success", "failure"], "duration_ms": "u64", "bytes": "option_u64" },
- "setup_failed": { "step": ["welcome", "harness", "model", "install", "ask"], "error_class": ["engine_unavailable", "engine_install_failed", "image_pull_failed", "invalid_configuration", "network_unavailable", "permission_denied", "unknown"] },
+ "setup_failed": { "step": ["welcome", "harness", "install", "model", "connect", "ask"], "error_class": ["engine_unavailable", "engine_install_failed", "image_pull_failed", "invalid_configuration", "network_unavailable", "permission_denied", "unknown"] },
"activated": {},
- "setup_abandoned": { "step": ["welcome", "harness", "model", "install", "ask"] }
+ "setup_abandoned": { "step": ["welcome", "harness", "install", "model", "connect", "ask"] }
}
})
}
diff --git a/desktop/src-tauri/tests/fixtures/engine.rs b/desktop/src-tauri/tests/fixtures/engine.rs
index e536e37e..4ffe224a 100644
--- a/desktop/src-tauri/tests/fixtures/engine.rs
+++ b/desktop/src-tauri/tests/fixtures/engine.rs
@@ -12,6 +12,25 @@ fn main() {
args.remove(0);
}
let joined = args.join(" ");
+ if SCENARIO == "runtime" {
+ assert_eq!(joined, "--version", "launch must not install dependencies");
+ println!("1.3.14");
+ return;
+ }
+ if joined.starts_with("image inspect ") {
+ return;
+ }
+ if SCENARIO == "installation-boundary" {
+ if joined.contains(" up ") || joined.contains(" run ") {
+ if !args.windows(2).any(|pair| pair == ["--pull", "never"]) {
+ eprintln!("launch may implicitly pull an uninstalled image: {joined}");
+ std::process::exit(61);
+ }
+ return;
+ }
+ eprintln!("unexpected installation boundary command: {joined}");
+ std::process::exit(62);
+ }
if joined == "context show" {
println!("fixture");
return;
@@ -104,9 +123,10 @@ fn main() {
}
}
value
- if value.starts_with("compose up -d --no-build ")
- || value.starts_with("compose --profile harness up -d --no-build ") => {}
- "compose run --rm migrate" => {
+ if value.starts_with("compose up -d --no-build --pull never ")
+ || value
+ .starts_with("compose --profile harness up -d --no-build --pull never ") => {}
+ "compose run --rm --pull never migrate" => {
if SCENARIO == "harness" {
eprintln!("synthetic migration barrier");
std::process::exit(71);
diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx
index 7ba293cf..8816f093 100644
--- a/desktop/src/App.test.tsx
+++ b/desktop/src/App.test.tsx
@@ -21,6 +21,9 @@ let invokeCalls: Array<{ command: string; args?: unknown }> = [];
let invokeHandler: Invoke = async () => {
throw new Error("invoke handler was not installed");
};
+const progressListeners = new Set<
+ (event: { payload: { step: string; ok: boolean; detail: string } }) => void
+>();
mock.module("@tauri-apps/api/core", () => ({
invoke: (command: string, args?: unknown) => {
@@ -30,7 +33,15 @@ mock.module("@tauri-apps/api/core", () => ({
}));
mock.module("@tauri-apps/api/event", () => ({
- listen: async () => () => {},
+ listen: async (
+ name: string,
+ listener: (event: {
+ payload: { step: string; ok: boolean; detail: string };
+ }) => void,
+ ) => {
+ if (name === "setup:progress") progressListeners.add(listener);
+ return () => progressListeners.delete(listener);
+ },
}));
mock.module("./Mark", () => ({
@@ -43,14 +54,23 @@ beforeAll(() => GlobalRegistrator.register());
afterEach(() => {
invokeCalls = [];
cleanup();
+ progressListeners.clear();
});
afterAll(() => GlobalRegistrator.unregister());
-async function renderApp() {
+async function renderApp(strictMode = false) {
let view!: ReturnType<typeof render>;
await act(async () => {
- view = render(<App />);
+ view = render(
+ strictMode ? (
+ <StrictMode>
+ <App />
+ </StrictMode>
+ ) : (
+ <App />
+ ),
+ );
});
return view;
@@ -62,6 +82,410 @@ function setupEvents() {
.map((call) => call.args);
}
+async function enterInstallation(view: Awaited<ReturnType<typeof renderApp>>) {
+ await userEvent.click(view.getByRole("button", { name: "Set up OpenBot" }));
+ await userEvent.click(view.getByRole("button", { name: "Continue" }));
+}
+
+async function completeInstallation(
+ view: Awaited<ReturnType<typeof renderApp>>,
+) {
+ await userEvent.click(view.getByRole("button", { name: "Install OpenBot" }));
+ await userEvent.click(
+ await view.findByRole("button", { name: "Continue to sign in" }),
+ );
+}
+
+function installationCalls() {
+ return invokeCalls.filter((call) =>
+ ["prepare_installation", "prepare_engine"].includes(call.command),
+ );
+}
+
+test("installation completes before either sign-in is available", async () => {
+ useRootConfigurationSetup("/tmp/install-before-signin", async () =>
+ emptyConfiguration(),
+ );
+ const preparation = deferred<void>();
+ const previous = invokeHandler;
+ invokeHandler = async (command, args) => {
+ if (command === "prepare_installation") return preparation.promise;
+ return previous(command, args);
+ };
+ const view = await renderApp();
+ await enterInstallation(view);
+ expect(view.getByRole("heading", { name: "Install OpenBot" })).toBeTruthy();
+ expect(view.getByLabelText("Where OpenBot lives")).toHaveProperty(
+ "value",
+ "/tmp/install-before-signin",
+ );
+ expect(
+ view.queryByRole("button", { name: /Sign in|Continue to sign in/i }),
+ ).toBeNull();
+ await userEvent.click(view.getByRole("button", { name: "Install OpenBot" }));
+ expect(installationCalls()).toEqual([
+ {
+ command: "prepare_installation",
+ args: {
+ root: "/tmp/install-before-signin",
+ harness: { id: "langgraph" },
+ },
+ },
+ ]);
+ expect(view.getByLabelText("Where OpenBot lives")).toHaveProperty(
+ "disabled",
+ true,
+ );
+ expect(view.getByRole("button", { name: "Back" })).toHaveProperty(
+ "disabled",
+ true,
+ );
+ expect(view.queryByRole("heading", { name: "Connect your AI" })).toBeNull();
+ expect(
+ invokeCalls.some((call) =>
+ /sign_in|start_stack|^providers$/.test(call.command),
+ ),
+ ).toBe(false);
+ await act(async () => {
+ for (const listener of progressListeners)
+ listener({
+ payload: {
+ step: "dependencies",
+ ok: true,
+ detail: "Local runtime installed.",
+ },
+ });
+ });
+ expect(view.getByText("Local runtime installed.")).toBeTruthy();
+ expect(
+ view.queryByRole("button", { name: "Continue to sign in" }),
+ ).toBeNull();
+ await act(async () => preparation.resolve());
+ expect(
+ view.getByRole("heading", { name: "Installation complete" }),
+ ).toBeTruthy();
+ expect(view.queryByRole("heading", { name: "Connect your AI" })).toBeNull();
+ await userEvent.click(
+ view.getByRole("button", { name: "Continue to sign in" }),
+ );
+ expect(view.getByRole("heading", { name: "Connect your AI" })).toBeTruthy();
+});
+
+test("failed installation blocks sign-in and retries before reporting completion", async () => {
+ useRootConfigurationSetup("/tmp/install-retry", async () =>
+ emptyConfiguration(),
+ );
+ const previous = invokeHandler;
+ let attempts = 0;
+ invokeHandler = async (command, args) => {
+ if (command === "prepare_installation") {
+ if (++attempts === 1)
+ throw {
+ said: "The download was interrupted.",
+ detail: "Synthetic network failure",
+ };
+ return null;
+ }
+ return previous(command, args);
+ };
+ const view = await renderApp();
+ await enterInstallation(view);
+ await userEvent.click(view.getByRole("button", { name: "Install OpenBot" }));
+ expect((await view.findByRole("alert")).textContent).toContain(
+ "The download was interrupted.",
+ );
+ expect(
+ view.queryByRole("button", { name: "Continue to sign in" }),
+ ).toBeNull();
+ expect(
+ invokeCalls.some((call) => /sign_in|^providers$/.test(call.command)),
+ ).toBe(false);
+ await userEvent.click(
+ view.getByRole("button", { name: "Retry installation" }),
+ );
+ expect(
+ await view.findByRole("heading", { name: "Installation complete" }),
+ ).toBeTruthy();
+ expect(view.queryByRole("alert")).toBeNull();
+ expect(attempts).toBe(2);
+});
+
+test("provider sign-in retries and Back reuse the completed local installation", async () => {
+ useRootConfigurationSetup("/tmp/provider-retry", async () =>
+ emptyConfiguration(),
+ );
+ const previous = invokeHandler;
+ let signIns = 0;
+ invokeHandler = async (command, args) => {
+ if (command === "prepare_installation") return null;
+ if (command === "providers")
+ return [
+ {
+ id: "openai",
+ name: "OpenAI",
+ summary: "Use OpenAI",
+ logins: ["plan"],
+ mark: null,
+ caution: null,
+ },
+ ];
+ if (command === "begin_chatgpt_sign_in") {
+ if (++signIns === 1) throw { said: "Sign-in was interrupted." };
+ return "https://sign-in.example";
+ }
+ if (command === "finish_chatgpt_sign_in") return "synthetic-token";
+ return previous(command, args);
+ };
+ const view = await renderApp();
+ await enterInstallation(view);
+ await completeInstallation(view);
+ await userEvent.click(view.getByRole("button", { name: "Back" }));
+ expect(
+ view.getByRole("heading", { name: "Installation complete" }),
+ ).toBeTruthy();
+ await userEvent.click(
+ view.getByRole("button", { name: "Continue to sign in" }),
+ );
+ await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
+ await userEvent.click(
+ view.getByRole("button", { name: "Sign in with OpenAI" }),
+ );
+ await view.findByText("Sign-in was interrupted.");
+ await userEvent.click(
+ view.getByRole("button", { name: "Sign in with OpenAI" }),
+ );
+ await view.findByText(/Signed in to OpenAI/);
+ expect(signIns).toBe(2);
+ expect(installationCalls()).toHaveLength(1);
+});
+
+test("a completed installation can be repaired after a provider reports missing assets", async () => {
+ useRootConfigurationSetup("/tmp/repair-installation", async () =>
+ emptyConfiguration(),
+ );
+ const previous = invokeHandler;
+ const repair = deferred<void>();
+ let installations = 0;
+ invokeHandler = async (command, args) => {
+ if (command === "prepare_installation")
+ return ++installations === 1 ? null : repair.promise;
+ if (command === "providers")
+ return [
+ {
+ id: "openai",
+ name: "OpenAI",
+ summary: "Use OpenAI",
+ logins: ["plan"],
+ mark: null,
+ caution: null,
+ },
+ ];
+ if (command === "begin_chatgpt_sign_in")
+ throw { said: "Return to Install and try again." };
+ return previous(command, args);
+ };
+ const view = await renderApp();
+ await enterInstallation(view);
+ await completeInstallation(view);
+ await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
+ await userEvent.click(
+ view.getByRole("button", { name: "Sign in with OpenAI" }),
+ );
+ await view.findByText("Return to Install and try again.");
+ await userEvent.click(view.getByRole("button", { name: "Back" }));
+ await userEvent.click(
+ view.getByRole("button", { name: "Repair installation" }),
+ );
+ expect(
+ view.queryByRole("button", { name: "Continue to sign in" }),
+ ).toBeNull();
+ await act(async () => repair.resolve());
+ expect(
+ await view.findByRole("button", { name: "Continue to sign in" }),
+ ).toBeTruthy();
+ expect(installations).toBe(2);
+});
+
+test("changing the Bot invalidates its completed installation", async () => {
+ useBringYourOwnHarnessSetup();
+ const view = await renderApp();
+ await enterInstallation(view);
+ await completeInstallation(view);
+ await userEvent.click(view.getByRole("button", { name: "Back" }));
+ await userEvent.click(view.getByRole("button", { name: "Back" }));
+ await userEvent.click(view.getByText("Choose the agent framework"));
+ await userEvent.click(
+ view.getByRole("radio", { name: /An agent you already run/ }),
+ );
+ await userEvent.type(
+ view.getByLabelText("AG-UI endpoint"),
+ "https://agent.example/ag-ui",
+ );
+ await userEvent.click(view.getByRole("button", { name: "Continue" }));
+ expect(
+ view.queryByRole("button", { name: "Continue to sign in" }),
+ ).toBeNull();
+ await completeInstallation(view);
+ expect(installationCalls()).toEqual([
+ {
+ command: "prepare_installation",
+ args: { root: "/tmp/openbot-app-test", harness: { id: "langgraph" } },
+ },
+ {
+ command: "prepare_installation",
+ args: {
+ root: "/tmp/openbot-app-test",
+ harness: { id: "byo-url", agentUrl: "https://agent.example/ag-ui" },
+ },
+ },
+ ]);
+});
+
+test.each([false, true])(
+ "reopening a successful setup starts its saved root and connections without the wizard or Ask (Strict Mode=%s)",
+ async (strictMode) => {
+ const root = "/tmp/successful-setup-root";
+ useRootConfigurationSetup("/tmp/default-root", async () => ({
+ values: {
+ INTELLIGENCE_API_URL: "https://own.example/api",
+ INTELLIGENCE_GATEWAY_WS_URL: "wss://own.example/ws",
+ },
+ saved: { ...savedOpenAiConfiguration().saved, model: "open-ai-api-key" },
+ launch: { harness: { id: "mastra" } },
+ }));
+ const launch = deferred<void>();
+ const previous = invokeHandler;
+ invokeHandler = async (command, args) => {
+ if (command === "selected_root") return root;
+ if (command === "start_stack") return launch.promise;
+ if (command === "show_openbot") return null;
+ return previous(command, args);
+ };
+ const view = await renderApp(strictMode);
+ expect(
+ view.getByRole("heading", { name: "Starting OpenBot" }),
+ ).toBeTruthy();
+ expect(
+ view.queryByRole("heading", { name: "Connect to CopilotKit" }),
+ ).toBeNull();
+ expect(view.queryByRole("button", { name: "Set up OpenBot" })).toBeNull();
+ await act(async () => launch.resolve());
+ await waitFor(() =>
+ expect(invokeCalls).toContainEqual({ command: "show_openbot" }),
+ );
+ expect(getStartStackPayload()).toEqual({
+ root,
+ apiKey: "",
+ apiUrl: "https://own.example/api",
+ gatewayWsUrl: "wss://own.example/ws",
+ harness: { id: "mastra" },
+ model: { provider: "openai", login: "api-key", saved: true },
+ });
+ expect(
+ invokeCalls.filter((call) => call.command === "start_stack"),
+ ).toHaveLength(1);
+ expect(
+ invokeCalls.some((call) =>
+ /prepare_|sign_in|^providers$|^harnesses$|ask_the_bot/.test(
+ call.command,
+ ),
+ ),
+ ).toBe(false);
+ expect(view.queryByRole("button", { name: "Set up OpenBot" })).toBeNull();
+ expect(view.queryByRole("button", { name: "Ask" })).toBeNull();
+ },
+);
+
+test("a failed automatic reopen offers recovery without retrying or installing", async () => {
+ useRootConfigurationSetup("/tmp/reopen-failure", async () => ({
+ ...savedOpenAiConfiguration(),
+ saved: { ...savedOpenAiConfiguration().saved, model: "open-ai-api-key" },
+ launch: { harness: { id: "langgraph" } },
+ }));
+ const previous = invokeHandler;
+ invokeHandler = async (command, args) => {
+ if (command === "start_stack")
+ throw { said: "Return to Install and try again." };
+ return previous(command, args);
+ };
+ const view = await renderApp();
+ expect((await view.findByRole("alert")).textContent).toContain(
+ "Return to Install and try again.",
+ );
+ expect(
+ invokeCalls.filter((call) => call.command === "start_stack"),
+ ).toHaveLength(1);
+ expect(installationCalls()).toHaveLength(0);
+ expect(view.getByRole("button", { name: "Start OpenBot" })).toHaveProperty(
+ "disabled",
+ false,
+ );
+ await userEvent.click(
+ view.getByRole("button", { name: "Change installation" }),
+ );
+ expect(view.getByRole("button", { name: "Install OpenBot" })).toBeTruthy();
+});
+
+test("reopening a retained root waits for its saved setup without flashing the wizard", async () => {
+ const root = "/tmp/reopen-pending-configuration";
+ const configuration = deferred<ReturnType<typeof savedOpenAiConfiguration>>();
+ useRootConfigurationSetup(root, async () => configuration.promise);
+ const previous = invokeHandler;
+ invokeHandler = async (command, args) => {
+ if (command === "selected_root") return root;
+ return previous(command, args);
+ };
+ const view = await renderApp();
+ expect(view.getByRole("heading", { name: "Opening OpenBot" })).toBeTruthy();
+ expect(view.queryByRole("button", { name: "Set up OpenBot" })).toBeNull();
+ await act(async () => configuration.resolve(savedOpenAiConfiguration()));
+ // A retained folder with no successful launch still needs the setup screens.
+ expect(
+ await view.findByRole("button", { name: "Set up OpenBot" }),
+ ).toBeTruthy();
+ expect(invokeCalls.some((call) => call.command === "start_stack")).toBe(
+ false,
+ );
+});
+
+test.each(["supervisor", "windows"])(
+ "automatic reopen respects the existing %s blocker",
+ async (blocker) => {
+ useRootConfigurationSetup("/tmp/reopen-blocked", async () => ({
+ ...savedOpenAiConfiguration(),
+ saved: { ...savedOpenAiConfiguration().saved, model: "open-ai-api-key" },
+ launch: { harness: { id: "langgraph" } },
+ }));
+ const previous = invokeHandler;
+ invokeHandler = async (command, args) => {
+ if (blocker === "supervisor" && command === "last_failure")
+ return { said: "The supervisor stopped retrying." };
+ if (blocker === "windows" && command === "windows_blocker")
+ return "wsl-absent";
+ if (command === "windows_blocker_instruction")
+ return "Install WSL before continuing.";
+ return previous(command, args);
+ };
+ const view = await renderApp();
+ await waitFor(() =>
+ expect(
+ invokeCalls.some((call) => call.command === "already_running"),
+ ).toBe(true),
+ );
+ expect(invokeCalls.some((call) => call.command === "start_stack")).toBe(
+ false,
+ );
+ expect(installationCalls()).toHaveLength(0);
+ expect(
+ view.getByText(
+ blocker === "supervisor"
+ ? "The supervisor stopped retrying."
+ : "Install WSL before continuing.",
+ ),
+ ).toBeTruthy();
+ },
+);
+
test("setup records telemetry without a consent gate and deduplicates viewed steps", async () => {
useRootConfigurationSetup("/tmp/private-setup-root", async () =>
emptyConfiguration(),
@@ -87,11 +511,12 @@ test("setup records telemetry without a consent gate and deduplicates viewed ste
]);
await userEvent.click(view.getByRole("button", { name: "Set up OpenBot" }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
+
expect(setupEvents()).toEqual([
{ event: { kind: "step_viewed", step: "welcome" } },
{ event: { kind: "step_viewed", step: "harness" } },
{ event: { kind: "harness_chosen", harness: "langgraph" } },
- { event: { kind: "step_viewed", step: "model" } },
+ { event: { kind: "step_viewed", step: "install" } },
]);
await userEvent.click(view.getByRole("button", { name: "Back" }));
expect(setupEvents().at(-1)).toEqual({
@@ -207,6 +632,7 @@ function useRootConfigurationSetup(
loadConfiguration: (root: string) => Promise<unknown>,
) {
invokeHandler = async (command, args) => {
+ if (command === "prepare_installation") return null;
if (command === "detect_engine") {
return {
engine: "docker",
@@ -258,7 +684,6 @@ function useRootConfigurationSetup(
},
];
}
- if (command === "prepare_engine") return null;
if (command === "start_stack") return null;
throw new Error(`unexpected command ${command}`);
};
@@ -358,7 +783,9 @@ test("disabled Virtual Machine Platform displays its feature-specific fix and bl
expect(view.queryByRole("button", { name: "Start OpenBot" })).toBeNull();
expect(
invokeCalls.some((call) =>
- ["prepare_engine", "start_stack"].includes(call.command),
+ ["prepare_installation", "prepare_engine", "start_stack"].includes(
+ call.command,
+ ),
),
).toBe(false);
});
@@ -376,6 +803,7 @@ function useCompatibleEndpointSetup(
existingValues: ExistingConfigurationValues,
) {
invokeHandler = async (command) => {
+ if (command === "prepare_installation") return null;
if (command === "detect_engine") {
return {
engine: "docker",
@@ -425,7 +853,6 @@ function useCompatibleEndpointSetup(
},
];
}
- if (command === "prepare_engine") return null;
if (command === "start_stack") return null;
throw new Error(`unexpected command ${command}`);
};
@@ -442,6 +869,7 @@ async function enterCompatibleEndpoint(
await view.findByRole("button", { name: "Set up OpenBot" }),
);
await userEvent.click(await view.findByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
await userEvent.click(
await view.findByRole("radio", { name: /OpenAI-compatible/ }),
);
@@ -516,6 +944,7 @@ test.each([true, false])(
const view = await renderApp();
await userEvent.click(view.getByRole("button", { name: "Set up OpenBot" }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
expect(view.getByLabelText("Base URL")).toHaveProperty(
"value",
"https://models.example/v1",
@@ -566,6 +995,7 @@ test.each([
const view = await renderApp();
await userEvent.click(view.getByRole("button", { name: "Set up OpenBot" }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
expect(view.getByRole("button", { name: "Continue" })).toHaveProperty(
"disabled",
true,
@@ -588,6 +1018,7 @@ test("an unsupported saved model kind does not become a startable endpoint", asy
const view = await renderApp();
await userEvent.click(view.getByRole("button", { name: "Set up OpenBot" }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
expect(view.getByRole("button", { name: "Continue" })).toHaveProperty(
"disabled",
true,
@@ -600,6 +1031,7 @@ test("an unsupported saved model kind does not become a startable endpoint", asy
test("Change the model after an Ask failure stops the stack and reaches the provider picker", async () => {
invokeHandler = async (command) => {
+ if (command === "prepare_installation") return null;
if (command === "detect_engine") {
return {
engine: "docker",
@@ -652,7 +1084,6 @@ test("Change the model after an Ask failure stops the stack and reaches the prov
},
];
}
- if (command === "prepare_engine") return null;
if (command === "start_stack") return null;
if (command === "ask_the_bot") {
throw { said: "The model could not answer.", detail: "401" };
@@ -667,6 +1098,7 @@ test("Change the model after an Ask failure stops the stack and reaches the prov
await view.findByRole("button", { name: "Set up OpenBot" }),
);
await userEvent.click(await view.findByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
await waitFor(() =>
@@ -695,6 +1127,7 @@ test("Change the model after an Ask failure stops the stack and reaches the prov
test("empty Intelligence projects keep sign-in retryable while Start waits for a project key", async () => {
let projectLists = 0;
invokeHandler = async (command) => {
+ if (command === "prepare_installation") return null;
if (command === "detect_engine") {
return {
engine: "docker",
@@ -763,6 +1196,7 @@ test("empty Intelligence projects keep sign-in retryable while Start waits for a
await view.findByRole("button", { name: "Set up OpenBot" }),
);
await userEvent.click(await view.findByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
await userEvent.click(
@@ -863,6 +1297,7 @@ for (const staleProbe of [false, true]) {
test("saved startup credentials enable Start without raw protected secrets on mount", async () => {
invokeHandler = async (command) => {
+ if (command === "prepare_installation") return null;
if (command === "detect_engine") {
return {
engine: "docker",
@@ -921,6 +1356,7 @@ test("saved startup credentials enable Start without raw protected secrets on mo
await view.findByRole("button", { name: "Set up OpenBot" }),
);
await userEvent.click(await view.findByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
@@ -939,13 +1375,8 @@ async function chooseModelAfterRootEdit(
view: Awaited<ReturnType<typeof renderApp>>,
apiKey?: string,
) {
- expect(view.getByRole("button", { name: "Start OpenBot" })).toHaveProperty(
- "disabled",
- true,
- );
- await userEvent.click(
- view.getByRole("button", { name: "Change AI connection" }),
- );
+ expect(view.queryByRole("button", { name: "Start OpenBot" })).toBeNull();
+ await completeInstallation(view);
await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
if (apiKey)
await userEvent.type(view.getByLabelText("OpenAI API key"), apiKey);
@@ -976,6 +1407,7 @@ test("root edits reload saved configuration for that root and ignore stale saved
await view.findByRole("button", { name: "Set up OpenBot" }),
);
await userEvent.click(await view.findByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
expect(view.getByText(/A saved OpenAI API key will be used/)).toBeTruthy();
await userEvent.click(view.getByRole("button", { name: "Continue" }));
@@ -986,6 +1418,9 @@ test("root edits reload saved configuration for that root and ignore stale saved
),
);
+ await userEvent.click(
+ view.getByRole("button", { name: "Change installation" }),
+ );
const rootField = view.getByLabelText("Where OpenBot lives");
const user = userEvent.setup({
document: view.container.ownerDocument,
@@ -1001,10 +1436,9 @@ test("root edits reload saved configuration for that root and ignore stale saved
invokeCalls.filter((call) => call.command === "already_configured"),
).toContainEqual({ command: "already_configured", args: { root: rootB } }),
);
- expect(view.getByRole("button", { name: "Start OpenBot" })).toHaveProperty(
- "disabled",
- true,
- );
+ expect(
+ view.queryByRole("button", { name: "Continue to sign in" }),
+ ).toBeNull();
await user.clear(rootField);
await user.type(rootField, rootC);
@@ -1020,10 +1454,9 @@ test("root edits reload saved configuration for that root and ignore stale saved
await act(async () => {
emptyForRootB.resolve(emptyConfiguration());
});
- expect(view.getByRole("button", { name: "Start OpenBot" })).toHaveProperty(
- "disabled",
- true,
- );
+ expect(
+ view.queryByRole("button", { name: "Continue to sign in" }),
+ ).toBeNull();
await act(async () => {
savedForRootC.resolve(savedOpenAiConfiguration());
@@ -1066,12 +1499,13 @@ test("same-process setup remount prefers the retained selected root", async () =
await view.findByRole("button", { name: "Set up OpenBot" }),
);
await userEvent.click(await view.findByRole("button", { name: "Continue" }));
- await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
- await userEvent.click(view.getByRole("button", { name: "Continue" }));
expect(view.getByLabelText("Where OpenBot lives")).toHaveProperty(
"value",
rootB,
);
+ await completeInstallation(view);
+ await userEvent.click(await view.findByRole("radio", { name: /OpenAI/ }));
+ await userEvent.click(view.getByRole("button", { name: "Continue" }));
await userEvent.click(
await view.findByRole("button", { name: "Start OpenBot" }),
);
@@ -1123,6 +1557,7 @@ test.each([
await view.findByRole("button", { name: "Set up OpenBot" }),
);
await user.click(await view.findByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
await user.click(await view.findByRole("radio", { name: /OpenAI/ }));
expect(
Boolean(view.queryByText(/A saved OpenAI API key will be used/)),
@@ -1134,15 +1569,14 @@ test.each([
);
}
await user.click(view.getByRole("button", { name: "Continue" }));
- await user.click(view.getByText("Point at your own Intelligence server"));
+ const previousStart = view.getByRole("button", { name: "Start OpenBot" });
+ expect(previousStart).toHaveProperty("disabled", !savedModel);
+ await user.click(view.getByRole("button", { name: "Change installation" }));
const rootField = view.getByLabelText("Where OpenBot lives");
- const startButton = view.getByRole("button", { name: "Start OpenBot" });
- expect(startButton).toHaveProperty("disabled", !savedModel);
await user.clear(rootField);
await user.type(rootField, rootB);
if (pendingRoot === "b") {
- // Start a new load on blur, then edit again while that load is pending.
await act(async () => rootField.blur());
}
if (currentRoot !== rootB) {
@@ -1153,33 +1587,22 @@ test.each([
expect(pending.root).toBe(`/tmp/openbot-root-${pendingRoot}`);
const requestCountBeforeBlur = requests.length;
- function expectClearedState() {
+ function expectBlockedSetup() {
expect(rootField).toHaveProperty("value", currentRoot);
expect(view.container.ownerDocument.activeElement === rootField).toBe(
true,
);
expect(
- view.queryByText(
- /Connected to CopilotKit|A saved CopilotKit connection/,
- ),
+ view.queryByRole("button", { name: "Continue to sign in" }),
).toBeNull();
- expect(view.getByLabelText("Project key")).toHaveProperty("value", "");
- expect(view.getByLabelText("API URL")).toHaveProperty(
- "value",
- "https://api.intelligence.copilotkit.ai",
- );
- expect(view.getByLabelText("Gateway WebSocket URL")).toHaveProperty(
- "value",
- "wss://realtime.intelligence.copilotkit.ai",
- );
- expect(startButton).toHaveProperty("disabled", true);
+ expect(view.queryByRole("button", { name: "Start OpenBot" })).toBeNull();
expect(requests).toHaveLength(requestCountBeforeBlur);
expect(invokeCalls.some((call) => call.command === "start_stack")).toBe(
false,
);
}
- expectClearedState();
+ expectBlockedSetup();
await act(async () =>
pending.response.resolve({
...savedOpenAiConfiguration(),
@@ -1190,10 +1613,10 @@ test.each([
},
}),
);
- expectClearedState();
+ expectBlockedSetup();
- // Intelligence alone cannot restore readiness for a saved model cleared by the edit.
if (savedModel) {
+ // A different root's Intelligence connection cannot restore the model cleared by an edit.
await act(async () => rootField.blur());
await act(async () =>
requests[requests.length - 1].response.resolve({
@@ -1201,17 +1624,22 @@ test.each([
saved: { ...emptyConfiguration().saved, intelligenceApiKey: true },
}),
);
+ await completeInstallation(view);
+ await user.click(await view.findByRole("radio", { name: /OpenAI/ }));
expect(
- view.getByText(
- "A saved CopilotKit connection will be checked when you start.",
- ),
- ).toBeTruthy();
- expect(startButton).toHaveProperty("disabled", true);
- await user.click(rootField);
+ view.queryByText(/A saved OpenAI API key will be used/),
+ ).toBeNull();
+ expect(view.getByRole("button", { name: "Continue" })).toHaveProperty(
+ "disabled",
+ true,
+ );
+ await user.click(view.getByRole("button", { name: "Back" }));
+ await user.click(view.getByLabelText("Where OpenBot lives"));
+ await act(async () => view.getByLabelText("Where OpenBot lives").blur());
+ } else {
+ await act(async () => rootField.blur());
}
- await act(async () => rootField.blur());
expect(requests[requests.length - 1].root).toBe(currentRoot);
- expect(startButton).toHaveProperty("disabled", true);
await act(async () =>
requests[requests.length - 1].response.resolve({
...savedOpenAiConfiguration(),
@@ -1221,14 +1649,29 @@ test.each([
},
}),
);
+ if (savedModel) {
+ await user.click(
+ view.getByRole("button", { name: "Continue to sign in" }),
+ );
+ await user.click(await view.findByRole("radio", { name: /OpenAI/ }));
+ await user.click(view.getByRole("button", { name: "Continue" }));
+ } else {
+ await chooseModelAfterRootEdit(view, "sk-synthetic-current-model");
+ }
expect(
view.getByText(
"A saved CopilotKit connection will be checked when you start.",
),
).toBeTruthy();
- await chooseModelAfterRootEdit(
- view,
- savedModel ? undefined : "sk-synthetic-current-model",
+ await user.click(view.getByText("Point at your own Intelligence server"));
+ expect(view.getByLabelText("Project key")).toHaveProperty("value", "");
+ expect(view.getByLabelText("API URL")).toHaveProperty(
+ "value",
+ "https://current.example/api",
+ );
+ expect(view.getByLabelText("Gateway WebSocket URL")).toHaveProperty(
+ "value",
+ "wss://current.example/ws",
);
const currentStart = view.getByRole("button", { name: "Start OpenBot" });
expect(currentStart).toHaveProperty("disabled", false);
@@ -1255,6 +1698,7 @@ test.each([
function useBringYourOwnHarnessSetup() {
invokeHandler = async (command) => {
+ if (command === "prepare_installation") return null;
if (command === "detect_engine") {
return {
engine: "docker",
@@ -1315,7 +1759,6 @@ function useBringYourOwnHarnessSetup() {
},
];
}
- if (command === "prepare_engine") return null;
if (command === "start_stack") return null;
throw new Error(`unexpected command ${command}`);
};
@@ -1382,6 +1825,7 @@ test.each([
const continueFromHarness = view.getByRole("button", { name: "Continue" });
expect(continueFromHarness).toHaveProperty("disabled", false);
await userEvent.click(continueFromHarness);
+ await completeInstallation(view);
expect(
await view.findByRole("heading", { name: "Connect your AI" }),
).toBeTruthy();
@@ -1501,6 +1945,7 @@ test("saved compatible endpoint restores the optional container URL", async () =
const view = await renderApp();
await userEvent.click(view.getByRole("button", { name: "Set up OpenBot" }));
await userEvent.click(view.getByRole("button", { name: "Continue" }));
+ await completeInstallation(view);
expect(
view.getByLabelText("Container Base URL, if different"),
@@ -1583,6 +2028,7 @@ for (const provider of [
await userEvent.click(
await view.findByRole("button", { name: "Continue" }),
);
+ await completeInstallation(view);
await userEvent.click(
await view.findByRole("radio", { name: new RegExp(provider.name) }),
);
@@ -1633,6 +2079,7 @@ for (const provider of [
test(`saved ${provider.name} plan session enables Start without raw protected secrets on mount`, async () => {
invokeHandler = async (command) => {
+ if (command === "prepare_installation") return null;
if (command === "detect_engine") {
return {
engine: "docker",
@@ -1685,7 +2132,6 @@ for (const provider of [
},
];
}
- if (command === "prepare_engine") return null;
if (command === "start_stack") return null;
throw new Error(`unexpected command ${command}`);
};
@@ -1698,6 +2144,7 @@ for (const provider of [
await userEvent.click(
await view.findByRole("button", { name: "Continue" }),
);
+ await completeInstallation(view);
await userEvent.click(
await view.findByRole("radio", { name: new RegExp(provider.name) }),
);
@@ -1779,6 +2226,7 @@ for (const provider of [
await userEvent.click(
await view.findByRole("button", { name: "Continue" }),
);
+ await completeInstallation(view);
await userEvent.click(
await view.findByRole("radio", { name: new RegExp(provider.name) }),
);
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 39ff0fcc..d2e65256 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -7,20 +7,21 @@ import {
type HarnessChoice,
HarnessPicker,
} from "./HarnessPicker";
+import { isHttpEndpointUrl } from "./http-endpoint-url";
import { asProblem, Failure, type Problem } from "./Problem";
import {
type HeldConfiguration,
type ModelChoice,
ProviderPicker,
+ recordedModel,
} from "./ProviderPicker";
-import { Welcome } from "./Welcome";
-import { isHttpEndpointUrl } from "./http-endpoint-url";
import {
harnessChoiceEvent,
modelChoiceEvent,
recordSetupEvent,
type SetupStep,
} from "./telemetry";
+import { Welcome } from "./Welcome";
type EngineStatus = {
engine: "docker" | "podman" | null;
@@ -41,8 +42,17 @@ type Progress = { step: string; ok: boolean; detail: string };
type AlreadyConfigured = {
values: Record<string, string>;
saved: NonNullable<HeldConfiguration["saved"]>;
+ launch?: { harness: HarnessChoice | null } | null;
};
+function installationKeyFor(root: string, harness: HarnessChoice | null) {
+ return JSON.stringify([
+ root.trim(),
+ harness?.id ?? DEFAULT_HARNESS,
+ harness?.agentUrl?.trim() ?? "",
+ ]);
+}
+
const MANAGED_INTELLIGENCE_API_URL = "https://api.intelligence.copilotkit.ai";
const MANAGED_INTELLIGENCE_GATEWAY_WS_URL =
"wss://realtime.intelligence.copilotkit.ai";
@@ -56,10 +66,6 @@ const MANAGED_INTELLIGENCE_GATEWAY_WS_URL =
*/
const SUGGESTED_QUESTION = "What is 17 times 23?";
-/**
- * One screen, four states: something is in the way, nothing is set up yet, it is working, it is
- * running. A wizard with more screens than states is a wizard that asks twice.
- */
export function App() {
const [engine, setEngine] = useState<EngineStatus | null>(null);
const [blocker, setBlocker] = useState<Blocker | null>(null);
@@ -140,9 +146,24 @@ export function App() {
const [wsUrl, setWsUrl] = useState(MANAGED_INTELLIGENCE_GATEWAY_WS_URL);
const [steps, setSteps] = useState<Progress[]>([]);
const [busy, setBusy] = useState(false);
+ const [resuming, setResuming] = useState(false);
+ const [checkingResume, setCheckingResume] = useState(true);
+ const [preparation, setPreparation] = useState<{
+ key: string;
+ status: "preparing" | "complete" | "failed";
+ } | null>(null);
+ const installationKey = installationKeyFor(root, harness);
+ const installationReady =
+ preparation?.key === installationKey && preparation.status === "complete";
const [running, setRunning] = useState(false);
const visibleSetupStep =
- blockerFailure || blocker || (running && step !== "ask") ? null : step;
+ checkingResume ||
+ resuming ||
+ blockerFailure ||
+ blocker ||
+ (running && step !== "ask")
+ ? null
+ : step;
const lastViewedStep = useRef<SetupStep | null>(null);
useEffect(() => {
if (visibleSetupStep === lastViewedStep.current) return;
@@ -209,16 +230,18 @@ export function App() {
clearRootScopedSavedState();
if (!trimmedRoot) return;
try {
- const { values, saved } = await invoke<AlreadyConfigured>(
+ const configured = await invoke<AlreadyConfigured>(
"already_configured",
{ root: trimmedRoot },
);
if (configuredRunRef.current !== run) return;
+ const { values, saved } = configured;
if (values.INTELLIGENCE_API_KEY) setApiKey(values.INTELLIGENCE_API_KEY);
if (values.INTELLIGENCE_API_URL) setApiUrl(values.INTELLIGENCE_API_URL);
if (values.INTELLIGENCE_GATEWAY_WS_URL)
setWsUrl(values.INTELLIGENCE_GATEWAY_WS_URL);
setAlreadyHeld({ ...values, saved });
+ return configured;
} catch {
if (configuredRunRef.current === run) {
setAlreadyHeld({});
@@ -229,15 +252,43 @@ export function App() {
);
useEffect(() => {
+ let active = true;
invoke<EngineStatus>("detect_engine")
.then(setEngine)
.catch(() => undefined);
+ const windowsReady = invoke<Blocker | null>("windows_blocker")
+ .then(async (found) => {
+ setBlocker(found);
+ if (found) {
+ setInstruction(
+ await invoke<string>("windows_blocker_instruction", {
+ blocker: found,
+ }),
+ );
+ }
+ return found === null;
+ })
+ .catch((error) => {
+ setBlockerFailure(asProblem(error));
+ return false;
+ });
+ // A supervisor that stopped retrying must stay stopped when it returns to this window.
+ const interruptedRun = invoke<Problem | null>("last_failure")
+ .then((found) => {
+ if (found) setRecoveryFailure(found);
+ return found;
+ })
+ .catch(() => null);
Promise.all([
invoke<string | null>("selected_root").catch(() => null),
invoke<string>("default_root"),
+ windowsReady,
+ interruptedRun,
])
- .then(async ([selected, fallback]) => {
+ .then(async ([selected, fallback, canResume, interrupted]) => {
+ if (!active) return;
const found = selected || fallback;
+ if (!selected) setCheckingResume(false);
setRoot(found);
/*
* Arrive filled in when a previous run already wrote these.
@@ -246,7 +297,8 @@ export function App() {
* a dotfile in a text editor — the exact thing this product exists not to require. Their own
* file, read back to them on their own machine.
*/
- loadConfiguredRoot(found);
+ const configured = await loadConfiguredRoot(found);
+ if (!active) return;
// A stack this app started may still be up from a previous window. Ask, rather than
// offering to set up something that is already running.
if (
@@ -257,29 +309,56 @@ export function App() {
// Already up from a previous window: show it, rather than a screen about it.
await invoke("show_openbot");
setRunning(true);
+ return;
}
- })
- .catch(() => undefined);
- invoke<Blocker | null>("windows_blocker")
- .then(async (found) => {
- setBlocker(found);
- if (found) {
- setInstruction(
- await invoke<string>("windows_blocker_instruction", {
- blocker: found,
- }),
- );
+ if (!active || !canResume || interrupted || !configured?.launch) return;
+ const resumedModel = recordedModel({
+ ...configured.values,
+ saved: configured.saved,
+ });
+ if (!resumedModel) return;
+ const resumedHarness = configured.launch.harness;
+ setHarness(resumedHarness);
+ setModel(resumedModel);
+ setPreparation({
+ key: installationKeyFor(found, resumedHarness),
+ status: "complete",
+ });
+ setStep("connect");
+ setBusy(true);
+ setResuming(true);
+ try {
+ // Only a successful previous setup supplies launch intent. Reopening uses its saved
+ // connections and already installed assets; the native start still validates both.
+ await invoke("start_stack", {
+ root: found,
+ apiKey: "",
+ apiUrl:
+ configured.values.INTELLIGENCE_API_URL ||
+ MANAGED_INTELLIGENCE_API_URL,
+ gatewayWsUrl:
+ configured.values.INTELLIGENCE_GATEWAY_WS_URL ||
+ MANAGED_INTELLIGENCE_GATEWAY_WS_URL,
+ model: resumedModel,
+ harness: resumedHarness,
+ });
+ if (!active) return;
+ setRunning(true);
+ setRecoveryFailure(null);
+ await invoke("show_openbot");
+ } catch (error) {
+ if (active) setRecoveryFailure(asProblem(error));
+ } finally {
+ if (active) {
+ setBusy(false);
+ setResuming(false);
+ }
}
})
- .catch((error) => setBlockerFailure(asProblem(error)));
- // Why the stack stopped, if it did while this screen was not loaded. The supervisor gives up
- // and sends the window back here, and without this the person arrives at a setup screen with
- // no indication that anything happened.
- invoke<Problem | null>("last_failure")
- .then((found) => {
- if (found) setRecoveryFailure(found);
- })
- .catch(() => undefined);
+ .catch(() => undefined)
+ .finally(() => {
+ if (active) setCheckingResume(false);
+ });
const stop = listen<Progress>("setup:progress", (event) => {
// One row per step, updated in place. A step that reports twice is the same step saying
// more, and a list that grows a line each time reads as a log rather than as progress.
@@ -294,18 +373,39 @@ export function App() {
});
});
return () => {
+ active = false;
stop.then((unlisten) => unlisten());
};
}, [loadConfiguredRoot]);
+ async function install() {
+ if (busy || !root.trim()) return;
+ setBusy(true);
+ setFailure(null);
+ setSteps([]);
+ setPreparation({ key: installationKey, status: "preparing" });
+ try {
+ await invoke("prepare_installation", { root: root.trim(), harness });
+ setPreparation({ key: installationKey, status: "complete" });
+ } catch (error) {
+ setPreparation({ key: installationKey, status: "failed" });
+ setFailure(asProblem(error));
+ } finally {
+ setBusy(false);
+ }
+ }
+
async function start() {
+ if (!installationReady) {
+ setStep("install");
+ return;
+ }
setBusy(true);
setFailure(null);
setSteps([]);
try {
- await invoke("prepare_engine");
await invoke("start_stack", {
- root,
+ root: root.trim(),
apiUrl,
gatewayWsUrl: wsUrl,
apiKey,
@@ -405,9 +505,23 @@ export function App() {
);
}
+ if (resuming || checkingResume) {
+ return (
+ <main>
+ <h1>{resuming ? "Starting OpenBot" : "Opening OpenBot"}</h1>
+ <p role="status">
+ {resuming
+ ? "Opening your saved setup…"
+ : "Checking your saved setup…"}
+ </p>
+ <SetupProgress steps={steps} />
+ </main>
+ );
+ }
+
/*
- * Which Bot, then which model, then install. Before this the screen asked for an OpenAI key in a
- * password field, which is the developer-shaped main path the audience rule exists to prevent.
+ * Install local software before showing either sign-in. A completed installation is retained
+ * while somebody changes or retries their connection; changing its folder or Bot invalidates it.
*
* Skipped entirely when a stack is already up: somebody returning to a running OpenBot is not
* setting one up, and asking them to pick a Bot again would be the wizard asking twice.
@@ -426,7 +540,16 @@ export function App() {
<main>
<HarnessPicker
chosen={harness}
- onChoose={setHarness}
+ onChoose={(choice) => {
+ if (
+ choice.id !== harness?.id ||
+ choice.agentUrl !== harness?.agentUrl
+ ) {
+ setPreparation(null);
+ setSteps([]);
+ }
+ setHarness(choice);
+ }}
onContinue={() => {
recordSetupEvent(
harnessChoiceEvent(harness?.id ?? DEFAULT_HARNESS),
@@ -436,7 +559,7 @@ export function App() {
? { ...choice, agentUrl: choice.agentUrl?.trim() }
: choice,
);
- setStep("model");
+ setStep("install");
}}
onBack={() => setStep("welcome")}
/>
@@ -444,6 +567,89 @@ export function App() {
);
}
+ if (!running && step === "install") {
+ return (
+ <main>
+ <div className="sheet">
+ <p className="steps-of">Step 2 of 4</p>
+ <h1>
+ {installationReady ? "Installation complete" : "Install OpenBot"}
+ </h1>
+ <p className="lede">
+ {installationReady
+ ? "OpenBot’s local software is ready. Next, connect your AI and CopilotKit accounts."
+ : "Install the software OpenBot needs on this computer. This can take a few minutes. You’ll sign in after installation finishes."}
+ </p>
+ {!installationReady && engine?.responding && (
+ <p className="footnote">
+ Using {engine.engine === "docker" ? "Docker" : "Podman"} for local
+ services.
+ </p>
+ )}
+ <div className="field">
+ <label htmlFor="root">Where OpenBot lives</label>
+ <input
+ id="root"
+ disabled={busy}
+ value={root}
+ onChange={(event) => {
+ configuredRunRef.current += 1;
+ setRoot(event.target.value);
+ setModel(null);
+ setPreparation(null);
+ setSteps([]);
+ clearRootScopedSavedState();
+ }}
+ onBlur={(event) => loadConfiguredRoot(event.target.value)}
+ spellCheck={false}
+ />
+ </div>
+ <SetupProgress steps={steps} />
+ {displayedFailure && <Failure problem={displayedFailure} />}
+ {busy && <p role="status">Installing local software…</p>}
+ {installationReady && (
+ <button type="button" className="quiet" onClick={install}>
+ Repair installation
+ </button>
+ )}
+ <div className="row">
+ <button
+ type="button"
+ className="quiet"
+ disabled={busy}
+ onClick={() => setStep("harness")}
+ >
+ Back
+ </button>
+ {installationReady ? (
+ <button
+ type="button"
+ onClick={() => {
+ setSteps([]);
+ setStep("model");
+ }}
+ >
+ Continue to sign in
+ </button>
+ ) : (
+ <button
+ type="button"
+ disabled={busy || !root.trim()}
+ onClick={install}
+ >
+ {busy
+ ? "Installing…"
+ : preparation?.status === "failed"
+ ? "Retry installation"
+ : "Install OpenBot"}
+ </button>
+ )}
+ </div>
+ </div>
+ </main>
+ );
+ }
+
/*
* Shown while the stack is running, which every other screen is skipped for. This is the one
* screen that needs a running stack: it is the proof, and there is nothing to ask before there
@@ -479,9 +685,12 @@ export function App() {
onChoose={(choice) => {
recordSetupEvent(modelChoiceEvent(choice));
setModel(choice);
+ setStep("connect");
+ }}
+ onBack={() => {
+ setSteps([]);
setStep("install");
}}
- onBack={() => setStep("harness")}
/>
</main>
);
@@ -492,26 +701,16 @@ export function App() {
{/* A failure outranks `running`. The supervisor gives up on a process and sends the window
back here, and a heading that still says everything is running while the box underneath
names the process that stopped is a screen arguing with itself. */}
+ {!running && <p className="steps-of">Step 4 of 4</p>}
<h1>
- {running && !displayedFailure ? "OpenBot is running" : "Set up OpenBot"}
+ {running && !displayedFailure
+ ? "OpenBot is running"
+ : "Connect to CopilotKit"}
</h1>
<p className="lede">
{running && !displayedFailure
? "The stack is up. OpenBot is in this window; the menu bar has it too, and stops it."
- : engine?.responding
- ? `Using ${engine.engine === "docker" ? "Docker" : "Podman"}. It is answering, so nothing needs installing.`
- : /* Two states, and only one of them is somebody's to act on.
-
- An engine that is there but not running is theirs: the backend says "podman is
- installed but not answering", and that is the sentence to show. Repeating a fixed
- one here threw that away and told somebody with Podman 6.1.1 on their PATH to go
- and install Podman, which was the one thing they had already done.
-
- No engine at all is ours. Start installs one, so this says so rather than sending
- somebody to a download page they were never going to read. */
- engine?.engine
- ? engine.detail
- : "OpenBot needs one more piece of software to run, and installs it for you. Press Start."}
+ : "Local installation is complete. Connect CopilotKit, then start OpenBot."}
</p>
{!running && (
@@ -622,23 +821,6 @@ export function App() {
Use a saved connection
</button>
)}
- <div className="field">
- <label htmlFor="root">Where OpenBot lives</label>
- <input
- id="root"
- disabled={busy}
- value={root}
- onChange={(event) => {
- // Invalidate pending loads before blur starts one for this edit.
- configuredRunRef.current += 1;
- setRoot(event.target.value);
- setModel(null);
- clearRootScopedSavedState();
- }}
- onBlur={(event) => loadConfiguredRoot(event.target.value)}
- spellCheck={false}
- />
- </div>
{/*
This used to be headed "Self-hosted Intelligence" over two fields pre-filled with the
MANAGED service's addresses, which says the opposite of what it does: somebody opening
@@ -685,19 +867,7 @@ export function App() {
</fieldset>
)}
- {steps.length > 0 && (
- <div className="steps">
- {steps.map((step) => (
- <div className="step" key={step.step}>
- <span className={`mark ${step.ok ? "good" : "bad"}`}>
- {step.ok ? "✓" : "✗"}
- </span>
- <span>{label(step.step)}</span>
- <span className="detail">{step.detail}</span>
- </div>
- ))}
- </div>
- )}
+ <SetupProgress steps={steps} />
{displayedFailure && <Failure problem={displayedFailure} />}
@@ -705,7 +875,21 @@ export function App() {
<button
type="button"
className="quiet"
- disabled={busy}
+ disabled={busy || signingIn}
+ onClick={() => {
+ setPreparation(null);
+ setSteps([]);
+ setStep("install");
+ }}
+ >
+ Change installation
+ </button>
+ )}
+ {!running && (
+ <button
+ type="button"
+ className="quiet"
+ disabled={busy || signingIn}
onClick={() => setStep("model")}
>
Change AI connection
@@ -750,6 +934,7 @@ export function App() {
// answered at all, not that some field on this screen is non-empty.
disabled={
busy ||
+ !installationReady ||
(apiKey.trim() === "" &&
!alreadyHeld.saved?.intelligenceApiKey &&
!reuseIntelligence) ||
@@ -765,6 +950,23 @@ export function App() {
);
}
+function SetupProgress({ steps }: { steps: Progress[] }) {
+ if (steps.length === 0) return null;
+ return (
+ <div className="steps" aria-live="polite">
+ {steps.map((step) => (
+ <div className="step" key={step.step}>
+ <span className={`mark ${step.ok ? "good" : "bad"}`}>
+ {step.ok ? "✓" : "✗"}
+ </span>
+ <span>{label(step.step)}</span>
+ <span className="detail">{step.detail}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
function titleFor(blocker: Blocker): string {
switch (blocker) {
case "wsl-absent":
@@ -798,6 +1000,10 @@ function label(step: string): string {
return "Ports";
case "dependencies":
return "Dependencies";
+ case "images":
+ return "Local software";
+ case "installation":
+ return "Installation";
case "answering":
return "Answering";
case "services":
diff --git a/desktop/src/HarnessPicker.tsx b/desktop/src/HarnessPicker.tsx
index f42a85bc..7fb430b5 100644
--- a/desktop/src/HarnessPicker.tsx
+++ b/desktop/src/HarnessPicker.tsx
@@ -83,7 +83,7 @@ export function HarnessPicker({
return (
<div className="sheet">
- <p className="steps-of">Step 1 of 2</p>
+ <p className="steps-of">Step 1 of 4</p>
<h1>Your first Bot</h1>
{/*
Written to the person who has to act, not about the situation.
@@ -138,7 +138,7 @@ export function HarnessPicker({
<span className="tile-note">No API key needed</span>
)}
{row.credential === "their-endpoint" && (
- <span className="tile-note">Nothing is installed</span>
+ <span className="tile-note">Uses your running agent</span>
)}
</label>
))}
diff --git a/desktop/src/ProviderPicker.tsx b/desktop/src/ProviderPicker.tsx
index 8ca636bf..c5c49052 100644
--- a/desktop/src/ProviderPicker.tsx
+++ b/desktop/src/ProviderPicker.tsx
@@ -57,7 +57,7 @@ export type HeldConfiguration = {
saved?: SavedConfiguration;
};
-function recordedModel(held: HeldConfiguration): ModelChoice | null {
+export function recordedModel(held: HeldConfiguration): ModelChoice | null {
switch (held.saved?.model) {
case "open-ai-api-key":
return { provider: "openai", login: "api-key", saved: true };
@@ -153,9 +153,8 @@ export function ProviderPicker({
/*
* What the sign-in is doing, while it is doing it.
*
- * A plan sign-in runs in a container, so on a first run it installs the engine and boots its
- * machine first, which is minutes. "Starting…" for that long is a hang as far as anybody
- * watching is concerned, so the same steps the setup screen lists are shown here as one line.
+ * Local software is already installed before this screen. A plan sign-in starts its prepared
+ * container, and progress explains what is happening while its browser session opens.
*/
const [progress, setProgress] = useState<string | null>(null);
// A problem, not a string: a sign-in failure carries the container's own output, and
@@ -326,7 +325,7 @@ export function ProviderPicker({
return (
<div className="sheet">
- <p className="steps-of">Step 2 of 2</p>
+ <p className="steps-of">Step 3 of 4</p>
<h1>Connect your AI</h1>
<p className="lede">
Sign in to the plan you already pay for. No key needed.
diff --git a/desktop/src/Welcome.tsx b/desktop/src/Welcome.tsx
index 3037c061..054c1d34 100644
--- a/desktop/src/Welcome.tsx
+++ b/desktop/src/Welcome.tsx
@@ -23,8 +23,8 @@ export function Welcome({ onStart }: { onStart: () => void }) {
</button>
</div>
<p className="footnote">
- Takes a few minutes. OpenBot installs what it needs and asks you to sign
- in to the AI plan you already have.
+ Takes a few minutes. OpenBot installs what it needs first, then asks you
+ to sign in to the AI plan you already have.
</p>
</div>
);
diff --git a/desktop/src/telemetry.ts b/desktop/src/telemetry.ts
index 8af42614..3b6e98fb 100644
--- a/desktop/src/telemetry.ts
+++ b/desktop/src/telemetry.ts
@@ -1,7 +1,13 @@
import { invoke } from "@tauri-apps/api/core";
import type { ModelChoice } from "./ProviderPicker";
-export type SetupStep = "welcome" | "harness" | "model" | "install" | "ask";
+export type SetupStep =
+ | "welcome"
+ | "harness"
+ | "install"
+ | "model"
+ | "connect"
+ | "ask";
const HARNESSES = {
crewai: "crewai",