Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 14 additions & 0 deletions src/service.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,20 @@ export class WebRuntime {
case 'debugger-stop':
await this.mcp.stop();
return true;
case 'debugger-rebind': {
// Self-healing path: the debugger mirror can drift out of sync with CDP
// after the CDP session is re-created (page switch, frame switch, host
// rebind). Tearing the kernel connection down and re-binding gives a
// clean target instead of leaving callers with contradictory states.
await this.mcp.stop();
await this.ensureDebugger(args.allowedRoot || this.root);
await this.bindTarget();
return {
tools: [...FINGERPRINT_TOOLS, ...ANTIDEBUG_TOOLS]
.map(({ name, description, schema }) => ({ name, description, inputSchema: schema }))
.concat(this.mcp.tools),
};
}
case 'debugger-bind':
await this.bindTarget();
return true;
Expand Down
37 changes: 35 additions & 2 deletions src/vendor/core-build/src/DebuggerContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,12 @@ export class DebuggerContext {
this.#breakpoints.clear();
this.#xhrBreakpoints.clear();
}
this.#pausedState = { isPaused: false, callFrames: [] };
// 关键:页面可能仍停在断点上,而 disable 摘掉了 Debugger.resumed 监听,
// 之后再也不会有人把状态改回 running。这里不能谎报「已恢复」,
// 而是记成 unknown,由下一次真实操作(或 get_paused_info)与 CDP 对账。
this.#pausedState = this.#pausedState.isPaused
? { isPaused: true, callFrames: this.#pausedState.callFrames || [], stale: true }
: { isPaused: false, callFrames: [] };
this.#enabled = false;
this.#client = null;
}
Expand Down Expand Up @@ -190,6 +195,16 @@ export class DebuggerContext {
isPaused() {
return this.#pausedState.isPaused;
}
/**
* The local paused mirror is known to be wrong (CDP already reports running).
* Correct it instead of leaving a stale isPaused=true that blocks every caller.
* Reconciliation happens where CDP actually answers: resume() and
* evaluate_script() both catch CDP's "Can only perform operation while paused"
* and call this.
*/
markRunning() {
this.#pausedState = { isPaused: false, callFrames: [] };
}
/**
* Get the current paused state.
*/
Expand All @@ -204,9 +219,27 @@ export class DebuggerContext {
throw new Error('Debugger not enabled');
}
if (!this.#pausedState.isPaused) {
// 陈旧镜像:CDP 早已恢复运行,目标状态已达成,按幂等处理而不是抛错。
if (this.#pausedState.stale) {
this.markRunning();
return { alreadyRunning: true };
}
throw new Error('Execution is not paused');
}
await this.#client.send('Debugger.resume');
try {
await this.#client.send('Debugger.resume');
}
catch (error) {
// CDP 明确说已经不在暂停态 → 以 CDP 为准修正本地状态,按幂等处理。
if (/Can only perform operation while paused|not paused/i.test(String(error?.message || ''))) {
this.markRunning();
return { alreadyRunning: true };
}
throw error;
}
// resume 是异步生效的;立刻清状态,避免下一次调用读到旧的 isPaused=true。
this.markRunning();
return { alreadyRunning: false };
}
/**
* Pause execution.
Expand Down
30 changes: 26 additions & 4 deletions src/vendor/core-build/src/tools/debugger.js
Original file line number Diff line number Diff line change
Expand Up @@ -997,6 +997,9 @@ export const getPausedInfo = defineTool({
}
}
response.appendResponseLine('\n💡 Use pause_or_resume(action="resume") to resume, or step with direction="over" | "into" | "out" to continue one step.');
if (pausedState.stale) {
response.appendResponseLine('⚠️ This paused state may be stale (the CDP listener was detached and re-attached). If a resume reports "already running", the page is actually running and no pause exists.');
}
response.setStructuredContent({
paused: true,
reason: pausedState.reason ?? null,
Expand Down Expand Up @@ -1033,12 +1036,31 @@ export const pauseOrResume = defineTool({
requireDebuggerEnabled(debugger_);
try {
if (request.params.action === 'resume') {
const stale = debugger_.getPausedState()?.stale;
if (!debugger_.isPaused()) {
throw new ToolError('CONFLICT', 'Execution is already running; action=resume is not applicable.');
if (!stale) {
throw new ToolError('CONFLICT', 'Execution is already running; action=resume is not applicable.');
}
// 陈旧镜像:以 CDP 为准,不拦这次调用。
debugger_.markRunning();
response.appendResponseLine('▶️ Execution was already running (the local paused state was stale and has been corrected).');
response.setStructuredContent({ action: 'resume', state: 'running', reconciled: true });
return;
}
if (stale) {
// 镜像说暂停,但它是 disable/enable 之后留下的旧值,CDP 侧很可能早已运行。
// 先尝试真正 resume;CDP 若确认未暂停,resume() 会幂等返回并修正镜像。
const healed = await debugger_.resume();
debugger_.markRunning();
response.appendResponseLine(healed?.alreadyRunning
? '▶️ Execution was already running; stale paused state corrected.'
: '▶️ Execution resumed (recovered from a stale paused state).');
response.setStructuredContent({ action: 'resume', state: 'running', reconciled: true });
return;
}
await debugger_.resume();
response.appendResponseLine('▶️ Execution resumed.');
response.setStructuredContent({ action: 'resume', state: 'running' });
const resumed = await debugger_.resume();
response.appendResponseLine(resumed?.alreadyRunning ? '▶️ Execution was already running; state reconciled.' : '▶️ Execution resumed.');
response.setStructuredContent({ action: 'resume', state: 'running', ...(resumed?.alreadyRunning ? { reconciled: true } : {}) });
}
else {
if (debugger_.isPaused()) {
Expand Down
55 changes: 35 additions & 20 deletions src/vendor/core-build/src/tools/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,28 +294,43 @@ export const evaluateScript = defineTool({
}
const callFrameId = pausedState.callFrames[frameIdx]?.callFrameId;
if (callFrameId) {
const result = await debugger_.evaluateSettledPromiseOnCallFrame(callFrameId, `(${wrapPausedResult()})()`);
if (result.exceptionDetails) {
const errMsg = result.exceptionDetails.exception?.description ||
result.exceptionDetails.text;
throw new ToolError('CDP_ERROR', `Script evaluation error: ${errMsg}`);
let result;
try {
result = await debugger_.evaluateSettledPromiseOnCallFrame(callFrameId, `(${wrapPausedResult()})()`);
}
if (result.settledPromise &&
(result.result.subtype === 'arraybuffer' ||
result.result.subtype === 'typedarray')) {
throw new ToolError('PRECONDITION_FAILED', 'Paused async binary results cannot be serialized safely. Resume execution or return JSON-serializable data.');
catch (error) {
// 本地 isPaused 与 CDP 真实状态不一致(disable/enable 之后很常见)。
// 以 CDP 为准修正状态,然后退化为页面求值,而不是把这一路彻底堵死。
if (/Can only perform operation while paused|not paused|no longer paused/i.test(String(error?.message || ''))) {
debugger_.markRunning();
response.appendResponseLine('ℹ️ Paused state was stale (page is already running); falling back to page evaluation.');
result = null;
}
else throw error;
}
if (result) {
if (result.exceptionDetails) {
const errMsg = result.exceptionDetails.exception?.description ||
result.exceptionDetails.text;
throw new ToolError('CDP_ERROR', `Script evaluation error: ${errMsg}`);
}
if (result.settledPromise &&
(result.result.subtype === 'arraybuffer' ||
result.result.subtype === 'typedarray')) {
throw new ToolError('PRECONDITION_FAILED', 'Paused async binary results cannot be serialized safely. Resume execution or return JSON-serializable data.');
}
const settledValue = result.settledPromise && result.result.objectId
? await debugger_.materializeRemoteObject(result.result)
: result.result.value;
const rawResult = result.settledPromise
? JSON.stringify({
type: 'json',
data: JSON.stringify(settledValue),
})
: settledValue;
await handleEvalResult(rawResult);
return;
}
const settledValue = result.settledPromise && result.result.objectId
? await debugger_.materializeRemoteObject(result.result)
: result.result.value;
const rawResult = result.settledPromise
? JSON.stringify({
type: 'json',
data: JSON.stringify(settledValue),
})
: settledValue;
await handleEvalResult(rawResult);
return;
}
}
if (mainWorld) {
Expand Down
149 changes: 149 additions & 0 deletions src/vendor/core-build/tests/paused-reconcile.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* Paused 状态与 CDP 真实状态对账。
*
* 背景:DebuggerContext 的 #pausedState 是事件镜像。切换页面/帧或宿主重新绑定 target
* 会 disable()+enable(),期间 Debugger.resumed 监听被摘掉,镜像就永久停在错误值上。
* 结果是快照说"暂停"、恢复说"未暂停"、求值报 not paused,三条路互斥。
* 这组测试用真实的 CDP 事件与假 client 锁住对账行为。
*/
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { DebuggerContext } from '../src/DebuggerContext.js';
import { pauseOrResume, getPausedInfo } from '../src/tools/debugger.js';

/** 最小 CDP client:可以派发事件,并记录 send 调用。 */
function fakeClient(overrides = {}) {
const listeners = new Map();
return {
sends: [],
on(name, fn) { if (!listeners.has(name)) listeners.set(name, new Set()); listeners.get(name).add(fn); },
off(name, fn) { listeners.get(name)?.delete(fn); },
emit(name, payload) { for (const fn of [...(listeners.get(name) || [])]) fn(payload); },
listenerCount(name) { return (listeners.get(name) || new Set()).size; },
async send(method, params) {
this.sends.push(method);
if (overrides.send) return overrides.send(method, params);
return {};
},
};
}

const PAUSED_EVENT = {
reason: 'other',
callFrames: [{
callFrameId: 'cf0',
functionName: 'fixtureRun',
url: 'https://example.test/a.js',
location: { scriptId: 's1', lineNumber: 4, columnNumber: 0 },
scopeChain: [{ type: 'local', object: { objectId: 'obj1', type: 'object' } }],
this: { type: 'undefined' },
}],
};

function fakeResponse() {
const lines = [];
let structured = null;
return {
lines,
get structured() { return structured; },
appendResponseLine: (line) => lines.push(line),
setStructuredContent: (value) => { structured = value; },
};
}

async function pausedContext() {
const dbg = new DebuggerContext();
const client = fakeClient();
await dbg.enable(client);
client.emit('Debugger.paused', PAUSED_EVENT);
assert.equal(dbg.isPaused(), true, '断言前置:已进入暂停');
return { dbg, client };
}

test('disable() keeps a paused mirror instead of falsely reporting running', async () => {
const { dbg } = await pausedContext();
await dbg.disable({ preserveBreakpoints: true });
assert.equal(dbg.isPaused(), true, '页面可能仍暂停,不能谎报已恢复');
assert.equal(dbg.getPausedState().stale, true, '必须标记为陈旧');
assert.equal(dbg.getPausedState().callFrames.length, 1, '保留现场,便于用户判断');
});

test('disable() on a running page stays running and is not marked stale', async () => {
const dbg = new DebuggerContext();
const client = fakeClient();
await dbg.enable(client);
await dbg.disable();
assert.equal(dbg.isPaused(), false);
assert.equal(dbg.getPausedState().stale, undefined);
});

test('resume() on a stale mirror is idempotent, not a hard failure', async () => {
const { dbg } = await pausedContext();
await dbg.disable({ preserveBreakpoints: true });
// 真实的漂移场景:disable 之后又 enable 了(换页/换帧/宿主重绑),
// 但新的 Debugger.paused 事件没到,镜像仍停在旧的暂停态。
await dbg.enable(fakeClient());
assert.equal(dbg.isPaused(), true);
const response = fakeResponse();
await pauseOrResume.handler({ params: { action: 'resume' } }, response, { debuggerContext: dbg });
assert.equal(dbg.isPaused(), false, '按 CDP 实际情况修正本地状态');
assert.equal(response.structured.state, 'running');
assert.equal(response.structured.reconciled, true);
});

test('resume() when already running without a stale mirror still conflicts', async () => {
const dbg = new DebuggerContext();
await dbg.enable(fakeClient());
await assert.rejects(
() => pauseOrResume.handler({ params: { action: 'resume' } }, fakeResponse(), { debuggerContext: dbg }),
(error) => error.code === 'CONFLICT',
'正常的「本来就运行中」仍应是稳定错误,不能被自愈逻辑吞掉',
);
});

test('resume() tolerates CDP reporting the page is not paused', async () => {
const dbg = new DebuggerContext();
const client = fakeClient({
send: async (method) => {
if (method === 'Debugger.resume') throw new Error('Can only perform operation while paused.');
return {};
},
});
await dbg.enable(client);
client.emit('Debugger.paused', PAUSED_EVENT);
const result = await dbg.resume();
assert.equal(result.alreadyRunning, true, 'CDP 说已不在暂停 → 幂等成功');
assert.equal(dbg.isPaused(), false, '以 CDP 为准修正镜像');
});

test('get_paused_info warns when the paused state may be stale', async () => {
const { dbg } = await pausedContext();
await dbg.disable({ preserveBreakpoints: true });
// 重新 enable 后没有新的 paused 事件:镜像仍是旧的
await dbg.enable(fakeClient());
const response = fakeResponse();
await getPausedInfo.handler(
{ params: { includeScopes: false, maxScopeDepth: 2, frameIndex: 0 } },
response,
{ debuggerContext: dbg },
);
assert.match(response.lines.join('\n'), /may be stale/);
});

test('markRunning() clears a drifted mirror', async () => {
const { dbg } = await pausedContext();
dbg.markRunning();
assert.equal(dbg.isPaused(), false);
assert.deepEqual(dbg.getPausedState().callFrames, []);
});

test('a fresh paused event clears the stale flag', async () => {
const { dbg, client } = await pausedContext();
await dbg.disable({ preserveBreakpoints: true });
const next = fakeClient();
await dbg.enable(next);
next.emit('Debugger.paused', PAUSED_EVENT);
assert.equal(dbg.isPaused(), true);
assert.equal(dbg.getPausedState().stale, undefined, '真实事件到了就不再是陈旧镜像');
assert.equal(client.listenerCount('Debugger.paused'), 0, 'disable 必须摘掉旧监听,避免双写');
});
Loading