Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(handoff): request card, folded row, connect suggestion and viewer pill

milind-soni27d5baab89cb
diff --git a/src/components/AskCard.tsx b/src/components/AskCard.tsx
index 3fcf536946..05a1ac99aa 100644
--- a/src/components/AskCard.tsx
+++ b/src/components/AskCard.tsx
@@ -27,10 +27,28 @@ export function AskHeader({ asker, line, origin }: { asker: Asker; line: string;
);
}
+/** A card's place row: a small icon chip and what the card is about, such as Browser or Computer. */
+export type AskKicker = { icon: ReactNode; label: string; meta?: ReactNode };
+
+export function AskKickerRow({ kicker }: { kicker: AskKicker }) {
+ return (
+ <div data-ask-kicker="" className="flex min-w-0 items-center gap-2 text-[13px] leading-5">
+ <span aria-hidden="true" className="flex size-5 shrink-0 items-center justify-center rounded-md bg-ink/[0.06] text-ink-secondary ring-[0.5px] ring-inset ring-ink/[0.06] [&>svg]:size-3">
+ {kicker.icon}
+ </span>
+ <span dir="auto" className="min-w-0 truncate font-medium text-ink">{kicker.label}</span>
+ {kicker.meta && <span className="ms-auto shrink-0 text-[12px] tabular-nums text-ink-tertiary">{kicker.meta}</span>}
+ </div>
+ );
+}
+
export function AskCard({
header,
+ kicker,
icon,
title,
+ subtitle,
+ media,
meta,
explanation,
onDismiss,
@@ -44,8 +62,14 @@ export function AskCard({
}: {
/** An AskHeader: who asks, above the question. */
header?: ReactNode;
+ /** The place row above the title; a card with one wears the roomier shell and a semibold title. */
+ kicker?: AskKicker;
icon?: ReactNode;
title: ReactNode;
+ /** One line under the title, in the secondary colour. */
+ subtitle?: ReactNode;
+ /** A picture that runs the card's full width, under the title. */
+ media?: ReactNode;
meta?: ReactNode;
explanation?: ReactNode;
onDismiss?: () => void;
@@ -65,12 +89,15 @@ export function AskCard({
data-tour={tour}
data-ask-card="pending" data-look="ask-card"
onKeyDown={onKeyDown}
- className={cn("w-full max-w-[560px] rounded-[18px] px-4 pb-3.5 pt-3 text-start", stays ? `sticky top-[60px] bottom-[72px] z-10 ${ELEVATED_FLOAT}` : ELEVATED_CARD)}
+ data-shell={kicker ? "kicker" : undefined}
+ className={cn("w-full max-w-[560px] rounded-[18px] text-start", kicker ? "overflow-hidden px-4 pb-4 pt-3.5" : "px-4 pb-3.5 pt-3",
+ stays ? `sticky top-[60px] bottom-[72px] z-10 ${ELEVATED_FLOAT}` : ELEVATED_CARD)}
>
{header && <div className="mb-1.5 pe-6">{header}</div>}
+ {kicker && <div className="mb-2"><AskKickerRow kicker={kicker} /></div>}
<div className="flex min-w-0 items-start gap-2">
{icon && <span aria-hidden="true" className="mt-[3px] flex shrink-0 text-ink-secondary">{icon}</span>}
- <div className="min-w-0 flex-1 break-words text-[15px] font-medium leading-[22px] text-ink">
+ <div className={cn("min-w-0 flex-1 break-words text-[15px]", kicker ? "font-semibold" : "font-medium", "leading-[22px] text-ink")}>
<bdi dir="auto">{title}</bdi>
</div>
{meta && <span className="mt-0.5 shrink-0 text-[12px] tabular-nums text-ink-tertiary">{meta}</span>}
@@ -89,7 +116,9 @@ export function AskCard({
</button>
)}
</div>
+ {subtitle && <div dir="auto" className="mt-0.5 break-words text-[14px] leading-5 text-ink-secondary">{subtitle}</div>}
{explanation && <div className="mt-1 text-[14px] leading-5 text-ink-secondary">{explanation}</div>}
+ {media && <div className="-mx-4 mt-4">{media}</div>}
{children && <div className="mt-3">{children}</div>}
{footer && <div className="mt-3 flex flex-wrap items-center justify-end gap-2">{footer}</div>}
</div>
@@ -289,6 +318,9 @@ export function askPrimary(color: MausColor | undefined, shape = ASK_BUTTON_SHAP
return botButton(color, shape, ASK_PRIMARY_LOOK);
}
+/** The one answer a place card waits for (Take over, Connect): the dark pill, whoever asks. */
+export const ASK_DARK_PRIMARY = `${ASK_BUTTON_SHAPE} ${ASK_LOOK} ui-button-primary bg-ink text-app enabled:hover:bg-ink/90`;
+
/** A card's other answers: Deny, Cancel, Not now. */
export const ASK_SECONDARY_BUTTON = `${ASK_BUTTON_SHAPE} ${ASK_LOOK} bg-ink/[0.07] text-ink enabled:hover:bg-ink/[0.11] enabled:active:bg-ink/[0.15]`;
/** An extra option that should not compete with the answer: Always allow, Details. */
diff --git a/src/components/BrowserPanel.tsx b/src/components/BrowserPanel.tsx
index 861f913bc7..44387ece03 100644
--- a/src/components/BrowserPanel.tsx
+++ b/src/components/BrowserPanel.tsx
@@ -10,6 +10,7 @@ import { ExtensionsMenu, extensionsOf, type BrowserExtension } from "./browser/E
import { MoreMenu } from "./browser/MoreMenu";
import { PasskeyNotice } from "./browser/PasskeyNotice";
import { StreamSurface, type StreamSurfaceHandle, type SurfaceConnect } from "./browser/StreamSurface";
+import { BrowserViewerPill } from "./viewer-pill-host";
import { createBrowserControl, startsInteraction, streamTransport, type BrowserControl, type BrowserTakeStatus } from "@/lib/browser-control";
import { resolveAddressBarInput } from "@/lib/browser-address";
import { closeBrowserPictureInPicture, openBrowserPictureInPicture, supportsBrowserPictureInPicture, useBrowserPictureInPicture } from "@/lib/browser-pip";
@@ -27,7 +28,8 @@ const BrowserDesktop = lazy(() => import("./browser/BrowserDesktop").then((modul
const button = "rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink disabled:opacity-40 disabled:cursor-not-allowed";
const NO_NAV: BrowserNav = { url: "", loading: false, canGoBack: false, canGoForward: false };
-export type BrowserSignIn = { url: string; site: string; nonce: number };
+/** `expand`: open the browser full size, as a handoff's Take over does. */
+export type BrowserSignIn = { url: string; site: string; nonce: number; expand?: boolean };
/** A page to open in a new tab once the view is connected and awake: a published page's Open (usePageOpener). */
export type BrowserPage = { url: string; nonce: number };
@@ -237,7 +239,8 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
return;
}
signInHandled.current = signIn.nonce;
- signInPage.current = signIn.url;
+ signInPage.current = signIn.url || null;
+ if (signIn.expand) setMaximized(true);
latest.current.takeControl();
latest.current.openSignInPage();
}, [signIn, connected, asleep]);
@@ -452,6 +455,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
</div>
) : null}
</div>
+ {maximized && <BrowserViewerPill bot={bot} you={you} pending={takeStatus === "pending" || takeStatus === "slow"} onTake={takeControl} onStop={handBack} onCollapse={() => setMaximized(false)} />}
<dialog ref={profilesDialog} onClose={() => setShowProfiles(false)} onClick={(e) => { if (e.target === e.currentTarget) setShowProfiles(false); }} className="m-auto w-[min(420px,calc(100%-32px))] max-h-[80vh] overflow-auto rounded-2xl border border-hairline/50 bg-card p-5 text-ink shadow-2xl backdrop:bg-black/40">
<div className="mb-4 flex items-center justify-between"><h2 className="text-[15px] font-medium">{t("browser.panel.profiles")}</h2><button className={button} aria-label={t("browser.panel.closeProfiles")} onClick={() => setShowProfiles(false)}><X size={16} /></button></div>
{(heldElsewhere || (you && takeStatus !== "")) && <p className="mb-3 text-[12px] text-ink-secondary">{t(heldElsewhere ? "browser.profiles.heldElsewhere" : "browser.profiles.busy")}</p>}
diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsx
index b5f3dbfe1b..effaa0e536 100644
--- a/src/components/ComputerPanel.tsx
+++ b/src/components/ComputerPanel.tsx
@@ -26,7 +26,7 @@ import { useDesktopCapabilities } from "./DesktopCapabilities";
import { RoutinesSection } from "./bot-settings/RoutinesSection";
import { routineRunLabel, routineRunTone } from "@/lib/routine-display";
import { AndroidDevicePanel, useAndroidUsbDevices } from "./AndroidDevicePanel";
-import { BrowserPanel } from "./BrowserPanel";
+import { BrowserPanel, type BrowserSignIn } from "./BrowserPanel";
import { usePanelPage, type PanelPage } from "@/lib/page-open";
const DataPanel = lazy(() => import("./data/DataPanel").then((module) => ({ default: module.DataPanel })));
const loadLiveDesktop = () => import("./LiveDesktop").then((module) => ({ default: module.LiveDesktop }));
@@ -322,17 +322,17 @@ export function ComputerPanel({
}, [bot.id, dispatch, requestedDataResult]);
const requestedSignIn = state.signInFocus?.botId === bot.id ? state.signInFocus : undefined;
- const [signInRequest, setSignInRequest] = useState<{ url: string; site: string; nonce: number }>();
+ const [signInRequest, setSignInRequest] = useState<BrowserSignIn>();
+ const takeControlNow = useRef<(expand?: boolean) => Promise<void>>(async () => undefined);
// A published page's Open (usePageOpener): this bot's browser shows, with the page in a new tab.
const [pageRequest, setPageRequest] = useState<PanelPage>();
usePanelPage(bot.id, (page) => { selectPanelView("browser"); setPageRequest(page); });
useEffect(() => {
if (!requestedSignIn || requestedSignIn.consumed) return;
const view = requestedSignIn.place === "browser" ? "browser" : "computer";
- explicitPanelView.current = true;
- setPanelView(view);
- writeComputerPanelView(bot.id, view);
- if (view === "browser") setSignInRequest({ url: requestedSignIn.url, site: requestedSignIn.site, nonce: requestedSignIn.requestId });
+ explicitPanelView.current = true; setPanelView(view); writeComputerPanelView(bot.id, view);
+ if (view === "browser") setSignInRequest({ url: requestedSignIn.url, site: requestedSignIn.site, nonce: requestedSignIn.requestId, ...(requestedSignIn.expand ? { expand: true } : {}) });
+ else if (requestedSignIn.expand) queueMicrotask(() => void takeControlNow.current(true));
dispatch({ type: "signInFocusConsumed", requestId: requestedSignIn.requestId });
}, [bot.id, dispatch, requestedSignIn]);
@@ -899,7 +899,7 @@ export function ComputerPanel({
setControlPending(false);
}
};
-
+ takeControlNow.current = takeControl;
const handBack = async () => {
setError(null);
void window.ogb?.desktopViewer?.close(bot.id);
@@ -1316,7 +1316,7 @@ export function ComputerPanel({
{liveHere && liveTarget ? (
<Suspense fallback={<Loader2 size={18} className="animate-spin text-ink-secondary" />}>
<LiveDesktop
- target={liveTarget} threadId={bot.threadId} name={bot.name} poster={frameSrc}
+ target={liveTarget} threadId={bot.threadId} name={bot.name} poster={frameSrc} botId={bot.id}
expanded={takeover.expanded} onExpandedChange={takeover.setExpanded}
onHandBack={() => void handBack()} handingBack={takeover.handingBack}
onUnreachable={() => { takeover.leave(); setError(new LocalizedPanelError("computer.err.openDesktop")); }}
diff --git a/src/components/HandoffCard.dom.test.ts b/src/components/HandoffCard.dom.test.ts
new file mode 100644
index 0000000000..6b764f5ba3
--- /dev/null
+++ b/src/components/HandoffCard.dom.test.ts
@@ -0,0 +1,152 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { SignInRequestCardData } from "../../shared/wire";
+import { initialState, StoreContext, type AppState, type Bot, type Message } from "@/state/store";
+import { HandoffSuggestion } from "./HandoffSuggestion";
+import { SignInRequestCard } from "./SignInRequestCard";
+import { ViewerPill } from "./ViewerPill";
+
+let container: HTMLDivElement, root: Root;
+let calls: Array<{ url: string; body: unknown }>;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ calls = [];
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ calls.push({ url, body: init?.body ? JSON.parse(String(init.body)) : undefined });
+ const body = url.includes("/api/connectors/catalog") ? { cards: [{ slug: "github", label: "GitHub", blurb: "", logo: null, domain: null }], source: "api", configured: true, mode: "managed" }
+ : url.includes("/api/connectors?") ? { services: { github: { connected: false } } } : url.includes("/saved-logins") ? { choices: [] } : { done: true };
+ return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
+ }));
+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); });
+
+const handoff = (fields: Partial<SignInRequestCardData> = {}): SignInRequestCardData => ({
+ url: "", site: "", place: "browser", instruction: "Solve the check on the page.", need: "captcha", expiresAt: Date.now() + 20 * 60_000, ...fields,
+});
+const row = (id: string, signIn: SignInRequestCardData): Message => ({ id, at: 1, role: "bot", kind: "signin", text: signIn.instruction ?? "", signIn } as Message);
+
+async function show(messages: Message[], index = messages.length - 1) {
+ const dispatch = vi.fn();
+ const bot = { id: "scout", name: "Scout", color: "teal", threadId: "t1", messages, tasks: [] } as unknown as Bot;
+ const state: AppState = { ...initialState, bots: [bot], selectedId: bot.id, connected: true };
+ const value = { state, dispatch, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ await act(async () => root.render(createElement(StoreContext.Provider, { value },
+ createElement(SignInRequestCard, { botId: "scout", botName: "Scout", threadId: "t1", message: messages[index]! }))));
+ await act(async () => { await new Promise((done) => setTimeout(done, 0)); });
+ return dispatch;
+}
+const button = (name: string) => [...container.querySelectorAll("button")].find((one) => one.textContent?.trim() === name);
+
+describe("a step the bot handed to the person", () => {
+ it("shows the place, a title for its kind, the instruction, the live picture and three answers", async () => {
+ await show([row("m1", handoff())]);
+ const card = container.querySelector('[data-shell="kicker"]')!;
+ expect(card.textContent).toContain("Browser");
+ expect(card.textContent).toContain("Human check needed");
+ expect(card.textContent).toContain("Solve the check on the page.");
+ expect(container.querySelector("[data-preview-phase]")?.getAttribute("aria-label")).toBe("Take over Scout's Browser");
+ expect([...card.querySelectorAll("button")].map((one) => one.textContent?.trim()).slice(-3)).toEqual(["Skip", "I'm done", "Take over"]);
+ expect(button("Take over")!.className).toContain("ui-button-primary");
+ });
+
+ it("Take over opens the place full size, on its request", async () => {
+ const dispatch = await show([row("m1", handoff({ place: "cloud" }))]);
+ expect(container.textContent).toContain("Computer");
+ await act(async () => button("Take over")!.click());
+ expect(dispatch).toHaveBeenCalledWith({ type: "openSignIn", botId: "scout", messageId: "m1", url: "", site: "", place: "cloud", expand: true, threadId: "t1" });
+ });
+
+ it("I'm done sends the person's note with the answer", async () => {
+ await show([row("m1", handoff())]);
+ await act(async () => button("Add a note")!.click());
+ const field = container.querySelector<HTMLInputElement>('input[aria-label="Note for Scout"]')!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(field, "Used the work account");
+ field.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => { button("I'm done")!.click(); await new Promise((done) => setTimeout(done, 0)); });
+ expect(calls.find((call) => call.url.endsWith("/sign-in-cards/m1/done"))?.body).toEqual({ threadId: "t1", note: "Used the work account" });
+ });
+
+ it("Skip answers it as cancelled", async () => {
+ await show([row("m1", handoff())]);
+ await act(async () => { button("Skip")!.click(); await new Promise((done) => setTimeout(done, 0)); });
+ expect(calls.some((call) => call.url.endsWith("/sign-in-cards/m1/cancel"))).toBe(true);
+ });
+
+ it("only the newest open request shows the picture", async () => {
+ await show([row("m1", handoff()), row("m2", handoff())], 0);
+ expect(container.querySelector("[data-preview-phase]")).toBeNull();
+ await show([row("m1", handoff()), row("m2", handoff())], 1);
+ expect(container.querySelector("[data-preview-phase]")).not.toBeNull();
+ });
+
+ it.each([
+ [{ done: true, resumed: true }, "Done · Solve the check on the page."],
+ [{ cancelled: true, resumed: true }, "Skipped · Solve the check on the page."],
+ [{ expired: true, resumed: true }, "Expired · Solve the check on the page."],
+ [{ answeredInChat: true }, "Answered in the chat · Solve the check on the page."],
+ ])("folds to one row once answered: %o", async (fields, summary) => {
+ await show([row("m1", handoff(fields))]);
+ expect(container.querySelector('[data-ask-card="settled"]')).not.toBeNull();
+ expect(container.querySelector("[data-handoff-summary]")?.textContent).toBe(summary);
+ expect(button("Take over")).toBeUndefined();
+ });
+
+ it("offers the app a sign-in site belongs to, and not for other kinds", async () => {
+ await show([row("m1", handoff({ need: "sign_in", site: "github.com", url: "https://github.com/" }))]);
+ expect(container.querySelector("[data-handoff-suggestion]")?.textContent).toContain("Connect GitHub so Scout can work with it directly");
+ await show([row("m2", handoff({ need: "captcha", site: "github.com", url: "https://github.com/" }))]);
+ expect(container.querySelector("[data-handoff-suggestion]")).toBeNull();
+ });
+
+ it("leaves a site sign-in without an instruction on its own card", async () => {
+ await show([row("m1", { url: "https://notion.so", site: "notion.so", place: "browser" })]);
+ expect(container.querySelector('[data-shell="kicker"]')).toBeNull();
+ expect(container.textContent).toContain("notion.so");
+ });
+});
+
+describe("the connect suggestion", () => {
+ it("answers the request as done with a note that the app was connected instead", async () => {
+ const bot = { id: "scout", name: "Scout", color: "teal", threadId: "t1", messages: [], tasks: [] } as unknown as Bot;
+ const value = { state: { ...initialState, bots: [bot] }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ await act(async () => root.render(createElement(StoreContext.Provider, { value }, createElement(HandoffSuggestion, {
+ app: { slug: "github", label: "GitHub", blurb: "", logo: null, domain: null }, status: { connected: true },
+ request: { botId: "scout", threadId: "t1", messageId: "m1", place: "browser" }, botName: "Scout",
+ }))));
+ await act(async () => { button("Connect")!.click(); await new Promise((done) => setTimeout(done, 0)); });
+ expect(calls.find((call) => call.url.endsWith("/sign-in-cards/m1/done"))?.body).toEqual({ threadId: "t1", note: "connected GitHub instead" });
+ expect(container.querySelector("[data-handoff-suggestion]")?.getAttribute("data-handoff-suggestion")).toBe("connected");
+ });
+
+ it("can be dismissed", async () => {
+ const value = { state: { ...initialState, bots: [] }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ await act(async () => root.render(createElement(StoreContext.Provider, { value }, createElement(HandoffSuggestion, {
+ app: { slug: "github", label: "GitHub", blurb: "", logo: null, domain: null }, status: { connected: false },
+ request: { botId: "scout", threadId: "t1", messageId: "m9", place: "browser" }, botName: "Scout",
+ }))));
+ await act(async () => container.querySelector<HTMLButtonElement>('button[aria-label="Not now"]')!.click());
+ expect(container.querySelector("[data-handoff-suggestion]")).toBeNull();
+ });
+});
+
+describe("the viewer pill", () => {
+ it.each([
+ ["watching", "Watching", "Take control"],
+ ["control", "You're in control", "Stop"],
+ ["control-request", "You're in control", "I'm done"],
+ ] as const)("%s says %s and offers %s", async (state, status, action) => {
+ const handlers = { onTake: vi.fn(), onStop: vi.fn(), onDone: vi.fn() };
+ await act(async () => root.render(createElement(ViewerPill, { state, ...handlers })));
+ expect(container.querySelector('[role="status"]')?.textContent).toBe(status);
+ await act(async () => button(action)!.click());
+ const pressed = state === "watching" ? handlers.onTake : state === "control" ? handlers.onStop : handlers.onDone;
+ expect(pressed).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/components/HandoffCard.tsx b/src/components/HandoffCard.tsx
new file mode 100644
index 0000000000..e868795280
--- /dev/null
+++ b/src/components/HandoffCard.tsx
@@ -0,0 +1,154 @@
+import { useState, type ReactNode } from "react";
+import { Check, Globe, Hand, Loader2, LockKeyhole, Monitor, RefreshCw } from "lucide-react";
+
+import { HANDOFF_NOTE_MAX } from "../../shared/sign-in-request";
+import type { Surface } from "../../shared/wire";
+import { cn } from "@/lib/cn";
+import { handoffEnd, handoffPlaceLabel, handoffSummary, handoffTitle, newestWaitingHandoff } from "@/lib/handoff";
+import { t } from "@/lib/i18n";
+import { answerSignIn, signInHostIsHere } from "@/lib/sign-in";
+import type { Bot, Message } from "@/state/store";
+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
+import { ASK_DARK_PRIMARY, ASK_QUIET_BUTTON, ASK_SECONDARY_BUTTON, AskCard, AskError, returnFocusToComposer } from "./AskCard";
+import { ELEVATED_CARD } from "./elevated";
+import { HandoffPreview } from "./HandoffPreview";
+import { HandoffSuggestion, useSuggestedApp } from "./HandoffSuggestion";
+
+export const placeIcon = (place: Surface) => place === "browser" ? <Globe /> : <Monitor />;
+
+/** The handed-off step once it ended: one row with the place, how it ended and the step. */
+export function HandoffSettledRow({ place, summary, action, error }: { place: Surface; summary: string; action?: ReactNode; error?: string }) {
+ return (
+ <div role="group" aria-label={handoffPlaceLabel(place)} data-ask-card="settled" data-look="handoff"
+ className={cn("w-full max-w-[560px] rounded-[18px] px-4 py-3 text-start", ELEVATED_CARD)}>
+ <div className="flex min-w-0 items-center gap-2 text-[13px] leading-5">
+ <span aria-hidden="true" className="flex size-5 shrink-0 items-center justify-center rounded-md bg-ink/[0.06] text-ink-secondary ring-[0.5px] ring-inset ring-ink/[0.06] [&>svg]:size-3">
+ {placeIcon(place)}
+ </span>
+ <span className="shrink-0 font-medium text-ink">{handoffPlaceLabel(place)}</span>
+ <span dir="auto" aria-live="polite" title={summary} data-handoff-summary="" className="min-w-0 flex-1 truncate text-ink-tertiary">{summary}</span>
+ {action}
+ </div>
+ {error && <p role="alert" className="ms-7 mt-1 text-[12px] text-danger">{error}</p>}
+ </div>
+ );
+}
+
+/**
+ * A step the bot handed to the person, where it works: what to do, the place live at card width, and Skip, I'm done and
+ * Take over. Take over (or the picture) opens that place full size, already in their control. Once answered it folds to
+ * one row. Security: the person types any password or card number into the page; nothing they type passes through here.
+ */
+export function HandoffCard({ botId, botName, color: _color, threadId, message, showPreview }: {
+ botId: string;
+ botName: string;
+ color?: Bot["color"];
+ threadId: string;
+ message: Message;
+ /** Only the newest open request shows the live picture; by default it is worked out from the bot's messages. */
+ showPreview?: boolean;
+}) {
+ const dispatch = useStoreDispatch();
+ const card = message.signIn!;
+ const newest = useStoreSelector((state) => newestWaitingHandoff(state.bots.find((bot) => bot.id === botId)?.messages ?? []));
+ const end = handoffEnd(card);
+ const suggested = useSuggestedApp(card.need === "sign_in" && !end ? card.site : "", botId);
+ const [pending, setPending] = useState<"done" | "cancel" | null>(null);
+ const [noting, setNoting] = useState(false);
+ const [note, setNote] = useState("");
+ const [explained, setExplained] = useState(false);
+ const [localError, setLocalError] = useState<string | null>(null);
+ const ref = { botId, threadId, messageId: message.id, place: card.place };
+ const instruction = card.instruction ?? "";
+ const placeLabel = handoffPlaceLabel(card.place);
+
+ const answer = async (choice: "done" | "cancel") => {
+ if (pending) return;
+ setPending(choice);
+ setLocalError(null);
+ try {
+ await answerSignIn(ref, choice, note);
+ returnFocusToComposer();
+ } catch {
+ setLocalError(t("handoff.error"));
+ } finally {
+ setPending(null);
+ }
+ };
+
+ if (end) {
+ const error = localError ?? card.error;
+ const retry = (end === "done" || end === "skipped") && !card.resumed && error ? (
+ <button type="button" onClick={() => void answer(end === "done" ? "done" : "cancel")} disabled={pending !== null} className={cn(ASK_QUIET_BUTTON, "text-accent-text")}>
+ {pending ? <Loader2 size={14} className="motion-safe:animate-spin" /> : <RefreshCw size={14} />}
+ {t("signIn.retry")}
+ </button>
+ ) : undefined;
+ return <HandoffSettledRow place={card.place} summary={handoffSummary(end, instruction)} action={retry} error={retry ? error : undefined} />;
+ }
+
+ const takeOver = () => {
+ if (card.place === "local") { setExplained(true); return; }
+ dispatch({ type: "openSignIn", botId, messageId: message.id, url: card.url, site: card.site, place: card.place, expand: true, threadId });
+ };
+ const preview = showPreview ?? (newest === null || newest === message.id);
+ const minutesLeft = card.expiresAt ? Math.max(1, Math.ceil((card.expiresAt - Date.now()) / 60_000)) : null;
+ const here = signInHostIsHere();
+
+ return (
+ <>
+ <AskCard
+ ariaLabel={t("handoff.cardLabel", { name: botName, instruction })}
+ kicker={{ icon: placeIcon(card.place), label: placeLabel, meta: minutesLeft !== null && minutesLeft <= 30 ? t("handoff.minutesLeft", { minutes: minutesLeft }) : undefined }}
+ title={handoffTitle(card.need)}
+ subtitle={<bdi dir="auto">{instruction}</bdi>}
+ media={preview && card.place !== "local" ? (
+ <HandoffPreview botId={botId} threadId={threadId} place={card.place} onOpen={takeOver} disabled={pending !== null}
+ label={t("handoff.previewLabel", { name: botName, place: placeLabel })} />
+ ) : undefined}
+ footer={<>
+ {!noting && (
+ <button type="button" onClick={() => setNoting(true)} className={cn(ASK_QUIET_BUTTON, "me-auto -ms-2")}>{t("handoff.addNote")}</button>
+ )}
+ <button type="button" onClick={() => void answer("cancel")} disabled={pending !== null} aria-busy={pending === "cancel" || undefined}
+ title={t("handoff.skipHint", { name: botName })} className={ASK_SECONDARY_BUTTON}>
+ {pending === "cancel" && <Loader2 size={14} className="motion-safe:animate-spin" />}
+ {t("handoff.skip")}
+ </button>
+ <button type="button" onClick={() => void answer("done")} disabled={pending !== null} aria-busy={pending === "done" || undefined} className={ASK_SECONDARY_BUTTON}>
+ {pending === "done" ? <Loader2 size={14} className="motion-safe:animate-spin" /> : <Check size={14} />}
+ {t("handoff.done")}
+ </button>
+ <button type="button" onClick={takeOver} disabled={pending !== null} className={ASK_DARK_PRIMARY}>
+ <Hand size={14} />
+ {t("handoff.takeOver")}
+ </button>
+ </>}
+ >
+ {noting && (
+ <input
+ dir="auto"
+ autoFocus
+ value={note}
+ maxLength={HANDOFF_NOTE_MAX}
+ onChange={(event) => setNote(event.target.value)}
+ onKeyDown={(event) => { if (event.key === "Escape") { setNoting(false); setNote(""); } }}
+ aria-label={t("handoff.noteLabel", { name: botName })}
+ placeholder={t("handoff.notePlaceholder", { name: botName })}
+ className="h-9 w-full rounded-full bg-ink/[0.045] px-3.5 text-[14px] text-ink outline-none ring-[0.5px] ring-ink/[0.14] placeholder:text-ink-tertiary focus:ring-ink/30"
+ />
+ )}
+ {explained && <p role="note" className="text-[13px] leading-snug text-ink">{t(here ? "signIn.local.explain" : "signIn.local.explainHost", { name: botName })}</p>}
+ {(card.need === "sign_in" || card.need === "payment") && (
+ <p className={cn("flex items-center gap-1 text-[12px] text-ink-tertiary", (noting || explained) && "mt-2")}>
+ <LockKeyhole size={11} aria-hidden="true" /> {t("handoff.private")}
+ </p>
+ )}
+ {localError && <AskError>{localError}</AskError>}
+ </AskCard>
+ {suggested && (
+ <HandoffSuggestion app={suggested.card} status={suggested.status} request={ref} botName={botName} />
+ )}
+ </>
+ );
+}
diff --git a/src/components/HandoffPreview.tsx b/src/components/HandoffPreview.tsx
new file mode 100644
index 0000000000..6108fea95c
--- /dev/null
+++ b/src/components/HandoffPreview.tsx
@@ -0,0 +1,108 @@
+import { useEffect, useRef, useState } from "react";
+import { Hand, Loader2, Monitor } from "lucide-react";
+
+import type { Surface } from "../../shared/wire";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { listenLiveFrames } from "@/lib/live-events";
+import { usePageVisible } from "@/lib/page-visible";
+import { browserStreamAccess, createPreviewFramePainter, createPreviewStreamClient } from "@/lib/browser-stream-client";
+import { browserScope } from "@/lib/team-browser";
+import { api } from "@/state/store";
+import { useStoreSelector } from "@/state/store-select";
+
+/** What the card shows of the place while it waits: the live page, the newest frame, or that it is connecting. */
+export type PreviewPhase = "connecting" | "live" | "frame" | "none";
+
+/**
+ * The place a handoff names, live at the card's width: the bot's browser as a watch-only stream (it neither sizes the
+ * page nor takes control), else the newest screen frame the bot's work sent. The whole picture is the Take over button.
+ */
+export function HandoffPreview({ botId, threadId, place, label, onOpen, disabled = false, still }: {
+ botId: string;
+ threadId: string;
+ place: Surface;
+ /** The button's name for screen readers: what pressing it does. */
+ label: string;
+ onOpen: () => void;
+ disabled?: boolean;
+ /** A fixed picture instead of a live one (previews of the card itself). */
+ still?: string | null;
+}) {
+ const visible = usePageVisible();
+ const streams = useStoreSelector((state) => state.config?.browserEngine?.engine === "chrome");
+ const team = useStoreSelector((state) => state.config?.team);
+ const canvas = useRef<HTMLCanvasElement>(null);
+ const [phase, setPhase] = useState<PreviewPhase>(still ? "frame" : "connecting");
+ const [frame, setFrame] = useState<string | null>(still ?? null);
+ const live = still === undefined && place === "browser" && streams && visible;
+
+ useEffect(() => {
+ if (!live || !canvas.current) return;
+ const painter = createPreviewFramePainter(canvas.current, () => setPhase("live"));
+ const client = createPreviewStreamClient(
+ { access: browserStreamAccess(botId, window.location, browserScope(team, threadId)), maxWidth: 1120, maxHeight: 700, interactive: false },
+ { onFrame: (jpeg) => painter.paint(jpeg), onViewport: () => undefined, onConnectedChange: () => undefined, onUnauthorized: () => setPhase((now) => (now === "live" ? now : "none")) },
+ );
+ return () => { client.stop(); painter.stop(); };
+ }, [live, botId, threadId, team]);
+
+ const seen = useStoreSelector((state) => {
+ const row = state.bots.find((bot) => bot.id === botId)?.messages.findLast((one) => one.kind === "screen" && one.png);
+ return row?.png ? `data:${row.mime ?? "image/png"};base64,${row.png}` : null;
+ });
+ useEffect(() => {
+ if (live || still !== undefined || !seen) return;
+ setFrame((now) => now ?? seen);
+ setPhase((now) => (now === "connecting" || now === "none" ? "frame" : now));
+ }, [live, still, seen]);
+ useEffect(() => {
+ if (live || still !== undefined || place !== "cloud") return;
+ const controller = new AbortController();
+ api(`/api/bots/${encodeURIComponent(botId)}/computer/screenshot?threadId=${encodeURIComponent(threadId)}`, { method: "POST", signal: AbortSignal.any([controller.signal, AbortSignal.timeout(30_000)]) })
+ .then(({ png, format }: { png?: unknown; format?: unknown }) => {
+ if (typeof png !== "string" || !png) return;
+ setFrame(`data:${format === "jpeg" ? "image/jpeg" : "image/png"};base64,${png}`);
+ setPhase("frame");
+ }, () => undefined);
+ return () => controller.abort();
+ }, [live, still, place, botId, threadId]);
+
+ useEffect(() => {
+ if (live || still !== undefined) return;
+ const surface = place === "browser" ? "browser" : "computer";
+ const stop = listenLiveFrames({ screens: true, onFrame: (next) => {
+ if (next.kind !== "screen" || next.botId !== botId || next.threadId !== threadId || (next.surface && next.surface !== surface)) return;
+ setFrame(`data:${next.mime ?? "image/png"};base64,${next.png}`);
+ setPhase("frame");
+ } });
+ const settle = setTimeout(() => setPhase((now) => (now === "connecting" ? "none" : now)), 8_000);
+ return () => { stop(); clearTimeout(settle); };
+ }, [live, still, place, botId, threadId]);
+
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ disabled={disabled}
+ aria-label={label}
+ data-preview-phase={phase}
+ className="group relative block aspect-[16/10] w-full overflow-hidden bg-black text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus disabled:cursor-wait"
+ >
+ {live && <canvas ref={canvas} aria-hidden="true" className={cn("absolute inset-0 h-full w-full object-contain", phase !== "live" && "opacity-0")} />}
+ {!live && frame && <img src={frame} alt="" className="absolute inset-0 h-full w-full object-contain" />}
+ {(phase === "connecting" || phase === "none") && (
+ <span className="absolute inset-0 flex flex-col items-center justify-center gap-2 text-[13px] text-white/70">
+ {phase === "connecting"
+ ? <><Loader2 size={18} aria-hidden="true" className="motion-safe:animate-spin" />{t("handoff.connecting")}</>
+ : <><Monitor size={20} aria-hidden="true" />{t("handoff.noPicture")}</>}
+ </span>
+ )}
+ <span aria-hidden="true" className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-0 transition-[opacity,background-color] duration-[120ms] ease-out group-hover:bg-black/40 group-hover:opacity-100 group-focus-within:bg-black/40 group-focus-within:opacity-100 touch:opacity-100 motion-reduce:transition-none">
+ <span className="inline-flex h-8 items-center gap-1.5 rounded-full bg-black/70 px-3 text-[13px] font-medium text-white">
+ <Hand size={14} />{t("handoff.takeOver")}
+ </span>
+ </span>
+ </button>
+ );
+}
diff --git a/src/components/HandoffSuggestion.tsx b/src/components/HandoffSuggestion.tsx
new file mode 100644
index 0000000000..af0c78dc89
--- /dev/null
+++ b/src/components/HandoffSuggestion.tsx
@@ -0,0 +1,157 @@
+import { useEffect, useRef, useState } from "react";
+import { Check, Copy, Loader2, RefreshCw, X } from "lucide-react";
+
+import { appForSite } from "../../shared/app-sites";
+import type { ComputerHelpRef } from "../../shared/wire";
+import { appSwitchPatch, botAppScope } from "@/lib/bot-app-access";
+import { loadAppCatalog } from "@/lib/app-catalog-cache";
+import { cn } from "@/lib/cn";
+import { copyText } from "@/lib/copy-text";
+import { pollConnector } from "@/lib/connector-poll";
+import { reserveConnectionPage } from "@/lib/connector-oauth";
+import type { ConnectorStatus } from "@/lib/connector-status";
+import { t } from "@/lib/i18n";
+import { mcpSignInLink } from "@/lib/mcp-sign-in";
+import { answerSignIn } from "@/lib/sign-in";
+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
+import { api } from "@/state/store";
+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
+import { ASK_DARK_PRIMARY, ASK_QUIET_BUTTON } from "./AskCard";
+import { ELEVATED_CARD } from "./elevated";
+import { ServiceIcon, type ToolkitCard } from "./ServiceIcon";
+
+/** Where the suggestion's Connect stands. */
+export type SuggestionPhase = "checking" | "ready" | "starting" | "waiting" | "stalled" | "failed" | "blocked" | "connected";
+
+const dismissedKey = (messageId: string) => `openmausbot.handoff-suggestion.${messageId}`;
+function dismissedBefore(messageId: string): boolean {
+ try { return sessionStorage.getItem(dismissedKey(messageId)) === "1"; } catch { return false; }
+}
+function rememberDismissed(messageId: string): void {
+ try { sessionStorage.setItem(dismissedKey(messageId), "1"); } catch { /* no storage: dismissed for this view only */ }
+}
+
+const readStatus = (slug: string): Promise<ConnectorStatus | undefined> =>
+ api(`/api/connectors?services=${encodeURIComponent(slug)}`).then((r: { services?: Record<string, ConnectorStatus> }) => r.services?.[slug]);
+
+/** The app a waiting sign-in could use instead, once the catalogue lists it and the bot does not have it yet. */
+export function useSuggestedApp(site: string, botId: string): { card: ToolkitCard; status: ConnectorStatus | undefined } | null {
+ const slug = appForSite(site);
+ const bot = useStoreSelector((state) => state.bots.find((one) => one.id === botId));
+ const [found, setFound] = useState<{ card: ToolkitCard; status: ConnectorStatus | undefined } | null>(null);
+ useEffect(() => {
+ if (!slug) return;
+ let live = true;
+ void loadAppCatalog().then(async (catalog) => {
+ const card = catalog.mode === "unavailable" ? undefined : catalog.cards.find((one) => one.slug === slug && !one.noAuth);
+ if (!card) return;
+ const status = await readStatus(slug).catch(() => undefined);
+ if (live) setFound({ card, status });
+ }, () => undefined);
+ return () => { live = false; };
+ }, [slug]);
+ if (!slug || found?.card.slug !== slug || !bot) return null;
+ return found.status?.connected && botAppScope(bot, found.card.slug) !== null ? null : found;
+}
+
+/**
+ * Under a sign-in the bot asked for, when the site is an app it could use directly: Connect starts that app's own
+ * connection, gives it to the bot, and answers the request as done so the bot goes on through the app.
+ */
+export function HandoffSuggestion({ app, status, request, botName, initialPhase = "ready", onDismiss }: {
+ app: ToolkitCard;
+ status: ConnectorStatus | undefined;
+ request: Pick<ComputerHelpRef, "botId" | "threadId" | "messageId" | "place">;
+ botName: string;
+ initialPhase?: SuggestionPhase;
+ onDismiss?: () => void;
+}) {
+ const dispatch = useStoreDispatch();
+ const bot = useStoreSelector((state) => state.bots.find((one) => one.id === request.botId));
+ const admin = useOwnerOrAdmin();
+ const [phase, setPhase] = useState<SuggestionPhase>(initialPhase);
+ const [link, setLink] = useState<string | null>(null);
+ const [gone, setGone] = useState(() => dismissedBefore(request.messageId));
+ const stopPoll = useRef<(() => void) | null>(null);
+ useEffect(() => () => stopPoll.current?.(), []);
+
+ const finish = async () => {
+ if (bot && admin === true && botAppScope(bot, app.slug) === null) {
+ const patch = appSwitchPatch(bot, [app.slug], app.slug, true);
+ if (Object.keys(patch).length) dispatch({ type: "updateBot", botId: bot.id, patch });
+ }
+ setPhase("connected");
+ await answerSignIn(request, "done", `connected ${app.label} instead`).catch(() => undefined);
+ };
+
+ const connect = async () => {
+ if (phase === "starting") return;
+ if (status?.connected) { await finish(); return; }
+ const launch = reserveConnectionPage();
+ setPhase("starting");
+ try {
+ const result = await api(`/api/connectors/${encodeURIComponent(app.slug)}/authorize`, { method: "POST" });
+ const url = mcpSignInLink(typeof result.url === "string" ? result.url : null);
+ if (!url) throw new Error("no link");
+ setLink(url);
+ if (!await launch.open(url)) { setPhase("blocked"); return; }
+ setPhase("waiting");
+ stopPoll.current?.();
+ stopPoll.current = pollConnector(status, () => readStatus(app.slug), (end) => {
+ if (end === "connected") void finish();
+ else setPhase(end === "timed_out" ? "stalled" : "failed");
+ });
+ } catch {
+ setPhase("failed");
+ } finally {
+ launch.cancel();
+ }
+ };
+
+ const reopen = () => { if (link) void reserveConnectionPage().open(link); };
+ if (gone) return null;
+ const dismiss = () => { rememberDismissed(request.messageId); setGone(true); onDismiss?.(); };
+ const line = phase === "connected" ? t("handoff.suggest.connected", { name: botName, app: app.label })
+ : phase === "waiting" ? t("handoff.suggest.waiting", { app: app.label })
+ : phase === "stalled" ? t("handoff.suggest.stalled", { app: app.label })
+ : phase === "failed" ? t("handoff.suggest.failed", { app: app.label })
+ : phase === "blocked" ? t("handoff.suggest.blocked")
+ : t("handoff.suggest.line", { app: app.label, name: botName });
+ const trouble = phase === "stalled" || phase === "failed" || phase === "blocked";
+
+ return (
+ <div role="group" aria-label={t("handoff.suggest.label", { app: app.label })} data-handoff-suggestion={phase}
+ className={cn("mt-3 flex w-full max-w-[560px] items-center gap-2.5 rounded-[18px] p-4 text-start", ELEVATED_CARD)}>
+ <span className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-composer ring-[0.5px] ring-inset ring-ink/10">
+ <ServiceIcon card={app} className="size-6" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div dir="auto" className="truncate text-[14px] font-medium leading-5 text-ink">{app.label}</div>
+ <div dir="auto" title={line} aria-live="polite"
+ className={cn("flex min-w-0 items-center gap-1 text-[13px] leading-[18px]", trouble ? "text-danger" : "text-ink-secondary")}>
+ {phase === "waiting" && <Loader2 size={12} aria-hidden="true" className="shrink-0 motion-safe:animate-spin" />}
+ {phase === "connected" && <Check size={13} aria-hidden="true" className="shrink-0 text-success" />}
+ <span className="truncate">{line}</span>
+ </div>
+ </div>
+ {phase === "waiting" && <button type="button" onClick={reopen} className={ASK_QUIET_BUTTON}>{t("handoff.suggest.reopen")}</button>}
+ {phase === "blocked" && link && (
+ <button type="button" onClick={() => void copyText(link)} className={ASK_QUIET_BUTTON}><Copy size={13} aria-hidden="true" />{t("handoff.suggest.copy")}</button>
+ )}
+ {(phase === "ready" || phase === "checking" || phase === "starting" || trouble) && (
+ <button type="button" onClick={() => void connect()} disabled={phase === "checking" || phase === "starting"} aria-busy={phase === "starting" || undefined}
+ className={ASK_DARK_PRIMARY}>
+ {phase === "starting" || phase === "checking" ? <Loader2 size={14} aria-hidden="true" className="motion-safe:animate-spin" />
+ : trouble ? <RefreshCw size={14} aria-hidden="true" /> : null}
+ {t(trouble ? "handoff.suggest.retry" : "handoff.suggest.connect")}
+ </button>
+ )}
+ {phase !== "connected" && (
+ <button type="button" onClick={dismiss} aria-label={t("handoff.suggest.dismiss")} title={t("handoff.suggest.dismiss")}
+ className="-me-1.5 flex size-7 shrink-0 items-center justify-center rounded-full text-ink-tertiary hover:bg-ink/[0.07] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus pointer-coarse:size-9">
+ <X size={15} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/LiveDesktop.tsx b/src/components/LiveDesktop.tsx
index 4859bb29ec..4c9f858a7a 100644
--- a/src/components/LiveDesktop.tsx
+++ b/src/components/LiveDesktop.tsx
@@ -5,12 +5,15 @@ import { cn } from "@/lib/cn";
import { connectDesktop, typeOnDesktop } from "@/lib/desktop-connection";
import { t } from "@/lib/i18n";
import { useCaptionChrome, useDesktopCapabilities } from "./DesktopCapabilities";
+import { DesktopViewerPill } from "./viewer-pill-host";
type Connection = "connecting" | "connected" | "disconnected";
/** The computer the person took control of, live and drivable where they were watching it. */
-export function LiveDesktop({ target, threadId, name, poster, expanded, onExpandedChange, onHandBack, handingBack, onUnreachable }: {
+export function LiveDesktop({ target, threadId, name, poster, expanded, onExpandedChange, onHandBack, handingBack, onUnreachable, botId }: {
target: string;
+ /** The bot whose computer this is: full size, its viewer pill answers that bot's waiting request. */
+ botId?: string;
threadId: string;
name: string;
/** The last watched frame, shown until the first live one arrives. */
@@ -149,6 +152,9 @@ export function LiveDesktop({ target, threadId, name, poster, expanded, onExpand
</div>
)}
</div>
+ {expanded && botId && (
+ <DesktopViewerPill botId={botId} inControl busy={handingBack} onTake={() => undefined} onStop={onHandBack} onCollapse={() => onExpandedChange(false)} />
+ )}
</div>
);
}
diff --git a/src/components/PendingApproval.tsx b/src/components/PendingApproval.tsx
index 16fa9e8dd0..c16bf3d8f2 100644
--- a/src/components/PendingApproval.tsx
+++ b/src/components/PendingApproval.tsx
@@ -1,12 +1,12 @@
import { memo, useState, type ReactNode } from "react";
-import { ChevronDown, Send, ShieldCheck, TriangleAlert } from "lucide-react";
+import { ChevronDown, Monitor, Send, ShieldCheck, TriangleAlert } from "lucide-react";
import { useStore, type Bot, type Message } from "@/state/store";
import { cn } from "@/lib/cn";
import { t, tFromServer } from "@/lib/i18n";
import type { LocaleKey } from "@/locales";
import { SkillRequestPreview } from "@/components/SkillRequestPreview";
import { titledCard, titledCardAction, toolLabel } from "./ApprovalCard";
-import { ASK_QUIET_ANSWER, ASK_QUIET_BUTTON, ASK_SECONDARY_BUTTON, AskDetail, AskHeader, askPrimary, type Asker } from "./AskCard";
+import { ASK_DARK_PRIMARY, ASK_QUIET_ANSWER, ASK_QUIET_BUTTON, ASK_SECONDARY_BUTTON, AskDetail, AskHeader, AskKickerRow, askPrimary, type Asker } from "./AskCard";
import { approvalDetailText, outboundSummary } from "@/lib/approval-summary";
import { reviewedSkillSha256 } from "../../shared/skill-request";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
@@ -174,6 +174,7 @@ export const PendingApprovalPanel = memo(function PendingApprovalPanel({
const detailsId = `approval-details-${pending.requestId}`;
const hidden = detail && detail !== inline ? detail : "";
const skill = pending.message.card?.skillRequest;
+ const placeCard = Boolean(pending.message.card?.computerAsk);
return (
<div
role="region"
@@ -186,12 +187,12 @@ export const PendingApprovalPanel = memo(function PendingApprovalPanel({
? t("approval.aria.pendingProfile")
: t("approval.aria.pending")
}
- data-ask-card="approval" data-look="approval-card"
- className="px-4 pb-3.5 pt-3"
+ data-ask-card="approval" data-look="approval-card" data-shell={placeCard ? "kicker" : undefined}
+ className={placeCard ? "px-4 pb-4 pt-3.5" : "px-4 pb-3.5 pt-3"}
>
<div className="flex min-w-0 items-center gap-2" aria-live="polite">
<div className="min-w-0 flex-1">
- {asker ? pending.message.inbox?.origin ? <CopyHeader message={pending.message} asker={asker} line={line} /> : <AskHeader asker={asker} line={line} /> : (
+ {placeCard ? <AskKickerRow kicker={{ icon: <Monitor />, label: line }} /> : asker ? pending.message.inbox?.origin ? <CopyHeader message={pending.message} asker={asker} line={line} /> : <AskHeader asker={asker} line={line} /> : (
<div className="flex items-center gap-1.5 text-[13px] leading-[18px] text-ink-secondary">
<ShieldCheck size={15} className="shrink-0" aria-hidden="true" /><span className="min-w-0 truncate">{line}</span>
</div>
@@ -216,7 +217,7 @@ export const PendingApprovalPanel = memo(function PendingApprovalPanel({
</button>
)}
</div>
- {summary && <p dir="auto" className="mt-1.5 break-words text-[15px] font-medium leading-[22px] text-ink">{summary}</p>}
+ {summary && <p dir="auto" className={cn("break-words text-[15px] leading-[22px] text-ink", placeCard ? "mt-2 font-semibold" : "mt-1.5 font-medium")}>{summary}</p>}
{inline && <AskDetail text={inline} mono label={t("approval.aria.reviewDetails")} />}
{note && <p dir="auto" data-computer-ask-reason className="mt-1 break-words text-[13px] leading-[18px] text-ink-secondary">{note}</p>}
{heldNote && (outbound ? (
@@ -301,7 +302,7 @@ export function PendingApprovalActions({
{t("computerAsk.action.notNow")}
</button>
{turnOn.turnOn && (
- <button key="allow" {...marked("allow")} type="button" onClick={() => decide("allow")} className={allow.className} style={allow.style}>{turnOn.turnOn}</button>
+ <button key="allow" {...marked("allow")} type="button" onClick={() => decide("allow")} className={ASK_DARK_PRIMARY}>{turnOn.turnOn}</button>
)}
</>
);
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 882185f1f8..ddc47d8676 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -16,7 +16,7 @@ import { cn } from "@/lib/cn";
import { searchMatchesThreads, useSearchDisclosure } from "@/lib/search-disclosure";
import { useHeldMenuMotion, useMenuMotion } from "./MenuMotion";
import { lastNonReceipt } from "@/lib/receipts";
-import { botPreview, groupPreview, lastLine } from "./sidebar-preview";
+import { botPreview, groupPreview, lastLine, waitingHandoffPreview } from "./sidebar-preview";
import { activeLocale, t } from "@/lib/i18n"; import { isBotHeld } from "@/lib/bot-pause";
import { copyText } from "@/lib/copy-text";
import type { LocaleKey } from "@/locales";
@@ -827,7 +827,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
{working ? (
<SidebarWorkingStep bot={bot} last={last} />
) : (
- <FadeLine>{waiting ? t("sidebar.preview.waiting") : teammateWait ? t("sidebar.preview.waitingOnTeammate") : queued && !failed ? t("task.queued") : failed ? lastLine(bot, visible, instances, advanced) : botPreview(bot, visible, instances, advanced)}</FadeLine>
+ <FadeLine>{waiting ? waitingHandoffPreview(visible) ?? t("sidebar.preview.waiting") : teammateWait ? t("sidebar.preview.waitingOnTeammate") : queued && !failed ? t("task.queued") : failed ? lastLine(bot, visible, instances, advanced) : botPreview(bot, visible, instances, advanced)}</FadeLine>
)}
</span>
)}
diff --git a/src/components/SignInRequestCard.test.ts b/src/components/SignInRequestCard.test.ts
index 3a0acc4516..bd4f00850f 100644
--- a/src/components/SignInRequestCard.test.ts
+++ b/src/components/SignInRequestCard.test.ts
@@ -29,7 +29,7 @@ vi.mock("@/lib/logins", () => ({
}));
import { LoginForm } from "./LoginForm";
-import { SignInBanner, SignInRequestCard } from "./SignInRequestCard";
+import { SignInBanner, SignInRequestCard, SiteSignInCard } from "./SignInRequestCard";
import { VaultChoices } from "./VaultChoices";
const card = (signIn: Record<string, unknown> = {}): Message => ({
@@ -51,7 +51,7 @@ const elements = (node: ReactNode): Node[] => {
};
const tree = (signIn?: Record<string, unknown>) => {
let root!: ReactNode;
- function Capture() { root = SignInRequestCard(props(signIn)); return root; }
+ function Capture() { root = SiteSignInCard(props(signIn)); return root; }
renderToStaticMarkup(createElement(Capture));
const top = elements(root);
return [...top, ...top.flatMap((node) => elements((node.props as { footer?: ReactNode }).footer))];
diff --git a/src/components/SignInRequestCard.tsx b/src/components/SignInRequestCard.tsx
index 37297ab4f0..0dc0d6d9e2 100644
--- a/src/components/SignInRequestCard.tsx
+++ b/src/components/SignInRequestCard.tsx
@@ -3,13 +3,14 @@ import { Check, Hand, KeyRound, Loader2, LockKeyhole, LogIn, RefreshCw, X } from
import type { ComputerHelpRef } from "../../shared/wire";
import { browserMatesOf } from "../../shared/browser-mates";
-import { signInOutcome } from "../../shared/sign-in-request";
+import { isHandoff, signInOutcome } from "../../shared/sign-in-request";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { cardSaveTarget, saveLoginFromCard } from "@/lib/logins";
import { answerSignIn, signInHostIsHere } from "@/lib/sign-in";
import { useStore, type Bot, type Message } from "@/state/store";
import { ASK_CHIP, ASK_CHIP_IDLE, askPrimary, ASK_QUIET_BUTTON, AskCard, AskSettledLine, returnFocusToComposer } from "./AskCard";
+import { HandoffCard } from "./HandoffCard";
import { LoginForm } from "./LoginForm";
import { VaultChoices } from "./VaultChoices";
@@ -24,19 +25,20 @@ const WHERE = {
host: "signIn.where.host",
} as const;
-export function SignInRequestCard({
- botId,
- botName,
- color,
- threadId,
- message,
-}: {
+type CardProps = {
botId: string;
botName: string;
color?: Bot["color"];
threadId: string;
message: Message;
-}) {
+};
+
+/** A bot's handoff (its own instruction) or a site sign-in. */
+export function SignInRequestCard(props: CardProps) {
+ return isHandoff(props.message.signIn) ? <HandoffCard {...props} /> : <SiteSignInCard {...props} />;
+}
+
+export function SiteSignInCard({ botId, botName, color, threadId, message }: CardProps) {
const { state, dispatch } = useStore();
const card = message.signIn!;
// A login saved here is kept to every bot this browser signs in (server/bot-logins.ts cardBots).
@@ -216,7 +218,7 @@ export function SignInBanner({
return (
<div className="mt-3 rounded-xl border border-warning/25 bg-warning/10 p-4 text-start" data-testid="sign-in-banner">
<div className="text-[13px] leading-relaxed text-warning">
- <b>{askerName}</b> {t("signIn.banner", { site: help.site })}
+ <b>{askerName}</b> {help.instruction ? <bdi dir="auto">{help.instruction}</bdi> : t("signIn.banner", { site: help.site })}
</div>
{help.place === "local" && (
<div className="mt-1 text-[12px] leading-relaxed text-ink-secondary">
diff --git a/src/components/ViewerPill.tsx b/src/components/ViewerPill.tsx
new file mode 100644
index 0000000000..a44b233f58
--- /dev/null
+++ b/src/components/ViewerPill.tsx
@@ -0,0 +1,49 @@
+import { Eye, Loader2, MousePointer2 } from "lucide-react";
+
+import { PILL_ACTION, type ViewerPillState } from "@/lib/handoff";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+
+const BUTTON = "inline-flex h-7 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-3 text-[13px] font-medium leading-5 transition-colors duration-[120ms] ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus disabled:cursor-wait disabled:opacity-60 motion-reduce:transition-none pointer-coarse:h-9";
+
+/**
+ * The one control over a full-size browser or computer: whether the person watches or drives it, and the single button
+ * that changes that. Stop hands control back; I'm done also answers the bot's request.
+ */
+export function ViewerPill({ state, busy = false, onTake, onStop, onDone, className }: {
+ state: ViewerPillState;
+ /** The button's change is on its way. */
+ busy?: boolean;
+ onTake: () => void;
+ onStop: () => void;
+ onDone: () => void;
+ className?: string;
+}) {
+ const action = PILL_ACTION[state];
+ const watching = state === "watching";
+ const press = action === "take" ? onTake : action === "stop" ? onStop : onDone;
+ const label = t(action === "take" ? "computer.takeControl" : action === "stop" ? "viewer.stop" : "handoff.done");
+ return (
+ <div
+ role="group"
+ aria-label={t("viewer.controls")}
+ data-viewer-pill={state}
+ className={cn("pointer-events-auto inline-flex h-9 items-center gap-2.5 rounded-full bg-composer ps-3 pe-1 text-[13px] shadow-(--shadow-float) ring-[0.5px] ring-ink/10 pointer-coarse:h-11", className)}
+ >
+ <span role="status" aria-live="polite" className={cn("flex items-center gap-1.5 whitespace-nowrap", watching ? "text-ink-secondary" : "font-medium text-ink")}>
+ {watching ? <Eye size={14} aria-hidden="true" /> : <MousePointer2 size={14} aria-hidden="true" />}
+ {t(watching ? "viewer.watching" : "computer.inControl")}
+ </span>
+ <button
+ type="button"
+ onClick={press}
+ disabled={busy}
+ aria-busy={busy || undefined}
+ className={cn(BUTTON, action === "stop" ? "bg-ink/[0.07] text-ink enabled:hover:bg-ink/[0.11]" : "ui-button-primary bg-ink text-app enabled:hover:bg-ink/90")}
+ >
+ {busy && <Loader2 size={13} aria-hidden="true" className="motion-safe:animate-spin" />}
+ {label}
+ </button>
+ </div>
+ );
+}
diff --git a/src/components/remote-desktop-panel.tsx b/src/components/remote-desktop-panel.tsx
index 6b961b54c4..c0000629a3 100644
--- a/src/components/remote-desktop-panel.tsx
+++ b/src/components/remote-desktop-panel.tsx
@@ -87,7 +87,7 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {
useEffect(() => {
if (!requestedSignIn || requestedSignIn.consumed) return;
setView(requestedSignIn.place === "browser" ? "browser" : "desktop");
- if (requestedSignIn.place === "browser") setSignIn({ url: requestedSignIn.url, site: requestedSignIn.site, nonce: requestedSignIn.requestId });
+ if (requestedSignIn.place === "browser") setSignIn({ url: requestedSignIn.url, site: requestedSignIn.site, nonce: requestedSignIn.requestId, ...(requestedSignIn.expand ? { expand: true } : {}) });
dispatch({ type: "signInFocusConsumed", requestId: requestedSignIn.requestId });
}, [dispatch, requestedSignIn]);
const botRoutines = state.routines
diff --git a/src/components/sidebar-preview.test.ts b/src/components/sidebar-preview.test.ts
index 45260c7fc5..b533894fc8 100644
--- a/src/components/sidebar-preview.test.ts
+++ b/src/components/sidebar-preview.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { Bot, Group, Message } from "@/state/store";
-import { botPreview, groupPreview, lastPreviewable, serverCardText } from "./sidebar-preview";
+import { botPreview, groupPreview, lastPreviewable, serverCardText, waitingHandoffPreview } from "./sidebar-preview";
import { setLocale } from "@/lib/i18n";
let at = 0;
@@ -9,6 +9,15 @@ const screen = () => message({ kind: "screen", png: "frame", mime: "image/jpeg"
const bot = { id: "ada", name: "Ada", messages: [], busy: false } as unknown as Bot;
describe("sidebar previews", () => {
+ it("says what a waiting bot waits for when it handed the person a step, and the plain wait otherwise", () => {
+ const waiting = { ...bot, activity: "waiting-on-you" } as Bot;
+ const step = (instruction: string, fields: object = {}) => message({ kind: "signin", signIn: { url: "", site: "", place: "browser", instruction, ...fields } } as Partial<Message>);
+ expect(botPreview(waiting, [step("Sign in to GitHub."), step("Approve the payment.")], [], false)).toBe("Waiting for you: Approve the payment.");
+ expect(botPreview(waiting, [step("Sign in to GitHub."), step("Approve the payment.", { done: true })], [], false)).toBe("Waiting for you: Sign in to GitHub.");
+ expect(waitingHandoffPreview([step("Sign in to GitHub.", { expired: true })])).toBeNull();
+ expect(botPreview(waiting, [message({ text: "Which one?" })], [], false)).toBe("Waiting for you…");
+ });
+
it("shows a bot's reply, not the screen frame its computer turn ended with", () => {
const visible = [message({ role: "user", text: "Paint a sunset" }), message({ text: "I painted a sunset in JS Paint." }), screen()];
expect(botPreview(bot, visible, [], false)).toBe("I painted a sunset in JS Paint.");
diff --git a/src/components/sidebar-preview.ts b/src/components/sidebar-preview.ts
index a3ff0c2c93..049f688137 100644
--- a/src/components/sidebar-preview.ts
+++ b/src/components/sidebar-preview.ts
@@ -4,6 +4,7 @@ import type { RoutineRunCardData } from "../../shared/routine-run";
import { peerLine } from "@/lib/peer-message";
import { isReceipt } from "@/lib/receipts";
import { activityPreview, botEngine, failedTurnCause, STATUS_MARKER } from "@/lib/failed-turn";
+import { newestWaitingHandoff } from "@/lib/handoff";
import { t } from "@/lib/i18n";
import { sidebarConnectorPreview, sidebarGoalRunPreview } from "@/lib/sidebar-layout";
import { citationPreviewText } from "@/lib/citations";
@@ -19,12 +20,19 @@ export function lastPreviewable<T extends { kind: string }>(messages: readonly T
}
export function botPreview(bot: Bot, visible: Message[], instances: InstanceInfo[], advanced: boolean): string {
- if (bot.activity === "waiting-on-you") return t("sidebar.preview.waiting");
+ if (bot.activity === "waiting-on-you") return waitingHandoffPreview(visible) ?? t("sidebar.preview.waiting");
if (bot.waitingForTeammates) return t("sidebar.preview.waitingOnTeammate");
if (bot.busy) return t("sidebar.preview.working");
return lastLine(bot, visible, instances, advanced);
}
+/** "Waiting for you: Sign in to GitHub on the open page", while a step the bot handed over waits. */
+export function waitingHandoffPreview(visible: readonly Message[]): string | null {
+ const id = newestWaitingHandoff(visible);
+ const instruction = id ? visible.find((message) => message.id === id)?.signIn?.instruction : undefined;
+ return instruction ? t("sidebar.preview.waitingFor", { what: instruction }) : null;
+}
+
function plainStep(message: Message): boolean {
const tool = message.kind === "activity" ? message.tool : undefined;
return Boolean(tool) && tool!.ok !== false && !message.dataResult && failedTurnCause(tool!.name) === null && !isStoppedTurnName(tool!.name) && !STATUS_MARKER.test(tool!.name);
diff --git a/src/components/viewer-pill-host.tsx b/src/components/viewer-pill-host.tsx
new file mode 100644
index 0000000000..5a78736065
--- /dev/null
+++ b/src/components/viewer-pill-host.tsx
@@ -0,0 +1,70 @@
+import { useState } from "react";
+
+import { signInWaits } from "../../shared/sign-in-request";
+import type { ComputerHelpRef } from "../../shared/wire";
+import { viewerPillState } from "@/lib/handoff";
+import { answerSignIn } from "@/lib/sign-in";
+import type { Bot } from "@/state/store";
+import { useStoreSelector } from "@/state/store-select";
+import { ViewerPill } from "./ViewerPill";
+
+/** The request a bot's place waits on, when it is this one: the card whose Take over opened the viewer while it still
+ * waits, else the newest request for the browser, or for its computer. */
+export function useWaitingHelp(botId: string, browser: boolean): ComputerHelpRef | null {
+ const help = useStoreSelector((state) => state.computerControl?.[botId]?.help ?? null);
+ const opened = useStoreSelector((state) => {
+ const focus = state.signInFocus;
+ if (!focus?.threadId || focus.botId !== botId || (focus.place === "browser") !== browser) return null;
+ const card = state.bots.find((bot) => bot.id === botId)?.messages.find((row) => row.id === focus.messageId)?.signIn;
+ return card && card.stopped !== true && signInWaits(card) ? { botId, threadId: focus.threadId, messageId: focus.messageId, site: focus.site, place: focus.place } : null;
+ }, (a, b) => a?.messageId === b?.messageId && a?.threadId === b?.threadId);
+ if (opened) return opened;
+ return help && (help.place === "browser") === browser ? help : null;
+}
+
+/** I'm done answers the request and folds the viewer back into the chat; a failed answer keeps both as they were. */
+function useDone(help: ComputerHelpRef | null, onCollapse: () => void) {
+ const [busy, setBusy] = useState(false);
+ const done = () => {
+ if (!help || busy) return;
+ setBusy(true);
+ answerSignIn(help, "done").then(onCollapse, () => undefined).finally(() => setBusy(false));
+ };
+ return { busy, done };
+}
+
+export function BrowserViewerPill({ bot, you, pending, onTake, onStop, onCollapse }: {
+ bot: Pick<Bot, "id">;
+ /** This person drives the browser now. */
+ you: boolean;
+ /** Their take is on its way. */
+ pending: boolean;
+ onTake: () => void;
+ onStop: () => void;
+ onCollapse: () => void;
+}) {
+ const help = useWaitingHelp(bot.id, true);
+ const { busy, done } = useDone(help, onCollapse);
+ return (
+ <div className="pointer-events-none absolute inset-x-0 bottom-4 z-20 flex justify-center px-4">
+ <ViewerPill state={viewerPillState({ inControl: you, requestPending: help !== null })} busy={busy || pending} onTake={onTake} onStop={onStop} onDone={done} />
+ </div>
+ );
+}
+
+export function DesktopViewerPill({ botId, inControl, busy: changing, onTake, onStop, onCollapse }: {
+ botId: string;
+ inControl: boolean;
+ busy: boolean;
+ onTake: () => void;
+ onStop: () => void;
+ onCollapse: () => void;
+}) {
+ const help = useWaitingHelp(botId, false);
+ const { busy, done } = useDone(help, onCollapse);
+ return (
+ <div className="pointer-events-none flex shrink-0 justify-center px-4 py-3">
+ <ViewerPill state={viewerPillState({ inControl, requestPending: help !== null })} busy={busy || changing} onTake={onTake} onStop={onStop} onDone={done} />
+ </div>
+ );
+}
diff --git a/src/handoff-preview.tsx b/src/handoff-preview.tsx
new file mode 100644
index 0000000000..6663fc19f1
--- /dev/null
+++ b/src/handoff-preview.tsx
@@ -0,0 +1,134 @@
+// Dev-only gallery of a bot handing a step to the person, served at /handoff-preview.html; not in the packaged app. It
+// mounts the real chat, sidebar and viewer pill over a fixed store with no server behind it.
+// ?view=pending|connecting|stack|collapsed|suggest-waiting|pill-watching|pill-control|pill-request|sidebar|site&skin=midnight|daylight
+import { StrictMode, useEffect, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import type { SignInRequestCardData } from "../shared/wire";
+import { ChatView } from "@/components/ChatView";
+import { HandoffSuggestion } from "@/components/HandoffSuggestion";
+import { Sidebar } from "@/components/Sidebar";
+import { ViewerPill } from "@/components/ViewerPill";
+import { setAdvancedMode } from "@/lib/interface-mode";
+import { publishLiveFrame } from "@/lib/live-events";
+import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";
+import { initialState, StoreContext, type AppState, type Bot, type Message } from "@/state/store";
+import "./styles.css";
+
+const params = new URLSearchParams(location.search);
+const view = params.get("view") ?? "pending";
+const skin = params.get("skin") ?? "midnight";
+setAdvancedMode(false);
+applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");
+
+const AT = Date.now() - 6 * 60_000;
+const THREAD = "scout-github";
+const INSTRUCTION = "Sign in to GitHub on the open page, then press I'm done.";
+const message = (id: string, minutes: number, fields: Partial<Message>): Message =>
+ ({ id, at: AT + minutes * 60_000, role: "bot", kind: "text", text: "", ...fields }) as Message;
+const handoff = (fields: Partial<SignInRequestCardData> = {}): SignInRequestCardData => ({
+ url: "https://github.com/", site: "github.com", place: "browser", instruction: INSTRUCTION, need: "sign_in", expiresAt: Date.now() + 28 * 60_000, ...fields,
+});
+
+/** A stand-in page: a plain sign-in form, drawn here. */
+const PAGE = `data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="800" viewBox="0 0 1280 800">
+<rect width="1280" height="800" fill="#ffffff"/><rect width="1280" height="44" fill="#eef1f5"/><rect x="12" y="8" width="220" height="28" rx="8" fill="#ffffff"/>
+<text x="28" y="27" font-family="Helvetica,Arial" font-size="13" fill="#444">Sign in - GitHub</text><rect x="0" y="44" width="1280" height="40" fill="#f6f8fa"/>
+<rect x="90" y="51" width="1100" height="26" rx="13" fill="#ffffff" stroke="#d0d7de"/><text x="110" y="69" font-family="Helvetica,Arial" font-size="13" fill="#57606a">github.com/login</text>
+<circle cx="640" cy="170" r="26" fill="#24292f"/><text x="640" y="245" text-anchor="middle" font-family="Helvetica,Arial" font-size="24" fill="#24292f">Sign in to GitHub</text>
+<rect x="500" y="275" width="280" height="230" rx="8" fill="#f6f8fa" stroke="#d0d7de"/><text x="520" y="305" font-family="Helvetica,Arial" font-size="14" fill="#24292f">Username or email address</text>
+<rect x="520" y="315" width="240" height="34" rx="6" fill="#ffffff" stroke="#d0d7de"/><text x="520" y="380" font-family="Helvetica,Arial" font-size="14" fill="#24292f">Password</text>
+<rect x="520" y="390" width="240" height="34" rx="6" fill="#ffffff" stroke="#d0d7de"/><rect x="520" y="445" width="240" height="36" rx="6" fill="#1f883d"/>
+<text x="640" y="468" text-anchor="middle" font-family="Helvetica,Arial" font-size="14" fill="#ffffff">Sign in</text></svg>`)}`;
+
+function messages(): Message[] {
+ const opening = [
+ message("ask", 0, { role: "user", text: "Read the open issues on our GitHub repo and summarise them." }),
+ message("reply", 1, { text: "I need to be signed in to GitHub for that. The sign-in page is open in my browser; over to you for this one step." }),
+ ];
+ if (view === "collapsed") return [...opening,
+ message("card", 2, { kind: "signin", text: INSTRUCTION, signIn: handoff({ done: true, resumed: true }) }),
+ message("after", 3, { text: "Thanks. I can see your avatar in the top bar, so you're signed in. Reading the issues now." }),
+ ];
+ if (view === "stack") return [...opening,
+ message("card", 2, { kind: "signin", text: INSTRUCTION, signIn: handoff({ need: "sign_in" }) }),
+ message("card2", 3, { kind: "signin", text: "Solve the human check on the page.", signIn: handoff({ need: "captcha", instruction: "Solve the human check on the page.", site: "", url: "" }) }),
+ ];
+ if (view === "site") return [...opening,
+ message("card", 2, { kind: "signin", signIn: { url: "https://github.com/login", site: "github.com", place: "browser", reason: "To read the issues on your repositories" } }),
+ ];
+ return [...opening, message("card", 2, { kind: "signin", text: INSTRUCTION, signIn: handoff() })];
+}
+
+const bot: Bot = {
+ title: "", description: "", notifications: true, unread: false, modelSelection: { instanceId: "claude", model: "claude-opus-5-5" },
+ id: "scout", name: "Scout", color: "teal", threadId: THREAD, mainThreadId: THREAD, busy: false, activity: view === "collapsed" ? "idle" : "waiting-on-you",
+ tasks: [{ threadId: THREAD, title: "GitHub issues", createdAt: AT, ...(view === "collapsed" ? {} : { activity: "waiting-on-you" }) }], messages: messages(),
+} as Bot;
+const others: Bot[] = [
+ { ...bot, id: "ledger", name: "Ledger", color: "orange", threadId: "ledger-main", mainThreadId: "ledger-main", activity: "idle", tasks: [{ threadId: "ledger-main", title: "Invoices", createdAt: AT }],
+ messages: [message("l1", 0, { text: "The March invoices are filed in your Drive." })] } as Bot,
+ { ...bot, id: "atlas", name: "Atlas", color: "blue", threadId: "atlas-main", mainThreadId: "atlas-main", activity: "idle", tasks: [{ threadId: "atlas-main", title: "Trip", createdAt: AT }],
+ messages: [message("a1", 0, { text: "Booked: the 9:40 train to Leeds on Friday." })] } as Bot,
+];
+
+const GITHUB = { slug: "github", label: "GitHub", blurb: "Code hosting", logo: null, domain: null };
+
+function Frame({ children }: { children: ReactNode }) {
+ return <div className="flex h-dvh w-full overflow-hidden bg-app text-ink">{children}</div>;
+}
+
+function Viewer({ state }: { state: "watching" | "control" | "control-request" }) {
+ return (
+ <div className="fixed inset-0 flex flex-col bg-card text-ink" data-preview="viewer">
+ <div className="flex h-11 shrink-0 items-center border-b border-hairline/40 px-4 text-[13px] text-ink-secondary">github.com/login</div>
+ <div className="relative min-h-0 flex-1 bg-inset/40">
+ <img src={PAGE} alt="" className="absolute inset-0 h-full w-full object-contain" />
+ <div className="pointer-events-none absolute inset-x-0 bottom-4 z-20 flex justify-center px-4">
+ <ViewerPill state={state} onTake={() => undefined} onStop={() => undefined} onDone={() => undefined} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Gallery() {
+ useEffect(() => {
+ if (view === "connecting") return;
+ const send = () => publishLiveFrame({ kind: "screen", botId: bot.id, threadId: THREAD, png: PAGE.slice(PAGE.indexOf(",") + 1), mime: "image/svg+xml", surface: "browser" });
+ const timer = setInterval(send, 300);
+ send();
+ return () => clearInterval(timer);
+ }, []);
+ const bots = [bot, ...others];
+ const state: AppState = { ...initialState, bots, selectedId: bot.id, connected: true };
+ const value = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ if (view.startsWith("pill-")) return <Viewer state={view === "pill-watching" ? "watching" : view === "pill-control" ? "control" : "control-request"} />;
+ return (
+ <StoreContext.Provider value={value}>
+ {view === "suggest-waiting" ? (
+ <Frame><div className="mx-auto w-full max-w-[600px] p-6" data-preview={view}>
+ <HandoffSuggestion app={GITHUB} status={{ connected: false }} request={{ botId: bot.id, threadId: THREAD, messageId: "card", place: "browser" }} botName="Scout" initialPhase="waiting" />
+ <HandoffSuggestion app={GITHUB} status={{ connected: false }} request={{ botId: bot.id, threadId: THREAD, messageId: "card2", place: "browser" }} botName="Scout" initialPhase="connected" />
+ </div></Frame>
+ ) : view === "sidebar" ? (
+ <Frame><div className="flex h-full w-[280px] shrink-0" data-preview={view}><Sidebar open onClose={() => {}} /></div><div className="flex min-w-0 flex-1 flex-col"><ChatView bot={bot} /></div></Frame>
+ ) : (
+ <Frame><div className="flex min-w-0 flex-1 flex-col" data-preview={view}><ChatView bot={bot} /></div></Frame>
+ )}
+ </StoreContext.Provider>
+ );
+}
+
+const realFetch = window.fetch.bind(window);
+window.fetch = async (input, init) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ const path = new URL(url, location.href).pathname;
+ if (!path.startsWith("/api/")) return realFetch(input, init);
+ const body = path.endsWith("/saved-logins") ? { choices: [] }
+ : path === "/api/connectors/catalog" ? { cards: [GITHUB], source: "api", configured: true, mode: "managed" }
+ : path === "/api/connectors" ? { services: { github: { connected: false } } }
+ : {};
+ return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
+};
+
+createRoot(document.getElementById("root")!).render(<StrictMode><Gallery /></StrictMode>);
diff --git a/src/lib/handoff.test.ts b/src/lib/handoff.test.ts
new file mode 100644
index 0000000000..95cd097a13
--- /dev/null
+++ b/src/lib/handoff.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+
+import type { SignInRequestCardData } from "../../shared/wire";
+import { handoffEnd, handoffSummary, newestWaitingHandoff, PILL_ACTION, viewerPillState } from "./handoff";
+
+const card = (fields: Partial<SignInRequestCardData> = {}): SignInRequestCardData =>
+ ({ url: "", site: "", place: "browser", instruction: "Solve the check.", need: "captcha", ...fields });
+
+describe("the viewer's one pill", () => {
+ it("watches until the person is in control", () => {
+ expect(viewerPillState({ inControl: false, requestPending: false })).toBe("watching");
+ expect(viewerPillState({ inControl: false, requestPending: true })).toBe("watching");
+ expect(PILL_ACTION.watching).toBe("take");
+ });
+
+ it("offers Stop for control the person took, and I'm done while a request waits", () => {
+ expect(viewerPillState({ inControl: true, requestPending: false })).toBe("control");
+ expect(PILL_ACTION.control).toBe("stop");
+ expect(viewerPillState({ inControl: true, requestPending: true })).toBe("control-request");
+ expect(PILL_ACTION["control-request"]).toBe("done");
+ });
+});
+
+describe("how a handoff ended", () => {
+ it.each([
+ [{}, null],
+ [{ done: true }, "done"],
+ [{ cancelled: true }, "skipped"],
+ [{ expired: true }, "expired"],
+ [{ answeredInChat: true }, "chat"],
+ [{ stopped: true }, "stopped"],
+ [{ superseded: true }, "replaced"],
+ ] as const)("%o is %s", (fields, end) => {
+ expect(handoffEnd(card(fields))).toBe(end);
+ });
+
+ it("folds to the outcome and the step", () => {
+ expect(handoffSummary("done", "Sign in to GitHub.")).toBe("Done · Sign in to GitHub.");
+ expect(handoffSummary("expired", "Sign in to GitHub.")).toBe("Expired · Sign in to GitHub.");
+ });
+});
+
+describe("which open request shows the live picture", () => {
+ it("is the newest handoff still waiting", () => {
+ const rows = [
+ { id: "a", kind: "signin", signIn: card() },
+ { id: "b", kind: "signin", signIn: card() },
+ { id: "c", kind: "signin", signIn: card({ done: true }) },
+ { id: "d", kind: "signin", signIn: { url: "https://x.example", site: "x.example", place: "browser" as const } },
+ { id: "e", kind: "text" },
+ ];
+ expect(newestWaitingHandoff(rows)).toBe("b");
+ expect(newestWaitingHandoff(rows.slice(0, 1))).toBe("a");
+ expect(newestWaitingHandoff([{ id: "s", kind: "signin", signIn: card({ stopped: true }) }])).toBeNull();
+ });
+});
diff --git a/src/lib/handoff.ts b/src/lib/handoff.ts
new file mode 100644
index 0000000000..59592a426b
--- /dev/null
+++ b/src/lib/handoff.ts
@@ -0,0 +1,78 @@
+import { isHandoff, signInOutcome, signInWaits, type HandoffNeed } from "../../shared/sign-in-request";
+import type { SignInRequestCardData, Surface } from "../../shared/wire";
+import type { LocaleKey } from "@/locales";
+import { t } from "./i18n";
+
+/** The viewer's one control: what the person can do with the screen they look at. */
+export type ViewerPillState = "watching" | "control" | "control-request";
+
+/** A pending handoff opens the viewer already in control, and its button hands the step back as done; control the person
+ * took on their own ends with Stop; otherwise they watch and may take control. */
+export function viewerPillState({ inControl, requestPending }: { inControl: boolean; requestPending: boolean }): ViewerPillState {
+ if (!inControl) return "watching";
+ return requestPending ? "control-request" : "control";
+}
+
+export const PILL_ACTION = { watching: "take", control: "stop", "control-request": "done" } as const satisfies Record<ViewerPillState, string>;
+
+const PLACE_LABEL: Record<Surface, LocaleKey> = {
+ browser: "handoff.place.browser",
+ vm: "handoff.place.computer",
+ cloud: "handoff.place.computer",
+ local: "handoff.place.computer",
+};
+
+export function handoffPlaceLabel(place: Surface): string {
+ return t(PLACE_LABEL[place] ?? "handoff.place.computer");
+}
+
+const TITLE: Record<HandoffNeed, LocaleKey> = {
+ sign_in: "handoff.title.signIn",
+ captcha: "handoff.title.captcha",
+ payment: "handoff.title.payment",
+ approval: "handoff.title.approval",
+ other: "handoff.title.other",
+};
+
+export function handoffTitle(need: HandoffNeed | undefined): string {
+ return t(TITLE[need ?? "other"] ?? "handoff.title.other");
+}
+
+export type HandoffEnd = "done" | "skipped" | "expired" | "chat" | "stopped" | "replaced";
+
+/** How a handoff card ended, or null while it waits. */
+export function handoffEnd(card: Pick<SignInRequestCardData, "done" | "cancelled" | "expired" | "answeredInChat" | "stopped" | "superseded">): HandoffEnd | null {
+ const outcome = signInOutcome(card);
+ if (outcome === "done") return "done";
+ if (outcome === "cancelled") return "skipped";
+ if (outcome === "expired") return "expired";
+ if (card.answeredInChat) return "chat";
+ if (card.superseded) return "replaced";
+ if (card.stopped) return "stopped";
+ return null;
+}
+
+const END_WORD: Record<HandoffEnd, LocaleKey> = {
+ done: "handoff.end.done",
+ skipped: "handoff.end.skipped",
+ expired: "handoff.end.expired",
+ chat: "handoff.end.chat",
+ stopped: "handoff.end.stopped",
+ replaced: "handoff.end.replaced",
+};
+
+/** "Done · Sign in to GitHub on the open page": the collapsed row after the place's own label. */
+export function handoffSummary(end: HandoffEnd, instruction: string): string {
+ return `${t(END_WORD[end])} · ${instruction}`;
+}
+
+type Row = { id: string; kind: string; signIn?: SignInRequestCardData };
+
+/** The newest handoff still waiting in these rows: only it shows a live picture, so stacked requests stay short. */
+export function newestWaitingHandoff(rows: readonly Row[]): string | null {
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
+ const row = rows[index]!;
+ if (row.kind === "signin" && isHandoff(row.signIn) && row.signIn!.stopped !== true && signInWaits(row.signIn!)) return row.id;
+ }
+ return null;
+}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 4533fcb6a5..16f48ff253 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -550,7 +550,7 @@ export interface AppState {
dataSheets: Record<string, DataSheet>;
dataTables: Record<string, DataTable[]>;
dataResultFocus: { botId: string; id: string; requestId: number; consumed: boolean } | null;
- signInFocus: { botId: string; messageId: string; url: string; site: string; place: import("../../shared/wire").Surface; requestId: number; consumed: boolean } | null;
+ signInFocus: { botId: string; messageId: string; url: string; site: string; place: import("../../shared/wire").Surface; expand?: boolean; threadId?: string; requestId: number; consumed: boolean } | null;
dataView: import("@/lib/composer-attachments").DataViewContext | null;
focusMessage: { threadId: string; messageId: string; matchText?: string; nonce: number; consumed: boolean } | null;
unreadDivider: UnreadDivider | null;
@@ -735,7 +735,7 @@ export type Action =
| { type: "toggleComputer"; open?: boolean; botId?: string }
| { type: "openDataResult"; botId: string; cardId: string }
| { type: "dataResultFocusConsumed"; requestId: number }
- | { type: "openSignIn"; botId: string; messageId: string; url: string; site: string; place: import("../../shared/wire").Surface }
+ | { type: "openSignIn"; botId: string; messageId: string; url: string; site: string; place: import("../../shared/wire").Surface; expand?: boolean; threadId?: string }
| { type: "signInFocusConsumed"; requestId: number }
| { type: "toggleInspector"; open?: boolean }
| { type: "toggleActivity"; open?: boolean }