auto-run-step6-restart.test.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. const test = require('node:test');
  2. const assert = require('node:assert/strict');
  3. const fs = require('node:fs');
  4. const source = fs.readFileSync('background.js', 'utf8');
  5. function extractFunction(name) {
  6. const markers = [`async function ${name}(`, `function ${name}(`];
  7. const start = markers
  8. .map((marker) => source.indexOf(marker))
  9. .find((index) => index >= 0);
  10. if (start < 0) {
  11. throw new Error(`missing function ${name}`);
  12. }
  13. let parenDepth = 0;
  14. let signatureEnded = false;
  15. let braceStart = -1;
  16. for (let i = start; i < source.length; i += 1) {
  17. const ch = source[i];
  18. if (ch === '(') {
  19. parenDepth += 1;
  20. } else if (ch === ')') {
  21. parenDepth -= 1;
  22. if (parenDepth === 0) {
  23. signatureEnded = true;
  24. }
  25. } else if (ch === '{' && signatureEnded) {
  26. braceStart = i;
  27. break;
  28. }
  29. }
  30. if (braceStart < 0) {
  31. throw new Error(`missing body for function ${name}`);
  32. }
  33. let depth = 0;
  34. let end = braceStart;
  35. for (; end < source.length; end += 1) {
  36. const ch = source[end];
  37. if (ch === '{') depth += 1;
  38. if (ch === '}') {
  39. depth -= 1;
  40. if (depth === 0) {
  41. end += 1;
  42. break;
  43. }
  44. }
  45. }
  46. return source.slice(start, end);
  47. }
  48. const bundle = [
  49. extractFunction('isAddPhoneAuthUrl'),
  50. extractFunction('isAddPhoneAuthState'),
  51. extractFunction('getPostStep6AutoRestartDecision'),
  52. extractFunction('runAutoSequenceFromStep'),
  53. ].join('\n');
  54. function createHarness(options = {}) {
  55. const {
  56. startStep = 6,
  57. failureStep = 9,
  58. failureBudget = 1,
  59. failureMessage = '认证失败: Request failed with status code 502',
  60. authState = { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  61. } = options;
  62. return new Function(`
  63. const AUTO_STEP_DELAYS = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0 };
  64. const LOG_PREFIX = '[test]';
  65. const chrome = {
  66. tabs: {
  67. update: async () => {},
  68. },
  69. };
  70. let remainingFailures = ${JSON.stringify(failureBudget)};
  71. const events = {
  72. steps: [],
  73. logs: [],
  74. invalidations: [],
  75. };
  76. async function addLog(message, level = 'info') {
  77. events.logs.push({ message, level });
  78. }
  79. async function ensureAutoEmailReady() {}
  80. async function broadcastAutoRunStatus() {}
  81. async function getState() {
  82. return {
  83. stepStatuses: { 3: 'completed' },
  84. mailProvider: '163',
  85. };
  86. }
  87. function isStopError(error) {
  88. return (error?.message || String(error || '')) === '流程已被用户停止。';
  89. }
  90. function isStepDoneStatus(status) {
  91. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  92. }
  93. async function executeStepAndWait(step) {
  94. events.steps.push(step);
  95. if (step === ${JSON.stringify(failureStep)} && remainingFailures > 0) {
  96. remainingFailures -= 1;
  97. throw new Error(${JSON.stringify(failureMessage)});
  98. }
  99. }
  100. async function getTabId() {
  101. return 1;
  102. }
  103. function shouldSkipLoginVerificationForCpaCallback() {
  104. return false;
  105. }
  106. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  107. events.invalidations.push({ step, options });
  108. }
  109. function getLoginAuthStateLabel(state) {
  110. return state || 'unknown';
  111. }
  112. function getErrorMessage(error) {
  113. return error?.message || String(error || '');
  114. }
  115. async function getLoginAuthStateFromContent() {
  116. return ${JSON.stringify(authState)};
  117. }
  118. ${bundle}
  119. return {
  120. async run() {
  121. await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
  122. targetRun: 1,
  123. totalRuns: 1,
  124. attemptRuns: 1,
  125. continued: false,
  126. });
  127. return events;
  128. },
  129. async runAndCaptureError() {
  130. try {
  131. await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
  132. targetRun: 1,
  133. totalRuns: 1,
  134. attemptRuns: 1,
  135. continued: false,
  136. });
  137. return null;
  138. } catch (error) {
  139. return { error, events };
  140. }
  141. },
  142. };
  143. `)();
  144. }
  145. test('auto-run keeps restarting from step 6 after post-login failures without a hard cap', async () => {
  146. const harness = createHarness({
  147. failureStep: 9,
  148. failureBudget: 6,
  149. failureMessage: '认证失败: Request failed with status code 502',
  150. authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  151. });
  152. const events = await harness.run();
  153. assert.equal(events.invalidations.length, 6);
  154. assert.deepStrictEqual(
  155. events.steps,
  156. [
  157. 6, 7, 8, 9,
  158. 6, 7, 8, 9,
  159. 6, 7, 8, 9,
  160. 6, 7, 8, 9,
  161. 6, 7, 8, 9,
  162. 6, 7, 8, 9,
  163. 6, 7, 8, 9,
  164. ]
  165. );
  166. assert.ok(events.logs.some(({ message }) => /回到步骤 6 重新开始授权流程/.test(message)));
  167. });
  168. test('auto-run stops restarting once add-phone is detected', async () => {
  169. const harness = createHarness({
  170. failureStep: 6,
  171. failureBudget: 1,
  172. failureMessage: '当前页面已进入手机号页。URL: https://auth.openai.com/add-phone',
  173. authState: { state: 'add_phone_page', url: 'https://auth.openai.com/add-phone' },
  174. });
  175. const result = await harness.runAndCaptureError();
  176. assert.ok(result?.error);
  177. assert.equal(result.events.invalidations.length, 0);
  178. assert.deepStrictEqual(result.events.steps, [6]);
  179. assert.ok(result.events.logs.some(({ message }) => /进入 add-phone/.test(message)));
  180. });
  181. test('auto-run stop errors after step 6 are rethrown immediately instead of restarting', async () => {
  182. const harness = createHarness({
  183. failureStep: 8,
  184. failureBudget: 1,
  185. failureMessage: '流程已被用户停止。',
  186. authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  187. });
  188. const result = await harness.runAndCaptureError();
  189. assert.equal(result?.error?.message, '流程已被用户停止。');
  190. assert.equal(result.events.invalidations.length, 0);
  191. assert.deepStrictEqual(result.events.steps, [6, 7, 8]);
  192. assert.ok(!result.events.logs.some(({ message }) => /回到步骤 6 重新开始授权流程/.test(message)));
  193. });