Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Local mode: show the bot's Chrome live in the side panel, no window

Lin (kwant bot)3765c9eb950d
diff --git a/docs/browser-service.md b/docs/browser-service.md
index 10f9e0e3..0f47f745 100644
--- a/docs/browser-service.md
+++ b/docs/browser-service.md
@@ -10,26 +10,31 @@ Take Control obtains an exclusive server-side lease. Bot navigation and selector
Kwnt runs bots' browser and shell commands in one of two places, chosen in **Settings → Computer** or with the browser panel's mode toggle:
-- **Local computer** (`local`, the default on macOS): Kwnt opens your installed Chrome or Chromium in a visible window with its own profile, `<data dir>/local-chrome`. It never uses your everyday Chrome profile. Each bot gets its own tab. Sign-ins made in that window are kept in the kwant profile and shared by its tabs. The debugging port is chosen by Chrome and listens on 127.0.0.1 only. Shell commands run on your computer in the bot's working folder, and **every command asks for your approval first**. "Always allow" applies to that one command; it is not remembered. Docker is not needed.
+- **Local computer** (`local`, the default on macOS): Kwnt runs your installed Chrome or Chromium without a window (`--headless=new`, 1280×800) with its own profile, `<data dir>/local-chrome`, and shows it live in the app's browser panel, the same way as the VM. To sign in or solve a CAPTCHA yourself, use **Open as window** in the panel: Kwnt closes the windowless Chrome and opens the same profile as a real window, with each bot's page reopened there (one profile can't be open twice). **Show it here instead**, or closing that window, brings it back into the panel. Saved sign-ins carry over; cookies that only last for a browser session do not. The window choice is not saved, so a restart goes back to the panel. Switching to VM closes the windowless Chrome; a window you opened stays open. It never uses your everyday Chrome profile. Each bot gets its own Chrome window (headless Chrome only paints the front tab of a window, so tabs would stall the other bots' screenshots). Sign-ins are kept in the kwant profile and shared by all bots. The debugging port is chosen by Chrome and listens on 127.0.0.1 only. Shell commands run on your computer in the bot's working folder, and **every command asks for your approval first**. "Always allow" applies to that one command; it is not remembered. Docker is not needed.
- **VM (isolated)** (`vm`, the default everywhere else, including a VPS): the Docker browser and execution containers described below.
-Switching takes effect at once, without a restart. Kwnt disconnects from the old browser without closing it: the local Chrome window and the VM container both keep running, and switching back reuses them. Each mode keeps its own saved pages (`browser-sessions-local.json` and `browser-sessions.json`). If the local window was closed, the next browser action opens it again. Kwnt does not close the window when it stops, either.
+Switching takes effect at once, without a restart. Kwnt disconnects from the old browser: the VM container and a local Chrome window keep running, and switching back reuses them; only the windowless local Chrome is closed, as nothing would show it. Each mode keeps its own saved pages (`browser-sessions-local.json` and `browser-sessions.json`). If the local Chrome was closed, the next browser action starts it again. Kwnt does not close Chrome when it stops, and reuses a running one on the next start.
Precedence: a choice saved in Settings wins; otherwise `KWNT_COMPUTER_MODE=local|vm`; otherwise the platform default. `KWNT_CHROME_PATH` names the browser binary local mode launches. Without it, Kwnt looks for Google Chrome, Chromium or Chrome Canary in `/Applications` and `~/Applications` on macOS, then for `google-chrome`, `google-chrome-stable`, `chromium`, `chromium-browser` or `chrome` on `PATH`.
-A mode that cannot run here is refused with the reason: local needs a Chrome binary and a display (always present on macOS; `DISPLAY` or `WAYLAND_DISPLAY` on Linux). VM needs Docker, or a `KWNT_BROWSER_CDP_URL` for the browser.
+A mode that cannot run here is refused with the reason: local needs a Chrome binary; only opening it as a window needs a display (always present on macOS; `DISPLAY` or `WAYLAND_DISPLAY` on Linux). VM needs Docker, or a `KWNT_BROWSER_CDP_URL` for the browser.
API (same authentication as the other settings routes):
```text
GET /api/settings/computer
-→ {"mode":"local"|"vm","available":{"local":bool,"vm":bool},"reasons":{"local":string|null,"vm":string|null}}
+→ {"mode":"local"|"vm","available":{"local":bool,"vm":bool},"reasons":{"local":string|null,"vm":string|null},
+ "window":{"visible":bool,"available":bool,"reason":string|null}}
PUT /api/settings/computer {"mode":"local"|"vm"}
→ the same shape after switching; 400 {"error":"<reason>"} for an unknown or unavailable mode
+
+PUT /api/settings/computer/window {"visible":bool}
+→ the same shape after restarting Chrome as a window (true) or back in the app (false);
+ 400 {"error":...} outside local mode or with no display for a window; 502 if Chrome could not restart
```
-Local mode gives up isolation: commands run with your user's access to your files, and the debugging port can be reached by other programs on the same computer while the kwant window is open. Use VM mode for untrusted work.
+Local mode gives up isolation: commands run with your user's access to your files, and the debugging port can be reached by other programs on the same computer while the kwant Chrome is running. Use VM mode for untrusted work.
## VM mode on a Mac or Linux VPS
diff --git a/frontend/src/components/ComputerModeSwitch.tsx b/frontend/src/components/ComputerModeSwitch.tsx
index 51a73c62..ba984dd2 100644
--- a/frontend/src/components/ComputerModeSwitch.tsx
+++ b/frontend/src/components/ComputerModeSwitch.tsx
@@ -1,5 +1,5 @@
-import React, { useCallback, useEffect, useReducer, useRef } from 'react';
-import { AlertTriangle, Box, Laptop, Loader2, X } from 'lucide-react';
+import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react';
+import { AlertTriangle, AppWindow, Box, Laptop, Loader2, PanelRight, X } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import {
COMPUTER_MODES,
@@ -13,6 +13,8 @@ import {
modeLabel,
otherMode,
saveComputerMode,
+ saveLocalWindow,
+ showsLocalWindow,
shownMode,
switchReducer,
unavailableReason,
@@ -23,6 +25,10 @@ export interface ComputerModeApi {
/** Saves at once; on failure the control goes back and `state.error` says why. */
select: (mode: ComputerMode) => void;
dismissError: () => void;
+ /** Local mode: opens the bots' Chrome as a window, or brings it back into the app. */
+ setWindow: (visible: boolean) => void;
+ /** True while a window switch restarts Chrome. */
+ windowPending: boolean;
}
/** Loads the setting while `enabled`, and follows switches made elsewhere in this tab. */
@@ -60,8 +66,36 @@ export function useComputerMode(enabled: boolean): ComputerModeApi {
});
}, []);
+ const [windowPending, setWindowPending] = useState(false);
+ const setWindow = useCallback((visible: boolean) => {
+ if (stateRef.current.pending) return;
+ playSfx('click');
+ setWindowPending(true);
+ saveLocalWindow(visible).then((r) => {
+ setWindowPending(false);
+ if (r.ok) {
+ dispatch({ type: 'saved', settings: r.settings });
+ window.dispatchEvent(new CustomEvent(COMPUTER_MODE_EVENT, { detail: r.settings }));
+ } else {
+ dispatch({ type: 'failed', error: r.error });
+ }
+ });
+ }, []);
+
+ // Closing the window puts the browser back in the app on the server; notice that.
+ const windowOpen = enabled && showsLocalWindow(state.settings);
+ useEffect(() => {
+ if (!windowOpen) return;
+ const timer = window.setInterval(() => {
+ fetchComputerSettings()
+ .then((s) => s && dispatch({ type: 'loaded', settings: s }))
+ .catch(() => {});
+ }, 5000);
+ return () => window.clearInterval(timer);
+ }, [windowOpen]);
+
const dismissError = useCallback(() => dispatch({ type: 'dismiss' }), []);
- return { state, select, dismissError };
+ return { state, select, dismissError, setWindow, windowPending };
}
const ICONS: Record<ComputerMode, typeof Laptop> = { local: Laptop, vm: Box };
@@ -179,13 +213,49 @@ export const ComputerModeChip: React.FC<{ api: ComputerModeApi }> = ({ api }) =>
);
};
-/** Shown in place of the live stream while kwant drives a real Chrome window. */
-export const LocalBrowserNote: React.FC = () => (
+/** Local mode, in-app view: opens the same browser as a real window for a sign-in or CAPTCHA. */
+export const OpenWindowButton: React.FC<{ api: ComputerModeApi; label?: boolean }> = ({ api, label }) => {
+ const settings = api.state.settings;
+ if (settings?.mode !== 'local' || settings.window.visible) return null;
+ const reason = settings.window.available ? null : settings.window.reason;
+ const title = reason
+ ? `Can't open a window: ${reason}`
+ : 'Open this browser as a window on your computer, to sign in or solve a CAPTCHA yourself';
+ return (
+ <button
+ type="button"
+ onClick={() => api.setWindow(true)}
+ disabled={!!reason || api.windowPending}
+ aria-busy={api.windowPending || undefined}
+ title={title}
+ aria-label={title}
+ className="flex items-center gap-1 p-1.5 rounded-md text-zinc-400 enabled:hover:text-zinc-100 enabled:hover:bg-zinc-800 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {api.windowPending ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : <AppWindow size={13} aria-hidden="true" />}
+ {label && <span className="text-[10px] font-semibold whitespace-nowrap">Open as window</span>}
+ </button>
+ );
+};
+
+/** Shown in place of the live view while the bots' Chrome is open as a window. */
+export const LocalBrowserNote: React.FC<{ api?: ComputerModeApi }> = ({ api }) => (
<div className="flex-1 flex items-center justify-center p-6 rounded-xl border border-zinc-800 bg-zinc-950 text-center">
<div className="max-w-xs space-y-2">
<Laptop size={28} className="mx-auto text-amber-300/80" aria-hidden="true" />
<p className="text-xs font-medium text-zinc-200">{LOCAL_BROWSER_NOTE}</p>
- <p className="text-[11px] text-zinc-500">Watch and use that window directly. Switch to VM to see a live view here instead.</p>
+ <p className="text-[11px] text-zinc-500">Sign in or finish what you need there. Closing the window, or the button below, brings it back here.</p>
+ {api && (
+ <button
+ type="button"
+ onClick={() => api.setWindow(false)}
+ disabled={api.windowPending}
+ aria-busy={api.windowPending || undefined}
+ className="inline-flex items-center gap-1.5 mt-1 px-3 py-1.5 rounded-lg text-[11px] font-semibold border border-sky-500/30 bg-sky-500/10 text-sky-200 enabled:hover:bg-sky-500/20 disabled:opacity-60"
+ >
+ {api.windowPending ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : <PanelRight size={12} aria-hidden="true" />}
+ Show it here instead
+ </button>
+ )}
</div>
</div>
);
diff --git a/frontend/src/components/SandboxViewer.tsx b/frontend/src/components/SandboxViewer.tsx
index 690fd98f..3d08d652 100644
--- a/frontend/src/components/SandboxViewer.tsx
+++ b/frontend/src/components/SandboxViewer.tsx
@@ -1,6 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Globe, Loader2, RefreshCw, Share2, MousePointerClick } from 'lucide-react';
-import { ComputerModeChip, ComputerModeError, LocalBrowserNote, useComputerMode } from './ComputerModeSwitch';
+import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, useComputerMode } from './ComputerModeSwitch';
+import { showsLocalWindow } from '../computerMode';
// Must match the sandbox Chromium --window-size (docker/entrypoint.sh)
const VIEWPORT_W = 1280;
@@ -36,7 +37,8 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {
const lastWheelRef = useRef(0);
const api = `/api/sandbox/${encodeURIComponent(teamId)}`;
const computer = useComputerMode(true);
- const isLocal = computer.state.settings?.mode === 'local';
+ // Local Chrome shows here like the VM, unless it is open as its own window.
+ const isWindow = showsLocalWindow(computer.state.settings);
const applyUrl = useCallback((next?: string) => {
if (!next || next === 'about:blank') return;
@@ -113,13 +115,13 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {
// Initial load + polling so page changes (loads, animations, bot actions) show up
useEffect(() => {
- if (isLocal) return;
+ if (isWindow) return;
refresh();
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') refresh();
}, POLL_MS);
return () => window.clearInterval(timer);
- }, [refresh, isLocal]);
+ }, [refresh, isWindow]);
// Live updates when the bot (or the in-app pane) drives the same browser
useEffect(() => {
@@ -240,6 +242,7 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {
</button>
<ComputerModeChip api={computer} />
+ <OpenWindowButton api={computer} label />
<div
className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-emerald-300 bg-emerald-500/10 border border-emerald-500/30 flex-shrink-0"
@@ -250,7 +253,7 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {
</div>
</header>
- {!isLocal && (
+ {!isWindow && (
<div className="px-4 py-1.5 text-[11px] text-zinc-500 border-b border-zinc-900 flex items-center gap-2">
<MousePointerClick size={12} className={isFocused ? 'text-sky-400' : ''} />
<span>
@@ -269,9 +272,9 @@ export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {
)}
<main className="flex-1 min-h-0 flex items-center justify-center p-4 overflow-hidden">
- {isLocal ? (
+ {isWindow ? (
<div className="w-full max-w-md flex">
- <LocalBrowserNote />
+ <LocalBrowserNote api={computer} />
</div>
) : error && !screenshot ? (
<div className="text-sm text-zinc-400">{error}</div>
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index 8c5405cf..209269cb 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -24,7 +24,8 @@ import {
import { playSfx } from '../audio/chiptune';
import { mapBrowserPoint } from '../browserViewport';
import { useBrowserStream } from '../useBrowserStream';
-import { ComputerModeChip, ComputerModeError, LocalBrowserNote, useComputerMode } from './ComputerModeSwitch';
+import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, useComputerMode } from './ComputerModeSwitch';
+import { showsLocalWindow } from '../computerMode';
export interface TerminalLogEntry {
command: string;
@@ -85,12 +86,14 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
const [newPassword, setNewPassword] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
- // Local mode drives a real Chrome window, so there's no stream to show. Unknown counts as vm.
+ // Local Chrome streams here like the VM, unless the person opened it as a window: then there's
+ // nothing to show. Unknown counts as vm.
const computer = useComputerMode(isOpen);
const isLocal = computer.state.settings?.mode === 'local';
+ const isWindow = showsLocalWindow(computer.state.settings);
// Interactive Remote Control State
- const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isLocal);
+ const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending);
const isControlMode = stream.controlling;
const isInteracting = stream.busy;
const [quickTypeText, setQuickTypeText] = useState('');
@@ -328,9 +331,10 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
<div className="flex items-center gap-1 shrink-0">
<ComputerModeChip api={computer} />
+ <OpenWindowButton api={computer} />
{/* Interactive Control Toggle */}
- {!isLocal && (
+ {!isWindow && (
<button
type="button"
onClick={() => {
@@ -463,9 +467,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
{/* Content Area */}
<div className="flex-1 overflow-hidden flex flex-col">
- {activeTab === 'browser' && isLocal ? (
+ {activeTab === 'browser' && isWindow ? (
<div className="flex-1 flex flex-col p-3 overflow-hidden">
- <LocalBrowserNote />
+ <LocalBrowserNote api={computer} />
</div>
) : activeTab === 'browser' ? (
<div className="flex-1 flex flex-col p-3 gap-2 overflow-hidden">
@@ -615,7 +619,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
<div className="text-center p-6 text-zinc-600 text-xs">
<Globe size={32} className="mx-auto mb-2 opacity-40 text-zinc-500" />
<p>{browserReady ? 'Browser idle' : 'Browser unavailable'}</p>
- <p className="text-[10px] text-zinc-500 mt-1">{browserReady ? 'Enter a URL above to open a page' : 'Start Docker, then use Restart Browser below'}</p>
+ <p className="text-[10px] text-zinc-500 mt-1">{browserReady ? 'Enter a URL above to open a page' : isLocal ? 'Check that Chrome is installed, then use Restart Browser below' : 'Start Docker, then use Restart Browser below'}</p>
</div>
)}
</div>
@@ -886,10 +890,15 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
{/* Footer Status */}
<div className="p-2.5 border-t border-zinc-800 bg-zinc-900/60 flex items-center justify-between text-[11px] text-zinc-400">
- {isLocal ? (
+ {isWindow ? (
<div className="flex items-center gap-1.5">
<Laptop size={12} className="text-amber-300/80" />
- <span>Chrome on your computer</span>
+ <span>Chrome window on your computer</span>
+ </div>
+ ) : isLocal ? (
+ <div className="flex items-center gap-1.5">
+ <Laptop size={12} className={browserReady ? 'text-amber-300/80' : 'text-zinc-500'} />
+ <span>{browserReady ? 'Chrome on your computer' : 'Chrome offline'}</span>
</div>
) : (
<div className="flex items-center gap-1.5">
@@ -897,7 +906,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
<span>{browserReady ? 'Browser Ready' : 'Browser Offline'}</span>
</div>
)}
- {onRestartVm && !isLocal && (
+ {onRestartVm && !isWindow && (
<button
type="button"
onClick={() => {
diff --git a/frontend/src/computerMode.ts b/frontend/src/computerMode.ts
index 926ac3d4..44413b40 100644
--- a/frontend/src/computerMode.ts
+++ b/frontend/src/computerMode.ts
@@ -3,10 +3,19 @@
export type ComputerMode = 'local' | 'vm';
+/** Local mode only: the bots' Chrome runs without a window and shows in the app, unless the
+ * person opened it as a real window (to sign in or solve a CAPTCHA). */
+export interface LocalWindow {
+ visible: boolean;
+ available: boolean;
+ reason: string | null;
+}
+
export interface ComputerSettings {
mode: ComputerMode;
available: Record<ComputerMode, boolean>;
reasons: Record<ComputerMode, string | null>;
+ window: LocalWindow;
}
export const COMPUTER_MODES: { id: ComputerMode; label: string; short: string; hint: string }[] = [
@@ -14,7 +23,10 @@ export const COMPUTER_MODES: { id: ComputerMode; label: string; short: string; h
{ id: 'vm', label: 'VM (isolated)', short: 'VM', hint: 'Runs in Docker containers, isolated from your files.' },
];
-export const LOCAL_BROWSER_NOTE = 'Your bots are using a Chrome window on your computer.';
+export const LOCAL_BROWSER_NOTE = "Your bots' Chrome is open as a window on your computer.";
+
+/** Whether the browser is in its own window instead of the app's live view. */
+export const showsLocalWindow = (s: ComputerSettings | null | undefined) => s?.mode === 'local' && s.window.visible;
/** Fired on window after a successful switch so every open control shows the new mode. */
export const COMPUTER_MODE_EVENT = 'kwnt:computer-mode';
@@ -27,10 +39,16 @@ export function parseComputerSettings(data: unknown): ComputerSettings | null {
const d = data as Record<string, any>;
if (!isMode(d.mode) || !d.available || typeof d.available !== 'object') return null;
const reason = (m: ComputerMode) => (typeof d.reasons?.[m] === 'string' && d.reasons[m].trim() ? d.reasons[m] : null);
+ const w = d.window && typeof d.window === 'object' ? d.window : {};
return {
mode: d.mode,
available: { local: d.available.local === true, vm: d.available.vm === true },
reasons: { local: reason('local'), vm: reason('vm') },
+ window: {
+ visible: w.visible === true,
+ available: w.available === true,
+ reason: typeof w.reason === 'string' && w.reason.trim() ? w.reason : null,
+ },
};
}
@@ -86,24 +104,30 @@ export async function fetchComputerSettings(): Promise<ComputerSettings | null>
return parseComputerSettings(await res.json().catch(() => null));
}
-export async function saveComputerMode(
- mode: ComputerMode,
-): Promise<{ ok: true; settings: ComputerSettings } | { ok: false; error: string }> {
+type SaveResult = { ok: true; settings: ComputerSettings } | { ok: false; error: string };
+
+async function putSettings(path: string, body: unknown, failed: string): Promise<SaveResult> {
let res: Response;
try {
- res = await fetch('/api/settings/computer', {
+ res = await fetch(path, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ mode }),
+ body: JSON.stringify(body),
});
} catch {
return { ok: false, error: 'Could not reach the server.' };
}
const data = await res.json().catch(() => null);
if (!res.ok) {
- const msg = data && typeof data.error === 'string' && data.error.trim() ? data.error : `Switching failed (HTTP ${res.status}).`;
+ const msg = data && typeof data.error === 'string' && data.error.trim() ? data.error : `${failed} (HTTP ${res.status}).`;
return { ok: false, error: msg };
}
const settings = parseComputerSettings(data);
return settings ? { ok: true, settings } : { ok: false, error: 'The server sent an unexpected answer.' };
}
+
+export const saveComputerMode = (mode: ComputerMode) => putSettings('/api/settings/computer', { mode }, 'Switching failed');
+
+/** Opens the bots' Chrome as a window (`true`) or puts it back in the app (`false`). */
+export const saveLocalWindow = (visible: boolean) =>
+ putSettings('/api/settings/computer/window', { visible }, visible ? 'Could not open the window' : 'Could not bring the browser back');
diff --git a/frontend/tests/computerMode.test.mjs b/frontend/tests/computerMode.test.mjs
index 73ee83b7..1bab6490 100644
--- a/frontend/tests/computerMode.test.mjs
+++ b/frontend/tests/computerMode.test.mjs
@@ -7,17 +7,18 @@ globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
const m = await loadBundled(`
export * from './src/computerMode';
- export { ComputerModeControl, ComputerModeChip, LocalBrowserNote } from './src/components/ComputerModeSwitch';
+ export { ComputerModeControl, ComputerModeChip, LocalBrowserNote, OpenWindowButton } from './src/components/ComputerModeSwitch';
export { renderToStaticMarkup } from 'react-dom/server.browser';
export { createElement } from 'react';
`);
-const settings = (mode, local = true, vm = true, reasons = {}) => ({
+const settings = (mode, local = true, vm = true, reasons = {}, window = {}) => ({
mode,
available: { local, vm },
reasons: { local: null, vm: null, ...reasons },
+ window: { visible: false, available: false, reason: null, ...window },
});
-const api = (state) => ({ state, select: () => {}, dismissError: () => {} });
+const api = (state, extra = {}) => ({ state, select: () => {}, dismissError: () => {}, setWindow: () => {}, windowPending: false, ...extra });
const render = (C, state) => m.renderToStaticMarkup(m.createElement(C, { api: api(state) }));
const ready = (s) => ({ ...m.initialSwitchState, settings: s });
@@ -115,5 +116,57 @@ test('chip names the current mode and offers the other one', () => {
});
test('local note text', () => {
- assert.match(m.renderToStaticMarkup(m.createElement(m.LocalBrowserNote)), /Your bots are using a Chrome window on your computer\./);
+ assert.match(m.renderToStaticMarkup(m.createElement(m.LocalBrowserNote)), /Your bots&#x27;? Chrome is open as a window on your computer\./);
+});
+
+test('the window flag parses, defaults to the in-app view and only counts in local mode', () => {
+ const parsed = m.parseComputerSettings({
+ mode: 'local', available: { local: true, vm: false }, reasons: {},
+ window: { visible: true, available: false, reason: 'no display' },
+ });
+ assert.deepEqual(parsed.window, { visible: true, available: false, reason: 'no display' });
+ assert.equal(m.showsLocalWindow(parsed), true);
+ // older servers have no window field: local streams in the app
+ const old = m.parseComputerSettings({ mode: 'local', available: { local: true, vm: true } });
+ assert.deepEqual(old.window, { visible: false, available: false, reason: null });
+ assert.equal(m.showsLocalWindow(old), false);
+ assert.equal(m.showsLocalWindow({ ...parsed, mode: 'vm' }), false);
+ assert.equal(m.showsLocalWindow(null), false);
+});
+
+test('open-as-window button: local in-app only, disabled with the reason when no display', () => {
+ const btn = (s, extra) => m.renderToStaticMarkup(m.createElement(m.OpenWindowButton, { api: api(ready(s), extra), label: true }));
+ assert.equal(btn(settings('vm', true, true, {}, { available: true })), '');
+ assert.equal(btn(settings('local', true, true, {}, { visible: true, available: true })), '');
+ const ok = btn(settings('local', true, true, {}, { available: true }));
+ assert.match(ok, /Open as window/);
+ assert.doesNotMatch(ok, /disabled=""/);
+ const blocked = btn(settings('local', true, true, {}, { reason: 'no display' }));
+ assert.match(blocked, /disabled=""/);
+ assert.match(blocked, /Can&#x27;t open a window: no display/);
+ assert.match(btn(settings('local', true, true, {}, { available: true }), { windowPending: true }), /aria-busy="true"/);
+});
+
+test('the note offers to bring the browser back, and saveLocalWindow sends the flag', async () => {
+ let asked = null;
+ const note = m.renderToStaticMarkup(m.createElement(m.LocalBrowserNote, { api: api(ready(settings('local')), { setWindow: (v) => (asked = v) }) }));
+ assert.match(note, /Show it here instead/);
+ const realFetch = globalThis.fetch;
+ try {
+ let call;
+ globalThis.fetch = async (url, init) => { call = { url, init }; return new Response(JSON.stringify(settings('local', true, true, {}, { visible: true, available: true })), { status: 200 }); };
+ const r = await m.saveLocalWindow(true);
+ assert.equal(r.ok, true);
+ assert.equal(r.settings.window.visible, true);
+ assert.equal(call.url, '/api/settings/computer/window');
+ assert.equal(call.init.method, 'PUT');
+ assert.equal(call.init.body, '{"visible":true}');
+ globalThis.fetch = async () => new Response(JSON.stringify({ error: 'no display' }), { status: 400 });
+ assert.deepEqual(await m.saveLocalWindow(true), { ok: false, error: 'no display' });
+ globalThis.fetch = async () => new Response('', { status: 502 });
+ assert.deepEqual(await m.saveLocalWindow(false), { ok: false, error: 'Could not bring the browser back (HTTP 502).' });
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ assert.equal(asked, null, 'rendering alone does not switch');
});
diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rs
index 1396ba87..2f49ad99 100644
--- a/src/sandbox/computer.rs
+++ b/src/sandbox/computer.rs
@@ -1,5 +1,6 @@
//! Where bots do computer work: the person's own computer ("local": their installed Chrome with a
-//! kwant-only profile, and host shell commands that each need approval) or isolated containers
+//! kwant-only profile, run without a window and streamed into the app unless the person asks for
+//! a window, and host shell commands that each need approval) or isolated containers
//! ("vm": the Docker browser and executor). Local is the default on macOS, vm everywhere else.
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
@@ -121,19 +122,17 @@ pub fn has_display(os: &str, display: Option<&str>, wayland: Option<&str>) -> bo
}
}
-/// Why local mode cannot run here, or `None` if it can.
-pub fn local_unavailable_reason(chrome: Option<&Path>, display: bool) -> Option<String> {
- if chrome.is_none() {
- return Some(format!(
- "No Chrome or Chromium was found. Install Google Chrome, or set {CHROME_PATH_ENV} to its path."
- ));
- }
- if !display {
- return Some(
- "This computer has no screen to show a browser window on (no display).".into(),
- );
- }
- None
+/// Why local mode cannot run here, or `None` if it can. No display is needed: local Chrome runs
+/// without a window and the app shows it.
+pub fn local_unavailable_reason(chrome: Option<&Path>) -> Option<String> {
+ chrome.is_none().then(|| format!(
+ "No Chrome or Chromium was found. Install Google Chrome, or set {CHROME_PATH_ENV} to its path."
+ ))
+}
+
+/// Why local Chrome cannot be opened as a window here, or `None` if it can.
+pub fn window_unavailable_reason(display: bool) -> Option<String> {
+ (!display).then(|| "This computer has no screen to show a browser window on (no display).".into())
}
/// Why vm mode cannot run here, or `None` if it can. A configured browser service URL is enough
@@ -158,13 +157,16 @@ pub fn local_chrome_path() -> Option<PathBuf> {
/// [`local_unavailable_reason`] for this process's environment.
pub fn local_reason() -> Option<String> {
- let os = std::env::consts::OS;
- let display = has_display(
- os,
+ local_unavailable_reason(local_chrome_path().as_deref())
+}
+
+/// [`window_unavailable_reason`] for this process's environment.
+pub fn window_reason() -> Option<String> {
+ window_unavailable_reason(has_display(
+ std::env::consts::OS,
std::env::var("DISPLAY").ok().as_deref(),
std::env::var("WAYLAND_DISPLAY").ok().as_deref(),
- );
- local_unavailable_reason(local_chrome_path().as_deref(), display)
+ ))
}
/// Reads the debugging port Chrome writes to `DevToolsActivePort` in its profile folder.
@@ -173,46 +175,85 @@ pub fn read_devtools_port(profile: &Path) -> Option<u16> {
text.lines().next()?.trim().parse().ok().filter(|&p| p > 0)
}
-/// Chrome's command line for local mode: a headed window with its own profile, never the
-/// person's everyday one, and a debugging port Chrome picks itself (it listens on 127.0.0.1).
-pub fn chrome_args(profile: &Path) -> Vec<String> {
- vec![
+/// The viewport of windowless local Chrome, matching the vm browser and the in-app viewer.
+pub const HEADLESS_WINDOW_SIZE: &str = "1280,800";
+
+/// Chrome's command line for local mode: its own profile, never the person's everyday one, and a
+/// debugging port Chrome picks itself (it listens on 127.0.0.1). Without a window (`headless`)
+/// unless the person asked to see one.
+pub fn chrome_args(profile: &Path, headless: bool) -> Vec<String> {
+ let mut args = vec![
format!("--user-data-dir={}", profile.display()),
"--remote-debugging-port=0".into(),
"--remote-debugging-address=127.0.0.1".into(),
"--no-first-run".into(),
"--no-default-browser-check".into(),
- "about:blank".into(),
- ]
+ ];
+ if headless {
+ args.push("--headless=new".into());
+ args.push(format!("--window-size={HEADLESS_WINDOW_SIZE}"));
+ }
+ args.push("about:blank".into());
+ args
+}
+
+/// Whether a running Chrome is windowless, from its `/json/version` user agent.
+pub fn is_headless_user_agent(user_agent: &str) -> bool {
+ user_agent.contains("HeadlessChrome")
}
-async fn answers(endpoint: &str) -> bool {
- let client = reqwest::Client::builder()
+fn client() -> reqwest::Client {
+ reqwest::Client::builder()
.timeout(Duration::from_secs(2))
.build()
- .unwrap_or_default();
- client
- .get(format!("{endpoint}/json/version"))
- .send()
- .await
- .is_ok_and(|r| r.status().is_success())
+ .unwrap_or_default()
}
-/// Returns the CDP endpoint of the kwant Chrome window, reusing it while it runs and launching
-/// it (detached, so it outlives a switch or a kwant restart) when it does not.
-pub async fn ensure_local_chrome(profile: &Path) -> Result<String, String> {
- if let Some(port) = read_devtools_port(profile) {
- let endpoint = format!("http://127.0.0.1:{port}");
- if answers(&endpoint).await {
- return Ok(endpoint);
+/// The user agent of the Chrome answering at `endpoint`, or `None` if nothing answers.
+async fn user_agent(endpoint: &str) -> Option<String> {
+ let resp = client().get(format!("{endpoint}/json/version")).send().await.ok()?;
+ if !resp.status().is_success() {
+ return None;
+ }
+ let version: serde_json::Value = resp.json().await.ok()?;
+ Some(version["User-Agent"].as_str().unwrap_or_default().to_string())
+}
+
+/// The kwant Chrome running on `profile`: its CDP endpoint and whether it is windowless.
+pub async fn running_local_chrome(profile: &Path) -> Option<(String, bool)> {
+ let port = read_devtools_port(profile)?;
+ let endpoint = format!("http://127.0.0.1:{port}");
+ let agent = user_agent(&endpoint).await?;
+ Some((endpoint, is_headless_user_agent(&agent)))
+}
+
+/// Waits until the kwant Chrome on `profile` stops answering (it was asked to close).
+pub async fn wait_local_chrome_gone(profile: &Path) -> Result<(), String> {
+ for _ in 0..60 {
+ if running_local_chrome(profile).await.is_none() {
+ // Chrome drops its profile lock just after the port closes
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ return Ok(());
}
+ tokio::time::sleep(Duration::from_millis(250)).await;
}
+ Err("Chrome did not close within 15 seconds.".into())
+}
+
+/// Launches the kwant Chrome on `profile` (detached, so it outlives a switch or a kwant restart)
+/// and returns its CDP endpoint. The caller makes sure none is running on this profile.
+pub async fn launch_local_chrome(profile: &Path, headless: bool) -> Result<String, String> {
let chrome = local_chrome_path().ok_or_else(|| local_reason().unwrap_or_default())?;
+ if !headless {
+ if let Some(reason) = window_reason() {
+ return Err(reason);
+ }
+ }
std::fs::create_dir_all(profile).map_err(|e| e.to_string())?;
- // a stale port file from a closed window would point at nothing
+ // a stale port file from a closed Chrome would point at nothing
let _ = std::fs::remove_file(profile.join("DevToolsActivePort"));
let mut cmd = std::process::Command::new(&chrome);
- cmd.args(chrome_args(profile))
+ cmd.args(chrome_args(profile, headless))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
@@ -230,11 +271,8 @@ pub async fn ensure_local_chrome(profile: &Path) -> Result<String, String> {
let _ = child.wait();
});
for _ in 0..80 {
- if let Some(port) = read_devtools_port(profile) {
- let endpoint = format!("http://127.0.0.1:{port}");
- if answers(&endpoint).await {
- return Ok(endpoint);
- }
+ if let Some((endpoint, _)) = running_local_chrome(profile).await {
+ return Ok(endpoint);
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
@@ -341,14 +379,14 @@ mod tests {
assert!(has_display("linux", Some(":0"), None));
assert!(has_display("linux", None, Some("wayland-0")));
+ // local Chrome runs without a window, so only a window needs a display
let chrome = Path::new("/usr/bin/chromium");
- assert_eq!(local_unavailable_reason(Some(chrome), true), None);
- assert!(local_unavailable_reason(None, true)
+ assert_eq!(local_unavailable_reason(Some(chrome)), None);
+ assert!(local_unavailable_reason(None)
.unwrap()
.contains(CHROME_PATH_ENV));
- assert!(local_unavailable_reason(Some(chrome), false)
- .unwrap()
- .contains("display"));
+ assert_eq!(window_unavailable_reason(true), None);
+ assert!(window_unavailable_reason(false).unwrap().contains("display"));
assert_eq!(vm_unavailable_reason(true, false), None);
assert_eq!(vm_unavailable_reason(false, true), None);
@@ -359,10 +397,24 @@ mod tests {
#[test]
fn chrome_uses_its_own_profile_and_a_loopback_port() {
- let args = chrome_args(Path::new("/data/local-chrome"));
- assert!(args.contains(&"--user-data-dir=/data/local-chrome".to_string()));
- assert!(args.contains(&"--remote-debugging-port=0".to_string()));
- assert!(args.contains(&"--remote-debugging-address=127.0.0.1".to_string()));
+ for headless in [true, false] {
+ let args = chrome_args(Path::new("/data/local-chrome"), headless);
+ assert!(args.contains(&"--user-data-dir=/data/local-chrome".to_string()));
+ assert!(args.contains(&"--remote-debugging-port=0".to_string()));
+ assert!(args.contains(&"--remote-debugging-address=127.0.0.1".to_string()));
+ }
+ }
+
+ #[test]
+ fn chrome_is_windowless_unless_a_window_is_asked_for() {
+ let args = chrome_args(Path::new("/p"), true);
+ assert!(args.contains(&"--headless=new".to_string()));
+ assert!(args.contains(&"--window-size=1280,800".to_string()));
+ let args = chrome_args(Path::new("/p"), false);
+ assert!(!args.iter().any(|a| a.starts_with("--headless")));
+ assert!(!args.iter().any(|a| a.starts_with("--window-size")));
+ assert!(is_headless_user_agent("Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/131.0 Safari/537.36"));
+ assert!(!is_headless_user_agent("Mozilla/5.0 (Macintosh) Chrome/131.0 Safari/537.36"));
}
#[test]
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index 154ebdd1..9919dcbf 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -18,6 +18,10 @@ pub struct BrowserService {
endpoint: Option<String>,
/// Local Chrome or the vm browser; changing it drops the connection (see [`Self::set_mode`]).
mode: std::sync::RwLock<ComputerMode>,
+ /// Local mode only: whether the person asked to see the kwant Chrome as a window (to sign in
+ /// or solve a CAPTCHA). Otherwise it runs without one and the app streams it. Not saved: a
+ /// restart goes back to the in-app view.
+ local_window: std::sync::atomic::AtomicBool,
// Serialize startup and session creation, including simultaneous status/frame requests.
state: Mutex<Option<ServiceState>>,
}
@@ -31,25 +35,113 @@ struct ServiceState {
impl BrowserService {
pub fn new(root: PathBuf, endpoint: Option<String>) -> Self {
let mode = computer::current_mode(None);
- Self { root, endpoint, mode: std::sync::RwLock::new(mode), state: Mutex::new(None) }
+ Self {
+ root, endpoint, mode: std::sync::RwLock::new(mode),
+ local_window: std::sync::atomic::AtomicBool::new(false), state: Mutex::new(None),
+ }
}
pub fn mode(&self) -> ComputerMode {
*self.mode.read().unwrap_or_else(|e| e.into_inner())
}
+ /// Whether local Chrome is shown as a window instead of in the app.
+ pub fn local_window(&self) -> bool {
+ self.local_window.load(std::sync::atomic::Ordering::SeqCst)
+ }
+
+ fn local_profile(&self) -> PathBuf { self.root.join("local-chrome") }
+
+ /// Shows the local Chrome as a real window (`visible`) or runs it without one, streamed into
+ /// the app. One profile cannot be open twice, so the running Chrome is closed and started
+ /// again in the other form; each bot's open page is reopened there, and sign-ins saved in the
+ /// profile carry over. On failure the previous form is kept.
+ pub async fn set_local_window(&self, visible: bool) -> Result<(), BrowserError> {
+ use std::sync::atomic::Ordering::SeqCst;
+ let mut lock = self.state.lock().await;
+ let previous = self.local_window.swap(visible, SeqCst);
+ if self.mode() != ComputerMode::Local { return Ok(()); }
+ // the page each bot had open, to reopen in the new Chrome
+ let mut urls: HashMap<String, String> = HashMap::new();
+ if let Some((endpoint, _)) = computer::running_local_chrome(&self.local_profile()).await {
+ let browser = BrowserController::at_endpoint(&endpoint, None, None, true);
+ if let Ok(targets) = browser.send_cdp_command("Target.getTargets", json!({})).await {
+ for info in targets["targetInfos"].as_array().into_iter().flatten() {
+ if let (Some(id), Some(url)) = (info["targetId"].as_str(), info["url"].as_str()) {
+ urls.insert(id.to_string(), url.to_string());
+ }
+ }
+ }
+ }
+ *lock = None;
+ let mut state = match self.connect().await {
+ Ok(state) => state,
+ Err(error) => { self.local_window.store(previous, SeqCst); return Err(error); }
+ };
+ let live = state.browser.send_cdp_command("Target.getTargets", json!({})).await?;
+ let live: Vec<(String, bool)> = live["targetInfos"].as_array().into_iter().flatten()
+ .filter_map(|t| Some((t["targetId"].as_str()?.to_string(), t["type"] == "page" && t["url"] == "about:blank")))
+ .collect();
+ for session in state.sessions.values_mut() {
+ if live.iter().any(|(id, _)| *id == session.target) { continue; }
+ let url = urls.get(&session.target).filter(|u| u.starts_with("http")).map_or("about:blank", |u| u.as_str());
+ if let Ok(target) = state.browser.send_cdp_command("Target.createTarget", json!({"url": url, "newWindow": true})).await {
+ if let Some(id) = target["targetId"].as_str() { session.target = id.to_string(); }
+ }
+ }
+ // Chrome's own blank start window would sit on top of the bots' pages in the window
+ if visible && !state.sessions.is_empty() {
+ for (id, _) in live.iter().filter(|(id, blank)| *blank && !state.sessions.values().any(|s| s.target == *id)) {
+ let _ = state.browser.send_cdp_command("Target.closeTarget", json!({"targetId": id})).await;
+ }
+ }
+ self.save_sessions(&state.sessions).await?;
+ *lock = Some(state);
+ Ok(())
+ }
+
+ /// The local Chrome's endpoint, in the form asked for (window or not), starting it if needed.
+ async fn local_endpoint(&self) -> Result<String, BrowserError> {
+ let profile = self.local_profile();
+ let headless = !self.local_window();
+ if let Some((endpoint, running_headless)) = computer::running_local_chrome(&profile).await {
+ if running_headless == headless { return Ok(endpoint); }
+ // the other form is running on this profile: close it first
+ let _ = BrowserController::at_endpoint(&endpoint, None, None, true)
+ .send_cdp_command("Browser.close", json!({})).await;
+ computer::wait_local_chrome_gone(&profile).await.map_err(BrowserError::Http)?;
+ }
+ computer::launch_local_chrome(&profile, headless).await.map_err(BrowserError::Http)
+ }
+
+ async fn save_sessions(&self, sessions: &HashMap<String, SessionTarget>) -> Result<(), BrowserError> {
+ tokio::fs::create_dir_all(&self.root).await.map_err(|e| BrowserError::Http(e.to_string()))?;
+ let file = self.sessions_file();
+ tokio::fs::write(file.with_extension("tmp"), serde_json::to_vec(sessions).unwrap()).await
+ .map_err(|e| BrowserError::Http(e.to_string()))?;
+ tokio::fs::rename(file.with_extension("tmp"), file).await.map_err(|e| BrowserError::Http(e.to_string()))
+ }
+
/// Whether a browser service URL (`KWNT_BROWSER_CDP_URL`) is configured for vm mode.
pub fn has_endpoint(&self) -> bool { self.endpoint.is_some() }
- /// Switches where the browser runs. The current connection is dropped, not the browser:
- /// the local Chrome window and the vm container both keep running. Returns whether the
- /// mode changed.
+ /// Switches where the browser runs. The current connection is dropped; the vm container and
+ /// a local Chrome window keep running, while a windowless local Chrome is closed, since
+ /// nothing would show it. Returns whether the mode changed.
pub async fn set_mode(&self, mode: ComputerMode) -> bool {
let mut lock = self.state.lock().await;
- let mut current = self.mode.write().unwrap_or_else(|e| e.into_inner());
- if *current == mode { return false; }
- *current = mode;
+ let previous = {
+ let mut current = self.mode.write().unwrap_or_else(|e| e.into_inner());
+ if *current == mode { return false; }
+ std::mem::replace(&mut *current, mode)
+ };
*lock = None;
+ if previous == ComputerMode::Local {
+ if let Some((endpoint, true)) = computer::running_local_chrome(&self.local_profile()).await {
+ let _ = BrowserController::at_endpoint(&endpoint, None, None, true)
+ .send_cdp_command("Browser.close", json!({})).await;
+ }
+ }
true
}
@@ -106,8 +198,7 @@ impl BrowserService {
async fn connect(&self) -> Result<ServiceState, BrowserError> {
let local = self.mode() == ComputerMode::Local;
let endpoint = match &self.endpoint {
- _ if local => computer::ensure_local_chrome(&self.root.join("local-chrome")).await
- .map_err(BrowserError::Http)?,
+ _ if local => self.local_endpoint().await?,
Some(endpoint) => endpoint.trim_end_matches('/').to_string(),
None => self.managed_endpoint().await?,
};
@@ -130,7 +221,9 @@ impl BrowserService {
if lock.is_none() { *lock = Some(self.connect().await?); }
let mut targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;
if targets.is_err() && self.mode() == ComputerMode::Local {
- // the person closed the Chrome window: open it again in this same call
+ // Chrome quit, or the person closed its window once done there: start it again in
+ // this same call, back in the app
+ self.local_window.store(false, std::sync::atomic::Ordering::SeqCst);
*lock = None;
*lock = Some(self.connect().await?);
targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;
@@ -145,8 +238,9 @@ impl BrowserService {
let local = self.mode() == ComputerMode::Local;
let session = if let Some(existing) = existing { existing.clone() } else if local {
// Local pages share the kwant profile's default context, so a sign-in in the window
- // is kept; each bot still gets its own tab. (`context` stays empty.)
- let target = state.browser.send_cdp_command("Target.createTarget", json!({"url": "about:blank"})).await?;
+ // is kept. (`context` stays empty.) Each bot gets its own window, not a tab: Chrome
+ // only paints the front tab of a window, so a background tab's screenshot never comes.
+ let target = state.browser.send_cdp_command("Target.createTarget", json!({"url": "about:blank", "newWindow": true})).await?;
SessionTarget { context: String::new(), target: target["targetId"].as_str()
.ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() }
} else {
@@ -168,14 +262,10 @@ impl BrowserService {
.ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() }
};
state.sessions.insert(id.to_string(), session.clone());
- tokio::fs::create_dir_all(&self.root).await.map_err(|e| BrowserError::Http(e.to_string()))?;
- let file = self.sessions_file();
- tokio::fs::write(file.with_extension("tmp"), serde_json::to_vec(&state.sessions).unwrap()).await
- .map_err(|e| BrowserError::Http(e.to_string()))?;
- tokio::fs::rename(file.with_extension("tmp"), file).await.map_err(|e| BrowserError::Http(e.to_string()))?;
+ self.save_sessions(&state.sessions).await?;
let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target), Some(workspace.to_path_buf()), false);
- // A real window keeps its own size; only the headless vm browser gets a fixed viewport.
- if !local {
+ // A real window keeps its own size; a windowless browser gets the viewer's fixed viewport.
+ if !local || !self.local_window() {
ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride", json!({
"width": 1280, "height": 800, "deviceScaleFactor": 1, "mobile": false
})).await?;
diff --git a/src/server/computer.rs b/src/server/computer.rs
index b83f93e9..dc8bea21 100644
--- a/src/server/computer.rs
+++ b/src/server/computer.rs
@@ -47,10 +47,16 @@ async fn view(state: &AppState) -> Value {
state.sandbox_manager.is_docker_available().await,
state.browser_service.has_endpoint(),
);
+ let window = computer::window_reason();
json!({
"mode": mode,
"available": {"local": local.is_none(), "vm": vm.is_none()},
"reasons": {"local": local, "vm": vm},
+ "window": {
+ "visible": mode == ComputerMode::Local && state.browser_service.local_window(),
+ "available": window.is_none(),
+ "reason": window,
+ },
})
}
@@ -94,6 +100,54 @@ pub async fn put_computer(
Ok(Json(view(&state).await))
}
+#[derive(Deserialize)]
+pub struct WindowPayload {
+ pub visible: bool,
+}
+
+/// `PUT /api/settings/computer/window` with `{"visible":bool}`: in local mode, shows the bots'
+/// Chrome as a real window (for a sign-in or CAPTCHA) or puts it back in the app. Each bot's open
+/// page is reopened in the other form. 400 outside local mode or with no display for a window;
+/// 502 if Chrome could not be restarted (the previous form is kept).
+pub async fn put_window(
+ State(state): State<AppState>,
+ payload: Result<Json<WindowPayload>, axum::extract::rejection::JsonRejection>,
+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
+ let fail = |status, m: String| (status, Json(json!({ "error": m })));
+ let Json(WindowPayload { visible }) = payload
+ .map_err(|_| fail(StatusCode::BAD_REQUEST, "visible must be true or false".into()))?;
+ if apply_mode(&state).await != ComputerMode::Local {
+ return Err(fail(
+ StatusCode::BAD_REQUEST,
+ "The browser runs in the VM, which has no window to open. Switch to Local computer first.".into(),
+ ));
+ }
+ if visible {
+ if let Some(reason) = computer::window_reason() {
+ return Err(fail(StatusCode::BAD_REQUEST, reason));
+ }
+ }
+ {
+ // the restarted Chrome has new pages: every controller must reconnect
+ let mut controllers = state.browser_controllers.lock().await;
+ if let Err(error) = state.browser_service.set_local_window(visible).await {
+ tracing::warn!("Could not restart local Chrome: {}", error);
+ return Err(fail(
+ StatusCode::BAD_GATEWAY,
+ format!("Could not restart Chrome: {error}"),
+ ));
+ }
+ for team_id in controllers.drain().map(|(id, _)| id) {
+ let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
+ team_id,
+ container_name: "browser-service".into(),
+ is_running: false,
+ });
+ }
+ }
+ Ok(Json(view(&state).await))
+}
+
/// Asks the person before a shell command runs on their own computer. Every command asks:
/// "always allow" is honoured for this one command only, never remembered.
pub async fn approve_local_shell(
diff --git a/src/server/mod.rs b/src/server/mod.rs
index eaa5dc49..5a1974e1 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -157,6 +157,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/approvals/:id/resolve", post(routes::resolve_approval))
.route("/api/settings", get(routes::get_settings).post(routes::save_settings))
.route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer))
+ .route("/api/settings/computer/window", put(computer::put_window))
.route("/api/system/directories", get(routes::list_system_directories))
.route("/api/system/select-folder", post(routes::select_folder))
.route("/api/sandbox/:team_id/status", get(routes::get_sandbox_status))
diff --git a/tests/computer_mode_test.rs b/tests/computer_mode_test.rs
index b57ad697..142844c9 100644
--- a/tests/computer_mode_test.rs
+++ b/tests/computer_mode_test.rs
@@ -1,5 +1,6 @@
//! Settings → Computer API and local-mode shell approval. One test function, because it changes
//! process environment (Chrome path, display, KWNT_COMPUTER_MODE) step by step.
+//! The real-Chrome side of local mode is in `local_chrome_test.rs`.
use axum::{
body::Body,
http::{Request, StatusCode},
@@ -36,6 +37,19 @@ async fn call(app: &axum::Router, method: &str, body: Option<Value>) -> (StatusC
)
}
+async fn put_window(app: &axum::Router, body: Value) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method("PUT")
+ .uri("/api/settings/computer/window")
+ .header("content-type", "application/json")
+ .body(Body::from(body.to_string()))
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
async fn next_approval(rx: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> (String, Value) {
loop {
let event = tokio::time::timeout(std::time::Duration::from_secs(10), rx.recv())
@@ -73,6 +87,8 @@ async fn computer_mode_api_and_local_shell_approval() {
let fake_chrome = tmp.path().join("fake-chrome");
std::fs::write(&fake_chrome, "").unwrap();
std::env::remove_var("KWNT_COMPUTER_MODE");
+ std::env::remove_var("DISPLAY");
+ std::env::remove_var("WAYLAND_DISPLAY");
std::env::set_var("KWNT_CHROME_PATH", tmp.path().join("missing-chrome"));
let db = Database::init(tmp.path()).await.unwrap();
@@ -102,6 +118,12 @@ async fn computer_mode_api_and_local_shell_approval() {
.unwrap()
.contains("KWNT_CHROME_PATH"));
assert_eq!(view["reasons"]["vm"], Value::Null);
+ assert_eq!(view["window"]["visible"], false);
+ if cfg!(target_os = "linux") {
+ // no display: Chrome can still run in the app, just not as a window
+ assert_eq!(view["window"]["available"], false);
+ assert!(view["window"]["reason"].as_str().unwrap().contains("display"));
+ }
// PUT: bad bodies and unavailable modes are 400 and save nothing
for body in [
@@ -134,15 +156,30 @@ async fn computer_mode_api_and_local_shell_approval() {
assert_eq!(call(&app, "GET", None).await.1["mode"], "vm");
assert_eq!(state.browser_service.mode(), ComputerMode::Vm);
- // with a Chrome and a display, local becomes available and switching works at runtime
+ // the window switch is local-only
+ let (status, err) = put_window(&app, json!({"visible": true})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(err["error"].as_str().unwrap().contains("Local computer"), "{err}");
+
+ // with a Chrome (no display needed), local becomes available and switching works at runtime
std::env::set_var("KWNT_CHROME_PATH", &fake_chrome);
- std::env::set_var("DISPLAY", ":99");
let (status, view) = call(&app, "PUT", Some(json!({"mode": "local"}))).await;
assert_eq!(status, StatusCode::OK, "{view}");
assert_eq!(view["mode"], "local");
assert_eq!(view["available"]["local"], true);
assert_eq!(state.browser_service.mode(), ComputerMode::Local);
+ // a window needs a display; a bad body is 400 too. Neither changes anything.
+ for body in [json!({}), json!({"visible": "yes"})] {
+ assert_eq!(put_window(&app, body).await.0, StatusCode::BAD_REQUEST);
+ }
+ if cfg!(target_os = "linux") {
+ let (status, err) = put_window(&app, json!({"visible": true})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(err["error"].as_str().unwrap().contains("display"), "{err}");
+ assert!(!state.browser_service.local_window());
+ }
+
// local shell: every command needs approval; a denied one does not run
let mut rx = state.event_sender.subscribe();
let marker = tmp.path().join("workspace").join("ran.txt");
diff --git a/tests/local_chrome_test.rs b/tests/local_chrome_test.rs
new file mode 100644
index 00000000..002f2fe5
--- /dev/null
+++ b/tests/local_chrome_test.rs
@@ -0,0 +1,119 @@
+//! Local mode against a real Chrome/Chromium: it runs without a window, pages render and take
+//! input at the viewer's 1280x800 size, and the window switch reopens the same page in a real
+//! window and back. Skipped when no Chrome is installed; the window part needs Xvfb on Linux.
+use kwnt::sandbox::{
+ computer::{self, ComputerMode},
+ service::BrowserService,
+};
+use kwnt::server::browser_stream::BrowserInput;
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+const PAGE: &str = "<!doctype html><title>before</title><body style=margin:0>\
+<button id=b style='position:absolute;left:0;top:0;width:400px;height:300px' \
+onclick=\"document.title='clicked '+innerWidth+'x'+innerHeight\">press</button>";
+
+/// A one-page HTTP server on 127.0.0.1, so the test needs no network.
+async fn serve_page() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 2048];
+ let _ = stream.read(&mut buf).await;
+ let reply = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{PAGE}",
+ PAGE.len()
+ );
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}/page")
+}
+
+async fn title_becomes(ctrl: &kwnt::sandbox::BrowserController, want: &str) -> String {
+ let mut title = String::new();
+ for _ in 0..40 {
+ if let Some((_, t)) = ctrl.sync_location().await {
+ title = t;
+ if title == want { break; }
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ title
+}
+
+#[tokio::test]
+async fn local_chrome_runs_windowless_and_can_open_as_a_window() {
+ std::env::remove_var("DISPLAY");
+ std::env::remove_var("WAYLAND_DISPLAY");
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let profile = tmp.path().join("local-chrome");
+ let service = BrowserService::new(tmp.path().to_path_buf(), None);
+ service.set_mode(ComputerMode::Local).await;
+ let url = serve_page().await;
+
+ // windowless: no display is needed, and the page gets the viewer's viewport
+ service.session("other", tmp.path()).await.expect("first session");
+ let ctrl = service.session("bot", tmp.path()).await.expect("local session");
+ let (endpoint, headless) = computer::running_local_chrome(&profile).await.expect("chrome running");
+ assert!(headless, "local Chrome must start without a window");
+ ctrl.navigate(&url).await.unwrap();
+ assert!(!ctrl.capture_screenshot().await.unwrap().is_empty());
+ // the same input path the in-app viewer uses
+ ctrl.dispatch_input(BrowserInput::Click { x: 100.0, y: 100.0 }).await.unwrap();
+ assert_eq!(title_becomes(&ctrl, "clicked 1280x800").await, "clicked 1280x800");
+ // the other bot's page must still paint while this one is in front: a background tab never
+ // does once its viewer override is gone, so look at it over a fresh connection
+ let sessions: serde_json::Value = serde_json::from_slice(
+ &std::fs::read(tmp.path().join("browser-sessions-local.json")).unwrap()).unwrap();
+ let other_target = sessions["other"]["target"].as_str().expect("other bot's page").to_string();
+ let other = kwnt::sandbox::BrowserController::at_endpoint(&endpoint, Some(other_target), None, false);
+ let shot = tokio::time::timeout(Duration::from_secs(5), other.capture_screenshot()).await;
+ assert!(matches!(shot, Ok(Ok(ref s)) if !s.is_empty()), "screenshot of the other bot's page: {shot:?}");
+
+ // the window switch, where a display exists (Xvfb stands in for a desktop)
+ let xvfb = std::process::Command::new("Xvfb").args([":97", "-screen", "0", "1440x900x24"])
+ .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn();
+ if let Ok(mut xvfb) = xvfb {
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ std::env::set_var("DISPLAY", ":97");
+ service.set_local_window(true).await.expect("open as a window");
+ assert!(service.local_window());
+ let (_, headless) = computer::running_local_chrome(&profile).await.expect("chrome running");
+ assert!(!headless, "the window form must be a real window");
+ // only the two bots' pages are open: Chrome's blank start window is not left on top
+ let (endpoint, _) = computer::running_local_chrome(&profile).await.unwrap();
+ let browser = kwnt::sandbox::BrowserController::at_endpoint(&endpoint, None, None, true);
+ let targets = browser.send_cdp_command("Target.getTargets", serde_json::json!({})).await.unwrap();
+ let pages: Vec<_> = targets["targetInfos"].as_array().unwrap().iter()
+ .filter(|t| t["type"] == "page").map(|t| t["url"].as_str().unwrap_or("").to_string()).collect();
+ assert_eq!(pages.len(), 2, "pages in the window form: {pages:?}");
+ // the bot's page was reopened there
+ let ctrl = service.session("bot", tmp.path()).await.unwrap();
+ ctrl.refresh_location().await.unwrap();
+ assert_eq!(ctrl.current_url.lock().await.as_deref(), Some(url.as_str()));
+
+ // and back into the app, again with the page
+ service.set_local_window(false).await.expect("back to the app");
+ let (_, headless) = computer::running_local_chrome(&profile).await.expect("chrome running");
+ assert!(headless);
+ let ctrl = service.session("bot", tmp.path()).await.unwrap();
+ ctrl.refresh_location().await.unwrap();
+ assert_eq!(ctrl.current_url.lock().await.as_deref(), Some(url.as_str()));
+ let _ = xvfb.kill();
+ let _ = xvfb.wait();
+ } else {
+ eprintln!("window part skipped: no Xvfb");
+ }
+
+ // leaving local mode closes the windowless Chrome, since nothing would show it
+ service.set_mode(ComputerMode::Vm).await;
+ computer::wait_local_chrome_gone(&profile).await.expect("windowless Chrome closed");
+}