sidepanel.js 40 KB

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