auto-run-fresh-attempt-reset.test.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. const assert = require('assert');
  2. const fs = require('fs');
  3. const source = fs.readFileSync('background.js', 'utf8');
  4. function extractFunction(name) {
  5. const markers = [`async function ${name}(`, `function ${name}(`];
  6. const start = markers
  7. .map(marker => source.indexOf(marker))
  8. .find(index => index >= 0);
  9. if (start < 0) {
  10. throw new Error(`missing function ${name}`);
  11. }
  12. let parenDepth = 0;
  13. let signatureEnded = false;
  14. let braceStart = -1;
  15. for (let i = start; i < source.length; i += 1) {
  16. const ch = source[i];
  17. if (ch === '(') {
  18. parenDepth += 1;
  19. } else if (ch === ')') {
  20. parenDepth -= 1;
  21. if (parenDepth === 0) {
  22. signatureEnded = true;
  23. }
  24. } else if (ch === '{' && signatureEnded) {
  25. braceStart = i;
  26. break;
  27. }
  28. }
  29. if (braceStart < 0) {
  30. throw new Error(`missing body for function ${name}`);
  31. }
  32. let depth = 0;
  33. let end = braceStart;
  34. for (; end < source.length; end += 1) {
  35. const ch = source[end];
  36. if (ch === '{') depth += 1;
  37. if (ch === '}') {
  38. depth -= 1;
  39. if (depth === 0) {
  40. end += 1;
  41. break;
  42. }
  43. }
  44. }
  45. return source.slice(start, end);
  46. }
  47. const bundle = [
  48. extractFunction('clearStopRequest'),
  49. extractFunction('throwIfStopped'),
  50. extractFunction('isStopError'),
  51. extractFunction('isStepDoneStatus'),
  52. extractFunction('isRestartCurrentAttemptError'),
  53. extractFunction('getFirstUnfinishedStep'),
  54. extractFunction('hasSavedProgress'),
  55. extractFunction('getRunningSteps'),
  56. extractFunction('getAutoRunStatusPayload'),
  57. extractFunction('createAutoRunRoundSummary'),
  58. extractFunction('normalizeAutoRunRoundSummary'),
  59. extractFunction('buildAutoRunRoundSummaries'),
  60. extractFunction('serializeAutoRunRoundSummaries'),
  61. extractFunction('getAutoRunRoundRetryCount'),
  62. extractFunction('formatAutoRunFailureReasons'),
  63. extractFunction('logAutoRunFinalSummary'),
  64. extractFunction('autoRunLoop'),
  65. ].join('\n');
  66. const api = new Function(`
  67. const STOP_ERROR_MESSAGE = 'Flow stopped.';
  68. const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
  69. const DEFAULT_STATE = {
  70. stepStatuses: {
  71. 1: 'pending',
  72. 2: 'pending',
  73. 3: 'pending',
  74. 4: 'pending',
  75. 5: 'pending',
  76. 6: 'pending',
  77. 7: 'pending',
  78. 8: 'pending',
  79. 9: 'pending',
  80. },
  81. };
  82. let stopRequested = false;
  83. let autoRunActive = false;
  84. let autoRunCurrentRun = 0;
  85. let autoRunTotalRuns = 1;
  86. let autoRunAttemptRun = 0;
  87. let runCalls = 0;
  88. const logs = [];
  89. const broadcasts = [];
  90. let currentState = {
  91. ...DEFAULT_STATE,
  92. stepStatuses: { ...DEFAULT_STATE.stepStatuses },
  93. vpsUrl: 'https://example.com/vps',
  94. vpsPassword: 'secret',
  95. customPassword: '',
  96. autoRunSkipFailures: false,
  97. autoRunFallbackThreadIntervalMinutes: 0,
  98. autoRunDelayEnabled: false,
  99. autoRunDelayMinutes: 30,
  100. autoStepDelaySeconds: null,
  101. mailProvider: '163',
  102. emailGenerator: 'duck',
  103. emailPrefix: 'demo',
  104. inbucketHost: '',
  105. inbucketMailbox: '',
  106. cloudflareDomain: '',
  107. cloudflareDomains: [],
  108. tabRegistry: {},
  109. sourceLastUrls: {},
  110. };
  111. async function getState() {
  112. return {
  113. ...currentState,
  114. stepStatuses: { ...(currentState.stepStatuses || {}) },
  115. tabRegistry: { ...(currentState.tabRegistry || {}) },
  116. sourceLastUrls: { ...(currentState.sourceLastUrls || {}) },
  117. };
  118. }
  119. async function setState(updates) {
  120. currentState = {
  121. ...currentState,
  122. ...updates,
  123. stepStatuses: updates.stepStatuses
  124. ? { ...updates.stepStatuses }
  125. : currentState.stepStatuses,
  126. tabRegistry: updates.tabRegistry
  127. ? { ...updates.tabRegistry }
  128. : currentState.tabRegistry,
  129. sourceLastUrls: updates.sourceLastUrls
  130. ? { ...updates.sourceLastUrls }
  131. : currentState.sourceLastUrls,
  132. };
  133. }
  134. async function resetState() {
  135. const prev = await getState();
  136. currentState = {
  137. ...DEFAULT_STATE,
  138. stepStatuses: { ...DEFAULT_STATE.stepStatuses },
  139. vpsUrl: prev.vpsUrl,
  140. vpsPassword: prev.vpsPassword,
  141. customPassword: prev.customPassword,
  142. autoRunSkipFailures: prev.autoRunSkipFailures,
  143. autoRunFallbackThreadIntervalMinutes: prev.autoRunFallbackThreadIntervalMinutes,
  144. autoRunDelayEnabled: prev.autoRunDelayEnabled,
  145. autoRunDelayMinutes: prev.autoRunDelayMinutes,
  146. autoStepDelaySeconds: prev.autoStepDelaySeconds,
  147. mailProvider: prev.mailProvider,
  148. emailGenerator: prev.emailGenerator,
  149. emailPrefix: prev.emailPrefix,
  150. inbucketHost: prev.inbucketHost,
  151. inbucketMailbox: prev.inbucketMailbox,
  152. cloudflareDomain: prev.cloudflareDomain,
  153. cloudflareDomains: [...(prev.cloudflareDomains || [])],
  154. tabRegistry: { ...(prev.tabRegistry || {}) },
  155. sourceLastUrls: { ...(prev.sourceLastUrls || {}) },
  156. };
  157. }
  158. async function addLog(message, level = 'info') {
  159. logs.push({ message, level });
  160. }
  161. async function broadcastAutoRunStatus(phase, payload = {}) {
  162. broadcasts.push({ phase, ...payload });
  163. await setState({
  164. ...getAutoRunStatusPayload(phase, payload),
  165. });
  166. }
  167. async function sleepWithStop() {}
  168. async function waitForRunningStepsToFinish() {
  169. return getState();
  170. }
  171. async function broadcastStopToContentScripts() {}
  172. function cancelPendingCommands() {}
  173. function normalizeAutoRunFallbackThreadIntervalMinutes(value) {
  174. return Math.max(0, Math.floor(Number(value) || 0));
  175. }
  176. const chrome = {
  177. runtime: {
  178. sendMessage() {
  179. return Promise.resolve();
  180. },
  181. },
  182. };
  183. async function runAutoSequenceFromStep() {
  184. runCalls += 1;
  185. const state = await getState();
  186. if (
  187. runCalls === 2
  188. && (Object.keys(state.tabRegistry || {}).length || Object.keys(state.sourceLastUrls || {}).length)
  189. ) {
  190. throw new Error('fresh auto-run attempt reused stale runtime tab context');
  191. }
  192. currentState = {
  193. ...currentState,
  194. stepStatuses: {
  195. 1: 'completed',
  196. 2: 'completed',
  197. 3: 'completed',
  198. 4: 'completed',
  199. 5: 'completed',
  200. 6: 'completed',
  201. 7: 'completed',
  202. 8: 'completed',
  203. 9: 'completed',
  204. },
  205. tabRegistry: {
  206. 'signup-page': { tabId: 88, ready: true },
  207. },
  208. sourceLastUrls: {
  209. 'signup-page': 'https://auth.openai.com/authorize',
  210. },
  211. };
  212. }
  213. ${bundle}
  214. return {
  215. autoRunLoop,
  216. snapshot() {
  217. return {
  218. runCalls,
  219. autoRunActive,
  220. autoRunCurrentRun,
  221. autoRunTotalRuns,
  222. autoRunAttemptRun,
  223. currentState,
  224. logs,
  225. broadcasts,
  226. };
  227. },
  228. };
  229. `)();
  230. (async () => {
  231. await api.autoRunLoop(2, { autoRunSkipFailures: false, mode: 'restart' });
  232. const snapshot = api.snapshot();
  233. assert.strictEqual(snapshot.runCalls, 2, 'auto-run should enter the second fresh attempt');
  234. assert.strictEqual(snapshot.currentState.autoRunPhase, 'complete', 'both runs should complete after reset');
  235. assert.strictEqual(snapshot.currentState.autoRunCurrentRun, 2, 'final run index should be recorded');
  236. assert.strictEqual(snapshot.autoRunActive, false, 'auto-run should exit active state after completion');
  237. console.log('auto-run fresh attempt reset tests passed');
  238. })().catch((error) => {
  239. console.error(error);
  240. process.exit(1);
  241. });