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

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