Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions apps/daemon/src/browser-sessions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const STARTUP_TIMEOUT_MS = 15_000;
const SHUTDOWN_GRACE_MS = 2_000;

export interface BrowserSessionView {
id: string;
websocketUrl: string;
}

interface BrowserSession extends BrowserSessionView {
child: ChildProcess;
profileDir: string;
closing: boolean;
}

function firstExisting(candidates: Array<string | undefined>): string | null {
return candidates.find((candidate): candidate is string => Boolean(candidate && fs.existsSync(candidate))) ?? null;
}

function executableFromPath(names: string[]): string | null {
const pathValue = process.env.PATH || process.env.Path || '';
const extensions = process.platform === 'win32'
? (process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';')
: [''];
for (const directory of pathValue.split(path.delimiter).filter(Boolean)) {
for (const name of names) {
for (const extension of extensions) {
const candidate = path.join(directory, `${name}${extension}`);
if (fs.existsSync(candidate)) return candidate;
}
}
}
return null;
}

export function findBrowserExecutable(): string | null {
const configured = process.env.OD_BROWSER_EXECUTABLE_PATH;
if (configured) return fs.existsSync(configured) ? configured : null;
if (process.platform === 'darwin') {
return firstExisting([
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
'/Applications/Chromium.app/Contents/MacOS/Chromium',
path.join(os.homedir(), 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'),
path.join(os.homedir(), 'Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'),
]);
}
if (process.platform === 'win32') {
const roots = [
process.env.PROGRAMFILES,
process.env['PROGRAMFILES(X86)'],
process.env.LOCALAPPDATA,
].filter((value): value is string => Boolean(value));
return firstExisting(roots.flatMap((root) => [
path.join(root, 'Google/Chrome/Application/chrome.exe'),
path.join(root, 'Microsoft/Edge/Application/msedge.exe'),
path.join(root, 'Chromium/Application/chrome.exe'),
]));
}
return executableFromPath([
'google-chrome-stable',
'google-chrome',
'microsoft-edge-stable',
'microsoft-edge',
'chromium',
'chromium-browser',
]);
}

function waitForExit(child: ChildProcess, timeoutMs: number): Promise<void> {
if (child.exitCode != null || child.signalCode != null) return Promise.resolve();
return Promise.race([
new Promise<void>((resolve) => child.once('exit', () => resolve())),
new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),
]);
}

export function createBrowserSessionService() {
const sessions = new Map<string, BrowserSession>();

const close = async (id: string): Promise<boolean> => {
const session = sessions.get(id);
if (!session) return false;
sessions.delete(id);
if (session.closing) return true;
session.closing = true;
if (session.child.exitCode == null && session.child.signalCode == null) {
session.child.kill('SIGTERM');
await waitForExit(session.child, SHUTDOWN_GRACE_MS);
if (session.child.exitCode == null && session.child.signalCode == null) {
session.child.kill('SIGKILL');
}
}
Comment thread
lefarcen marked this conversation as resolved.
fs.rmSync(session.profileDir, { recursive: true, force: true });
return true;
};

const create = async (): Promise<BrowserSessionView> => {
const executablePath = findBrowserExecutable();
if (!executablePath) {
throw new Error(
'No compatible Chrome, Edge, or Chromium executable is available. '
+ 'Install a system browser or set OD_BROWSER_EXECUTABLE_PATH.',
);
}
const id = randomUUID();
const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), 'od-browser-session-'));
const child = spawn(executablePath, [
'--headless=new',
'--remote-debugging-port=0',
'--remote-allow-origins=*',
`--user-data-dir=${profileDir}`,
'--no-first-run',
'--no-default-browser-check',
'--disable-background-networking',
'--disable-component-update',
Comment thread
lefarcen marked this conversation as resolved.
'--disable-default-apps',
'--disable-sync',
'--metrics-recording-only',
'about:blank',
], { stdio: ['ignore', 'pipe', 'pipe'] });

let output = '';
const websocketUrl = await new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('system browser startup timed out')), STARTUP_TIMEOUT_MS);
timer.unref?.();
const finish = (callback: () => void) => {
clearTimeout(timer);
child.stdout?.off('data', inspect);
child.stderr?.off('data', inspect);
child.off('error', onError);
child.off('exit', onExit);
callback();
};
const inspect = (chunk: Buffer | string) => {
output = `${output}${String(chunk)}`.slice(-16_384);
const match = output.match(/DevTools listening on (ws:\/\/[^\s]+)/);
const discoveredUrl = match?.[1];
if (discoveredUrl) finish(() => resolve(discoveredUrl));
};
const onError = (error: Error) => finish(() => reject(error));
const onExit = (code: number | null, signal: NodeJS.Signals | null) => finish(() => reject(
new Error(`system browser exited before CDP was ready (code ${code}, signal ${signal})\n${output}`),
));
child.stdout?.on('data', inspect);
child.stderr?.on('data', inspect);
child.once('error', onError);
child.once('exit', onExit);
}).catch((error) => {
child.kill('SIGKILL');
fs.rmSync(profileDir, { recursive: true, force: true });
throw error;
});

const session: BrowserSession = { id, websocketUrl, child, profileDir, closing: false };
sessions.set(id, session);
child.once('exit', () => {
if (!session.closing) {
sessions.delete(id);
fs.rmSync(profileDir, { recursive: true, force: true });
}
});
return { id, websocketUrl };
};

