auto-run-controller.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. (function attachBackgroundAutoRunController(root, factory) {
  2. root.MultiPageBackgroundAutoRunController = factory();
  3. })(typeof self !== 'undefined' ? self : globalThis, function createBackgroundAutoRunControllerModule() {
  4. function createAutoRunController(deps = {}) {
  5. const {
  6. addLog,
  7. appendAccountRunRecord,
  8. AUTO_RUN_MAX_RETRIES_PER_ROUND,
  9. AUTO_RUN_RETRY_DELAY_MS,
  10. AUTO_RUN_TIMER_KIND_BEFORE_RETRY,
  11. AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS,
  12. broadcastAutoRunStatus,
  13. broadcastStopToContentScripts,
  14. cancelPendingCommands,
  15. clearStopRequest,
  16. createAutoRunSessionId,
  17. getAutoRunStatusPayload,
  18. getErrorMessage,
  19. getFirstUnfinishedStep,
  20. getPendingAutoRunTimerPlan,
  21. getRunningSteps,
  22. getState,
  23. hasSavedProgress,
  24. isAddPhoneAuthFailure,
  25. isRestartCurrentAttemptError,
  26. isStopError,
  27. launchAutoRunTimerPlan,
  28. normalizeAutoRunFallbackThreadIntervalMinutes,
  29. persistAutoRunTimerPlan,
  30. resetState,
  31. runAutoSequenceFromStep,
  32. runtime,
  33. setState,
  34. sleepWithStop,
  35. throwIfAutoRunSessionStopped,
  36. waitForRunningStepsToFinish,
  37. } = deps;
  38. function createAutoRunRoundSummary(round) {
  39. return {
  40. round,
  41. status: 'pending',
  42. attempts: 0,
  43. failureReasons: [],
  44. finalFailureReason: '',
  45. };
  46. }
  47. function normalizeAutoRunRoundSummary(summary, round) {
  48. const base = createAutoRunRoundSummary(round);
  49. if (!summary || typeof summary !== 'object') {
  50. return base;
  51. }
  52. const status = String(summary.status || '').trim().toLowerCase();
  53. return {
  54. round,
  55. status: ['pending', 'success', 'failed'].includes(status) ? status : base.status,
  56. attempts: Math.max(0, Math.floor(Number(summary.attempts) || 0)),
  57. failureReasons: Array.isArray(summary.failureReasons)
  58. ? summary.failureReasons.map((item) => String(item || '').trim()).filter(Boolean)
  59. : [],
  60. finalFailureReason: String(summary.finalFailureReason || '').trim(),
  61. };
  62. }
  63. function buildAutoRunRoundSummaries(totalRuns, rawSummaries = []) {
  64. return Array.from({ length: totalRuns }, (_, index) => normalizeAutoRunRoundSummary(rawSummaries[index], index + 1));
  65. }
  66. function serializeAutoRunRoundSummaries(totalRuns, roundSummaries = []) {
  67. return buildAutoRunRoundSummaries(totalRuns, roundSummaries).map((summary) => ({
  68. ...summary,
  69. failureReasons: [...summary.failureReasons],
  70. }));
  71. }
  72. function getAutoRunRoundRetryCount(summary) {
  73. return Math.max(0, Number(summary?.attempts || 0) - 1);
  74. }
  75. function formatAutoRunFailureReasons(reasons = []) {
  76. if (!Array.isArray(reasons) || !reasons.length) {
  77. return '未知错误';
  78. }
  79. const counts = new Map();
  80. for (const reason of reasons) {
  81. const normalized = String(reason || '').trim() || '未知错误';
  82. counts.set(normalized, (counts.get(normalized) || 0) + 1);
  83. }
  84. return Array.from(counts.entries())
  85. .map(([reason, count]) => (count > 1 ? `${reason}(${count}次)` : reason))
  86. .join(';');
  87. }
  88. async function logAutoRunFinalSummary(totalRuns, roundSummaries = []) {
  89. const summaries = buildAutoRunRoundSummaries(totalRuns, roundSummaries);
  90. const successRounds = summaries.filter((item) => item.status === 'success');
  91. const failedRounds = summaries.filter((item) => item.status === 'failed');
  92. const pendingRounds = summaries.filter((item) => item.status === 'pending');
  93. await addLog('=== 自动运行汇总 ===', failedRounds.length ? 'warn' : 'ok');
  94. await addLog(
  95. `总轮数:${totalRuns};成功:${successRounds.length};失败:${failedRounds.length};未完成:${pendingRounds.length}`,
  96. failedRounds.length ? 'warn' : 'ok'
  97. );
  98. if (successRounds.length) {
  99. await addLog(
  100. `成功轮次:${successRounds
  101. .map((item) => `第 ${item.round} 轮(重试 ${getAutoRunRoundRetryCount(item)} 次)`)
  102. .join(';')}`,
  103. 'ok'
  104. );
  105. }
  106. if (failedRounds.length) {
  107. await addLog(
  108. `失败轮次:${failedRounds
  109. .map((item) => {
  110. const retryCount = getAutoRunRoundRetryCount(item);
  111. const finalReason = item.finalFailureReason || item.failureReasons[item.failureReasons.length - 1] || '未知错误';
  112. const reasonSummary = formatAutoRunFailureReasons(item.failureReasons);
  113. return `第 ${item.round} 轮(重试 ${retryCount} 次,最终原因:${finalReason};失败记录:${reasonSummary})`;
  114. })
  115. .join(';')}`,
  116. 'error'
  117. );
  118. }
  119. if (pendingRounds.length) {
  120. await addLog(
  121. `未完成轮次:${pendingRounds.map((item) => `第 ${item.round} 轮`).join(';')}`,
  122. 'warn'
  123. );
  124. }
  125. }
  126. async function skipAutoRunCountdown() {
  127. const state = await getState();
  128. const plan = getPendingAutoRunTimerPlan(state);
  129. if (!plan || state.autoRunPhase !== 'waiting_interval') {
  130. return false;
  131. }
  132. return launchAutoRunTimerPlan('manual', {
  133. expectedKinds: [
  134. AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS,
  135. AUTO_RUN_TIMER_KIND_BEFORE_RETRY,
  136. ],
  137. });
  138. }
  139. async function waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary, options = {}) {
  140. const { autoRunSkipFailures = false, roundSummaries = [] } = options;
  141. if (totalRuns <= 1 || targetRun >= totalRuns) {
  142. return false;
  143. }
  144. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  145. (await getState()).autoRunFallbackThreadIntervalMinutes
  146. );
  147. if (fallbackThreadIntervalMinutes <= 0) {
  148. return false;
  149. }
  150. const currentRuntime = runtime.get();
  151. const statusLabel = roundSummary?.status === 'failed' ? '失败' : '完成';
  152. await addLog(
  153. `线程间隔:第 ${targetRun}/${totalRuns} 轮已${statusLabel},等待 ${fallbackThreadIntervalMinutes} 分钟后开始下一轮。`,
  154. 'info'
  155. );
  156. await persistAutoRunTimerPlan({
  157. kind: AUTO_RUN_TIMER_KIND_BETWEEN_ROUNDS,
  158. fireAt: Date.now() + fallbackThreadIntervalMinutes * 60 * 1000,
  159. currentRun: targetRun,
  160. totalRuns,
  161. attemptRun: currentRuntime.autoRunAttemptRun,
  162. autoRunSessionId: currentRuntime.autoRunSessionId,
  163. autoRunSkipFailures,
  164. roundSummaries,
  165. countdownTitle: '线程间隔中',
  166. countdownNote: `第 ${Math.min(targetRun + 1, totalRuns)}/${totalRuns} 轮即将开始`,
  167. }, {
  168. autoRunSkipFailures,
  169. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  170. });
  171. runtime.set({ autoRunActive: false });
  172. return true;
  173. }
  174. async function waitBeforeAutoRunRetry(targetRun, totalRuns, nextAttemptRun, options = {}) {
  175. const { autoRunSkipFailures = false, roundSummaries = [] } = options;
  176. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  177. (await getState()).autoRunFallbackThreadIntervalMinutes
  178. );
  179. if (fallbackThreadIntervalMinutes <= 0) {
  180. return false;
  181. }
  182. await addLog(
  183. `线程间隔:等待 ${fallbackThreadIntervalMinutes} 分钟后开始第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试。`,
  184. 'info'
  185. );
  186. await persistAutoRunTimerPlan({
  187. kind: AUTO_RUN_TIMER_KIND_BEFORE_RETRY,
  188. fireAt: Date.now() + fallbackThreadIntervalMinutes * 60 * 1000,
  189. currentRun: targetRun,
  190. totalRuns,
  191. attemptRun: nextAttemptRun,
  192. autoRunSessionId: runtime.get().autoRunSessionId,
  193. autoRunSkipFailures,
  194. roundSummaries,
  195. countdownTitle: '线程间隔中',
  196. countdownNote: `第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试即将开始`,
  197. }, {
  198. autoRunSkipFailures,
  199. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  200. });
  201. runtime.set({ autoRunActive: false });
  202. return true;
  203. }
  204. async function handleAutoRunLoopUnhandledError(error) {
  205. const currentRuntime = runtime.get();
  206. console.error('Auto run loop crashed:', error);
  207. if (!isStopError(error)) {
  208. await addLog(`自动运行异常终止:${getErrorMessage(error) || '未知错误'}`, 'error');
  209. }
  210. runtime.set({ autoRunActive: false, autoRunSessionId: 0 });
  211. await broadcastAutoRunStatus('stopped', {
  212. currentRun: currentRuntime.autoRunCurrentRun,
  213. totalRuns: currentRuntime.autoRunTotalRuns,
  214. attemptRun: currentRuntime.autoRunAttemptRun,
  215. sessionId: 0,
  216. }, {
  217. autoRunSessionId: 0,
  218. autoRunTimerPlan: null,
  219. scheduledAutoRunPlan: null,
  220. });
  221. clearStopRequest();
  222. }
  223. function startAutoRunLoop(totalRuns, options = {}) {
  224. autoRunLoop(totalRuns, options).catch((error) => {
  225. handleAutoRunLoopUnhandledError(error).catch(() => {});
  226. });
  227. }
  228. async function autoRunLoop(totalRuns, options = {}) {
  229. let currentRuntime = runtime.get();
  230. if (currentRuntime.autoRunActive) {
  231. await addLog('自动运行已在进行中', 'warn');
  232. return;
  233. }
  234. let sessionId = Number.isInteger(options.autoRunSessionId) && options.autoRunSessionId > 0
  235. ? options.autoRunSessionId
  236. : 0;
  237. if (sessionId) {
  238. throwIfAutoRunSessionStopped(sessionId);
  239. } else {
  240. sessionId = createAutoRunSessionId();
  241. }
  242. clearStopRequest();
  243. runtime.set({
  244. autoRunActive: true,
  245. autoRunTotalRuns: totalRuns,
  246. autoRunCurrentRun: 0,
  247. autoRunAttemptRun: 0,
  248. autoRunSessionId: sessionId,
  249. });
  250. currentRuntime = runtime.get();
  251. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  252. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  253. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) && options.resumeCurrentRun > 0
  254. ? Math.min(totalRuns, options.resumeCurrentRun)
  255. : 1;
  256. const resumeAttemptRun = Number.isInteger(options.resumeAttemptRun) && options.resumeAttemptRun > 0
  257. ? Math.min(AUTO_RUN_MAX_RETRIES_PER_ROUND + 1, options.resumeAttemptRun)
  258. : 1;
  259. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  260. let forceFreshTabsNextRun = false;
  261. let stoppedEarly = false;
  262. let parkedByTimer = false;
  263. const roundSummaries = buildAutoRunRoundSummaries(totalRuns, options.resumeRoundSummaries);
  264. if (continueCurrentOnFirstAttempt && resumeCurrentRun > 1) {
  265. for (let round = 1; round < resumeCurrentRun; round += 1) {
  266. const summary = roundSummaries[round - 1];
  267. if (summary.status === 'pending') {
  268. summary.status = 'success';
  269. if (!summary.attempts) {
  270. summary.attempts = 1;
  271. }
  272. }
  273. }
  274. }
  275. let successfulRuns = roundSummaries.filter((item) => item.status === 'success').length;
  276. const initialState = await getState();
  277. const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses).length
  278. ? 'waiting_step'
  279. : 'running';
  280. const showResumePosition = continueCurrentOnFirstAttempt || resumeCurrentRun > 1 || resumeAttemptRun > 1;
  281. await setState({
  282. autoRunSessionId: sessionId,
  283. autoRunSkipFailures,
  284. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  285. ...getAutoRunStatusPayload(initialPhase, {
  286. currentRun: showResumePosition ? resumeCurrentRun : 0,
  287. totalRuns,
  288. attemptRun: showResumePosition ? resumeAttemptRun : 0,
  289. sessionId,
  290. }),
  291. });
  292. for (let targetRun = resumeCurrentRun; targetRun <= totalRuns; targetRun += 1) {
  293. const roundSummary = roundSummaries[targetRun - 1];
  294. let roundRecordAppended = false;
  295. const resumingCurrentRound = continueCurrentOnFirstAttempt && targetRun === resumeCurrentRun;
  296. let attemptRun = resumingCurrentRound ? resumeAttemptRun : 1;
  297. let reuseExistingProgress = resumingCurrentRound;
  298. const maxAttemptsForRound = autoRunSkipFailures
  299. ? AUTO_RUN_MAX_RETRIES_PER_ROUND + 1
  300. : Math.max(1, attemptRun);
  301. while (attemptRun <= maxAttemptsForRound) {
  302. runtime.set({
  303. autoRunCurrentRun: targetRun,
  304. autoRunAttemptRun: attemptRun,
  305. });
  306. roundSummary.attempts = attemptRun;
  307. let startStep = 1;
  308. let useExistingProgress = false;
  309. if (reuseExistingProgress) {
  310. let currentState = await getState();
  311. if (getRunningSteps(currentState.stepStatuses).length) {
  312. currentState = await waitForRunningStepsToFinish({
  313. currentRun: targetRun,
  314. totalRuns,
  315. attemptRun,
  316. });
  317. }
  318. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  319. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  320. startStep = resumeStep;
  321. useExistingProgress = true;
  322. } else if (hasSavedProgress(currentState.stepStatuses)) {
  323. await addLog('检测到当前流程已处理完成,本轮将改为从步骤 1 重新开始。', 'info');
  324. }
  325. }
  326. if (!useExistingProgress) {
  327. const prevState = await getState();
  328. const keepSettings = {
  329. vpsUrl: prevState.vpsUrl,
  330. vpsPassword: prevState.vpsPassword,
  331. customPassword: prevState.customPassword,
  332. autoRunSkipFailures: prevState.autoRunSkipFailures,
  333. autoRunFallbackThreadIntervalMinutes: prevState.autoRunFallbackThreadIntervalMinutes,
  334. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  335. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  336. autoStepDelaySeconds: prevState.autoStepDelaySeconds,
  337. mailProvider: prevState.mailProvider,
  338. emailGenerator: prevState.emailGenerator,
  339. gmailBaseEmail: prevState.gmailBaseEmail,
  340. mail2925BaseEmail: prevState.mail2925BaseEmail,
  341. emailPrefix: prevState.emailPrefix,
  342. inbucketHost: prevState.inbucketHost,
  343. inbucketMailbox: prevState.inbucketMailbox,
  344. cloudflareDomain: prevState.cloudflareDomain,
  345. cloudflareDomains: prevState.cloudflareDomains,
  346. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  347. autoRunSessionId: sessionId,
  348. tabRegistry: {},
  349. sourceLastUrls: {},
  350. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun, sessionId }),
  351. };
  352. await resetState();
  353. await setState(keepSettings);
  354. deps.chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  355. await sleepWithStop(500);
  356. } else {
  357. await setState({
  358. autoRunSessionId: sessionId,
  359. autoRunSkipFailures,
  360. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  361. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun, sessionId }),
  362. });
  363. }
  364. if (forceFreshTabsNextRun) {
  365. await addLog(`上一轮尝试已放弃,当前开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试。`, 'warn');
  366. forceFreshTabsNextRun = false;
  367. }
  368. const appendRoundRecordIfNeeded = async (status, reason = '') => {
  369. if (roundRecordAppended) {
  370. return;
  371. }
  372. if (typeof appendAccountRunRecord !== 'function') {
  373. return;
  374. }
  375. const record = await appendAccountRunRecord(status, null, reason);
  376. if (record) {
  377. roundRecordAppended = true;
  378. }
  379. };
  380. try {
  381. throwIfAutoRunSessionStopped(sessionId);
  382. await broadcastAutoRunStatus('running', {
  383. currentRun: targetRun,
  384. totalRuns,
  385. attemptRun,
  386. sessionId,
  387. });
  388. await runAutoSequenceFromStep(startStep, {
  389. targetRun,
  390. totalRuns,
  391. attemptRuns: attemptRun,
  392. continued: useExistingProgress,
  393. });
  394. roundSummary.status = 'success';
  395. roundSummary.finalFailureReason = '';
  396. successfulRuns += 1;
  397. await setState({
  398. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  399. });
  400. await addLog(`=== 第 ${targetRun}/${totalRuns} 轮完成(第 ${attemptRun} 次尝试成功)===`, 'ok');
  401. break;
  402. } catch (err) {
  403. if (isStopError(err)) {
  404. stoppedEarly = true;
  405. await appendRoundRecordIfNeeded('stopped', getErrorMessage(err));
  406. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  407. await broadcastAutoRunStatus('stopped', {
  408. currentRun: targetRun,
  409. totalRuns,
  410. attemptRun,
  411. sessionId: 0,
  412. });
  413. break;
  414. }
  415. const reason = getErrorMessage(err);
  416. roundSummary.failureReasons.push(reason);
  417. const blockedByAddPhone = typeof isAddPhoneAuthFailure === 'function' && isAddPhoneAuthFailure(err);
  418. const canRetry = !blockedByAddPhone && autoRunSkipFailures && attemptRun < maxAttemptsForRound;
  419. if (blockedByAddPhone) {
  420. roundSummary.status = 'failed';
  421. roundSummary.finalFailureReason = reason;
  422. }
  423. await setState({
  424. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  425. });
  426. if (blockedByAddPhone) {
  427. await appendRoundRecordIfNeeded('failed', reason);
  428. cancelPendingCommands('当前轮因认证流程进入 add-phone 已终止。');
  429. await broadcastStopToContentScripts();
  430. await addLog(
  431. `第 ${targetRun}/${totalRuns} 轮触发 add-phone/手机号页,当前自动运行将立即停止,不再重试或进入下一轮。`,
  432. 'warn'
  433. );
  434. stoppedEarly = true;
  435. await broadcastAutoRunStatus('stopped', {
  436. currentRun: targetRun,
  437. totalRuns,
  438. attemptRun,
  439. sessionId: 0,
  440. });
  441. break;
  442. }
  443. if (canRetry) {
  444. const retryIndex = attemptRun;
  445. if (isRestartCurrentAttemptError(err)) {
  446. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试需要整轮重开:${reason}`, 'warn');
  447. } else {
  448. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试失败:${reason}`, 'error');
  449. }
  450. cancelPendingCommands('当前尝试已放弃。');
  451. await broadcastStopToContentScripts();
  452. await broadcastAutoRunStatus('retrying', {
  453. currentRun: targetRun,
  454. totalRuns,
  455. attemptRun,
  456. sessionId,
  457. });
  458. forceFreshTabsNextRun = true;
  459. await addLog(
  460. `自动重试:${Math.round(AUTO_RUN_RETRY_DELAY_MS / 1000)} 秒后开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun + 1} 次尝试(第 ${retryIndex}/${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试)。`,
  461. 'warn'
  462. );
  463. try {
  464. await sleepWithStop(AUTO_RUN_RETRY_DELAY_MS);
  465. } catch (sleepError) {
  466. if (isStopError(sleepError)) {
  467. stoppedEarly = true;
  468. await appendRoundRecordIfNeeded('stopped', getErrorMessage(sleepError));
  469. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  470. await broadcastAutoRunStatus('stopped', {
  471. currentRun: targetRun,
  472. totalRuns,
  473. attemptRun,
  474. sessionId: 0,
  475. });
  476. break;
  477. }
  478. throw sleepError;
  479. }
  480. try {
  481. const parkedForRetry = await waitBeforeAutoRunRetry(targetRun, totalRuns, attemptRun + 1, {
  482. autoRunSkipFailures,
  483. roundSummaries,
  484. });
  485. if (parkedForRetry) {
  486. parkedByTimer = true;
  487. break;
  488. }
  489. } catch (sleepError) {
  490. if (isStopError(sleepError)) {
  491. stoppedEarly = true;
  492. await appendRoundRecordIfNeeded('stopped', getErrorMessage(sleepError));
  493. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  494. await broadcastAutoRunStatus('stopped', {
  495. currentRun: targetRun,
  496. totalRuns,
  497. attemptRun,
  498. sessionId: 0,
  499. });
  500. break;
  501. }
  502. throw sleepError;
  503. }
  504. attemptRun += 1;
  505. reuseExistingProgress = false;
  506. continue;
  507. }
  508. roundSummary.status = 'failed';
  509. roundSummary.finalFailureReason = reason;
  510. await setState({
  511. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  512. });
  513. await appendRoundRecordIfNeeded('failed', reason);
  514. if (!autoRunSkipFailures) {
  515. cancelPendingCommands('当前轮执行失败。');
  516. await broadcastStopToContentScripts();
  517. await addLog('自动重试未开启,自动运行将在当前失败后停止。', 'warn');
  518. stoppedEarly = true;
  519. await broadcastAutoRunStatus('stopped', {
  520. currentRun: targetRun,
  521. totalRuns,
  522. attemptRun,
  523. sessionId: 0,
  524. });
  525. break;
  526. }
  527. await addLog(`第 ${targetRun}/${totalRuns} 轮最终失败:${reason}`, 'error');
  528. await addLog(
  529. targetRun < totalRuns
  530. ? `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,继续下一轮。`
  531. : `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,本次自动运行结束。`,
  532. 'warn'
  533. );
  534. cancelPendingCommands('当前轮已达到重试上限。');
  535. await broadcastStopToContentScripts();
  536. forceFreshTabsNextRun = true;
  537. break;
  538. } finally {
  539. reuseExistingProgress = false;
  540. continueCurrentOnFirstAttempt = false;
  541. }
  542. }
  543. if (stoppedEarly || parkedByTimer) {
  544. break;
  545. }
  546. try {
  547. const parkedForNextRound = await waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary, {
  548. autoRunSkipFailures,
  549. roundSummaries,
  550. });
  551. if (parkedForNextRound) {
  552. parkedByTimer = true;
  553. break;
  554. }
  555. } catch (sleepError) {
  556. if (isStopError(sleepError)) {
  557. stoppedEarly = true;
  558. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  559. await broadcastAutoRunStatus('stopped', {
  560. currentRun: targetRun,
  561. totalRuns,
  562. attemptRun: runtime.get().autoRunAttemptRun,
  563. sessionId: 0,
  564. });
  565. break;
  566. }
  567. throw sleepError;
  568. }
  569. }
  570. if (parkedByTimer) {
  571. runtime.set({ autoRunActive: false });
  572. clearStopRequest();
  573. return;
  574. }
  575. await setState({
  576. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  577. });
  578. await logAutoRunFinalSummary(totalRuns, roundSummaries);
  579. const finalRuntime = runtime.get();
  580. if (deps.getStopRequested() || stoppedEarly) {
  581. await addLog(`=== 已停止,完成 ${successfulRuns}/${finalRuntime.autoRunTotalRuns} 轮 ===`, 'warn');
  582. await broadcastAutoRunStatus('stopped', {
  583. currentRun: finalRuntime.autoRunCurrentRun,
  584. totalRuns: finalRuntime.autoRunTotalRuns,
  585. attemptRun: finalRuntime.autoRunAttemptRun,
  586. sessionId: 0,
  587. });
  588. } else {
  589. await addLog(`=== 全部 ${finalRuntime.autoRunTotalRuns} 轮已执行完成,成功 ${successfulRuns} 轮 ===`, 'ok');
  590. await broadcastAutoRunStatus('complete', {
  591. currentRun: finalRuntime.autoRunTotalRuns,
  592. totalRuns: finalRuntime.autoRunTotalRuns,
  593. attemptRun: finalRuntime.autoRunAttemptRun,
  594. sessionId: 0,
  595. });
  596. }
  597. runtime.set({ autoRunActive: false, autoRunSessionId: 0 });
  598. const afterRuntime = runtime.get();
  599. await setState({
  600. autoRunSessionId: 0,
  601. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  602. autoRunTimerPlan: null,
  603. scheduledAutoRunPlan: null,
  604. ...getAutoRunStatusPayload(deps.getStopRequested() || stoppedEarly ? 'stopped' : 'complete', {
  605. currentRun: deps.getStopRequested() || stoppedEarly ? afterRuntime.autoRunCurrentRun : afterRuntime.autoRunTotalRuns,
  606. totalRuns: afterRuntime.autoRunTotalRuns,
  607. attemptRun: afterRuntime.autoRunAttemptRun,
  608. sessionId: 0,
  609. }),
  610. });
  611. clearStopRequest();
  612. }
  613. return {
  614. autoRunLoop,
  615. buildAutoRunRoundSummaries,
  616. createAutoRunRoundSummary,
  617. formatAutoRunFailureReasons,
  618. getAutoRunRoundRetryCount,
  619. handleAutoRunLoopUnhandledError,
  620. logAutoRunFinalSummary,
  621. normalizeAutoRunRoundSummary,
  622. serializeAutoRunRoundSummaries,
  623. skipAutoRunCountdown,
  624. startAutoRunLoop,
  625. waitBetweenAutoRunRounds,
  626. waitBeforeAutoRunRetry,
  627. };
  628. }
  629. return {
  630. createAutoRunController,
  631. };
  632. });