mirror of
https://github.com/garrytan/gstack.git
synced 2026-05-19 02:42:29 +08:00
* plan: batch command endpoint + multi-tab parallel execution for GStack Browser * refactor: extract TabSession from BrowserManager for per-tab state Move per-tab state (refMap, lastSnapshot, frame) into a new TabSession class. BrowserManager delegates to the active TabSession via getActiveSession(). Zero behavior change — all existing tests pass. This is the foundation for the /batch endpoint: both /command and /batch will use the same handler functions with TabSession, eliminating shared state races during parallel tab execution. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: update handler signatures to use TabSession Change handleReadCommand and handleSnapshot to take TabSession instead of BrowserManager. Change handleWriteCommand to take both TabSession (per-tab ops) and BrowserManager (global ops like viewport, headers, dialog). handleMetaCommand keeps BrowserManager for tab management. Tests use thin wrapper functions that bridge the old 3-arg call pattern to the new signatures via bm.getActiveSession(). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add POST /batch endpoint for parallel multi-tab execution Execute multiple commands across tabs in a single HTTP request. Commands targeting different tabs run concurrently via Promise.allSettled. Commands targeting the same tab run sequentially within that group. Features: - Batch-safe command subset (text, goto, click, snapshot, screenshot, etc.) - newtab/closetab as special commands within batch - SSE streaming mode (stream: true) for partial results - Per-command error isolation (one tab failing doesn't abort the batch) - Max 50 commands per batch, soft batch-level timeout A 143-page crawl drops from ~45 min (serial HTTP) to ~5 min (20 tabs in parallel, batched commands). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: add batch endpoint integration tests 10 tests covering: - Multi-tab parallel execution (goto + text on different tabs) - Same-tab sequential ordering - Per-command error isolation (one tab fails, others succeed) - Page-scoped refs (snapshot refs are per-session, not global) - Per-tab lastSnapshot (snapshot -D with independent baselines) - getSession/getActiveSession API - Batch-safe command subset validation - closeTab via page.close preserves at-least-one-page invariant - Parallel goto on 3 tabs simultaneously Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: harden codex-review E2E — extract SKILL.md section, bump maxTurns to 25 The test was copying the full 55KB/1075-line codex SKILL.md into the fixture, requiring 8 Read calls just to consume it and exhausting the 15-turn budget before reaching the actual codex review command. Now extracts only the review-relevant section (~6KB/148 lines), reducing Read calls from 8 to 1. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: move batch endpoint plan into BROWSER.md as feature documentation The batch endpoint is implemented — document it as an actual feature in BROWSER.md (architecture, API shape, design decisions, usage pattern) and remove the standalone plan file. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v0.15.16.0) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: gstack <ship@gstack.dev> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
230 lines
8.6 KiB
TypeScript
230 lines
8.6 KiB
TypeScript
/**
|
|
* Cookie picker route handler — HTTP + Playwright glue
|
|
*
|
|
* Handles all /cookie-picker/* routes. Imports from cookie-import-browser.ts
|
|
* (decryption) and cookie-picker-ui.ts (HTML generation).
|
|
*
|
|
* Routes (no auth — localhost-only, accepted risk):
|
|
* GET /cookie-picker → serves the picker HTML page
|
|
* GET /cookie-picker/browsers → list installed browsers
|
|
* GET /cookie-picker/domains → list domains + counts for a browser
|
|
* POST /cookie-picker/import → decrypt + import cookies to Playwright
|
|
* POST /cookie-picker/remove → clear cookies for domains
|
|
* GET /cookie-picker/imported → currently imported domains + counts
|
|
*/
|
|
|
|
import type { BrowserManager } from './browser-manager';
|
|
import { findInstalledBrowsers, listProfiles, listDomains, importCookies, CookieImportError, type PlaywrightCookie } from './cookie-import-browser';
|
|
import { getCookiePickerHTML } from './cookie-picker-ui';
|
|
|
|
// ─── State ──────────────────────────────────────────────────────
|
|
// Tracks which domains were imported via the picker.
|
|
// /imported only returns cookies for domains in this Set.
|
|
// /remove clears from this Set.
|
|
const importedDomains = new Set<string>();
|
|
const importedCounts = new Map<string, number>();
|
|
|
|
// ─── JSON Helpers ───────────────────────────────────────────────
|
|
|
|
function corsOrigin(port: number): string {
|
|
return `http://127.0.0.1:${port}`;
|
|
}
|
|
|
|
function jsonResponse(data: any, opts: { port: number; status?: number }): Response {
|
|
return new Response(JSON.stringify(data), {
|
|
status: opts.status ?? 200,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': corsOrigin(opts.port),
|
|
},
|
|
});
|
|
}
|
|
|
|
function errorResponse(message: string, code: string, opts: { port: number; status?: number; action?: string }): Response {
|
|
return jsonResponse(
|
|
{ error: message, code, ...(opts.action ? { action: opts.action } : {}) },
|
|
{ port: opts.port, status: opts.status ?? 400 },
|
|
);
|
|
}
|
|
|
|
// ─── Route Handler ──────────────────────────────────────────────
|
|
|
|
export async function handleCookiePickerRoute(
|
|
url: URL,
|
|
req: Request,
|
|
bm: BrowserManager,
|
|
authToken?: string,
|
|
): Promise<Response> {
|
|
const pathname = url.pathname;
|
|
const port = parseInt(url.port, 10) || 9400;
|
|
|
|
// CORS preflight
|
|
if (req.method === 'OPTIONS') {
|
|
return new Response(null, {
|
|
status: 204,
|
|
headers: {
|
|
'Access-Control-Allow-Origin': corsOrigin(port),
|
|
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
},
|
|
});
|
|
}
|
|
|
|
try {
|
|
// GET /cookie-picker — serve the picker UI
|
|
if (pathname === '/cookie-picker' && req.method === 'GET') {
|
|
const html = getCookiePickerHTML(port, authToken);
|
|
return new Response(html, {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'text/html; charset=utf-8' },
|
|
});
|
|
}
|
|
|
|
// ─── Auth gate: all data/action routes below require Bearer token ───
|
|
// Auth is mandatory — if authToken is undefined, reject all requests
|
|
const authHeader = req.headers.get('authorization');
|
|
if (!authToken || !authHeader || authHeader !== `Bearer ${authToken}`) {
|
|
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
|
|
status: 401,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
// GET /cookie-picker/browsers — list installed browsers
|
|
if (pathname === '/cookie-picker/browsers' && req.method === 'GET') {
|
|
const browsers = findInstalledBrowsers();
|
|
return jsonResponse({
|
|
browsers: browsers.map(b => ({
|
|
name: b.name,
|
|
aliases: b.aliases,
|
|
})),
|
|
}, { port });
|
|
}
|
|
|
|
// GET /cookie-picker/profiles?browser=<name> — list profiles for a browser
|
|
if (pathname === '/cookie-picker/profiles' && req.method === 'GET') {
|
|
const browserName = url.searchParams.get('browser');
|
|
if (!browserName) {
|
|
return errorResponse("Missing 'browser' parameter", 'missing_param', { port });
|
|
}
|
|
const profiles = listProfiles(browserName);
|
|
return jsonResponse({ profiles }, { port });
|
|
}
|
|
|
|
// GET /cookie-picker/domains?browser=<name>&profile=<profile> — list domains + counts
|
|
if (pathname === '/cookie-picker/domains' && req.method === 'GET') {
|
|
const browserName = url.searchParams.get('browser');
|
|
if (!browserName) {
|
|
return errorResponse("Missing 'browser' parameter", 'missing_param', { port });
|
|
}
|
|
const profile = url.searchParams.get('profile') || 'Default';
|
|
const result = listDomains(browserName, profile);
|
|
return jsonResponse({
|
|
browser: result.browser,
|
|
domains: result.domains,
|
|
}, { port });
|
|
}
|
|
|
|
// POST /cookie-picker/import — decrypt + import to Playwright session
|
|
if (pathname === '/cookie-picker/import' && req.method === 'POST') {
|
|
let body: any;
|
|
try {
|
|
body = await req.json();
|
|
} catch {
|
|
return errorResponse('Invalid JSON body', 'bad_request', { port });
|
|
}
|
|
|
|
const { browser, domains, profile } = body;
|
|
if (!browser) return errorResponse("Missing 'browser' field", 'missing_param', { port });
|
|
if (!domains || !Array.isArray(domains) || domains.length === 0) {
|
|
return errorResponse("Missing or empty 'domains' array", 'missing_param', { port });
|
|
}
|
|
|
|
// Decrypt cookies from the browser DB
|
|
const result = await importCookies(browser, domains, profile || 'Default');
|
|
|
|
if (result.cookies.length === 0) {
|
|
return jsonResponse({
|
|
imported: 0,
|
|
failed: result.failed,
|
|
domainCounts: {},
|
|
message: result.failed > 0
|
|
? `All ${result.failed} cookies failed to decrypt`
|
|
: 'No cookies found for the specified domains',
|
|
}, { port });
|
|
}
|
|
|
|
// Add to Playwright context
|
|
const page = bm.getActiveSession().getPage();
|
|
await page.context().addCookies(result.cookies);
|
|
|
|
// Track what was imported
|
|
for (const domain of Object.keys(result.domainCounts)) {
|
|
importedDomains.add(domain);
|
|
importedCounts.set(domain, (importedCounts.get(domain) || 0) + result.domainCounts[domain]);
|
|
}
|
|
|
|
console.log(`[cookie-picker] Imported ${result.count} cookies for ${Object.keys(result.domainCounts).length} domains`);
|
|
|
|
return jsonResponse({
|
|
imported: result.count,
|
|
failed: result.failed,
|
|
domainCounts: result.domainCounts,
|
|
}, { port });
|
|
}
|
|
|
|
// POST /cookie-picker/remove — clear cookies for domains
|
|
if (pathname === '/cookie-picker/remove' && req.method === 'POST') {
|
|
let body: any;
|
|
try {
|
|
body = await req.json();
|
|
} catch {
|
|
return errorResponse('Invalid JSON body', 'bad_request', { port });
|
|
}
|
|
|
|
const { domains } = body;
|
|
if (!domains || !Array.isArray(domains) || domains.length === 0) {
|
|
return errorResponse("Missing or empty 'domains' array", 'missing_param', { port });
|
|
}
|
|
|
|
const page = bm.getActiveSession().getPage();
|
|
const context = page.context();
|
|
for (const domain of domains) {
|
|
await context.clearCookies({ domain });
|
|
importedDomains.delete(domain);
|
|
importedCounts.delete(domain);
|
|
}
|
|
|
|
console.log(`[cookie-picker] Removed cookies for ${domains.length} domains`);
|
|
|
|
return jsonResponse({
|
|
removed: domains.length,
|
|
domains,
|
|
}, { port });
|
|
}
|
|
|
|
// GET /cookie-picker/imported — currently imported domains + counts
|
|
if (pathname === '/cookie-picker/imported' && req.method === 'GET') {
|
|
const entries: Array<{ domain: string; count: number }> = [];
|
|
for (const domain of importedDomains) {
|
|
entries.push({ domain, count: importedCounts.get(domain) || 0 });
|
|
}
|
|
entries.sort((a, b) => b.count - a.count);
|
|
|
|
return jsonResponse({
|
|
domains: entries,
|
|
totalDomains: entries.length,
|
|
totalCookies: entries.reduce((sum, e) => sum + e.count, 0),
|
|
}, { port });
|
|
}
|
|
|
|
return new Response('Not found', { status: 404 });
|
|
} catch (err: any) {
|
|
if (err instanceof CookieImportError) {
|
|
return errorResponse(err.message, err.code, { port, status: 400, action: err.action });
|
|
}
|
|
console.error(`[cookie-picker] Error: ${err.message}`);
|
|
return errorResponse(err.message || 'Internal error', 'internal_error', { port, status: 500 });
|
|
}
|
|
}
|