Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(browser): 补齐导航等待、页签绑定与响应截断信息
Dash94b8b4ed7dd0
diff --git a/packages/browser-control-runtime/src/recipe-sessions.test.ts b/packages/browser-control-runtime/src/recipe-sessions.test.tsindex 0a49f09754..230f83654a 100644--- a/packages/browser-control-runtime/src/recipe-sessions.test.ts+++ b/packages/browser-control-runtime/src/recipe-sessions.test.ts@@ -2,6 +2,35 @@ import { describe, expect, it, vi } from "vitest";import { RecipeBrowserSessions } from "./recipe-sessions.js";describe("recipe browser sessions", () => {+ // Review #6826: a valid large response must be distinguishable from malformed+ // JSON. Public session capture/read entry; unit tier. Existing small-body+ // coverage did not cross the one-million-character boundary or cover base64.+ it.each([[999_999, false], [1_000_000, false], [1_000_001, false], [1_000_001, true]] as const)(+ 'reports truncation for body length %s (base64=%s)', async (length, base64Encoded) => {+ const sessions = new RecipeBrowserSessions();+ let event = (_method: string, _params: Record<string, unknown>) => {};+ const body = 'x'.repeat(length);+ const id = sessions.begin('target', {+ send: async () => ({ body, base64Encoded }),+ subscribe: listener => { event = listener; return () => {}; },+ dispose: () => {},+ });+ try {+ await sessions.call('target', id, 'Cindy.captureStart');+ event('Network.requestWillBeSent', { requestId: 'r', request: { url: 'https://example.test/api' } });+ event('Network.loadingFinished', { requestId: 'r' });+ await Promise.resolve();+ const result = await sessions.call('target', id, 'Cindy.captureRead') as { entries: Array<Record<string, unknown>> };+ expect(result.entries).toHaveLength(1);+ expect(result.entries[0]).toMatchObject({+ captureComplete: true, responseBodyFullSize: length,+ responseBodyTruncated: length > 1_000_000,+ responsePreview: `${base64Encoded ? 'base64:' : ''}${body.slice(0, 1_000_000)}`,+ });+ } finally { sessions.dispose(); }+ },+ );+it("captures and drains responses across navigation without losing unfinished requests", async () => {const sessions = new RecipeBrowserSessions();let event: (diff --git a/packages/browser-control-runtime/src/recipe-sessions.ts b/packages/browser-control-runtime/src/recipe-sessions.tsindex 76f4e76cb0..495d2dfdfc 100644--- a/packages/browser-control-runtime/src/recipe-sessions.ts+++ b/packages/browser-control-runtime/src/recipe-sessions.ts@@ -21,6 +21,8 @@ interface CaptureEntry {responseStatus?: number;responseHeaders?: Record<string, unknown>;responsePreview?: string;+ responseBodyFullSize?: number;+ responseBodyTruncated?: boolean;captureComplete?: boolean;error?: string;}@@ -152,7 +154,10 @@ export class RecipeBrowserSessions {const body = (await session.transport.send("Network.getResponseBody", {requestId,})) as { body?: string; base64Encoded?: boolean };- entry.responsePreview = `${body.base64Encoded ? "base64:" : ""}${(body.body ?? "").slice(0, 1_000_000)}`;+ const text = body.body ?? '';+ entry.responseBodyFullSize = text.length;+ entry.responseBodyTruncated = text.length > 1_000_000;+ entry.responsePreview = `${body.base64Encoded ? "base64:" : ""}${text.slice(0, 1_000_000)}`;// Keep the total retained payload bounded as well as the entry count.let retained = [...capture.entries.values()].reduce((sum, item) => sum + (item.responsePreview?.length ?? 0),diff --git a/packages/lizi-mcps/src/browser/opencli-page.ts b/packages/lizi-mcps/src/browser/opencli-page.tsindex dbc57f1cde..5618bcb269 100644--- a/packages/lizi-mcps/src/browser/opencli-page.ts+++ b/packages/lizi-mcps/src/browser/opencli-page.ts@@ -2,6 +2,7 @@ import { readFile, writeFile } from "node:fs/promises";import {CDPBasePage,buildEvaluateExpression,+ waitForDomStableJs,executeAdapter,loadAdapter,type BrowserCookie,@@ -36,10 +37,11 @@ export class OpenCliPage extends CDPBasePage {private async request(request: BrowserControlRequest,+ adoptTarget = true,): Promise<Record<string, unknown>> {const result = await this.deps.call({...request,- ...(this.targetId ? { targetId: this.targetId } : {}),+ ...((request.targetId ?? this.targetId) ? { targetId: request.targetId ?? this.targetId } : {}),});if (!result.ok)throw new Error(result.message ?? `Browser ${request.action} failed`);@@ -49,7 +51,7 @@ export class OpenCliPage extends CDPBasePage {`Browser interaction requires attention: ${JSON.stringify(data.barrier)}`,);const target = data.targetId ?? data.tabId;- if (typeof target === "string") this.targetId = target;+ if (adoptTarget && typeof target === "string") this.targetId = target;return data;}@@ -61,12 +63,16 @@ export class OpenCliPage extends CDPBasePage {if (!this.targetId) throw new Error("Browser did not return a targetId");}- async goto(url: string): Promise<void> {+ async goto(url: string, options?: { waitUntil?: 'load' | 'none'; settleMs?: number }): Promise<void> {if (!isHttpUrl(url))throw new Error("Recipe navigation requires an http(s) URL");if (!this.targetId) await this.request({ action: "open", url });else await this.request({ action: "navigate", url });this._lastUrl = url;+ if (options?.waitUntil !== 'none') {+ const maxMs = options?.settleMs ?? 1000;+ if (maxMs > 0) await this.evaluate(waitForDomStableJs(maxMs, Math.min(500, maxMs)));+ }}async evaluate<T = unknown>(js: string): Promise<T>;@@ -215,19 +221,28 @@ export class OpenCliPage extends CDPBasePage {return this.targetId;}async closeTab(target?: number | string): Promise<void> {- if (target !== undefined) await this.selectTab(target);- if (this.targetId) {- const sessionId = this.sessions.get(this.targetId);+ let closing = this.targetId;+ if (target !== undefined) {+ const tabs = await this.tabs();+ closing = typeof target === 'number' ? tabs[target]?.page : tabs.find(tab => tab.page === target)?.page;+ if (!closing) throw new Error(`Browser tab not found: ${target}`);+ }+ if (closing) {+ const sessionId = this.sessions.get(closing);if (sessionId) {await this.request({action: "recipeCommand",+ targetId: closing,recipeCommand: { method: "Cindy.end", sessionId },- });- this.sessions.delete(this.targetId);+ }, false);+ this.sessions.delete(closing);}- await this.request({ action: "close" });+ await this.request({ action: "close", targetId: closing }, false);+ }+ if (closing === this.targetId) {+ this.targetId = undefined;+ this._lastUrl = null;}- this.targetId = undefined;}// OpenCLI's closeWindow releases a lease. Cindy owns browser/tab lifetime.async closeWindow(): Promise<void> {}diff --git a/packages/lizi-mcps/src/browser/opencli-recipes.test.ts b/packages/lizi-mcps/src/browser/opencli-recipes.test.tsindex 17c9597e5b..45f3cb96aa 100644--- a/packages/lizi-mcps/src/browser/opencli-recipes.test.ts+++ b/packages/lizi-mcps/src/browser/opencli-recipes.test.ts@@ -8,10 +8,62 @@ import { loadRecipes, RecipeSchema, type Recipe } from "./recipe-loader.js";import { runRecipe } from "./recipe-runner.js";afterEach(() => {+ vi.useRealTimers();vi.unstubAllGlobals();});describe("bundled OpenCLI recipes", () => {+ // Review #6826: goto must await the requested DOM settle interval on both+ // initial open and existing-tab navigation. Unit tier, real page JS with+ // fake timers/DOM; no prior adapter test exercised navigation options.+ it.each([undefined, 'existing-target'])('honors navigation settlement from target %s', async (targetId) => {+ vi.useFakeTimers();+ vi.stubGlobal('document', { body: {} });+ vi.stubGlobal('MutationObserver', class { observe() {} disconnect() {} });+ const call = vi.fn(async (request: BrowserControlRequest) => ({+ ok: true, action: request.action,+ data: request.action === 'act'+ ? { result: await Function(`return (${request.request!.fn})`)()() }+ : { targetId: 'live-target' },+ }));+ const page = new OpenCliPage({ targetId, call });+ let completed = false;+ const navigation = page.goto('https://example.test', { settleMs: 80 }).then(() => { completed = true; });+ await vi.advanceTimersByTimeAsync(79);+ expect(completed).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ await navigation;+ expect(completed).toBe(true);+ expect(call.mock.calls[0][0].action).toBe(targetId ? 'navigate' : 'open');+ call.mockClear();+ await page.goto('https://example.test/next', { waitUntil: 'none', settleMs: 80 });+ expect(call.mock.calls.map(([request]) => request.action)).toEqual(['navigate']);+ });++ // Review #6826: a fresh tab must remain selected when recovery closes the old+ // tab by ID or index; closing the current tab clears it. Unit/public page API.+ it.each(['old-target', 0])('preserves the fresh target when closing old tab %s', async (target) => {+ const calls: BrowserControlRequest[] = [];+ const page = new OpenCliPage({ targetId: 'old-target', call: async (request) => {+ calls.push(request);+ return { ok: true, action: request.action, data: request.action === 'tabs'+ ? { tabs: [{ targetId: 'old-target' }, { targetId: 'fresh-target' }] }+ : request.action === 'close' ? { tabId: request.targetId }+ : { sessionId: 's', cookies: [], result: 'fresh content' } };+ } });+ await page.getCookies();+ page.setActivePage('fresh-target');+ await page.closeTab(target);+ expect(page.getActivePage()).toBe('fresh-target');+ expect(await page.evaluate('document.title')).toBe('fresh content');+ expect(calls.find(call => call.action === 'close')?.targetId).toBe('old-target');+ expect(calls.find(call => call.recipeCommand?.method === 'Cindy.end')?.targetId).toBe('old-target');+ expect(calls.at(-1)?.targetId).toBe('fresh-target');+ await page.closeTab();+ expect(page.getActivePage()).toBeUndefined();+ await page.dispose();+ });+it("executes a legacy alias through the real adapter with its original parameter name", async () => {const fetch = vi.fn(async (_url: string) =>@@ -61,10 +113,8 @@ describe("bundled OpenCLI recipes", () => {expect(result.ok).toBe(true);expect(result.output).toMatchObject([{ rank: 1, title: "Example" }]);expect(calls[1].targetId).toBe("new-target");- expect(- (calls.find((call) => call.action === "act")!.request as { fn: string })- .fn,- ).toContain("ps=20");+ expect(calls.filter(call => call.action === 'act').map(call => call.request?.fn))+ .toEqual(expect.arrayContaining([expect.stringContaining('ps=20')]));});it("rejects invalid numeric inputs before any browser operation", async () => {diff --git a/packages/opencli-vendor/cindy/index.ts b/packages/opencli-vendor/cindy/index.tsindex 6a9c3356bb..acae3a4985 100644--- a/packages/opencli-vendor/cindy/index.ts+++ b/packages/opencli-vendor/cindy/index.ts@@ -9,6 +9,7 @@ export type { RecipeSecrets } from "./host.js";export { CDPBasePage } from "../src/browser/base-page.js";export { buildEvaluateExpression } from "../src/browser/utils.js";+export { waitForDomStableJs } from "../src/browser/dom-helpers.js";export type {IPage,BrowserCookie,diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex ae3e50d7e0..14329d8ff0 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -531,6 +531,8 @@ export default {requiredUnitWorkspace('@cindy/maker-scheduler', 'packages/maker-scheduler'),requiredUnitWorkspace('@cindy/maker-shared', 'packages/maker-shared'),requiredUnitWorkspace('@cindy/model-providers', 'packages/model-providers'),+ noCollectableWorkspace('@jackwener/opencli', 'packages/opencli-vendor',+ 'Pinned production adapter sources; execution, host credentials and discovery are tested through @cindy/mcps and the browser-control-runtime.'),{name: '@cindy/orca-workflow',cwd: 'packages/orca-workflow',