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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. const assert = require('assert');
  2. const fs = require('fs');
  3. const helperSource = fs.readFileSync('background.js', 'utf8');
  4. const autoRunModuleSource = fs.readFileSync('background/auto-run-controller.js', 'utf8');
  5. function extractFunction(source, 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 helperBundle = [
  49. extractFunction(helperSource, 'clearStopRequest'),
  50. extractFunction(helperSource, 'throwIfStopped'),
  51. extractFunction(helperSource, 'isStopError'),
  52. extractFunction(helperSource, 'isStepDoneStatus'),
  53. extractFunction(helperSource, 'isRestartCurrentAttemptError'),
  54. extractFunction(helperSource, 'getFirstUnfinishedStep'),
  55. extractFunction(helperSource, 'hasSavedProgress'),
  56. extractFunction(helperSource, 'getRunningSteps'),
  57. extractFunction(helperSource, 'getAutoRunStatusPayload'),
  58. ].join('\n');
  59. const api = new Function('autoRunModuleSource', `
  60. const self = {};
  61. const STOP_ERROR_MESSAGE = 'Flow stopped.';
  62. const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
  63. const AUTO_RUN_RETRY_DELAY_MS = 3000;
  64. const AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS = 'between_rounds';
  65. const AUTO_RUN_TIMER_KIND_BEFORE_RETRY = 'before_retry';
  66. const DEFAULT_STATE = {
  67. stepStatuses: {
  68. 1: 'pending',
  69. 2: 'pending',
  70. 3: 'pending',
  71. 4: 'pending',
  72. 5: 'pending',
  73. 6: 'pending',
  74. 7: 'pending',
  75. 8: 'pending',
  76. 9: 'pending',
  77. },
  78. };
  79. let stopRequested = false;
  80. let runCalls = 0;
  81. const logs = [];
  82. const broadcasts = [];
  83. let currentState = {
  84. ...DEFAULT_STATE,
  85. stepStatuses: { ...DEFAULT_STATE.stepStatuses },
  86. vpsUrl: 'https://example.com/vps',
  87. vpsPassword: 'secret',
  88. customPassword: '',
  89. autoRunSkipFailures: false,
  90. autoRunFallbackThreadIntervalMinutes: 0,
  91. autoRunDelayEnabled: false,
  92. autoRunDelayMinutes: 30,
  93. autoStepDelaySeconds: null,
  94. mailProvider: '163',
  95. emailGenerator: 'duck',
  96. gmailBaseEmail: 'demo@gmail.com',
  97. mail2925BaseEmail: 'demo@2925.com',
  98. emailPrefix: 'demo',
  99. inbucketHost: '',
  100. inbucketMailbox: '',
  101. cloudflareDomain: '',
  102. cloudflareDomains: [],
  103. tabRegistry: {},
  104. sourceLastUrls: {},
  105. };
  106. async function getState() {
  107. return {
  108. ...currentState,
  109. stepStatuses: { ...(currentState.stepStatuses || {}) },
  110. tabRegistry: { ...(currentState.tabRegistry || {}) },
  111. sourceLastUrls: { ...(currentState.sourceLastUrls || {}) },
  112. };
  113. }
  114. async function setState(updates) {
  115. currentState = {
  116. ...currentState,
  117. ...updates,
  118. stepStatuses: updates.stepStatuses
  119. ? { ...updates.stepStatuses }
  120. : currentState.stepStatuses,
  121. tabRegistry: updates.tabRegistry
  122. ? { ...updates.tabRegistry }
  123. : currentState.tabRegistry,
  124. sourceLastUrls: updates.sourceLastUrls
  125. ? { ...updates.sourceLastUrls }
  126. : currentState.sourceLastUrls,
  127. };
  128. }
  129. async function resetState() {
  130. const prev = await getState();
  131. currentState = {
  132. ...DEFAULT_STATE,
  133. stepStatuses: { ...DEFAULT_STATE.stepStatuses },
  134. vpsUrl: prev.vpsUrl,
  135. vpsPassword: prev.vpsPassword,
  136. customPassword: prev.customPassword,
  137. autoRunSkipFailures: prev.autoRunSkipFailures,
  138. autoRunFallbackThreadIntervalMinutes: prev.autoRunFallbackThreadIntervalMinutes,
  139. autoRunDelayEnabled: prev.autoRunDelayEnabled,
  140. autoRunDelayMinutes: prev.autoRunDelayMinutes,
  141. autoStepDelaySeconds: prev.autoStepDelaySeconds,
  142. mailProvider: prev.mailProvider,
  143. emailGenerator: prev.emailGenerator,
  144. gmailBaseEmail: prev.gmailBaseEmail,
  145. mail2925BaseEmail: prev.mail2925BaseEmail,
  146. emailPrefix: prev.emailPrefix,
  147. inbucketHost: prev.inbucketHost,
  148. inbucketMailbox: prev.inbucketMailbox,
  149. cloudflareDomain: prev.cloudflareDomain,
  150. cloudflareDomains: [...(prev.cloudflareDomains || [])],
  151. tabRegistry: { ...(prev.tabRegistry || {}) },
  152. sourceLastUrls: { ...(prev.sourceLastUrls || {}) },
  153. };
  154. }
  155. async function addLog(message, level = 'info') {
  156. logs.push({ message, level });
  157. }
  158. async function broadcastAutoRunStatus(phase, payload = {}) {
  159. broadcasts.push({ phase, ...payload });
  160. await setState({
  161. ...getAutoRunStatusPayload(phase, payload),
  162. });
  163. }
  164. async function sleepWithStop() {}
  165. async function waitForRunningStepsToFinish() {
  166. return getState();
  167. }
  168. async function broadcastStopToContentScripts() {}
  169. function cancelPendingCommands() {}
  170. function normalizeAutoRunFallbackThreadIntervalMinutes(value) {
  171. return Math.max(0, Math.floor(Number(value) || 0));
  172. }
  173. async function persistAutoRunTimerPlan() {}
  174. async function launchAutoRunTimerPlan() { return false; }
  175. function getPendingAutoRunTimerPlan() { return null; }
  176. function getErrorMessage(error) { return error?.message || String(error || ''); }
  177. const chrome = {
  178. runtime: {
  179. sendMessage() {
  180. return Promise.resolve();
  181. },
  182. },
  183. };
  184. async function runAutoSequenceFromStep() {
  185. runCalls += 1;
  186. const state = await getState();
  187. if (
  188. runCalls === 2
  189. && (Object.keys(state.tabRegistry || {}).length || Object.keys(state.sourceLastUrls || {}).length)
  190. ) {
  191. throw new Error('fresh auto-run attempt reused stale runtime tab context');
  192. }
  193. currentState = {
  194. ...currentState,
  195. stepStatuses: {
  196. 1: 'completed',
  197. 2: 'completed',
  198. 3: 'completed',
  199. 4: 'completed',
  200. 5: 'completed',
  201. 6: 'completed',
  202. 7: 'completed',
  203. 8: 'completed',
  204. 9: 'completed',
  205. },
  206. tabRegistry: {
  207. 'signup-page': { tabId: 88, ready: true },
  208. },
  209. sourceLastUrls: {
  210. 'signup-page': 'https://auth.openai.com/authorize',
  211. },
  212. };
  213. }
  214. ${helperBundle}
  215. ${autoRunModuleSource}
  216. const runtime = {
  217. state: {
  218. autoRunActive: false,
  219. autoRunCurrentRun: 0,
  220. autoRunTotalRuns: 1,
  221. autoRunAttemptRun: 0,
  222. },
  223. get() {
  224. return { ...this.state };
  225. },
  226. set(updates = {}) {
  227. this.state = { ...this.state, ...updates };
  228. },
  229. };
  230. const controller = self.MultiPageBackgroundAutoRunController.createAutoRunController({
  231. addLog,
  232. AUTO_RUN_MAX_RETRIES_PER_ROUND,
  233. AUTO_RUN_RETRY_DELAY_MS,
  234. AUTO_RUN_TIMER_KIND_BEFORE_RETRY,
  235. AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS,
  236. broadcastAutoRunStatus,
  237. broadcastStopToContentScripts,
  238. cancelPendingCommands,
  239. clearStopRequest,
  240. getAutoRunStatusPayload,
  241. getErrorMessage,
  242. getFirstUnfinishedStep,
  243. getPendingAutoRunTimerPlan,
  244. getRunningSteps,
  245. getState,
  246. getStopRequested: () => stopRequested,
  247. hasSavedProgress,
  248. isRestartCurrentAttemptError,
  249. isStopError,
  250. launchAutoRunTimerPlan,
  251. normalizeAutoRunFallbackThreadIntervalMinutes,
  252. persistAutoRunTimerPlan,
  253. resetState,
  254. runAutoSequenceFromStep,
  255. runtime,
  256. setState,
  257. sleepWithStop,
  258. waitForRunningStepsToFinish,
  259. throwIfStopped,
  260. chrome,
  261. });
  262. return {
  263. autoRunLoop: controller.autoRunLoop,
  264. snapshot() {
  265. return {
  266. runCalls,
  267. autoRunActive: runtime.state.autoRunActive,
  268. autoRunCurrentRun: runtime.state.autoRunCurrentRun,
  269. autoRunTotalRuns: runtime.state.autoRunTotalRuns,
  270. autoRunAttemptRun: runtime.state.autoRunAttemptRun,
  271. currentState,
  272. logs,
  273. broadcasts,
  274. };
  275. },
  276. };
  277. `)(autoRunModuleSource);
  278. (async () => {
  279. await api.autoRunLoop(2, { autoRunSkipFailures: false, mode: 'restart' });
  280. const snapshot = api.snapshot();
  281. assert.strictEqual(snapshot.runCalls, 2, 'auto-run should enter the second fresh attempt');
  282. assert.strictEqual(snapshot.currentState.autoRunPhase, 'complete', 'both runs should complete after reset');
  283. assert.strictEqual(snapshot.currentState.autoRunCurrentRun, 2, 'final run index should be recorded');
  284. assert.strictEqual(snapshot.autoRunActive, false, 'auto-run should exit active state after completion');
  285. assert.strictEqual(snapshot.currentState.gmailBaseEmail, 'demo@gmail.com', 'gmail base email should survive fresh-attempt reset');
  286. assert.strictEqual(snapshot.currentState.mail2925BaseEmail, 'demo@2925.com', '2925 base email should survive fresh-attempt reset');
  287. console.log('auto-run fresh attempt reset tests passed');
  288. })().catch((error) => {
  289. console.error(error);
  290. process.exit(1);
  291. });