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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 = 7,
  57. failureStep = 10,
  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, 10: 0 };
  64. const LAST_STEP_ID = 10;
  65. const FINAL_OAUTH_CHAIN_START_STEP = 7;
  66. const LOG_PREFIX = '[test]';
  67. const chrome = {
  68. tabs: {
  69. update: async () => {},
  70. },
  71. };
  72. let remainingFailures = ${JSON.stringify(failureBudget)};
  73. const events = {
  74. steps: [],
  75. logs: [],
  76. invalidations: [],
  77. };
  78. async function addLog(message, level = 'info') {
  79. events.logs.push({ message, level });
  80. }
  81. async function ensureAutoEmailReady() {}
  82. async function broadcastAutoRunStatus() {}
  83. async function getState() {
  84. return {
  85. stepStatuses: { 3: 'completed' },
  86. mailProvider: '163',
  87. };
  88. }
  89. function isStopError(error) {
  90. return (error?.message || String(error || '')) === '流程已被用户停止。';
  91. }
  92. function isStepDoneStatus(status) {
  93. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  94. }
  95. async function executeStepAndWait(step) {
  96. events.steps.push(step);
  97. if (step === ${JSON.stringify(failureStep)} && remainingFailures > 0) {
  98. remainingFailures -= 1;
  99. throw new Error(${JSON.stringify(failureMessage)});
  100. }
  101. }
  102. async function getTabId() {
  103. return 1;
  104. }
  105. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  106. events.invalidations.push({ step, options });
  107. }
  108. function getLoginAuthStateLabel(state) {
  109. return state || 'unknown';
  110. }
  111. function getErrorMessage(error) {
  112. return error?.message || String(error || '');
  113. }
  114. async function getLoginAuthStateFromContent() {
  115. return ${JSON.stringify(authState)};
  116. }
  117. ${bundle}
  118. return {
  119. async run() {
  120. await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
  121. targetRun: 1,
  122. totalRuns: 1,
  123. attemptRuns: 1,
  124. continued: false,
  125. });
  126. return events;
  127. },
  128. async runAndCaptureError() {
  129. try {
  130. await runAutoSequenceFromStep(${JSON.stringify(startStep)}, {
  131. targetRun: 1,
  132. totalRuns: 1,
  133. attemptRuns: 1,
  134. continued: false,
  135. });
  136. return null;
  137. } catch (error) {
  138. return { error, events };
  139. }
  140. },
  141. };
  142. `)();
  143. }
  144. test('auto-run keeps restarting from step 7 after post-login failures without a hard cap', async () => {
  145. const harness = createHarness({
  146. failureStep: 10,
  147. failureBudget: 6,
  148. failureMessage: '认证失败: Request failed with status code 502',
  149. authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  150. });
  151. const events = await harness.run();
  152. assert.equal(events.invalidations.length, 6);
  153. assert.deepStrictEqual(
  154. events.steps,
  155. [
  156. 7, 8, 9, 10,
  157. 7, 8, 9, 10,
  158. 7, 8, 9, 10,
  159. 7, 8, 9, 10,
  160. 7, 8, 9, 10,
  161. 7, 8, 9, 10,
  162. 7, 8, 9, 10,
  163. ]
  164. );
  165. assert.ok(events.logs.some(({ message }) => /回到步骤 7 重新开始授权流程/.test(message)));
  166. });
  167. test('auto-run stops restarting once add-phone is detected', async () => {
  168. const harness = createHarness({
  169. failureStep: 7,
  170. failureBudget: 1,
  171. failureMessage: '当前页面已进入手机号页面。URL: https://auth.openai.com/add-phone',
  172. authState: { state: 'add_phone_page', url: 'https://auth.openai.com/add-phone' },
  173. });
  174. const result = await harness.runAndCaptureError();
  175. assert.ok(result?.error);
  176. assert.equal(result.events.invalidations.length, 0);
  177. assert.deepStrictEqual(result.events.steps, [7]);
  178. assert.ok(result.events.logs.some(({ message }) => /进入 add-phone/.test(message)));
  179. });
  180. test('auto-run stop errors after step 7 are rethrown immediately instead of restarting', async () => {
  181. const harness = createHarness({
  182. failureStep: 9,
  183. failureBudget: 1,
  184. failureMessage: '流程已被用户停止。',
  185. authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  186. });
  187. const result = await harness.runAndCaptureError();
  188. assert.equal(result?.error?.message, '流程已被用户停止。');
  189. assert.equal(result.events.invalidations.length, 0);
  190. assert.deepStrictEqual(result.events.steps, [7, 8, 9]);
  191. assert.ok(!result.events.logs.some(({ message }) => /回到步骤 7 重新开始授权流程/.test(message)));
  192. });