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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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('isAddPhoneAuthFailure'),
  50. extractFunction('isAddPhoneAuthUrl'),
  51. extractFunction('isAddPhoneAuthState'),
  52. extractFunction('getPostStep6AutoRestartDecision'),
  53. extractFunction('runAutoSequenceFromStep'),
  54. ].join('\n');
  55. function createHarness(options = {}) {
  56. const {
  57. startStep = 7,
  58. failureStep = 10,
  59. failureBudget = 1,
  60. failureMessage = '认证失败: Request failed with status code 502',
  61. authState = { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  62. } = options;
  63. return new Function(`
  64. const AUTO_STEP_DELAYS = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0 };
  65. const LAST_STEP_ID = 10;
  66. const FINAL_OAUTH_CHAIN_START_STEP = 7;
  67. const LOG_PREFIX = '[test]';
  68. const chrome = {
  69. tabs: {
  70. update: async () => {},
  71. },
  72. };
  73. let remainingFailures = ${JSON.stringify(failureBudget)};
  74. const events = {
  75. steps: [],
  76. logs: [],
  77. invalidations: [],
  78. };
  79. async function addLog(message, level = 'info') {
  80. events.logs.push({ message, level });
  81. }
  82. async function ensureAutoEmailReady() {}
  83. async function broadcastAutoRunStatus() {}
  84. async function getState() {
  85. return {
  86. stepStatuses: { 3: 'completed' },
  87. mailProvider: '163',
  88. };
  89. }
  90. function isStopError(error) {
  91. return (error?.message || String(error || '')) === '流程已被用户停止。';
  92. }
  93. function isStepDoneStatus(status) {
  94. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  95. }
  96. async function executeStepAndWait(step) {
  97. events.steps.push(step);
  98. if (step === ${JSON.stringify(failureStep)} && remainingFailures > 0) {
  99. remainingFailures -= 1;
  100. throw new Error(${JSON.stringify(failureMessage)});
  101. }
  102. }
  103. async function getTabId() {
  104. return 1;
  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 7 after post-login failures without a hard cap', async () => {
  146. const harness = createHarness({
  147. failureStep: 10,
  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. 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. 7, 8, 9, 10,
  164. ]
  165. );
  166. assert.ok(events.logs.some(({ message }) => /回到步骤 7 重新开始授权流程/.test(message)));
  167. });
  168. test('auto-run stops restarting once add-phone is detected', async () => {
  169. const harness = createHarness({
  170. failureStep: 7,
  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, [7]);
  179. assert.ok(result.events.logs.some(({ message }) => /进入 add-phone/.test(message)));
  180. });
  181. test('auto-run stops restarting on generic phone-page failure messages even without add-phone url', async () => {
  182. const harness = createHarness({
  183. failureStep: 9,
  184. failureBudget: 1,
  185. failureMessage: '步骤 8:当前认证页进入手机号页面,当前流程无法继续自动授权。',
  186. authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  187. });
  188. const result = await harness.runAndCaptureError();
  189. assert.ok(result?.error);
  190. assert.equal(result.events.invalidations.length, 0);
  191. assert.deepStrictEqual(result.events.steps, [7, 8, 9]);
  192. assert.ok(!result.events.logs.some(({ message }) => /回到步骤 7 重新开始授权流程/.test(message)));
  193. });
  194. test('auto-run stop errors after step 7 are rethrown immediately instead of restarting', async () => {
  195. const harness = createHarness({
  196. failureStep: 9,
  197. failureBudget: 1,
  198. failureMessage: '流程已被用户停止。',
  199. authState: { state: 'password_page', url: 'https://auth.openai.com/log-in' },
  200. });
  201. const result = await harness.runAndCaptureError();
  202. assert.equal(result?.error?.message, '流程已被用户停止。');
  203. assert.equal(result.events.invalidations.length, 0);
  204. assert.deepStrictEqual(result.events.steps, [7, 8, 9]);
  205. assert.ok(!result.events.logs.some(({ message }) => /回到步骤 7 重新开始授权流程/.test(message)));
  206. });