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

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