feat: Enhance Step 9 diagnostics and error handling

- Refactor getStatusBadgeEntries to use createStep9Entry for better encapsulation.
- Introduce error visual signals detection in createStep9Entry.
- Add functions to identify OAuth callback timeout failures and step 9 failure texts.
- Update buildStep9StatusDiagnostics to include error visual summaries and handle conflicts between success and failure states.
- Implement new tests for step 9 diagnostics, ensuring correct behavior with success badges and error banners.
- Remove outdated tests related to step 5 onboarding and redirect race conditions.
- Add new tests for auto-run behavior in step 6 restart scenarios.
This commit is contained in:
QLHazyCoder
2026-04-17 04:33:14 +08:00
parent 1a5f569d16
commit c745405f90
17 changed files with 772 additions and 691 deletions
+10
View File
@@ -71,6 +71,16 @@ test('isRecoverableStep9AuthFailure matches timeout and CPA auth failure statuse
true
);
assert.equal(
isRecoverableStep9AuthFailure('认证失败: timeout of 30000ms exceeded'),
true
);
assert.equal(
isRecoverableStep9AuthFailure('回调 URL 提交失败: oauth flow is not pending'),
true
);
assert.equal(
isRecoverableStep9AuthFailure('认证成功!'),
false
+197
View File
@@ -0,0 +1,197 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const source = fs.readFileSync('background.js', 'utf8');
function extractFunction(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 bundle = [
extractFunction('isAddPhoneAuthUrl'),
extractFunction('isAddPhoneAuthState'),
extractFunction('getPostStep6AutoRestartDecision'),
extractFunction('runAutoSequenceFromStep'),
].join('\n');
function createHarness(options = {}) {
const {
startStep = 6,
failureStep = 9,
failureBudget = 1,
failureMessage = '认证失败: Request failed with status code 502',
authState = { state: 'password_page', url: 'https://auth.openai.com/log-in' },
} = options;
return new Function(`
const AUTO_STEP_DELAYS = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0 };
const LOG_PREFIX = '[test]';
const chrome = {
tabs: {
update: async () => {},
},
};
let remainingFailures = ${JSON.stringify(failureBudget)};
const events = {
steps: [],
logs: [],
invalidations: [],
};
async function addLog(message, level = 'info') {
events.logs.push({ message, level });
}
async function ensureAutoEmailReady() {}
async function broadcastAutoRunStatus() {}
async function getState() {
return {
stepStatuses: { 3: 'completed' },
mailProvider: '163',
};
}
function isStepDoneStatus(status) {
return status === 'completed' || status === 'manual_completed' || status === 'skipped';
}
async function executeStepAndWait(step) {
events.steps.push(step);
if (step === ${JSON.stringify(failureStep)} && remainingFailures > 0) {
remainingFailures -= 1;
throw new Error(${JSON.stringify(failureMessage)});
}
}
async function getTabId() {
return 1;
}
function shouldSkipLoginVerificationForCpaCallback() {
return false;
}
async function invalidateDownstreamAfterStepRestart(step, options = {}) {
events.invalidations.push({ step, options });
}
function getLoginAuthStateLabel(state) {
return state || 'unknown';
}
function getErrorMessage(error) {
return error?.message || String(error || '');
}
async function getLoginAuthStateFromContent() {
return ${JSON.stringify(authState)};
}
${bundle}
return {
async run() {
await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
targetRun: 1,
totalRuns: 1,
attemptRuns: 1,
continued: false,
});
return events;
},
async runAndCaptureError() {
try {
await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
targetRun: 1,
totalRuns: 1,
attemptRuns: 1,
continued: false,
});
return null;
} catch (error) {
return { error, events };
}
},
};
`)();
}
test('auto-run keeps restarting from step 6 after post-login failures without a hard cap', async () => {
const harness = createHarness({
failureStep: 9,
failureBudget: 6,
failureMessage: '认证失败: Request failed with status code 502',
authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
});
const events = await harness.run();
assert.equal(events.invalidations.length, 6);
assert.deepStrictEqual(
events.steps,
[
6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
6, 7, 8, 9,
]
);
assert.ok(events.logs.some(({ message }) => /回到步骤 6 重新开始授权流程/.test(message)));
});
test('auto-run stops restarting once add-phone is detected', async () => {
const harness = createHarness({
failureStep: 6,
failureBudget: 1,
failureMessage: '当前页面已进入手机号页。URL: https://auth.openai.com/add-phone',
authState: { state: 'add_phone_page', url: 'https://auth.openai.com/add-phone' },
});
const result = await harness.runAndCaptureError();
assert.ok(result?.error);
assert.equal(result.events.invalidations.length, 0);
assert.deepStrictEqual(result.events.steps, [6]);
assert.ok(result.events.logs.some(({ message }) => /进入 add-phone/.test(message)));
});
@@ -6,47 +6,42 @@ const source = fs.readFileSync('background/steps/fill-profile.js', 'utf8');
const globalScope = {};
const api = new Function('self', `${source}; return self.MultiPageBackgroundStep5;`)(globalScope);
test('step 5 transport error returns immediately after completion signal arrives', async () => {
test('step 5 forwards generated profile data and relies on completion signal flow', async () => {
const events = {
redirectWaitCalls: 0,
onboardingCalls: 0,
logs: [],
messages: [],
};
const transportError = new Error('The message port closed before a response was received.');
const executor = api.createStep5Executor({
addLog: async (message, level) => {
events.logs.push({ message, level: level || 'info' });
},
generateRandomBirthday: () => ({ year: 2003, month: 6, day: 19 }),
generateRandomName: () => ({ firstName: 'Test', lastName: 'User' }),
getState: async () => ({
stepStatuses: {
5: 'completed',
},
}),
getTabId: async () => 123,
handleChatgptOnboardingSkip: async () => {
events.onboardingCalls += 1;
},
isRetryableContentScriptTransportError: (error) => error === transportError,
LOG_PREFIX: '[test]',
sendToContentScript: async () => {
throw transportError;
},
waitForStep5ChatgptRedirect: async () => {
events.redirectWaitCalls += 1;
return { id: 123, url: 'https://chatgpt.com/' };
sendToContentScript: async (source, message) => {
events.messages.push({ source, message });
return { accepted: true };
},
});
await executor.executeStep5();
assert.equal(events.redirectWaitCalls, 0, '收到完成信号后不应再等待 ChatGPT 跳转');
assert.equal(events.onboardingCalls, 0, '收到完成信号后不应再触发 onboarding 跳过');
assert.ok(
events.logs.some(({ message }) => /已收到完成信号直接结束当前步骤/.test(message)),
'应记录 Step 5 已按完成信号直接结束'
);
assert.deepStrictEqual(events.messages, [
{
source: 'signup-page',
message: {
type: 'EXECUTE_STEP',
step: 5,
source: 'background',
payload: {
firstName: 'Test',
lastName: 'User',
year: 2003,
month: 6,
day: 19,
},
},
},
]);
assert.ok(events.logs.some(({ message }) => /已生成姓名 Test User/.test(message)));
});
@@ -15,3 +15,45 @@ test('tab runtime module exposes a factory', () => {
assert.equal(typeof api?.createTabRuntime, 'function');
});
test('tab runtime waitForTabComplete waits until tab status becomes complete', async () => {
const source = fs.readFileSync('background/tab-runtime.js', 'utf8');
const globalScope = {};
const api = new Function('self', `${source}; return self.MultiPageBackgroundTabRuntime;`)(globalScope);
let getCalls = 0;
const runtime = api.createTabRuntime({
LOG_PREFIX: '[test]',
addLog: async () => {},
buildLocalhostCleanupPrefix: () => '',
chrome: {
tabs: {
get: async () => {
getCalls += 1;
return {
id: 9,
url: 'https://example.com',
status: getCalls >= 3 ? 'complete' : 'loading',
};
},
query: async () => [],
},
},
getSourceLabel: (source) => source || 'unknown',
getState: async () => ({ tabRegistry: {}, sourceLastUrls: {} }),
matchesSourceUrlFamily: () => false,
normalizeLocalCpaStep9Mode: () => 'submit',
parseUrlSafely: () => null,
registerTab: async () => {},
setState: async () => {},
shouldBypassStep9ForLocalCpa: () => false,
});
const result = await runtime.waitForTabComplete(9, {
timeoutMs: 2000,
retryDelayMs: 1,
});
assert.equal(result?.status, 'complete');
assert.equal(getCalls, 3);
});
-172
View File
@@ -1,172 +0,0 @@
const assert = require('assert');
const fs = require('fs');
const source = fs.readFileSync('content/signup-page.js', 'utf8');
function extractFunction(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 bundle = [
extractFunction('getPageTextSnapshot'),
extractFunction('findChatgptSkipButton'),
extractFunction('waitForChatgptSkipButton'),
extractFunction('isChatgptOnboardingPage'),
extractFunction('isChatgptUrl'),
extractFunction('hasVisibleElementMatchingSelector'),
extractFunction('isChatgptAuthenticatedHomePage'),
extractFunction('waitForChatgptPostSignupState'),
extractFunction('skipChatgptOnboarding'),
].join('\n');
const api = new Function(`
const CHATGPT_ONBOARDING_TEXT_PATTERN = /welcome\\s+to\\s+chatgpt|what\\s+should\\s+chatgpt\\s+call\\s+you|how\\s+do\\s+you\\s+want\\s+chatgpt\\s+to\\s+respond|tell\\s+chatgpt\\s+what\\s+traits|personal(?:ize|ise)\\s+your\\s+experience|介绍一下你自己|ChatGPT 应该如何称呼你|你希望 ChatGPT 如何回应/i;
const CHATGPT_HOME_TEXT_PATTERN = /new\\s+chat|temporary\\s+chat|message\\s+chatgpt|send\\s+a\\s+message|chatgpt\\s+can\\s+make\\s+mistakes|新建聊天|临时聊天|给\\s*ChatGPT\\s*发消息|ChatGPT\\s*可能会犯错/i;
let buttonList = [];
let selectorMap = {};
let pageText = '';
let clickedButtons = [];
let logs = [];
const location = { href: 'https://chatgpt.com/' };
const document = {
body: { innerText: '', textContent: '' },
querySelectorAll(selector) {
if (selector === 'button') {
return buttonList;
}
return selectorMap[selector] || [];
},
};
function isVisibleElement(el) {
return Boolean(el) && !el.hidden;
}
function throwIfStopped() {}
async function sleep() {}
async function humanPause() {}
function log(message, level = 'info') {
logs.push({ message, level });
}
function simulateClick(button) {
clickedButtons.push(button.textContent || button.id || 'button');
button.hidden = true;
}
${bundle}
return {
setPage({ href = 'https://chatgpt.com/', text = '', buttons = [], selectors = {} }) {
location.href = href;
pageText = text;
buttonList = buttons.map((button, index) => ({
id: button.id || \`button-\${index}\`,
textContent: button.textContent || '',
className: button.className || '',
hidden: Boolean(button.hidden),
}));
selectorMap = {};
for (const [selector, count] of Object.entries(selectors)) {
selectorMap[selector] = Array.from({ length: count }, (_, index) => ({ id: \`\${selector}-\${index}\`, hidden: false }));
}
document.body.innerText = pageText;
document.body.textContent = pageText;
clickedButtons = [];
logs = [];
},
isChatgptOnboardingPage() {
return isChatgptOnboardingPage();
},
isChatgptAuthenticatedHomePage() {
return isChatgptAuthenticatedHomePage();
},
async skipChatgptOnboarding() {
return skipChatgptOnboarding();
},
snapshot() {
return { clickedButtons, logs };
},
};
`)();
(async () => {
api.setPage({
href: 'https://chatgpt.com/',
text: 'New chat ChatGPT can make mistakes',
selectors: {
'textarea[placeholder*="Message" i]': 1,
},
});
assert.strictEqual(api.isChatgptOnboardingPage(), false, '已登录主页不应仅因 chatgpt.com URL 被误判为 onboarding');
assert.strictEqual(api.isChatgptAuthenticatedHomePage(), true, '主页特征存在时应识别为已登录 ChatGPT 页面');
let result = await api.skipChatgptOnboarding();
let snapshot = api.snapshot();
assert.deepStrictEqual(result, { success: true, alreadyCompleted: true }, '无 Skip 按钮但已进入主页时应按成功处理');
assert.deepStrictEqual(snapshot.clickedButtons, [], '已登录主页场景不应再误点按钮');
api.setPage({
href: 'https://chatgpt.com/',
text: 'Welcome to ChatGPT',
buttons: [
{ textContent: 'Skip', className: 'btn-ghost' },
{ textContent: 'Skip', className: 'btn-ghost' },
],
});
assert.strictEqual(api.isChatgptOnboardingPage(), true, '存在 Skip 按钮时应识别为 onboarding');
result = await api.skipChatgptOnboarding();
snapshot = api.snapshot();
assert.deepStrictEqual(result, { success: true }, '真实 onboarding 仍应继续执行跳过逻辑');
assert.deepStrictEqual(snapshot.clickedButtons, ['Skip', 'Skip'], '双 Skip onboarding 应依次点击两个按钮');
console.log('step5 chatgpt onboarding tests passed');
})().catch((error) => {
console.error(error);
process.exit(1);
});
-123
View File
@@ -1,123 +0,0 @@
const assert = require('assert');
const fs = require('fs');
const source = fs.readFileSync('background.js', 'utf8');
function extractFunction(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 bundle = [
extractFunction('waitForStep5ChatgptRedirect'),
].join('\n');
const api = new Function(`
let waitArgs = null;
let waitResult = null;
let currentTab = null;
const chrome = {
tabs: {
async get() {
return currentTab;
},
},
};
async function waitForTabUrlMatch(tabId, matcher, options = {}) {
waitArgs = { tabId, matcher, options };
return waitResult;
}
${bundle}
return {
async run(tabId, timeoutMs) {
return waitForStep5ChatgptRedirect(tabId, timeoutMs);
},
setWaitResult(value) {
waitResult = value;
},
setCurrentTab(value) {
currentTab = value;
},
snapshot() {
return { waitArgs };
},
};
`)();
(async () => {
const redirected = { id: 86, url: 'https://chatgpt.com/' };
api.setWaitResult(redirected);
api.setCurrentTab({ id: 86, url: 'https://auth.openai.com/' });
let result = await api.run(86, 22000);
let snapshot = api.snapshot();
assert.deepStrictEqual(result, redirected, '等待命中 chatgpt.com 时应直接返回匹配到的标签页');
assert.strictEqual(snapshot.waitArgs.tabId, 86, '应使用 signup-page 当前标签页等待跳转');
assert.strictEqual(snapshot.waitArgs.options.timeoutMs, 22000, '应透传等待超时时间');
assert.strictEqual(snapshot.waitArgs.options.retryDelayMs, 300, '应使用较短轮询间隔覆盖 URL 更新 race');
assert.strictEqual(snapshot.waitArgs.matcher('https://chatgpt.com/?model=gpt-5'), true, 'matcher 应接受 chatgpt.com');
assert.strictEqual(snapshot.waitArgs.matcher('https://auth.openai.com/u/signup'), false, 'matcher 不应把旧认证页误判为成功');
api.setWaitResult(null);
api.setCurrentTab({ id: 86, url: 'https://chatgpt.com/?temporary-chat=true' });
result = await api.run(86, 15000);
assert.deepStrictEqual(result, { id: 86, url: 'https://chatgpt.com/?temporary-chat=true' }, '等待超时后仍应回读当前标签页 URL 兜底');
api.setCurrentTab({ id: 86, url: 'https://auth.openai.com/u/signup' });
result = await api.run(86, 15000);
assert.strictEqual(result, null, '仍停留旧域名时不应误判为跳转成功');
result = await api.run(null, 15000);
assert.strictEqual(result, null, '无有效标签页时应直接返回 null');
console.log('step5 chatgpt redirect race tests passed');
})().catch((error) => {
console.error(error);
process.exit(1);
});
+126
View File
@@ -0,0 +1,126 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const source = fs.readFileSync('content/vps-panel.js', 'utf8');
function extractFunction(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 bundle = [
"const STEP9_SUCCESS_STATUSES = new Set(['Authentication successful!', 'Аутентификация успешна!', '认证成功!']);",
extractFunction('getInlineTextSnippet'),
extractFunction('summarizeStatusBadgeEntries'),
extractFunction('normalizeStep9StatusText'),
extractFunction('isOAuthCallbackTimeoutFailure'),
extractFunction('isStep9FailureText'),
extractFunction('isStep9SuccessStatus'),
extractFunction('isStep9SuccessLikeStatus'),
extractFunction('buildStep9StatusDiagnostics'),
].join('\n');
function createApi() {
return new Function(`
function isRecoverableStep9AuthFailure(text) {
return /(?:认证失败|回调 URL 提交失败):\\s*/i.test(String(text || '').trim())
|| /oauth flow is not pending/i.test(String(text || '').trim());
}
${bundle}
return {
buildStep9StatusDiagnostics,
};
`)();
}
test('step 9 does not treat red success badges as exact success', () => {
const api = createApi();
const diagnostics = api.buildStep9StatusDiagnostics([
{
visible: true,
text: '认证成功!',
className: 'status-badge text-danger',
hasErrorVisualSignal: true,
errorVisualSummary: 'color=rgb(220, 38, 38)',
},
], [], 'page');
assert.equal(diagnostics.hasSuccessLikeVisibleBadge, true);
assert.equal(diagnostics.hasExactSuccessVisibleBadge, false);
assert.equal(diagnostics.hasErrorStyledVisibleBadge, true);
});
test('step 9 keeps failure state dominant when success badge and error banner coexist', () => {
const api = createApi();
const diagnostics = api.buildStep9StatusDiagnostics(
[
{
visible: true,
text: '认证成功!',
className: 'status-badge',
hasErrorVisualSignal: false,
errorVisualSummary: '',
},
],
[
{
visible: true,
text: '回调 URL 提交失败: oauth flow is not pending',
className: 'alert alert-danger',
hasErrorVisualSignal: true,
errorVisualSummary: 'color=rgb(220, 38, 38)',
},
],
'page'
);
assert.equal(diagnostics.hasExactSuccessVisibleBadge, true);
assert.equal(diagnostics.hasFailureVisibleBadge, true);
assert.equal(diagnostics.failureText, '回调 URL 提交失败: oauth flow is not pending');
});