Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(browser): 绑定实际配方身份并随宿主切换清除旧证据

Dash17f10cc32706
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts
index 4dcdf169cc..e9168f41fa 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts
@@ -32,6 +32,33 @@ function fakeBackend(kind: BackendKind): BrowserBackend & {
}
describe('BrowserBackendController', () => {
+ // Review regression, unit: cached page evidence must expire both when a
+ // transition is admitted and when its backend actually becomes active.
+ it('exposes stable scope identities across queued, applied and return transitions', async () => {
+ const external = fakeBackend('external');
+ let release!: () => void;
+ const controller = new BrowserBackendController({
+ initialKind: 'external', externalBackend: external,
+ createRsbBackend: () => fakeBackend('rsb-webview'), logger: fakeLogger(),
+ });
+ const initial = controller.getBackendScope();
+ expect(controller.getBackendScope()).toEqual(initial);
+ const changed = controller.setKind('rsb-webview', () => new Promise<void>(resolve => { release = resolve; }));
+ const queued = controller.getBackendScope();
+ expect(queued.lifecycle).not.toBe(initial.lifecycle);
+ expect(queued.backend).toBe(initial.backend);
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ release();
+ await changed;
+ const applied = controller.getBackendScope();
+ expect(applied.lifecycle).toBe(queued.lifecycle);
+ expect(applied.backend).not.toBe(queued.backend);
+ await controller.setKind('external');
+ const returned = controller.getBackendScope();
+ expect(returned.backend).toBe(initial.backend);
+ expect(returned.lifecycle).not.toBe(initial.lifecycle);
+ });
+
it('serializes reset cleanup after outgoing profile disposal without deadlocking', async () => {
const queue = createBrowserProfileLifecycleQueue();
const external = fakeBackend('external');
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts
index ee6e642126..2ca137c6b5 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts
@@ -45,6 +45,11 @@ export class BrowserBackendController implements BrowserBackend {
return this.router.getCurrentBackendKind();
}
+ /** Reuse existing lifecycle references; no second generation counter or queue. */
+ getBackendScope(): { lifecycle: object; backend: object } {
+ return { lifecycle: this.transition, backend: this.router.getBackendIdentity() };
+ }
+
probeActiveControl(options?: { ensureHost?: boolean }): Promise<void> {
return this.router.probeActiveControl(options);
}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/router.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/router.ts
index ad25031f91..03c20f8737 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/router.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/router.ts
@@ -51,6 +51,11 @@ export class BackendRouter implements BrowserBackend {
return this.current.kind;
}
+ /** Identity only, for invalidating evidence owned by the outgoing backend. */
+ getBackendIdentity(): object {
+ return this.current;
+ }
+
/** Verify the active backend's real control path when it exposes a probe. */
async probeActiveControl(options?: { ensureHost?: boolean }): Promise<void> {
await this.current.probeControl?.(options);
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index 4491b69f47..b7e8786145 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -67,6 +67,7 @@ import {
readCopiedLoginsCdpPort,
wrapRuntimeWithRealProfile,
wrapRuntimeWithProfileLifecycleQueue,
+ activeManagedProfileName,
} from './browser-real-profile/index.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { createBrowserBackendIpcHandlers } from './browser-backend/settings-ipc.js';
@@ -464,6 +465,8 @@ function browserRecipeSecretId(key: string): string {
export function getBrowserMcpDeps(): {
experienceStore: NonNullable<BrowserMcpDeps['experienceStore']>;
getRuntime(): BrowserControlRuntime;
+ resolveProfile: NonNullable<BrowserMcpDeps['resolveProfile']>;
+ getBackendScope: NonNullable<BrowserMcpDeps['getBackendScope']>;
resolveScreenshot: NonNullable<BrowserMcpDeps['resolveScreenshot']>;
compressInlineImage: NonNullable<BrowserMcpDeps['compressInlineImage']>;
setBackend(kind: BackendKind): Promise<BackendKind>;
@@ -506,6 +509,9 @@ export function getBrowserMcpDeps(): {
// the backend split. Swapping the active backend (Phase 5) is invisible from
// @cindy/mcps' perspective.
getRuntime: () => backendController,
+ resolveProfile: (profile) => backendController.kind === 'rsb-webview'
+ ? 'rsb' : profile || activeManagedProfileName(readBrowserBackendSettings().useRealProfile),
+ getBackendScope: () => backendController.getBackendScope(),
resolveScreenshot: (result) =>
resolveBrowserScreenshot(result, {
runtimeDir: process.env.XDT_BROWSER_RUNTIME_DIR,
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index fd05bbea2f..75530e3e36 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -199,7 +199,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复
| Codex 包内 shell 入口 | `<userData>/codex-package/<版本>/codex-path/codex`,打包版 macOS/Linux 在 `getMaker()` 选定实际运行的 Codex 后由主进程原子写入,转发到同包的 `bin/codex`;只更新带 Cindy 标记的旧脚本,不覆盖外来文件。随旧版本目录整体删除,不含凭证。实现见 `agent-binaries/codex-cli-launcher.ts` |
| Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 |
| 浏览器用户配方与经验 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存参数化定义及 candidate/active/suspended 状态、浏览器 profile 范围,不保存试跑 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。同站 `experience.json` 最多保存 32 种操作形状(动作枚举、次数、时间),不保存 URL 路径/查询、选择器、脚本或输入输出;删除站点目录一并重置。重复形状仅提示当前 Agent 判断,不触发后台模型。试跑凭证与单轮修复预算只在 MCP 会话内存,暂停状态跨重启保留。 |
-| 浏览器大结果补读 | MCP 工具会话内存中保留最近四份原始 JSON,每份最多 200 万字符;不落盘、不上传,关闭会话后释放。`readResult` 只能读当前会话生成的引用,沿用原页面代输入读取限制;切换后端、stop 或读取受保护页面时清除。超过上限明确截断,不能声称完整原文已保存。 |
+| 浏览器大结果补读 | MCP 工具会话内存中保留最近四份原始 JSON,每份最多 200 万字符;不落盘、不上传,关闭会话后释放。`readResult` 只能读当前会话生成的引用,沿用原页面实际 profile 的代输入读取限制;切换后端、stop 或读取受保护页面时清除。工具复用宿主现有生命周期与后端对象引用,在下一次访问及异步预检后核对,包括设置/其它任务切换、切走再切回和嵌入后端恢复;切换中的动作仍报告真实结果,但不缓存原文或保存试跑凭证。超过上限明确截断,不能声称完整原文已保存。 |
| 本机应用 Agent 授权 | `owners/<owner-key>/local-agent/grants.json`,仅含令牌 SHA-256、自报应用资料、账号范围和按授权归属的原生恢复绑定,不存令牌明文、供应商凭据或消息。复用原子写入与恢复 helper;profile 根 `local-agent/host.lock` 复用跨进程锁,保证一个发现端点和写入者。开发连接码从当前服务内存按需生成,不新增公共实例登记或短码映射文件。临时输入与新授权的 Codex 运行历史在同一 owner 下的 `local-agent/clients/<grant-hash>/`;撤权同时关闭执行及工具入口,不允许跨授权恢复。协议与旧版兼容见 [本机应用接入](../local-agent-api.md) |
| 预创建 worktree 的取消标记 | `userData/worktree-cancelled-creations/<sessionId 的 SHA-256>`,空文件原子排他创建;不含路径、草稿或关联密钥。保留以拒绝重启后迟到的创建请求,不按超时删除。只在核实未被任务认领后写入。同路径加 `.lock` 是可释放的跨进程操作锁,复用既有锁协议;同一 profile、同一任务的创建登记与取消回收串行,拿不到锁不得确认回收完成。异步创建完成后、登记前再次核对取消标记 |
| Mobile 已取消创建的草稿 | 复用账号隔离的 durable outbox;持久创建流程先保存草稿、原项目目录和附件,再登记 reservation 和发送远端 worktree 创建;创建回包前暂停发件箱投递。回收确认后,`creation.cancelled` 与原项目目录先持久写入,再忘记回收账本。重建使用新远端 ID,`storageSessionId` 保持原 AsyncStorage 键和附件目录,通过单次记录写入提交;写入失败时原草稿仍可读。编辑页恢复目录时重新探测资格,不沿用旧 worktree 的资格或分支偏好 |
diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.md
index 498f32a725..8dcd46aae9 100644
--- a/packages/browser-control-runtime/upstream/MAINTAINING.md
+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md
@@ -207,6 +207,8 @@ pnpm --filter @cindy/browser-control-runtime test # 契约 + SSRF guard
### 经验缓存与按需学习(2026-10-27)
+- Desktop `resolveProfile` 先把省略值解析为实际 `Cindy` / `Cindy-real` 或嵌入端唯一 `rsb`;发现、试跑、保存、执行与补读检查共用该值,不能把空字符串当实际身份。显式 profile 和解析后的默认 profile 等价,旧配方不新增隐式身份限定。
+- `getBackendScope` 只读复用 controller 的既有 transition Promise 与 router 的当前后端引用,不新增计数器、锁或队列。任一变化使会话原文、发现缓存、未完成观察与试跑凭证失效;异步预检后和结果返回时再次核对,避免设置或另一任务切换宿主后继续引用旧页面。动作已成功时保留成功,切换后的失败不误标配方过时,不重放。
- `open/navigate` 随结果返回最多三条站点配方候选,可用 `intent` 进行本地词匹配;匹配仅建议,不执行。域名按边界匹配,profile 不匹配或 suspended 不建议;同任务同站点/意图/目录版本不重复提示。目录内容变化后重新发现。`siteguide(site,intent)` 支持主动窄查询,旧完整目录接口保留。
- `list_tools` 仅加载通用工作流,`recipeHelp` 才提供完整编写手册。当前 Agent 结合已完成步骤整理,不另起后台模型、不扫描完整聊天。重复形状观察仅留动作枚举和站点,第二次才提示考虑学习;这不是业务成功证明,不能自动猜参数或自动执行配方。
- 流程由成功导航开始,按 tab/profile 分开,第一次成功 extract/evaluate 结束;错误、敏感页、配方执行和后端切换清除未完成观察。只作为廉价学习线索,不完整覆盖含多次读取或跨站导航的业务流程。持久结构观察与现有配方共用站点目录,具体边界见 credentials-and-local-storage.md。
diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
index 2623425296..71af102555 100644
--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
@@ -55,6 +55,89 @@ describe('browser experience cache', () => {
inputs: { query: { required: true } }, steps: [{ action: 'evaluate', fn: '() => ({title: "found"})',
guard: { url: 'https://experience.test/' }, expect: { requiredFields: ['title'] }, as: 'items' }], output: '{{items}}' };
+ // Review regression, unit/MCP entry: omitted and explicit profile names must
+ // refer to the same host identity; changing the default must not widen scope.
+ it.each([true, false])('binds learned recipes to the resolved host profile (deferred=%s)', async deferred => {
+ let profile = 'Cindy';
+ let stored: Recipe | undefined;
+ let version = 0;
+ const h = await makeHarness({
+ resolveProfile: requested => requested || profile,
+ getUserRecipes: async () => ({ version: `resolved-profile-${deferred}-${version}`,
+ recipes: new Map(stored ? [[stored.id, stored]] : []), siteGuides: new Map() }),
+ saveUserRecipe: async ({ recipe }) => { stored = recipe; version++; return { ok: true }; },
+ }, (_req, i) => ({ targetId: 'tab', result: i % 2 === 0 ? true : { title: 'found' } }));
+ try {
+ if (!deferred) {
+ expect((await invoke(h, { action: 'recipe', site: 'experience.test', recipeDraft: draft,
+ inputs: { query: 'book' } })).verified).toBe(true);
+ profile = 'Cindy-real';
+ expect((await invoke(h, { action: 'saveRecipe', site: 'experience.test', recipeDraft: draft })).ok).toBe(false);
+ profile = 'Cindy';
+ }
+ expect((await invoke(h, { action: 'saveRecipe', site: 'experience.test', recipeDraft: draft,
+ profile: 'Cindy', deferValidation: deferred })).ok).toBe(true);
+ expect(stored?.validation?.profile).toBe('Cindy');
+ expect((await invoke(h, { action: 'siteguide', site: 'experience.test', intent: 'Search' })).recipes).toHaveLength(1);
+ profile = 'Cindy-real';
+ expect((await invoke(h, { action: 'siteguide', site: 'experience.test', intent: 'Search' })).recipes).toHaveLength(0);
+ const count = h.calls.length;
+ expect((await invoke(h, { action: 'recipe', recipeId: draft.id, inputs: { query: 'book' } })).ok).toBe(false);
+ expect(h.calls).toHaveLength(count);
+ expect((await invoke(h, { action: 'recipe', recipeId: draft.id, profile: 'Cindy', inputs: { query: 'book' } })).ok).toBe(true);
+ expect(h.calls.slice(-2).every(req => (req as { profile: string }).profile === 'Cindy')).toBe(true);
+ } finally { await h.cleanup(); }
+ });
+
+ // Review regression, unit/MCP entry: another task/Settings can change the
+ // shared host while this tool is idle or awaiting a protected-page check.
+ it.each(['idle', 'preflight', 'inflight'] as const)('invalidates original results after an external backend change (%s)', async timing => {
+ let scope = { lifecycle: {}, backend: {} };
+ let switchOnCheck = false;
+ const deps: Partial<BrowserMcpDeps> = {
+ getBackendScope: () => scope,
+ pageReadsRestricted: async () => { if (switchOnCheck) scope = { ...scope, lifecycle: {} }; return false; },
+ };
+ const h = await makeHarness(deps, () => {
+ if (timing === 'inflight') scope = { ...scope, lifecycle: {} };
+ return { targetId: 'tab', result: 'x'.repeat(17_000) };
+ });
+ try {
+ const result = await invoke(h, { action: 'act', targetId: 'tab', request: { kind: 'evaluate', fn: '() => []' } });
+ if (timing === 'inflight') {
+ expect(result.ok).toBe(true);
+ expect(result.fullResult).toBeUndefined();
+ } else {
+ expect(result.fullResult).toBeDefined();
+ if (timing === 'idle') scope = { ...scope, lifecycle: {} };
+ else switchOnCheck = true;
+ expect((await invoke(h, { action: 'readResult', resultId: result.fullResult.id })).ok).toBe(false);
+ switchOnCheck = false;
+ expect((await invoke(h, { action: 'readResult', resultId: result.fullResult.id })).ok).toBe(false);
+ }
+ expect(h.calls).toHaveLength(1);
+ } finally { await h.cleanup(); }
+ });
+
+ it('rejects a backend change during recipe preflight without dispatch or suspension', async () => {
+ let scope = { lifecycle: {}, backend: {} };
+ const stored = { ...draft, validation: { site: 'experience.test', state: 'active' as const } };
+ let saves = 0;
+ const h = await makeHarness({
+ getBackendScope: () => scope,
+ pageReadsRestricted: async () => { scope = { ...scope, backend: {} }; return false; },
+ getUserRecipes: async () => ({ version: 'backend-preflight-rejection', recipes: new Map([[stored.id, stored]]), siteGuides: new Map() }),
+ saveUserRecipe: async () => { saves++; return { ok: true }; },
+ });
+ try {
+ const result = await invoke(h, { action: 'recipe', recipeId: draft.id, inputs: { query: 'book' } });
+ expect(result.ok).toBe(false);
+ expect(h.calls).toHaveLength(0);
+ expect(saves).toBe(0);
+ expect(stored.validation.state).toBe('active');
+ } finally { await h.cleanup(); }
+ });
+
it('suggests matching recipes with navigation once per catalog version, without executing them', async () => {
let version = 0;
const stored = { ...draft, validation: { site: 'experience.test', state: 'active' as const, profile: '' } };
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index a0a6483d93..a52295a207 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -127,10 +127,10 @@ function readsPageState(request: BrowserControlRequest): boolean {
return request.action === 'act' && (act?.kind === 'evaluate' || (act?.kind === 'wait' && act.fn !== undefined));
}
-function getRuntime(deps: BrowserMcpDeps, onDispatch?: () => void): BrowserControlRuntime {
+function getRuntime(deps: BrowserMcpDeps, onDispatch?: () => void, scopeIsCurrent?: () => boolean): BrowserControlRuntime {
const runtime = deps.getRuntime();
const restricted = deps.pageReadsRestricted;
- if (!restricted && !onDispatch) return runtime;
+ if (!restricted && !onDispatch && !scopeIsCurrent) return runtime;
// Every path (tool actions, extract, recipes, hints) goes through this check.
return {
call: async (request) => {
@@ -149,6 +149,10 @@ function getRuntime(deps: BrowserMcpDeps, onDispatch?: () => void): BrowserContr
}
// This is the sole boundary after host preflight and before execution;
// callers must count attempts here, including throws/timeouts afterwards.
+ if (scopeIsCurrent && !scopeIsCurrent()) return {
+ ok: false, action: request.action, errorCode: 'BROWSER_RUNTIME_INVALID_REQUEST',
+ message: '浏览器后端已切换;请重新观察当前页面后再操作,不要重放写操作。',
+ };
onDispatch?.();
return runtime.call(request);
},
@@ -502,6 +506,19 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
const failedRecipes = new Set<string>();
const repairUsed = new Set<string>();
const runningRecipes = new Set<string>();
+ let backendScope = deps.getBackendScope?.();
+ function syncBackendScope() {
+ const next = deps.getBackendScope?.();
+ if (next?.lifecycle !== backendScope?.lifecycle || next?.backend !== backendScope?.backend) {
+ experiences.clear();
+ discovered.clear();
+ learningHints.clear();
+ results.clear();
+ verifiedDrafts.clear();
+ backendScope = next;
+ }
+ return backendScope;
+ }
const recovery = '先重新观察当前页面;当前任务每个配方最多验证一轮修订。失败后回普通操作。写操作先核实是否已成功,不得自动重放。';
function draftIssue(recipe: Recipe, site: string | undefined): string | undefined {
if (recipe.validation) return 'validation 由宿主管理,recipeDraft 不得提供';
@@ -653,6 +670,10 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
},
handler: async (args) => {
try {
+ const scope = syncBackendScope();
+ const scopeIsCurrent = () => syncBackendScope() === scope;
+ const profile = deps.resolveProfile?.(args.profile);
+ if (profile !== undefined) args = { ...args, profile };
if (args.action === 'readResult') {
if (!args.resultId) return errorResult(args.action, 'readResult requires resultId');
const source = results.source(args.resultId);
@@ -660,6 +681,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
results.clear();
return errorResult(args.action, '该页面处于代输入保护期,已清除缓存;请离开敏感页面后重新只读获取');
}
+ scopeIsCurrent(); // A switch during the async restriction check expires originals too.
const value = results.read(args.resultId, args.offset ?? 0, Math.max(1, Math.min(args.maxChars ?? 12_000, 24_000)));
return { content: [{ type: 'text', text: resultText(value) }], isError: !value.ok };
}
@@ -720,7 +742,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
}
}
let onRecipeDispatch: (() => void) | undefined;
- const runtime = getRuntime(deps, () => onRecipeDispatch?.());
+ const runtime = getRuntime(deps, () => onRecipeDispatch?.(), scopeIsCurrent);
// Block non-web schemes at the boundary: navigate/open to file:// /
// chrome:// / data: would let the agent reach local files or browser
// internals. Only the scheme is constrained — localhost/private HTTP
@@ -844,7 +866,10 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
logger: deps.logger,
}).finally(() => runningRecipes.delete(id));
let maintenanceMessage: string | undefined;
- if (runResult.ok && candidate) {
+ const contextCurrent = scopeIsCurrent();
+ if (runResult.ok && !contextCurrent) {
+ maintenanceMessage = '本次执行成功,但浏览器后端已切换;未保留试跑凭证或更新配方状态,不要重放动作。';
+ } else if (runResult.ok && candidate) {
verifiedDrafts.set(id, { site: args.site!, content: JSON.stringify(entry.recipe), profile: args.profile ?? '' });
} else if (runResult.ok && persisted?.validation?.state === 'candidate' && deps.saveUserRecipe) {
// Promotion describes the actual checks on this invocation, not
@@ -855,7 +880,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
if (!saved.ok) maintenanceMessage = '本次执行成功,候选状态保存失败;下次仍会按候选验证。';
recipeCache = null;
} catch { maintenanceMessage = '本次执行成功,候选状态保存失败;下次仍会按候选验证。'; }
- } else if (!runResult.ok && lastCallDispatched && runResult.failureKind !== 'input' && runResult.failedStep !== undefined) {
+ } else if (contextCurrent && !runResult.ok && lastCallDispatched && runResult.failureKind !== 'input' && runResult.failedStep !== undefined) {
// A failed draft is not evidence that the saved active version is
// stale. Keep its state, while limiting new/previously failed drafts.
if (!candidate || !persisted || suspended) failedRecipes.add(id);
@@ -878,10 +903,10 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
}
return {
content: [
- { type: 'text', text: textResult({ action: 'recipe', provenance: entry.provenance, ...runResult,
+ { type: 'text', text: (scopeIsCurrent() ? textResult : resultText)({ action: 'recipe', provenance: entry.provenance, ...runResult,
...(maintenanceMessage ? { maintenanceMessage } : {}),
...(runResult.ok && lintBrowserOutput(runResult.output).length ? { advisory: lintBrowserOutput(runResult.output) } : {}),
- ...(!runResult.ok ? { recovery, maintenanceMessage } : candidate ? { verified: true } : {}) }, { profile: args.profile, targetId: activeTargetId }) },
+ ...(!runResult.ok ? { recovery, maintenanceMessage } : candidate ? { verified: contextCurrent } : {}) }, { profile: args.profile, targetId: activeTargetId }) },
],
isError: !runResult.ok,
};
@@ -1052,6 +1077,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
} else if (!verified || verified.site !== args.site || verified.content !== JSON.stringify(parsed.data) || verified.profile !== (args.profile ?? '')) {
return errorResult('saveRecipe', '请先用 action=recipe、site、相同 recipeDraft 试跑并通过校验;不能保存未验证或已改动的配方');
}
+ if (!scopeIsCurrent()) return errorResult('saveRecipe', '浏览器后端已切换,请重新核对配方适用范围后保存');
const saved = await deps.saveUserRecipe({ site: args.site,
recipe: { ...parsed.data, validation: { site: args.site, state: args.deferValidation ? 'candidate' : 'active', profile: args.profile ?? '' } }, siteGuide: guide });
if (saved.ok) {
@@ -1158,12 +1184,12 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
// failure (especially a write that the agent might otherwise replay).
const targetId = readTargetId(result) ?? args.request?.targetId ?? args.targetId;
const targetKey = targetId && JSON.stringify([args.profile ?? '', targetId]);
- let retainResult = true;
+ let retainResult = scopeIsCurrent();
try {
if (args.action === 'stop') { experiences.clear(); discovered.clear(); results.clear(); }
const restricted = deps.pageReadsRestricted && await deps.pageReadsRestricted({ profile: args.profile, targetId }).catch(() => true);
if (restricted) { retainResult = false; results.clear(); }
- if (!result.ok || extractFailed || restricted || args.action === 'close' || args.request?.kind === 'close') {
+ if (!scopeIsCurrent() || !result.ok || extractFailed || restricted || args.action === 'close' || args.request?.kind === 'close') {
if (targetKey) experiences.clear(targetKey);
} else if (args.action === 'open' || args.action === 'navigate') {
const actualUrl = (result.data as { url?: unknown } | undefined)?.url;
@@ -1201,7 +1227,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
const advisory = lintBrowserOutput((result.data as { result?: unknown } | undefined)?.result);
if (advisory.length) result = { ...result, advisory } as typeof result;
return {
- content: [{ type: 'text', text: retainResult ? textResult(result as unknown as Record<string, unknown>, { profile: args.profile, targetId }) : resultText(result) }],
+ content: [{ type: 'text', text: retainResult && scopeIsCurrent() ? textResult(result as unknown as Record<string, unknown>, { profile: args.profile, targetId }) : resultText(result) }],
isError: !result.ok || extractFailed,
};
} catch (err) {
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 52a5104707..e8aa725a65 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -651,6 +651,10 @@ export interface BrowserMcpDeps {
/** Local structural observations only; no URLs, scripts, selectors or input values. */
experienceStore?: import('./browser/experience.js').BrowserExperienceStore;
getRuntime(): BrowserControlRuntime;
+ /** Resolve the actual host profile before validation, discovery and execution. */
+ resolveProfile?(profile?: string): string;
+ /** Existing host lifecycle/backend identities; changes invalidate session evidence. */
+ getBackendScope?(): { lifecycle: object; backend: object };
/**
* Resolve a successful screenshot runtime result into verified image bytes.
* The host owns file-system access so this package never receives a generic
diff --git a/scripts/browser-experience-live.mjs b/scripts/browser-experience-live.mjs
index 11304114db..d965b83550 100644
--- a/scripts/browser-experience-live.mjs
+++ b/scripts/browser-experience-live.mjs
@@ -50,7 +50,9 @@ try {
const { registerBrowserTools: registerBaseline } = await baselineVite.ssrLoadModule(
'/packages/lizi-mcps/src/browser/tools.ts',
);
- const { BrowserToolRegistry } = await moduleAt('packages/lizi-mcps/src/browser/tool-registry.ts');
+ const { BrowserToolRegistry } = await moduleAt(
+ 'packages/lizi-mcps/src/browser/tool-registry.ts',
+ );
const { RecipeSchema } = await vite.ssrLoadModule(
'/packages/lizi-mcps/src/browser/recipe-loader.ts',
);
@@ -72,7 +74,9 @@ try {
enabled: true,
attachOnly: true,
defaultProfile: 'experience-live',
- profiles: { 'experience-live': { cdpUrl, attachOnly: true, color: '#00D9C5' } },
+ profiles: {
+ 'experience-live': { cdpUrl, attachOnly: true, color: '#00D9C5' },
+ },
ssrfPolicy: { dangerouslyAllowPrivateNetwork: true },
},
},
@@ -152,10 +156,18 @@ try {
};
const url = 'https://itch.io/search?q=sokoban';
- const opened = await call('automatic-discovery', { action: 'navigate', url, intent: 'search' });
+ const opened = await call('automatic-discovery', {
+ action: 'navigate',
+ url,
+ intent: 'search',
+ });
assert(opened.result.recipeSuggestions.some((recipe) => recipe.id === 'itch-search'));
assert.equal(opened.runtime.length, 1);
- const again = await call('discovery-cache', { action: 'navigate', url, intent: 'search' });
+ const again = await call('discovery-cache', {
+ action: 'navigate',
+ url,
+ intent: 'search',
+ });
assert.equal(again.result.recipeSuggestions, undefined);
report.checks.discoveryWithoutExtraBrowserCall = true;
@@ -259,12 +271,16 @@ try {
? { author: 'J.K. Rowling', tag: 'choices' }
: { author: 'Albert Einstein', tag: 'learning' };
let read;
- for (const step of draft.steps) read = await call(`observe-${i}`, stepToRequest(step, inputs));
+ for (const step of draft.steps)
+ read = await call(`observe-${i}`, stepToRequest(step, inputs));
assert.equal(read.result.data.result.matched, true);
if (i === 1) assert(read.result.learningOpportunity);
}
report.checks.repetitionAcrossToolSessions = true;
- await call('learn-help', { action: 'recipeHelp', site: 'quotes.toscrape.com' });
+ await call('learn-help', {
+ action: 'recipeHelp',
+ site: 'quotes.toscrape.com',
+ });
const save = await call('learn-candidate', {
action: 'saveRecipe',
site: 'quotes.toscrape.com',
@@ -389,16 +405,32 @@ try {
report.error = err.stack ?? String(err);
process.exitCode = 1;
} finally {
- await fs.writeFile(output, JSON.stringify(report, null, 2));
- await disconnect?.();
- await vite?.close();
- await baselineVite?.close();
- await fs.rm(temp, { recursive: true, force: true });
+ // Reporting and every cleanup are independent: one failure must not leak
+ // the remaining connection, Vite server or temporary candidate directory.
+ const cleanupErrors = [];
+ for (const clean of [
+ () => fs.writeFile(output, JSON.stringify(report, null, 2)),
+ () => disconnect?.(),
+ () => vite?.close(),
+ () => baselineVite?.close(),
+ () => fs.rm(temp, { recursive: true, force: true }),
+ ]) {
+ try {
+ await clean();
+ } catch (err) {
+ cleanupErrors.push(String(err));
+ }
+ }
+ if (cleanupErrors.length) {
+ process.exitCode = 1;
+ report.cleanupErrors = cleanupErrors;
+ }
console.log(
JSON.stringify({
output,
checks: report.checks,
error: report.error,
+ cleanupErrors: report.cleanupErrors,
calls: report.calls.length,
}),
);