feat: 修复停止逻辑

This commit is contained in:
祁连海
2026-04-17 23:29:10 +08:00
parent adf0cccd77
commit 73f9deb53e
12 changed files with 460 additions and 63 deletions
@@ -53,6 +53,7 @@ function extractFunction(source, name) {
const helperBundle = [
extractFunction(helperSource, 'clearStopRequest'),
extractFunction(helperSource, 'normalizeAutoRunSessionId'),
extractFunction(helperSource, 'throwIfStopped'),
extractFunction(helperSource, 'isStopError'),
extractFunction(helperSource, 'isStepDoneStatus'),
@@ -88,6 +89,8 @@ const DEFAULT_STATE = {
let stopRequested = false;
let runCalls = 0;
let autoRunSessionId = 0;
let autoRunSessionSeed = 1000;
const logs = [];
const broadcasts = [];
@@ -191,6 +194,17 @@ async function persistAutoRunTimerPlan() {}
async function launchAutoRunTimerPlan() { return false; }
function getPendingAutoRunTimerPlan() { return null; }
function getErrorMessage(error) { return error?.message || String(error || ''); }
function createAutoRunSessionId() {
autoRunSessionSeed += 1;
autoRunSessionId = autoRunSessionSeed;
return autoRunSessionId;
}
function throwIfAutoRunSessionStopped(sessionId) {
if (sessionId && sessionId !== autoRunSessionId) {
throw new Error(STOP_ERROR_MESSAGE);
}
throwIfStopped();
}
const chrome = {
runtime: {
sendMessage() {
@@ -242,6 +256,7 @@ const runtime = {
autoRunCurrentRun: 0,
autoRunTotalRuns: 1,
autoRunAttemptRun: 0,
autoRunSessionId: 0,
},
get() {
return { ...this.state };
@@ -261,6 +276,7 @@ const controller = self.MultiPageBackgroundAutoRunController.createAutoRunContro
broadcastStopToContentScripts,
cancelPendingCommands,
clearStopRequest,
createAutoRunSessionId,
getAutoRunStatusPayload,
getErrorMessage,
getFirstUnfinishedStep,
@@ -279,6 +295,7 @@ const controller = self.MultiPageBackgroundAutoRunController.createAutoRunContro
runtime,
setState,
sleepWithStop,
throwIfAutoRunSessionStopped,
waitForRunningStepsToFinish,
throwIfStopped,
chrome,
@@ -309,6 +326,7 @@ return {
assert.strictEqual(snapshot.currentState.autoRunPhase, 'complete', 'both runs should complete after reset');
assert.strictEqual(snapshot.currentState.autoRunCurrentRun, 2, 'final run index should be recorded');
assert.strictEqual(snapshot.autoRunActive, false, 'auto-run should exit active state after completion');
assert.strictEqual(snapshot.currentState.autoRunSessionId, 0, 'session id should be cleared after completion');
assert.strictEqual(snapshot.currentState.gmailBaseEmail, 'demo@gmail.com', 'gmail base email should survive fresh-attempt reset');
assert.strictEqual(snapshot.currentState.mail2925BaseEmail, 'demo@2925.com', '2925 base email should survive fresh-attempt reset');
+147
View File
@@ -0,0 +1,147 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const helperSource = fs.readFileSync('background.js', 'utf8');
function extractFunction(source, name) {
const markers = [`async function ${name}(`, `function ${name}(`];
const start = markers
.map((marker) => source.indexOf(marker))
.find((index) => index >= 0);
if (start < 0) {
throw new Error(`missing function ${name}`);
}
let parenDepth = 0;
let signatureEnded = false;
let braceStart = -1;
for (let i = start; i < source.length; i += 1) {
const ch = source[i];
if (ch === '(') {
parenDepth += 1;
} else if (ch === ')') {
parenDepth -= 1;
if (parenDepth === 0) {
signatureEnded = true;
}
} else if (ch === '{' && signatureEnded) {
braceStart = i;
break;
}
}
if (braceStart < 0) {
throw new Error(`missing body for function ${name}`);
}
let depth = 0;
let end = braceStart;
for (; end < source.length; end += 1) {
const ch = source[end];
if (ch === '{') depth += 1;
if (ch === '}') {
depth -= 1;
if (depth === 0) {
end += 1;
break;
}
}
}
return source.slice(start, end);
}
const helperBundle = [
extractFunction(helperSource, 'normalizeRunCount'),
extractFunction(helperSource, 'normalizeAutoRunTimerKind'),
extractFunction(helperSource, 'normalizeAutoRunSessionId'),
extractFunction(helperSource, 'isCurrentAutoRunSessionId'),
extractFunction(helperSource, 'normalizeAutoRunTimerPlan'),
extractFunction(helperSource, 'getAutoRunTimerResumeOptions'),
extractFunction(helperSource, 'launchAutoRunTimerPlan'),
].join('\n');
test('launchAutoRunTimerPlan ignores stale timer plans after stop invalidates the session', async () => {
const api = new Function(`
const AUTO_RUN_TIMER_KIND_SCHEDULED_START = 'scheduled_start';
const AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS = 'between_rounds';
const AUTO_RUN_TIMER_KIND_BEFORE_RETRY = 'before_retry';
const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
let autoRunTimerLaunching = false;
let autoRunActive = false;
let autoRunCurrentRun = 0;
let autoRunTotalRuns = 1;
let autoRunAttemptRun = 0;
let autoRunSessionId = 0;
const state = {
autoRunDelayEnabled: false,
autoRunTimerPlan: {
kind: AUTO_RUN_TIMER_KIND_SCHEDULED_START,
fireAt: Date.now() + 60_000,
totalRuns: 2,
autoRunSkipFailures: false,
autoRunSessionId: 42,
countdownTitle: '已计划自动运行',
countdownNote: '等待启动',
},
};
let startCalls = 0;
let clearStopCalls = 0;
let clearAlarmCalls = 0;
async function getState() {
return { ...state };
}
function getPendingAutoRunTimerPlan() {
return state.autoRunTimerPlan;
}
async function clearAutoRunTimerAlarm() {
clearAlarmCalls += 1;
}
async function broadcastAutoRunStatus() {}
async function addLog() {}
async function setAutoRunDelayEnabledState() {}
function serializeAutoRunRoundSummaries(totalRuns, summaries = []) {
return Array.isArray(summaries) ? summaries : [];
}
function clearStopRequest() {
clearStopCalls += 1;
}
function startAutoRunLoop() {
startCalls += 1;
}
${helperBundle}
return {
launchAutoRunTimerPlan,
snapshot() {
return {
startCalls,
clearStopCalls,
clearAlarmCalls,
autoRunCurrentRun,
autoRunTotalRuns,
autoRunAttemptRun,
};
},
};
`)();
const started = await api.launchAutoRunTimerPlan('alarm');
const snapshot = api.snapshot();
assert.equal(started, false);
assert.equal(snapshot.startCalls, 0, 'stale timer plan should not restart auto-run');
assert.equal(snapshot.clearStopCalls, 0, 'stale timer plan should not clear the stop flag for a cancelled run');
assert.equal(snapshot.clearAlarmCalls, 0, 'stale timer plan should not clear a potentially newer alarm');
assert.equal(snapshot.autoRunCurrentRun, 0);
assert.equal(snapshot.autoRunTotalRuns, 1);
assert.equal(snapshot.autoRunAttemptRun, 0);
});
@@ -47,6 +47,7 @@ test('tab runtime waitForTabComplete waits until tab status becomes complete', a
registerTab: async () => {},
setState: async () => {},
shouldBypassStep9ForLocalCpa: () => false,
throwIfStopped: () => {},
});
const result = await runtime.waitForTabComplete(9, {
@@ -57,3 +58,43 @@ test('tab runtime waitForTabComplete waits until tab status becomes complete', a
assert.equal(result?.status, 'complete');
assert.equal(getCalls, 3);
});
test('tab runtime waitForTabComplete aborts promptly when stop is requested', async () => {
const source = fs.readFileSync('background/tab-runtime.js', 'utf8');
const globalScope = {};
const api = new Function('self', `${source}; return self.MultiPageBackgroundTabRuntime;`)(globalScope);
let throwCalls = 0;
const runtime = api.createTabRuntime({
LOG_PREFIX: '[test]',
addLog: async () => {},
chrome: {
tabs: {
get: async () => ({
id: 9,
url: 'https://example.com',
status: 'loading',
}),
query: async () => [],
},
},
getSourceLabel: (sourceName) => sourceName || 'unknown',
getState: async () => ({ tabRegistry: {}, sourceLastUrls: {} }),
matchesSourceUrlFamily: () => false,
setState: async () => {},
throwIfStopped: () => {
throwCalls += 1;
if (throwCalls >= 2) {
throw new Error('Flow stopped.');
}
},
});
await assert.rejects(
runtime.waitForTabComplete(9, {
timeoutMs: 2000,
retryDelayMs: 1,
}),
/Flow stopped\./
);
});
+4
View File
@@ -98,6 +98,10 @@ function fillInput(input, value) {
async function humanPause() {}
async function sleep() {}
function throwIfStopped() {}
function isStopError() {
return false;
}
function log(message, level = 'info') {
logs.push({ message, level });
+5
View File
@@ -52,6 +52,8 @@ function extractFunction(source, name) {
}
const helperBundle = [
extractFunction(helperSource, 'normalizeAutoRunSessionId'),
extractFunction(helperSource, 'clearCurrentAutoRunSessionId'),
extractFunction(helperSource, 'throwIfStopped'),
extractFunction(helperSource, 'cleanupStep8NavigationListeners'),
extractFunction(helperSource, 'rejectPendingStep8'),
@@ -71,6 +73,7 @@ let autoRunActive = true;
let autoRunCurrentRun = 2;
let autoRunTotalRuns = 3;
let autoRunAttemptRun = 4;
let autoRunSessionId = 99;
const AUTO_RUN_TIMER_KIND_SCHEDULED_START = 'scheduled_start';
const STEP8_CLICK_RETRY_DELAY_MS = 500;
const STEP8_MAX_ROUNDS = 5;
@@ -257,6 +260,7 @@ return {
sentMessages,
clickCount,
autoRunActive,
autoRunSessionId,
};
},
};
@@ -288,6 +292,7 @@ return {
assert.strictEqual(state.webNavCommittedListener, null, 'Stop 后 onCommitted 引用应为空');
assert.strictEqual(state.step8TabUpdatedListener, null, 'Stop 后 tabs.onUpdated 引用应为空');
assert.strictEqual(state.step8PendingReject, null, 'Stop 后不应保留 Step 8 挂起 reject');
assert.strictEqual(state.autoRunSessionId, 0, 'Stop 后自动运行 session 应失效');
console.log('step8 stop cleanup tests passed');
})().catch((error) => {