const shutdownActive = async (): Promise<void> => {
await Promise.all([...sessions.keys()].map((id) => close(id)));
};

return { create, close, shutdownActive };
}

export type BrowserSessionService = ReturnType<typeof createBrowserSessionService>;
40 changes: 40 additions & 0 deletions apps/daemon/src/routes/browser-sessions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Express } from 'express';
import type { BrowserSessionService } from '../browser-sessions.js';
import type { AuthorizeProjectRequest } from '../collab/project-request-authority.js';
import type { RouteDeps } from '../server-context.js';

export interface RegisterBrowserSessionRoutesDeps extends RouteDeps<'db' | 'http' | 'projectStore'> {
browserSessions: BrowserSessionService;
authorizeProjectRequest: AuthorizeProjectRequest;
}

export function registerBrowserSessionRoutes(app: Express, ctx: RegisterBrowserSessionRoutesDeps): void {
const { db, browserSessions, authorizeProjectRequest } = ctx;
const { getProject } = ctx.projectStore;
const { sendApiError } = ctx.http;

app.post('/api/projects/:id/browser-sessions', async (req, res) => {
if (!getProject(db, req.params.id)) {
return sendApiError(res, 404, 'PROJECT_NOT_FOUND', 'project not found');
}
if (!await authorizeProjectRequest(req, res, req.params.id, { mode: 'read' })) return;
try {
res.json({ browserSession: await browserSessions.create() });
} catch (error) {
sendApiError(
res,
503,
'BROWSER_SESSION_START_FAILED',
error instanceof Error ? error.message : String(error),
);
}
});

app.delete('/api/projects/:id/browser-sessions/:sessionId', async (req, res) => {
if (!getProject(db, req.params.id)) {
return sendApiError(res, 404, 'PROJECT_NOT_FOUND', 'project not found');
}
if (!await authorizeProjectRequest(req, res, req.params.id, { mode: 'read' })) return;
res.json({ closed: await browserSessions.close(req.params.sessionId) });
});
}
11 changes: 11 additions & 0 deletions apps/daemon/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,9 @@ import { TranscriptExportLockedError } from './transcript-export.js';
import { registerChatRoutes } from './routes/chat.js';
import { registerRunRoutes } from './routes/runs.js';
import { registerTerminalRoutes } from './routes/terminal.js';
import { registerBrowserSessionRoutes } from './routes/browser-sessions.js';
import { createTerminalService } from './terminals.js';
import { createBrowserSessionService } from './browser-sessions.js';
import { registerSocialShareRoutes } from './routes/social-share.js';
import { registerOpenDesignPublicMetadataRoutes } from './routes/open-design-public-metadata.js';
import { registerWhatsNewRoutes } from './routes/whats-new.js';
Expand Down Expand Up @@ -7109,6 +7111,7 @@ export async function startServer({
// Interactive Terminal sessions (node-pty). In-memory, process-local, and
// killed on daemon shutdown — see shutdownDaemonRuns below.
const terminalService = createTerminalService();
const browserSessionService = createBrowserSessionService();

// Tracks runs whose finalized assistant message has already been forwarded
// to Langfuse so repeated message updates only emit one final trace per run.
Expand Down Expand Up @@ -7948,6 +7951,13 @@ export async function startServer({
terminals: terminalService,
authorizeProjectRequest,
});
registerBrowserSessionRoutes(app, {
db,
http: httpDeps,
projectStore: projectStoreDeps,
browserSessions: browserSessionService,
authorizeProjectRequest,
});
registerImportRoutes(app, {
db,
http: httpDeps,
Expand Down Expand Up @@ -14989,6 +14999,7 @@ export async function startServer({
daemonShuttingDown = true;
await design.runs.shutdownActive({ graceMs: resolveChatRunShutdownGraceMs() });
await terminalService.shutdownActive();
await browserSessionService.shutdownActive();
await design.analytics.shutdown();
};
let server;
Expand Down
8 changes: 8 additions & 0 deletions apps/daemon/tests/server-bootstrap-regression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,13 @@ describe('server route inventory', () => {
'POST /api/media/tasks/:id/wait',
'GET /api/projects/:id/media/tasks',
];
// Website Clone agents use these project-scoped routes to ask the daemon
// to launch system Chrome outside their process sandbox. This is also the
// headless `od` CLI path, so it must remain registered without Electron.
const browserSessionRouteKeys = [
'POST /api/projects/:id/browser-sessions',
'DELETE /api/projects/:id/browser-sessions/:sessionId',
];

expect(routeKeys).toEqual(expect.arrayContaining([
'GET /api/health',
Expand Down Expand Up @@ -257,6 +264,7 @@ describe('server route inventory', () => {
expect(routeKeys.filter((key) => designSystemRouteKeys.includes(key))).toEqual(designSystemRouteKeys);
expect(routeKeys.filter((key) => staticCatalogRouteKeys.includes(key))).toEqual(staticCatalogRouteKeys);
expect(routeKeys.filter((key) => mediaConfigRouteKeys.includes(key))).toEqual(mediaConfigRouteKeys);
expect(routeKeys.filter((key) => browserSessionRouteKeys.includes(key))).toEqual(browserSessionRouteKeys);

expect(fallbackIndex).toBeGreaterThan(-1);
expect(routeKeys.indexOf('GET /api/health')).toBeLessThan(fallbackIndex);
Expand Down
Loading
Loading