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

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