sidepanel.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. // sidepanel/sidepanel.js — Side Panel logic
  2. const STATUS_ICONS = {
  3. pending: '',
  4. running: '',
  5. completed: '\u2713', // ✓
  6. failed: '\u2717', // ✗
  7. stopped: '\u25A0', // ■
  8. manual_completed: '跳',
  9. skipped: '跳',
  10. };
  11. const logArea = document.getElementById('log-area');
  12. const displayOauthUrl = document.getElementById('display-oauth-url');
  13. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  14. const displayStatus = document.getElementById('display-status');
  15. const statusBar = document.getElementById('status-bar');
  16. const inputEmail = document.getElementById('input-email');
  17. const inputPassword = document.getElementById('input-password');
  18. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  19. const btnFetchEmail = document.getElementById('btn-fetch-email');
  20. const btnTogglePassword = document.getElementById('btn-toggle-password');
  21. const btnSaveSettings = document.getElementById('btn-save-settings');
  22. const btnStop = document.getElementById('btn-stop');
  23. const btnReset = document.getElementById('btn-reset');
  24. const stepsProgress = document.getElementById('steps-progress');
  25. const btnAutoRun = document.getElementById('btn-auto-run');
  26. const btnAutoContinue = document.getElementById('btn-auto-continue');
  27. const autoContinueBar = document.getElementById('auto-continue-bar');
  28. const autoScheduleBar = document.getElementById('auto-schedule-bar');
  29. const autoScheduleTitle = document.getElementById('auto-schedule-title');
  30. const autoScheduleMeta = document.getElementById('auto-schedule-meta');
  31. const btnAutoRunNow = document.getElementById('btn-auto-run-now');
  32. const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule');
  33. const btnClearLog = document.getElementById('btn-clear-log');
  34. const inputVpsUrl = document.getElementById('input-vps-url');
  35. const inputVpsPassword = document.getElementById('input-vps-password');
  36. const selectMailProvider = document.getElementById('select-mail-provider');
  37. const rowInbucketHost = document.getElementById('row-inbucket-host');
  38. const inputInbucketHost = document.getElementById('input-inbucket-host');
  39. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  40. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  41. const inputRunCount = document.getElementById('input-run-count');
  42. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  43. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  44. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  45. const autoStartModal = document.getElementById('auto-start-modal');
  46. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  47. const autoStartMessage = document.getElementById('auto-start-message');
  48. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  49. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  50. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  51. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  52. const STEP_DEFAULT_STATUSES = {
  53. 1: 'pending',
  54. 2: 'pending',
  55. 3: 'pending',
  56. 4: 'pending',
  57. 5: 'pending',
  58. 6: 'pending',
  59. 7: 'pending',
  60. 8: 'pending',
  61. 9: 'pending',
  62. };
  63. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  64. const AUTO_DELAY_MIN_MINUTES = 1;
  65. const AUTO_DELAY_MAX_MINUTES = 1440;
  66. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  67. let latestState = null;
  68. let currentAutoRun = {
  69. autoRunning: false,
  70. phase: 'idle',
  71. currentRun: 0,
  72. totalRuns: 1,
  73. attemptRun: 0,
  74. scheduledAt: null,
  75. };
  76. let settingsDirty = false;
  77. let settingsSaveInFlight = false;
  78. let settingsAutoSaveTimer = null;
  79. let modalChoiceResolver = null;
  80. let currentModalActions = [];
  81. let scheduledCountdownTimer = null;
  82. const EYE_OPEN_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>';
  83. const EYE_CLOSED_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19C5 19 1 12 1 12a21.77 21.77 0 0 1 5.06-6.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 5c7 0 11 7 11 7a21.86 21.86 0 0 1-2.16 3.19"/><path d="M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg>';
  84. // ============================================================
  85. // Toast Notifications
  86. // ============================================================
  87. const toastContainer = document.getElementById('toast-container');
  88. const TOAST_ICONS = {
  89. error: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
  90. warn: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
  91. success: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
  92. info: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
  93. };
  94. const LOG_LEVEL_LABELS = {
  95. info: '信息',
  96. ok: '成功',
  97. warn: '警告',
  98. error: '错误',
  99. };
  100. function showToast(message, type = 'error', duration = 4000) {
  101. const toast = document.createElement('div');
  102. toast.className = `toast toast-${type}`;
  103. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  104. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  105. toastContainer.appendChild(toast);
  106. if (duration > 0) {
  107. setTimeout(() => dismissToast(toast), duration);
  108. }
  109. }
  110. function dismissToast(toast) {
  111. if (!toast.parentNode) return;
  112. toast.classList.add('toast-exit');
  113. toast.addEventListener('animationend', () => toast.remove());
  114. }
  115. function resetActionModalButtons() {
  116. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  117. buttons.forEach((button) => {
  118. if (!button) return;
  119. button.hidden = true;
  120. button.disabled = false;
  121. button.onclick = null;
  122. });
  123. currentModalActions = [];
  124. }
  125. function configureActionModalButton(button, action) {
  126. if (!button) return;
  127. if (!action) {
  128. button.hidden = true;
  129. button.onclick = null;
  130. return;
  131. }
  132. button.hidden = false;
  133. button.disabled = false;
  134. button.textContent = action.label;
  135. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  136. button.onclick = () => resolveModalChoice(action.id);
  137. }
  138. function resolveModalChoice(choice) {
  139. if (modalChoiceResolver) {
  140. modalChoiceResolver(choice);
  141. modalChoiceResolver = null;
  142. }
  143. resetActionModalButtons();
  144. if (autoStartModal) {
  145. autoStartModal.hidden = true;
  146. }
  147. }
  148. function openActionModal({ title, message, actions }) {
  149. if (!autoStartModal) {
  150. return Promise.resolve(null);
  151. }
  152. if (modalChoiceResolver) {
  153. resolveModalChoice(null);
  154. }
  155. autoStartTitle.textContent = title;
  156. autoStartMessage.textContent = message;
  157. currentModalActions = actions || [];
  158. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  159. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  160. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  161. autoStartModal.hidden = false;
  162. return new Promise((resolve) => {
  163. modalChoiceResolver = resolve;
  164. });
  165. }
  166. function openAutoStartChoiceDialog(startStep) {
  167. return openActionModal({
  168. title: '启动自动',
  169. message: `检测到当前已有流程进度。继续当前会从步骤 ${startStep} 开始自动执行,重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  170. actions: [
  171. { id: null, label: '取消', variant: 'btn-ghost' },
  172. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  173. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  174. ],
  175. });
  176. }
  177. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  178. const choice = await openActionModal({
  179. title,
  180. message,
  181. actions: [
  182. { id: null, label: '取消', variant: 'btn-ghost' },
  183. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  184. ],
  185. });
  186. return choice === 'confirm';
  187. }
  188. function isDoneStatus(status) {
  189. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  190. }
  191. function getStepStatuses(state = latestState) {
  192. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  193. }
  194. function getFirstUnfinishedStep(state = latestState) {
  195. const statuses = getStepStatuses(state);
  196. for (let step = 1; step <= 9; step++) {
  197. if (!isDoneStatus(statuses[step])) {
  198. return step;
  199. }
  200. }
  201. return null;
  202. }
  203. function hasSavedProgress(state = latestState) {
  204. const statuses = getStepStatuses(state);
  205. return Object.values(statuses).some((status) => status !== 'pending');
  206. }
  207. function shouldOfferAutoModeChoice(state = latestState) {
  208. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  209. }
  210. function syncLatestState(nextState) {
  211. const mergedStepStatuses = nextState?.stepStatuses
  212. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  213. : getStepStatuses(latestState);
  214. latestState = {
  215. ...(latestState || {}),
  216. ...(nextState || {}),
  217. stepStatuses: mergedStepStatuses,
  218. };
  219. }
  220. function syncAutoRunState(source = {}) {
  221. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  222. const autoRunning = source.autoRunning !== undefined
  223. ? Boolean(source.autoRunning)
  224. : (source.autoRunPhase !== undefined || source.phase !== undefined
  225. ? ['scheduled', 'running', 'waiting_email', 'retrying'].includes(phase)
  226. : currentAutoRun.autoRunning);
  227. currentAutoRun = {
  228. autoRunning,
  229. phase,
  230. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  231. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  232. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  233. scheduledAt: source.scheduledAutoRunAt ?? source.scheduledAt ?? currentAutoRun.scheduledAt,
  234. };
  235. }
  236. function isAutoRunLockedPhase() {
  237. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'retrying';
  238. }
  239. function isAutoRunPausedPhase() {
  240. return currentAutoRun.phase === 'waiting_email';
  241. }
  242. function isAutoRunScheduledPhase() {
  243. return currentAutoRun.phase === 'scheduled';
  244. }
  245. function getAutoRunLabel(payload = currentAutoRun) {
  246. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  247. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  248. }
  249. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  250. if ((payload.totalRuns || 1) > 1) {
  251. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  252. }
  253. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  254. }
  255. function normalizeAutoDelayMinutes(value) {
  256. const numeric = Number(value);
  257. if (!Number.isFinite(numeric)) {
  258. return AUTO_DELAY_DEFAULT_MINUTES;
  259. }
  260. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  261. }
  262. function updateAutoDelayInputState() {
  263. const scheduled = isAutoRunScheduledPhase();
  264. inputAutoDelayEnabled.disabled = scheduled;
  265. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  266. }
  267. function formatCountdown(remainingMs) {
  268. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  269. const hours = Math.floor(totalSeconds / 3600);
  270. const minutes = Math.floor((totalSeconds % 3600) / 60);
  271. const seconds = totalSeconds % 60;
  272. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  273. }
  274. function formatScheduleTime(timestamp) {
  275. return new Date(timestamp).toLocaleString('zh-CN', {
  276. hour12: false,
  277. month: '2-digit',
  278. day: '2-digit',
  279. hour: '2-digit',
  280. minute: '2-digit',
  281. second: '2-digit',
  282. });
  283. }
  284. function stopScheduledCountdownTicker() {
  285. clearInterval(scheduledCountdownTimer);
  286. scheduledCountdownTimer = null;
  287. }
  288. function renderScheduledAutoRunInfo() {
  289. if (!autoScheduleBar) {
  290. return;
  291. }
  292. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  293. autoScheduleBar.style.display = 'none';
  294. return;
  295. }
  296. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  297. autoScheduleBar.style.display = 'flex';
  298. autoScheduleTitle.textContent = '已计划自动运行';
  299. autoScheduleMeta.textContent = remainingMs > 0
  300. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  301. : '倒计时即将结束,正在准备启动...';
  302. }
  303. function syncScheduledCountdownTicker() {
  304. renderScheduledAutoRunInfo();
  305. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  306. stopScheduledCountdownTicker();
  307. return;
  308. }
  309. if (scheduledCountdownTimer) {
  310. return;
  311. }
  312. scheduledCountdownTimer = setInterval(() => {
  313. renderScheduledAutoRunInfo();
  314. updateStatusDisplay(latestState);
  315. }, 1000);
  316. }
  317. function setDefaultAutoRunButton() {
  318. btnAutoRun.disabled = false;
  319. inputRunCount.disabled = false;
  320. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> 自动';
  321. }
  322. function collectSettingsPayload() {
  323. return {
  324. vpsUrl: inputVpsUrl.value.trim(),
  325. vpsPassword: inputVpsPassword.value,
  326. customPassword: inputPassword.value,
  327. mailProvider: selectMailProvider.value,
  328. inbucketHost: inputInbucketHost.value.trim(),
  329. inbucketMailbox: inputInbucketMailbox.value.trim(),
  330. autoRunSkipFailures: inputAutoSkipFailures.checked,
  331. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  332. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  333. };
  334. }
  335. function markSettingsDirty(isDirty = true) {
  336. settingsDirty = isDirty;
  337. updateSaveButtonState();
  338. }
  339. function updateSaveButtonState() {
  340. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  341. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  342. }
  343. function scheduleSettingsAutoSave() {
  344. clearTimeout(settingsAutoSaveTimer);
  345. settingsAutoSaveTimer = setTimeout(() => {
  346. saveSettings({ silent: true }).catch(() => { });
  347. }, 500);
  348. }
  349. async function saveSettings(options = {}) {
  350. const { silent = false } = options;
  351. clearTimeout(settingsAutoSaveTimer);
  352. if (!settingsDirty && !settingsSaveInFlight && silent) {
  353. return;
  354. }
  355. const payload = collectSettingsPayload();
  356. settingsSaveInFlight = true;
  357. updateSaveButtonState();
  358. try {
  359. const response = await chrome.runtime.sendMessage({
  360. type: 'SAVE_SETTING',
  361. source: 'sidepanel',
  362. payload,
  363. });
  364. if (response?.error) {
  365. throw new Error(response.error);
  366. }
  367. syncLatestState(payload);
  368. markSettingsDirty(false);
  369. updateMailProviderUI();
  370. updateButtonStates();
  371. if (!silent) {
  372. showToast('配置已保存', 'success', 1800);
  373. }
  374. } catch (err) {
  375. markSettingsDirty(true);
  376. if (!silent) {
  377. showToast(`保存失败:${err.message}`, 'error');
  378. }
  379. throw err;
  380. } finally {
  381. settingsSaveInFlight = false;
  382. updateSaveButtonState();
  383. }
  384. }
  385. function applyAutoRunStatus(payload = currentAutoRun) {
  386. syncAutoRunState(payload);
  387. const runLabel = getAutoRunLabel(currentAutoRun);
  388. const locked = isAutoRunLockedPhase();
  389. const paused = isAutoRunPausedPhase();
  390. const scheduled = isAutoRunScheduledPhase();
  391. inputRunCount.disabled = currentAutoRun.autoRunning;
  392. btnAutoRun.disabled = currentAutoRun.autoRunning;
  393. btnFetchEmail.disabled = locked;
  394. inputEmail.disabled = locked;
  395. inputAutoSkipFailures.disabled = scheduled;
  396. if (currentAutoRun.totalRuns > 0) {
  397. inputRunCount.value = String(currentAutoRun.totalRuns);
  398. }
  399. switch (currentAutoRun.phase) {
  400. case 'scheduled':
  401. autoContinueBar.style.display = 'none';
  402. btnAutoRun.innerHTML = `已计划${runLabel}`;
  403. break;
  404. case 'waiting_email':
  405. autoContinueBar.style.display = 'flex';
  406. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  407. break;
  408. case 'running':
  409. autoContinueBar.style.display = 'none';
  410. btnAutoRun.innerHTML = `运行中${runLabel}`;
  411. break;
  412. case 'retrying':
  413. autoContinueBar.style.display = 'none';
  414. btnAutoRun.innerHTML = `重试中${runLabel}`;
  415. break;
  416. default:
  417. autoContinueBar.style.display = 'none';
  418. setDefaultAutoRunButton();
  419. inputEmail.disabled = false;
  420. if (!locked) {
  421. btnFetchEmail.disabled = false;
  422. }
  423. break;
  424. }
  425. updateAutoDelayInputState();
  426. syncScheduledCountdownTicker();
  427. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  428. }
  429. function initializeManualStepActions() {
  430. document.querySelectorAll('.step-row').forEach((row) => {
  431. const step = Number(row.dataset.step);
  432. const statusEl = row.querySelector('.step-status');
  433. if (!statusEl) return;
  434. const actions = document.createElement('div');
  435. actions.className = 'step-actions';
  436. const manualBtn = document.createElement('button');
  437. manualBtn.type = 'button';
  438. manualBtn.className = 'step-manual-btn';
  439. manualBtn.dataset.step = String(step);
  440. manualBtn.title = '跳过此步';
  441. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  442. manualBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="13 17 18 12 13 7"/><polyline points="6 17 11 12 6 7"/></svg>';
  443. manualBtn.addEventListener('click', async (event) => {
  444. event.stopPropagation();
  445. try {
  446. await handleSkipStep(step);
  447. } catch (err) {
  448. showToast(err.message, 'error');
  449. }
  450. });
  451. statusEl.parentNode.replaceChild(actions, statusEl);
  452. actions.appendChild(manualBtn);
  453. actions.appendChild(statusEl);
  454. });
  455. }
  456. // ============================================================
  457. // State Restore on load
  458. // ============================================================
  459. async function restoreState() {
  460. try {
  461. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  462. syncLatestState(state);
  463. syncAutoRunState(state);
  464. if (state.oauthUrl) {
  465. displayOauthUrl.textContent = state.oauthUrl;
  466. displayOauthUrl.classList.add('has-value');
  467. }
  468. if (state.localhostUrl) {
  469. displayLocalhostUrl.textContent = state.localhostUrl;
  470. displayLocalhostUrl.classList.add('has-value');
  471. }
  472. if (state.email) {
  473. inputEmail.value = state.email;
  474. }
  475. syncPasswordField(state);
  476. if (state.vpsUrl) {
  477. inputVpsUrl.value = state.vpsUrl;
  478. }
  479. if (state.vpsPassword) {
  480. inputVpsPassword.value = state.vpsPassword;
  481. }
  482. if (state.mailProvider) {
  483. selectMailProvider.value = state.mailProvider;
  484. }
  485. if (state.inbucketHost) {
  486. inputInbucketHost.value = state.inbucketHost;
  487. }
  488. if (state.inbucketMailbox) {
  489. inputInbucketMailbox.value = state.inbucketMailbox;
  490. }
  491. inputAutoSkipFailures.checked = Boolean(state.autoRunSkipFailures);
  492. inputAutoDelayEnabled.checked = Boolean(state.autoRunDelayEnabled);
  493. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state.autoRunDelayMinutes));
  494. if (state.autoRunTotalRuns) {
  495. inputRunCount.value = String(state.autoRunTotalRuns);
  496. }
  497. if (state.stepStatuses) {
  498. for (const [step, status] of Object.entries(state.stepStatuses)) {
  499. updateStepUI(Number(step), status);
  500. }
  501. }
  502. if (state.logs) {
  503. for (const entry of state.logs) {
  504. appendLog(entry);
  505. }
  506. }
  507. applyAutoRunStatus(state);
  508. markSettingsDirty(false);
  509. updateAutoDelayInputState();
  510. updateStatusDisplay(latestState);
  511. updateProgressCounter();
  512. updateMailProviderUI();
  513. updateButtonStates();
  514. } catch (err) {
  515. console.error('Failed to restore state:', err);
  516. }
  517. }
  518. function syncPasswordField(state) {
  519. inputPassword.value = state.customPassword || state.password || '';
  520. }
  521. function updateMailProviderUI() {
  522. const useInbucket = selectMailProvider.value === 'inbucket';
  523. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  524. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  525. }
  526. // ============================================================
  527. // UI Updates
  528. // ============================================================
  529. function updateStepUI(step, status) {
  530. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  531. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  532. syncLatestState({
  533. stepStatuses: {
  534. ...getStepStatuses(),
  535. [step]: status,
  536. },
  537. });
  538. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  539. if (row) {
  540. row.className = `step-row ${status}`;
  541. }
  542. updateButtonStates();
  543. updateProgressCounter();
  544. }
  545. function updateProgressCounter() {
  546. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  547. stepsProgress.textContent = `${completed} / 9`;
  548. }
  549. function updateButtonStates() {
  550. const statuses = getStepStatuses();
  551. const anyRunning = Object.values(statuses).some(s => s === 'running');
  552. const autoLocked = isAutoRunLockedPhase();
  553. const autoScheduled = isAutoRunScheduledPhase();
  554. for (let step = 1; step <= 9; step++) {
  555. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  556. if (!btn) continue;
  557. if (anyRunning || autoLocked || autoScheduled) {
  558. btn.disabled = true;
  559. } else if (step === 1) {
  560. btn.disabled = false;
  561. } else {
  562. const prevStatus = statuses[step - 1];
  563. const currentStatus = statuses[step];
  564. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  565. }
  566. }
  567. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  568. const step = Number(btn.dataset.step);
  569. const currentStatus = statuses[step];
  570. const prevStatus = statuses[step - 1];
  571. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  572. btn.style.display = 'none';
  573. btn.disabled = true;
  574. btn.title = '当前不可跳过';
  575. return;
  576. }
  577. if (step > 1 && !isDoneStatus(prevStatus)) {
  578. btn.style.display = 'none';
  579. btn.disabled = true;
  580. btn.title = `请先完成步骤 ${step - 1}`;
  581. return;
  582. }
  583. btn.style.display = '';
  584. btn.disabled = false;
  585. btn.title = `跳过步骤 ${step}`;
  586. });
  587. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  588. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  589. }
  590. function updateStopButtonState(active) {
  591. btnStop.disabled = !active;
  592. }
  593. function updateStatusDisplay(state) {
  594. if (!state || !state.stepStatuses) return;
  595. statusBar.className = 'status-bar';
  596. if (isAutoRunScheduledPhase()) {
  597. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  598. ? currentAutoRun.scheduledAt - Date.now()
  599. : 0;
  600. displayStatus.textContent = remainingMs > 0
  601. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  602. : '倒计时即将结束,正在准备启动...';
  603. statusBar.classList.add('scheduled');
  604. return;
  605. }
  606. if (isAutoRunPausedPhase()) {
  607. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  608. statusBar.classList.add('paused');
  609. return;
  610. }
  611. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  612. if (running) {
  613. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  614. statusBar.classList.add('running');
  615. return;
  616. }
  617. if (isAutoRunLockedPhase()) {
  618. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  619. statusBar.classList.add('running');
  620. return;
  621. }
  622. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  623. if (failed) {
  624. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  625. statusBar.classList.add('failed');
  626. return;
  627. }
  628. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  629. if (stopped) {
  630. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  631. statusBar.classList.add('stopped');
  632. return;
  633. }
  634. const lastCompleted = Object.entries(state.stepStatuses)
  635. .filter(([, s]) => isDoneStatus(s))
  636. .map(([k]) => Number(k))
  637. .sort((a, b) => b - a)[0];
  638. if (lastCompleted === 9) {
  639. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  640. statusBar.classList.add('completed');
  641. } else if (lastCompleted) {
  642. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  643. ? `步骤 ${lastCompleted} 已跳过`
  644. : `步骤 ${lastCompleted} 已完成`;
  645. } else {
  646. displayStatus.textContent = '就绪';
  647. }
  648. }
  649. function appendLog(entry) {
  650. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  651. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  652. const line = document.createElement('div');
  653. line.className = `log-line log-${entry.level}`;
  654. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  655. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  656. let html = `<span class="log-time">${time}</span> `;
  657. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  658. if (stepNum) {
  659. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  660. }
  661. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  662. line.innerHTML = html;
  663. logArea.appendChild(line);
  664. logArea.scrollTop = logArea.scrollHeight;
  665. }
  666. function escapeHtml(text) {
  667. const div = document.createElement('div');
  668. div.textContent = text;
  669. return div.innerHTML;
  670. }
  671. async function fetchDuckEmail(options = {}) {
  672. const { showFailureToast = true } = options;
  673. const defaultLabel = '获取';
  674. btnFetchEmail.disabled = true;
  675. btnFetchEmail.textContent = '...';
  676. try {
  677. const response = await chrome.runtime.sendMessage({
  678. type: 'FETCH_DUCK_EMAIL',
  679. source: 'sidepanel',
  680. payload: { generateNew: true },
  681. });
  682. if (response?.error) {
  683. throw new Error(response.error);
  684. }
  685. if (!response?.email) {
  686. throw new Error('未返回 Duck 邮箱。');
  687. }
  688. inputEmail.value = response.email;
  689. showToast(`已获取 ${response.email}`, 'success', 2500);
  690. return response.email;
  691. } catch (err) {
  692. if (showFailureToast) {
  693. showToast(`自动获取失败:${err.message}`, 'error');
  694. }
  695. throw err;
  696. } finally {
  697. btnFetchEmail.disabled = false;
  698. btnFetchEmail.textContent = defaultLabel;
  699. }
  700. }
  701. function syncToggleButtonLabel(button, input, labels) {
  702. if (!button || !input) return;
  703. const isHidden = input.type === 'password';
  704. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  705. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  706. button.title = isHidden ? labels.show : labels.hide;
  707. }
  708. function syncPasswordToggleLabel() {
  709. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  710. show: '显示密码',
  711. hide: '隐藏密码',
  712. });
  713. }
  714. function syncVpsUrlToggleLabel() {
  715. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  716. show: '显示 CPA 地址',
  717. hide: '隐藏 CPA 地址',
  718. });
  719. }
  720. async function maybeTakeoverAutoRun(actionLabel) {
  721. if (!isAutoRunPausedPhase()) {
  722. return true;
  723. }
  724. const confirmed = await openConfirmModal({
  725. title: '接管自动',
  726. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  727. confirmLabel: '确认接管',
  728. confirmVariant: 'btn-primary',
  729. });
  730. if (!confirmed) {
  731. return false;
  732. }
  733. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  734. return true;
  735. }
  736. async function handleSkipStep(step) {
  737. if (isAutoRunPausedPhase()) {
  738. const takeoverResponse = await chrome.runtime.sendMessage({
  739. type: 'TAKEOVER_AUTO_RUN',
  740. source: 'sidepanel',
  741. payload: {},
  742. });
  743. if (takeoverResponse?.error) {
  744. throw new Error(takeoverResponse.error);
  745. }
  746. }
  747. const response = await chrome.runtime.sendMessage({
  748. type: 'SKIP_STEP',
  749. source: 'sidepanel',
  750. payload: { step },
  751. });
  752. if (response?.error) {
  753. throw new Error(response.error);
  754. }
  755. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  756. }
  757. // ============================================================
  758. // Button Handlers
  759. // ============================================================
  760. document.querySelectorAll('.step-btn').forEach(btn => {
  761. btn.addEventListener('click', async () => {
  762. try {
  763. const step = Number(btn.dataset.step);
  764. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  765. return;
  766. }
  767. if (step === 3) {
  768. if (inputPassword.value !== (latestState?.customPassword || '')) {
  769. await chrome.runtime.sendMessage({
  770. type: 'SAVE_SETTING',
  771. source: 'sidepanel',
  772. payload: { customPassword: inputPassword.value },
  773. });
  774. syncLatestState({ customPassword: inputPassword.value });
  775. }
  776. let email = inputEmail.value.trim();
  777. if (!email) {
  778. try {
  779. email = await fetchDuckEmail({ showFailureToast: false });
  780. } catch (err) {
  781. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  782. return;
  783. }
  784. }
  785. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  786. if (response?.error) {
  787. throw new Error(response.error);
  788. }
  789. } else {
  790. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  791. if (response?.error) {
  792. throw new Error(response.error);
  793. }
  794. }
  795. } catch (err) {
  796. showToast(err.message, 'error');
  797. }
  798. });
  799. });
  800. btnFetchEmail.addEventListener('click', async () => {
  801. await fetchDuckEmail().catch(() => { });
  802. });
  803. btnTogglePassword.addEventListener('click', () => {
  804. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  805. syncPasswordToggleLabel();
  806. });
  807. btnToggleVpsUrl.addEventListener('click', () => {
  808. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  809. syncVpsUrlToggleLabel();
  810. });
  811. btnSaveSettings.addEventListener('click', async () => {
  812. if (!settingsDirty) {
  813. showToast('配置已是最新', 'info', 1400);
  814. return;
  815. }
  816. await saveSettings({ silent: false }).catch(() => { });
  817. });
  818. btnStop.addEventListener('click', async () => {
  819. btnStop.disabled = true;
  820. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  821. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  822. });
  823. autoStartModal?.addEventListener('click', (event) => {
  824. if (event.target === autoStartModal) {
  825. resolveModalChoice(null);
  826. }
  827. });
  828. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  829. // Auto Run
  830. btnAutoRun.addEventListener('click', async () => {
  831. try {
  832. const totalRuns = Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  833. let mode = 'restart';
  834. if (shouldOfferAutoModeChoice()) {
  835. const startStep = getFirstUnfinishedStep();
  836. const choice = await openAutoStartChoiceDialog(startStep);
  837. if (!choice) {
  838. return;
  839. }
  840. mode = choice;
  841. }
  842. btnAutoRun.disabled = true;
  843. inputRunCount.disabled = true;
  844. const delayEnabled = inputAutoDelayEnabled.checked;
  845. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  846. inputAutoDelayMinutes.value = String(delayMinutes);
  847. btnAutoRun.innerHTML = delayEnabled
  848. ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 计划中...'
  849. : '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 运行中...';
  850. const response = await chrome.runtime.sendMessage({
  851. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  852. source: 'sidepanel',
  853. payload: {
  854. totalRuns,
  855. delayMinutes,
  856. autoRunSkipFailures: inputAutoSkipFailures.checked,
  857. mode,
  858. },
  859. });
  860. if (response?.error) {
  861. throw new Error(response.error);
  862. }
  863. } catch (err) {
  864. setDefaultAutoRunButton();
  865. inputRunCount.disabled = false;
  866. showToast(err.message, 'error');
  867. }
  868. });
  869. btnAutoContinue.addEventListener('click', async () => {
  870. const email = inputEmail.value.trim();
  871. if (!email) {
  872. showToast('请先获取或粘贴 DuckDuckGo 邮箱。', 'warn');
  873. return;
  874. }
  875. autoContinueBar.style.display = 'none';
  876. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  877. });
  878. btnAutoRunNow?.addEventListener('click', async () => {
  879. try {
  880. btnAutoRunNow.disabled = true;
  881. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  882. } catch (err) {
  883. showToast(err.message, 'error');
  884. } finally {
  885. btnAutoRunNow.disabled = false;
  886. }
  887. });
  888. btnAutoCancelSchedule?.addEventListener('click', async () => {
  889. try {
  890. btnAutoCancelSchedule.disabled = true;
  891. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  892. showToast('已取消倒计时计划。', 'info', 1800);
  893. } catch (err) {
  894. showToast(err.message, 'error');
  895. } finally {
  896. btnAutoCancelSchedule.disabled = false;
  897. }
  898. });
  899. // Reset
  900. btnReset.addEventListener('click', async () => {
  901. const confirmed = await openConfirmModal({
  902. title: '重置流程',
  903. message: '确认重置全部步骤和数据吗?',
  904. confirmLabel: '确认重置',
  905. confirmVariant: 'btn-danger',
  906. });
  907. if (!confirmed) {
  908. return;
  909. }
  910. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  911. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES });
  912. syncAutoRunState({ autoRunning: false, autoRunPhase: 'idle', autoRunCurrentRun: 0, autoRunTotalRuns: 1, autoRunAttemptRun: 0, scheduledAutoRunAt: null });
  913. displayOauthUrl.textContent = '等待中...';
  914. displayOauthUrl.classList.remove('has-value');
  915. displayLocalhostUrl.textContent = '等待中...';
  916. displayLocalhostUrl.classList.remove('has-value');
  917. inputEmail.value = '';
  918. displayStatus.textContent = '就绪';
  919. statusBar.className = 'status-bar';
  920. logArea.innerHTML = '';
  921. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  922. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  923. setDefaultAutoRunButton();
  924. applyAutoRunStatus(currentAutoRun);
  925. markSettingsDirty(false);
  926. updateStopButtonState(false);
  927. updateButtonStates();
  928. updateProgressCounter();
  929. });
  930. // Clear log
  931. btnClearLog.addEventListener('click', () => {
  932. logArea.innerHTML = '';
  933. });
  934. // Save settings on change
  935. inputEmail.addEventListener('change', async () => {
  936. const email = inputEmail.value.trim();
  937. if (email) {
  938. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  939. }
  940. });
  941. inputEmail.addEventListener('input', updateButtonStates);
  942. inputVpsUrl.addEventListener('input', () => {
  943. markSettingsDirty(true);
  944. scheduleSettingsAutoSave();
  945. });
  946. inputVpsUrl.addEventListener('blur', () => {
  947. saveSettings({ silent: true }).catch(() => { });
  948. });
  949. inputVpsPassword.addEventListener('input', () => {
  950. markSettingsDirty(true);
  951. scheduleSettingsAutoSave();
  952. });
  953. inputVpsPassword.addEventListener('blur', () => {
  954. saveSettings({ silent: true }).catch(() => { });
  955. });
  956. inputPassword.addEventListener('input', () => {
  957. markSettingsDirty(true);
  958. updateButtonStates();
  959. scheduleSettingsAutoSave();
  960. });
  961. inputPassword.addEventListener('blur', () => {
  962. saveSettings({ silent: true }).catch(() => { });
  963. });
  964. selectMailProvider.addEventListener('change', () => {
  965. updateMailProviderUI();
  966. markSettingsDirty(true);
  967. saveSettings({ silent: true }).catch(() => { });
  968. });
  969. inputInbucketMailbox.addEventListener('input', () => {
  970. markSettingsDirty(true);
  971. scheduleSettingsAutoSave();
  972. });
  973. inputInbucketMailbox.addEventListener('blur', () => {
  974. saveSettings({ silent: true }).catch(() => { });
  975. });
  976. inputInbucketHost.addEventListener('input', () => {
  977. markSettingsDirty(true);
  978. scheduleSettingsAutoSave();
  979. });
  980. inputInbucketHost.addEventListener('blur', () => {
  981. saveSettings({ silent: true }).catch(() => { });
  982. });
  983. inputAutoSkipFailures.addEventListener('change', () => {
  984. markSettingsDirty(true);
  985. saveSettings({ silent: true }).catch(() => { });
  986. });
  987. inputAutoDelayEnabled.addEventListener('change', () => {
  988. updateAutoDelayInputState();
  989. markSettingsDirty(true);
  990. saveSettings({ silent: true }).catch(() => { });
  991. });
  992. inputAutoDelayMinutes.addEventListener('input', () => {
  993. markSettingsDirty(true);
  994. scheduleSettingsAutoSave();
  995. });
  996. inputAutoDelayMinutes.addEventListener('blur', () => {
  997. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  998. saveSettings({ silent: true }).catch(() => { });
  999. });
  1000. // ============================================================
  1001. // Listen for Background broadcasts
  1002. // ============================================================
  1003. chrome.runtime.onMessage.addListener((message) => {
  1004. switch (message.type) {
  1005. case 'LOG_ENTRY':
  1006. appendLog(message.payload);
  1007. if (message.payload.level === 'error') {
  1008. showToast(message.payload.message, 'error');
  1009. }
  1010. break;
  1011. case 'STEP_STATUS_CHANGED': {
  1012. const { step, status } = message.payload;
  1013. updateStepUI(step, status);
  1014. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  1015. syncLatestState(state);
  1016. syncAutoRunState(state);
  1017. updateStatusDisplay(latestState);
  1018. updateButtonStates();
  1019. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  1020. syncPasswordField(state);
  1021. if (state.oauthUrl) {
  1022. displayOauthUrl.textContent = state.oauthUrl;
  1023. displayOauthUrl.classList.add('has-value');
  1024. }
  1025. if (state.localhostUrl) {
  1026. displayLocalhostUrl.textContent = state.localhostUrl;
  1027. displayLocalhostUrl.classList.add('has-value');
  1028. }
  1029. }
  1030. }
  1031. ).catch(() => { });
  1032. break;
  1033. }
  1034. case 'AUTO_RUN_RESET': {
  1035. // Full UI reset for next run
  1036. syncLatestState({
  1037. oauthUrl: null,
  1038. localhostUrl: null,
  1039. email: null,
  1040. password: null,
  1041. stepStatuses: STEP_DEFAULT_STATUSES,
  1042. logs: [],
  1043. scheduledAutoRunAt: null,
  1044. });
  1045. displayOauthUrl.textContent = '等待中...';
  1046. displayOauthUrl.classList.remove('has-value');
  1047. displayLocalhostUrl.textContent = '等待中...';
  1048. displayLocalhostUrl.classList.remove('has-value');
  1049. inputEmail.value = '';
  1050. displayStatus.textContent = '就绪';
  1051. statusBar.className = 'status-bar';
  1052. logArea.innerHTML = '';
  1053. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1054. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1055. applyAutoRunStatus(currentAutoRun);
  1056. updateProgressCounter();
  1057. updateButtonStates();
  1058. break;
  1059. }
  1060. case 'DATA_UPDATED': {
  1061. syncLatestState(message.payload);
  1062. if (message.payload.email) {
  1063. inputEmail.value = message.payload.email;
  1064. }
  1065. if (message.payload.password !== undefined) {
  1066. inputPassword.value = message.payload.password || '';
  1067. }
  1068. if (message.payload.oauthUrl) {
  1069. displayOauthUrl.textContent = message.payload.oauthUrl;
  1070. displayOauthUrl.classList.add('has-value');
  1071. }
  1072. if (message.payload.localhostUrl) {
  1073. displayLocalhostUrl.textContent = message.payload.localhostUrl;
  1074. displayLocalhostUrl.classList.add('has-value');
  1075. }
  1076. if (message.payload.autoRunDelayEnabled !== undefined) {
  1077. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  1078. updateAutoDelayInputState();
  1079. }
  1080. if (message.payload.autoRunDelayMinutes !== undefined) {
  1081. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  1082. }
  1083. break;
  1084. }
  1085. case 'AUTO_RUN_STATUS': {
  1086. syncLatestState({
  1087. autoRunning: ['scheduled', 'running', 'waiting_email', 'retrying'].includes(message.payload.phase),
  1088. autoRunPhase: message.payload.phase,
  1089. autoRunCurrentRun: message.payload.currentRun,
  1090. autoRunTotalRuns: message.payload.totalRuns,
  1091. autoRunAttemptRun: message.payload.attemptRun,
  1092. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  1093. });
  1094. applyAutoRunStatus(message.payload);
  1095. updateStatusDisplay(latestState);
  1096. updateButtonStates();
  1097. break;
  1098. }
  1099. }
  1100. });
  1101. // ============================================================
  1102. // Theme Toggle
  1103. // ============================================================
  1104. const btnTheme = document.getElementById('btn-theme');
  1105. function setTheme(theme) {
  1106. document.documentElement.setAttribute('data-theme', theme);
  1107. localStorage.setItem('multipage-theme', theme);
  1108. }
  1109. function initTheme() {
  1110. const saved = localStorage.getItem('multipage-theme');
  1111. if (saved) {
  1112. setTheme(saved);
  1113. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  1114. setTheme('dark');
  1115. }
  1116. }
  1117. btnTheme.addEventListener('click', () => {
  1118. const current = document.documentElement.getAttribute('data-theme');
  1119. setTheme(current === 'dark' ? 'light' : 'dark');
  1120. });
  1121. // ============================================================
  1122. // Init
  1123. // ============================================================
  1124. initializeManualStepActions();
  1125. initTheme();
  1126. updateSaveButtonState();
  1127. restoreState().then(() => {
  1128. syncPasswordToggleLabel();
  1129. syncVpsUrlToggleLabel();
  1130. updateButtonStates();
  1131. updateStatusDisplay(latestState);
  1132. });