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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 isStepDoneStatus(status) {
  88. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  89. }
  90. async function executeStepAndWait(step) {
  91. events.steps.push(step);
  92. if (step === ${JSON.stringify(failureStep)} && remainingFailures > 0) {
  93. remainingFailures -= 1;
  94. throw new Error(${JSON.stringify(failureMessage)});
  95. }
  96. }
  97. async function getTabId() {
  98. return 1;
  99. }
  100. function shouldSkipLoginVerificationForCpaCallback() {
  101. return false;
  102. }
  103. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  104. events.invalidations.push({ step, options });
  105. }
  106. function getLoginAuthStateLabel(state) {
  107. return state || 'unknown';
  108. }
  109. function getErrorMessage(error) {
  110. return error?.message || String(error || '');
  111. }
  112. async function getLoginAuthStateFromContent() {
  113. return ${JSON.stringify(authState)};
  114. }
  115. ${bundle}
  116. return {
  117. async run() {
  118. await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
  119. targetRun: 1,
  120. totalRuns: 1,
  121. attemptRuns: 1,
  122. continued: false,
  123. });
  124. return events;
  125. },
  126. async runAndCaptureError() {
  127. try {
  128. await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
  129. targetRun: 1,
  130. totalRuns: 1,
  131. attemptRuns: 1,
  132. continued: false,
  133. });
  134. return null;
  135. } catch (error) {
  136. return { error, events };
  137. }
  138. },
  139. };
  140. `)();
  141. }
  142. test('auto-run keeps restarting from step 6 after post-login failures without a hard cap', async () => {
  143. const harness = createHarness({
  144. failureStep: 9,
  145. failureBudget: 6,
  146. failureMessage: '认证失败: Request failed with status code 502',
  147. authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  148. });
  149. const events = await harness.run();
  150. assert.equal(events.invalidations.length, 6);
  151. assert.deepStrictEqual(
  152. events.steps,
  153. [
  154. 6, 7, 8, 9,
  155. 6, 7, 8, 9,
  156. 6, 7, 8, 9,
  157. 6, 7, 8, 9,
  158. 6, 7, 8, 9,
  159. 6, 7, 8, 9,
  160. 6, 7, 8, 9,
  161. ]
  162. );
  163. assert.ok(events.logs.some(({ message }) => /回到步骤 6 重新开始授权流程/.test(message)));
  164. });
  165. test('auto-run stops restarting once add-phone is detected', async () => {
  166. const harness = createHarness({
  167. failureStep: 6,
  168. failureBudget: 1,
  169. failureMessage: '当前页面已进入手机号页。URL: https://auth.openai.com/add-phone',
  170. authState: { state: 'add_phone_page', url: 'https://auth.openai.com/add-phone' },
  171. });
  172. const result = await harness.runAndCaptureError();
  173. assert.ok(result?.error);
  174. assert.equal(result.events.invalidations.length, 0);
  175. assert.deepStrictEqual(result.events.steps, [6]);
  176. assert.ok(result.events.logs.some(({ message }) => /进入 add-phone/.test(message)));
  177. });