sidepanel.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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. break;
  1077. }
  1078. case 'AUTO_RUN_STATUS': {
  1079. syncLatestState({
  1080. autoRunning: ['scheduled', 'running', 'waiting_email', 'retrying'].includes(message.payload.phase),
  1081. autoRunPhase: message.payload.phase,
  1082. autoRunCurrentRun: message.payload.currentRun,
  1083. autoRunTotalRuns: message.payload.totalRuns,
  1084. autoRunAttemptRun: message.payload.attemptRun,
  1085. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  1086. });
  1087. applyAutoRunStatus(message.payload);
  1088. updateStatusDisplay(latestState);
  1089. updateButtonStates();
  1090. break;
  1091. }
  1092. }
  1093. });
  1094. // ============================================================
  1095. // Theme Toggle
  1096. // ============================================================
  1097. const btnTheme = document.getElementById('btn-theme');
  1098. function setTheme(theme) {
  1099. document.documentElement.setAttribute('data-theme', theme);
  1100. localStorage.setItem('multipage-theme', theme);
  1101. }
  1102. function initTheme() {
  1103. const saved = localStorage.getItem('multipage-theme');
  1104. if (saved) {
  1105. setTheme(saved);
  1106. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  1107. setTheme('dark');
  1108. }
  1109. }
  1110. btnTheme.addEventListener('click', () => {
  1111. const current = document.documentElement.getAttribute('data-theme');
  1112. setTheme(current === 'dark' ? 'light' : 'dark');
  1113. });
  1114. // ============================================================
  1115. // Init
  1116. // ============================================================
  1117. initializeManualStepActions();
  1118. initTheme();
  1119. updateSaveButtonState();
  1120. restoreState().then(() => {
  1121. syncPasswordToggleLabel();
  1122. syncVpsUrlToggleLabel();
  1123. updateButtonStates();
  1124. updateStatusDisplay(latestState);
  1125. });