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

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