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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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('waitBetweenAutoRunRounds'),
  65. extractFunction('autoRunLoop'),
  66. ].join('\n');
  67. const api = new Function(`
  68. const STOP_ERROR_MESSAGE = 'Flow stopped.';
  69. const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
  70. const DEFAULT_STATE = {
  71. stepStatuses: {
  72. 1: 'pending',
  73. 2: 'pending',
  74. 3: 'pending',
  75. 4: 'pending',
  76. 5: 'pending',
  77. 6: 'pending',
  78. 7: 'pending',
  79. 8: 'pending',
  80. 9: 'pending',
  81. },
  82. };
  83. let stopRequested = false;
  84. let autoRunActive = false;
  85. let autoRunCurrentRun = 0;
  86. let autoRunTotalRuns = 1;
  87. let autoRunAttemptRun = 0;
  88. let runCalls = 0;
  89. const logs = [];
  90. const broadcasts = [];
  91. let currentState = {
  92. ...DEFAULT_STATE,
  93. stepStatuses: { ...DEFAULT_STATE.stepStatuses },
  94. vpsUrl: 'https://example.com/vps',
  95. vpsPassword: 'secret',
  96. customPassword: '',
  97. autoRunSkipFailures: false,
  98. autoRunFallbackThreadIntervalMinutes: 0,
  99. autoRunDelayEnabled: false,
  100. autoRunDelayMinutes: 30,
  101. autoStepDelaySeconds: null,
  102. mailProvider: '163',
  103. emailGenerator: 'duck',
  104. emailPrefix: 'demo',
  105. inbucketHost: '',
  106. inbucketMailbox: '',
  107. cloudflareDomain: '',
  108. cloudflareDomains: [],
  109. tabRegistry: {},
  110. sourceLastUrls: {},
  111. };
  112. async function getState() {
  113. return {
  114. ...currentState,
  115. stepStatuses: { ...(currentState.stepStatuses || {}) },
  116. tabRegistry: { ...(currentState.tabRegistry || {}) },
  117. sourceLastUrls: { ...(currentState.sourceLastUrls || {}) },
  118. };
  119. }
  120. async function setState(updates) {
  121. currentState = {
  122. ...currentState,
  123. ...updates,
  124. stepStatuses: updates.stepStatuses
  125. ? { ...updates.stepStatuses }
  126. : currentState.stepStatuses,
  127. tabRegistry: updates.tabRegistry
  128. ? { ...updates.tabRegistry }
  129. : currentState.tabRegistry,
  130. sourceLastUrls: updates.sourceLastUrls
  131. ? { ...updates.sourceLastUrls }
  132. : currentState.sourceLastUrls,
  133. };
  134. }
  135. async function resetState() {
  136. const prev = await getState();
  137. currentState = {
  138. ...DEFAULT_STATE,
  139. stepStatuses: { ...DEFAULT_STATE.stepStatuses },
  140. vpsUrl: prev.vpsUrl,
  141. vpsPassword: prev.vpsPassword,
  142. customPassword: prev.customPassword,
  143. autoRunSkipFailures: prev.autoRunSkipFailures,
  144. autoRunFallbackThreadIntervalMinutes: prev.autoRunFallbackThreadIntervalMinutes,
  145. autoRunDelayEnabled: prev.autoRunDelayEnabled,
  146. autoRunDelayMinutes: prev.autoRunDelayMinutes,
  147. autoStepDelaySeconds: prev.autoStepDelaySeconds,
  148. mailProvider: prev.mailProvider,
  149. emailGenerator: prev.emailGenerator,
  150. emailPrefix: prev.emailPrefix,
  151. inbucketHost: prev.inbucketHost,
  152. inbucketMailbox: prev.inbucketMailbox,
  153. cloudflareDomain: prev.cloudflareDomain,
  154. cloudflareDomains: [...(prev.cloudflareDomains || [])],
  155. tabRegistry: { ...(prev.tabRegistry || {}) },
  156. sourceLastUrls: { ...(prev.sourceLastUrls || {}) },
  157. };
  158. }
  159. async function addLog(message, level = 'info') {
  160. logs.push({ message, level });
  161. }
  162. async function broadcastAutoRunStatus(phase, payload = {}) {
  163. broadcasts.push({ phase, ...payload });
  164. await setState({
  165. ...getAutoRunStatusPayload(phase, payload),
  166. });
  167. }
  168. async function sleepWithStop() {}
  169. async function waitForRunningStepsToFinish() {
  170. return getState();
  171. }
  172. async function broadcastStopToContentScripts() {}
  173. function cancelPendingCommands() {}
  174. function normalizeAutoRunFallbackThreadIntervalMinutes(value) {
  175. return Math.max(0, Math.floor(Number(value) || 0));
  176. }
  177. function buildAutoRunRoundSummaries(totalRuns, rawSummaries = []) {
  178. return Array.from({ length: totalRuns }, (_, index) => ({
  179. round: index + 1,
  180. status: rawSummaries[index]?.status || 'pending',
  181. attempts: rawSummaries[index]?.attempts || 0,
  182. failureReasons: [...(rawSummaries[index]?.failureReasons || [])],
  183. finalFailureReason: rawSummaries[index]?.finalFailureReason || '',
  184. }));
  185. }
  186. function serializeAutoRunRoundSummaries(totalRuns, roundSummaries = []) {
  187. return buildAutoRunRoundSummaries(totalRuns, roundSummaries);
  188. }
  189. async function logAutoRunFinalSummary() {}
  190. async function waitBetweenAutoRunRounds() {}
  191. const chrome = {
  192. runtime: {
  193. sendMessage() {
  194. return Promise.resolve();
  195. },
  196. },
  197. };
  198. async function runAutoSequenceFromStep() {
  199. runCalls += 1;
  200. const state = await getState();
  201. if (
  202. runCalls === 2
  203. && (Object.keys(state.tabRegistry || {}).length || Object.keys(state.sourceLastUrls || {}).length)
  204. ) {
  205. throw new Error('fresh auto-run attempt reused stale runtime tab context');
  206. }
  207. currentState = {
  208. ...currentState,
  209. stepStatuses: {
  210. 1: 'completed',
  211. 2: 'completed',
  212. 3: 'completed',
  213. 4: 'completed',
  214. 5: 'completed',
  215. 6: 'completed',
  216. 7: 'completed',
  217. 8: 'completed',
  218. 9: 'completed',
  219. },
  220. tabRegistry: {
  221. 'signup-page': { tabId: 88, ready: true },
  222. },
  223. sourceLastUrls: {
  224. 'signup-page': 'https://auth.openai.com/authorize',
  225. },
  226. };
  227. }
  228. ${bundle}
  229. return {
  230. autoRunLoop,
  231. snapshot() {
  232. return {
  233. runCalls,
  234. autoRunActive,
  235. autoRunCurrentRun,
  236. autoRunTotalRuns,
  237. autoRunAttemptRun,
  238. currentState,
  239. logs,
  240. broadcasts,
  241. };
  242. },
  243. };
  244. `)();
  245. (async () => {
  246. await api.autoRunLoop(2, { autoRunSkipFailures: false, mode: 'restart' });
  247. const snapshot = api.snapshot();
  248. assert.strictEqual(snapshot.runCalls, 2, 'auto-run should enter the second fresh attempt');
  249. assert.strictEqual(snapshot.currentState.autoRunPhase, 'complete', 'both runs should complete after reset');
  250. assert.strictEqual(snapshot.currentState.autoRunCurrentRun, 2, 'final run index should be recorded');
  251. assert.strictEqual(snapshot.autoRunActive, false, 'auto-run should exit active state after completion');
  252. console.log('auto-run fresh attempt reset tests passed');
  253. })().catch((error) => {
  254. console.error(error);
  255. process.exit(1);
  256. });