Spaces:
Paused
fix: Electron OAuth login + i18n layout shift + update modal (#53)
Browse files* fix: Electron OAuth login + i18n toggle layout shift + update modal
1. OAuth login fix for Electron:
- Add focus/visibilitychange listeners to detect new accounts immediately
when user switches back from system browser (bypasses Chromium throttling)
- Track completed sessions server-side so code-relay returns success
instead of "Invalid or expired session" after callback server handled it
2. i18n layout stability:
- Push Star/Updates buttons from md to lg breakpoint to reduce crowding
- Add inline-grid overlay to Star, Check for Updates, Proxy Settings buttons
3. Update modal: extract from Header into standalone UpdateModal component
with auto-restart support (git mode spawns new process, frontend auto-refreshes)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: add polling guard + fix Star button inline-grid reference width
- Add re-entrancy guard to checkForNewAccount (both shared/ and web/)
to prevent concurrent fetches from rapid focus/visibility events
- Fix Star button invisible reference text "Star" → "Star on GitHub"
so inline-grid actually prevents layout shift between languages
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: icebear0828 <icebear0828@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (12)
- CHANGELOG.md+4
- shared/hooks/use-accounts.ts+29-6
- shared/hooks/use-update-status.ts+63-5
- shared/i18n/translations.ts+8
- src/auth/oauth-pkce.ts+19
- src/index.ts+18-1
- src/routes/auth.ts+14
- src/self-update.ts+30-3
- web/src/App.tsx+34-11
- web/src/components/Header.tsx+19-92
- web/src/components/UpdateModal.tsxAdded+180
- web/src/hooks/use-accounts.ts+29-6
5 unmodified lines67891011121314155 unmodified lines
## [Unreleased]
### Added
- 更新弹窗 + 自动重启:点击"有可用更新"弹出 Modal 显示 changelog,一键更新后服务器自动重启、前端自动刷新,零人工干预(git 模式 spawn 新进程、Docker/Electron 显示对应操作指引)
### Fixed
- Docker 端口修复:锁定容器内 `PORT=8080`(`environment` 覆盖 `env_file`),HEALTHCHECK 固定检查 8080,`.env` 的 PORT 仅控制宿主机暴露端口,修复自定义 PORT 时健康检查失败和端口映射不匹配的问题 (#40)53 unmodified lines5455565757585960616262636465666768696770717273747273757677787980818283848586878889909192759394959697989910010153 unmodified lines window.open(data.authUrl, "oauth_add", "width=600,height=700,scrollbars=yes"); setAddVisible(true);
// Poll for new account // Poll for new account + focus/visibility detection const prevResp = await fetch("/auth/accounts"); const prevData = await prevResp.json(); const prevCount = prevData.accounts?.length || 0;
const pollTimer = setInterval(async () => { let checking = false; const checkForNewAccount = async () => { if (checking) return; checking = true; try { const r = await fetch("/auth/accounts"); const d = await r.json(); if ((d.accounts?.length || 0) > prevCount) { clearInterval(pollTimer); cleanup(); setAddVisible(false); setAddInfo("accountAdded"); await loadAccounts(); } } catch {} }, 2000); } catch {} finally { checking = false; } };
// Focus event — check immediately when window regains focus const onFocus = () => { checkForNewAccount(); }; window.addEventListener("focus", onFocus);
// Visibility change — check when tab becomes visible const onVisible = () => { if (document.visibilityState === "visible") checkForNewAccount(); }; document.addEventListener("visibilitychange", onVisible);
// Interval polling as fallback const pollTimer = setInterval(checkForNewAccount, 2000);
setTimeout(() => clearInterval(pollTimer), 5 * 60 * 1000); const cleanup = () => { clearInterval(pollTimer); window.removeEventListener("focus", onFocus); document.removeEventListener("visibilitychange", onVisible); }; setTimeout(cleanup, 5 * 60 * 1000); } catch (err) { setAddError(err instanceof Error ? err.message : "failedStartLogin"); }1123440 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710831 unmodified lines1401411429114314414514614714814915015115215315415515615799158159102160161104162163import { useState, useEffect, useCallback } from "preact/hooks";import { useState, useEffect, useCallback, useRef } from "preact/hooks";
export interface UpdateStatus { proxy: {40 unmodified lines codex_update_in_progress: boolean;}
const RESTART_POLL_INTERVAL = 2000;const RESTART_TIMEOUT = 30000;
export function useUpdateStatus() { const [status, setStatus] = useState<UpdateStatus | null>(null); const [checking, setChecking] = useState(false); const [result, setResult] = useState<CheckResult | null>(null); const [error, setError] = useState<string | null>(null); const [applying, setApplying] = useState(false); const [restarting, setRestarting] = useState(false); const [restartFailed, setRestartFailed] = useState(false); const pollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null); const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const clearPolling = useCallback(() => { if (pollTimerRef.current) { clearInterval(pollTimerRef.current); pollTimerRef.current = null; } if (timeoutRef.current) { clearTimeout(timeoutRef.current); timeoutRef.current = null; } }, []);
// Cleanup on unmount useEffect(() => clearPolling, [clearPolling]);
const startRestartPolling = useCallback(() => { setRestarting(true); setRestartFailed(false); clearPolling();
// Wait a bit before first poll (server needs time to shut down) const initialDelay = setTimeout(() => { pollTimerRef.current = setInterval(async () => { try { const resp = await fetch("/health", { signal: AbortSignal.timeout(3000) }); if (resp.ok) { clearPolling(); location.reload(); } } catch { // Server still down, keep polling } }, RESTART_POLL_INTERVAL);
// Timeout fallback timeoutRef.current = setTimeout(() => { clearPolling(); setRestarting(false); setRestartFailed(true); }, RESTART_TIMEOUT); }, 2000);
// Store the initial delay timer for cleanup timeoutRef.current = initialDelay; }, [clearPolling]);
const load = useCallback(async () => { try {31 unmodified lines setError(null); try { const resp = await fetch("/admin/apply-update", { method: "POST" }); const data = await resp.json() as { started: boolean; error?: string }; const data = await resp.json() as { started: boolean; restarting?: boolean; error?: string }; if (!resp.ok || !data.started) { setError(data.error ?? "Apply failed"); setApplying(false); } else if (data.restarting) { // Server will restart — start polling for it to come back setApplying(false); startRestartPolling(); } else { // Update succeeded but no auto-restart setApplying(false); await load(); } } catch (err) { setError(err instanceof Error ? err.message : "Network error"); } finally { setApplying(false); } }, [load]); }, [load, startRestartPolling]);
return { status, checking, result, error, checkForUpdate, applyUpdate, applying }; return { status, checking, result, error, checkForUpdate, applyUpdate, applying, restarting, restartFailed };}148 unmodified lines149150151152153154155156157158148 unmodified lines307308309310311312313314315316148 unmodified lines newVersion: "New version", dockerUpdateCmd: "Run to update:", downloadUpdate: "Download", updateTitle: "Update Available", updateRestarting: "Restarting server...", restartFailed: "Server not responding. Please restart manually.", close: "Close", }, zh: { serverOnline: "\u670d\u52a1\u8fd0\u884c\u4e2d",148 unmodified lines newVersion: "\u65b0\u7248\u672c", dockerUpdateCmd: "\u6267\u884c\u66f4\u65b0\u547d\u4ee4\uff1a", downloadUpdate: "\u4e0b\u8f7d", updateTitle: "\u6709\u53ef\u7528\u66f4\u65b0", updateRestarting: "\u6b63\u5728\u91cd\u542f\u670d\u52a1...", restartFailed: "\u670d\u52a1\u5668\u672a\u54cd\u5e94\uff0c\u8bf7\u624b\u52a8\u91cd\u542f\u3002", close: "\u5173\u95ed", },} as const;
46 unmodified lines4748495051525354553 unmodified lines5960616263646566676869707172737475767778798081363 unmodified lines44544644744844945045146 unmodified lines/** In-memory store for pending OAuth sessions, keyed by `state`. */const pendingSessions = new Map<string, PendingSession>();
/** Track completed sessions so code-relay doesn't error after callback server already handled it. */const completedSessions = new Map<string, number>();
// Clean up expired sessions every 60 secondsconst SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutessetInterval(() => {3 unmodified lines pendingSessions.delete(state); } } for (const [state, completedAt] of completedSessions) { if (now - completedAt > SESSION_TTL_MS) { completedSessions.delete(state); } }}, 60_000).unref();
/** Mark a session as successfully completed. */export function markSessionCompleted(state: string): void { completedSessions.set(state, Date.now());}
/** Check if a session was already completed (callback server handled it). */export function isSessionCompleted(state: string): boolean { return completedSessions.has(state);}
/** * Generate a PKCE code_verifier + code_challenge (S256). */363 unmodified lines startCallbackServer(port, (accessToken, refreshToken) => { const entryId = pool.addAccount(accessToken, refreshToken); scheduler.scheduleOne(entryId, accessToken); markSessionCompleted(state); console.log(`[Auth] OAuth via callback server — account ${entryId} added`); }); return { authUrl, state };123415 unmodified lines2021222223242526121 unmodified lines148149150151152153154155156157158159160161162163164165166167168169import { spawn } from "child_process";import { Hono } from "hono";import { serve } from "@hono/node-server";import { loadConfig, loadFingerprint, getConfig } from "./config.js";15 unmodified linesimport { createProxyRoutes } from "./routes/proxies.js";import { createResponsesRoutes } from "./routes/responses.js";import { startUpdateChecker, stopUpdateChecker } from "./update-checker.js";import { startProxyUpdateChecker, stopProxyUpdateChecker } from "./self-update.js";import { startProxyUpdateChecker, stopProxyUpdateChecker, setRestartHandler } from "./self-update.js";import { initProxy } from "./tls/curl-binary.js";import { initTransport } from "./tls/transport.js";import { loadStaticModels } from "./models/model-store.js";121 unmodified lines }); };
// Register restart handler for self-update auto-restart setRestartHandler(() => { close().then(() => { const child = spawn(process.argv[0], process.argv.slice(1), { detached: true, stdio: "ignore", cwd: process.cwd(), windowsHide: true, }); child.unref(); process.exit(0); }).catch(() => { process.exit(1); }); });
return { close, port };}
9 unmodified lines101112131415161764 unmodified lines828384858687888990911 unmodified line9394959697989922 unmodified lines1221231241251261271281291301311321331 unmodified line1351361371381391401419 unmodified lines requestDeviceCode, pollDeviceToken, importCliAuth, markSessionCompleted, isSessionCompleted,} from "../auth/oauth-pkce.js";
export function createAuthRoutes(64 unmodified lines
const session = consumeSession(state); if (!session) { // Session already consumed by callback server — treat as success if (isSessionCompleted(state)) { return c.json({ success: true }); } return c.json({ error: "Invalid or expired session. Please try again." }, 400); }
1 unmodified line const tokens = await exchangeCode(code, session.codeVerifier, session.redirectUri); const entryId = pool.addAccount(tokens.access_token, tokens.refresh_token); scheduler.scheduleOne(entryId, tokens.access_token); markSessionCompleted(state);
console.log(`[Auth] OAuth via code-relay — account ${entryId} added`); return c.json({ success: true });22 unmodified lines
const session = consumeSession(state); if (!session) { // Session already consumed by callback server — redirect home if (isSessionCompleted(state)) { const config = getConfig(); const host = c.req.header("host") || `localhost:${config.server.port}`; return c.redirect(`http://${host}/`); } return c.html(errorPage("Invalid or expired OAuth session. Please try again."), 400); }
1 unmodified line const tokens = await exchangeCode(code, session.codeVerifier, session.redirectUri); const entryId = pool.addAccount(tokens.access_token, tokens.refresh_token); scheduler.scheduleOne(entryId, tokens.access_token); markSessionCompleted(state);
console.log(`[Auth] OAuth login completed — account ${entryId} added`);
10 unmodified lines111213141516171819202122232425262728293031323334353637216 unmodified lines25425525623625725825926011 unmodified lines27227327425427527625627727827928028128228328428528610 unmodified linesimport { promisify } from "util";import { getRootDir, isEmbedded } from "./paths.js";
// ── Restart handler ──────────────────────────────────────────────────let _onRestart: (() => void) | null = null;
/** Register a handler that will be called to restart the server process. */export function setRestartHandler(handler: () => void): void { _onRestart = handler;}
/** Schedule a server restart after a short delay (allows HTTP response to flush). */export function scheduleRestart(): void { if (!_onRestart) { console.warn("[SelfUpdate] No restart handler registered, manual restart required."); return; } const handler = _onRestart; setTimeout(() => { console.log("[SelfUpdate] Restarting server..."); handler(); }, 500);}
const execFileAsync = promisify(execFile);
const GITHUB_REPO = "icebear0828/codex-proxy";216 unmodified lines * Apply proxy self-update: git pull + npm install + npm run build. * Only works in git (CLI) mode. */export async function applyProxySelfUpdate(): Promise<{ started: boolean; error?: string }> {export async function applyProxySelfUpdate(): Promise<{ started: boolean; restarting?: boolean; error?: string }> { if (_proxyUpdateInProgress) { return { started: false, error: "Update already in progress" }; }11 unmodified lines console.log("[SelfUpdate] Building..."); await execFileAsync("npm", ["run", "build"], { cwd, timeout: 120000, shell: true });
console.log("[SelfUpdate] Update complete. Server restart required."); console.log("[SelfUpdate] Update complete. Scheduling restart..."); _proxyUpdateInProgress = false; return { started: true };
const willRestart = _onRestart !== null; if (willRestart) { scheduleRestart(); }
return { started: true, restarting: willRestart }; } catch (err) { _proxyUpdateInProgress = false; const msg = err instanceof Error ? err.message : String(err);11234567843 unmodified lines5253545455565756575859606158596061626365646566671 unmodified line697071727374757677787980818283845 unmodified lines909192939495969798899910010110242 unmodified lines14514614714814915015115215315415515615715815916016116216335 unmodified lines199200201179202203204205import { useState, useEffect } from "preact/hooks";import { useState, useEffect, useRef } from "preact/hooks";import { I18nProvider } from "../../shared/i18n/context";import { ThemeProvider } from "../../shared/theme/context";import { Header } from "./components/Header";import { UpdateModal } from "./components/UpdateModal";import { AccountList } from "./components/AccountList";import { AddAccount } from "./components/AddAccount";import { ProxyPool } from "./components/ProxyPool";43 unmodified lines color = "text-red-500"; }
const proxyUpdate = update.status?.proxy.update_available const hasUpdate = update.status?.proxy.update_available ?? false; const proxyUpdateInfo = hasUpdate ? { mode: update.status.proxy.mode, updateAvailable: true as const, commits: update.status.proxy.commits, release: update.status.proxy.release, onApply: update.applyUpdate, applying: update.applying, mode: update.status!.proxy.mode, commits: update.status!.proxy.commits, release: update.status!.proxy.release, } : null;
return { ...update, msg, color, proxyUpdate }; return { ...update, msg, color, hasUpdate, proxyUpdateInfo };}
function Dashboard() {1 unmodified line const proxies = useProxies(); const status = useStatus(accounts.list.length); const update = useUpdateMessage(); const [showModal, setShowModal] = useState(false); const prevUpdateAvailable = useRef(false);
// Auto-open modal when update becomes available after a check useEffect(() => { if (update.hasUpdate && !prevUpdateAvailable.current) { setShowModal(true); } prevUpdateAvailable.current = update.hasUpdate; }, [update.hasUpdate]);
const handleProxyChange = async (accountId: string, proxyId: string) => { accounts.patchLocal(accountId, { proxyId });5 unmodified lines <Header onAddAccount={accounts.startAdd} onCheckUpdate={update.checkForUpdate} onOpenUpdateModal={() => setShowModal(true)} checking={update.checking} updateStatusMsg={update.msg} updateStatusColor={update.color} version={update.status?.proxy.version ?? null} commit={update.status?.proxy.commit ?? null} proxyUpdate={update.proxyUpdate} hasUpdate={update.hasUpdate} /> <main class="flex-grow px-4 md:px-8 lg:px-40 py-8 flex justify-center"> <div class="flex flex-col w-full max-w-[960px] gap-6">42 unmodified lines </div> </main> <Footer updateStatus={update.status} /> {update.proxyUpdateInfo && ( <UpdateModal open={showModal} onClose={() => setShowModal(false)} mode={update.proxyUpdateInfo.mode} commits={update.proxyUpdateInfo.commits} release={update.proxyUpdateInfo.release} onApply={update.applyUpdate} applying={update.applying} restarting={update.restarting} restartFailed={update.restartFailed} /> )} </> );}35 unmodified lines version={update.status?.proxy.version ?? null} commit={update.status?.proxy.commit ?? null} isProxySettings proxyUpdate={update.proxyUpdate} hasUpdate={update.hasUpdate} /> <ProxySettings /> </>11239 unmodified lines1314151718192021222324251617181920212223242535262728382930314132333445 unmodified lines808182938384858687988889909192939495961049798991001011091101021031041051061071081091161171101111121131142 unmodified lines11711811912612012112212315 unmodified lines13914014114814214314414514614714812 unmodified lines161162163167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236164165166import { useState } from "preact/hooks";import { useI18n } from "../../../shared/i18n/context";import { useTheme } from "../../../shared/theme/context";
9 unmodified lines </svg>);
export interface ProxyUpdateInfo { mode: "git" | "docker" | "electron"; updateAvailable: boolean; commits: { hash: string; message: string }[]; release: { version: string; body: string; url: string } | null; onApply: () => void; applying: boolean;}
interface HeaderProps { onAddAccount: () => void; onCheckUpdate: () => void; onOpenUpdateModal?: () => void; checking: boolean; updateStatusMsg: string | null; updateStatusColor: string; version: string | null; commit?: string | null; isProxySettings?: boolean; proxyUpdate?: ProxyUpdateInfo | null; hasUpdate?: boolean;}
export function Header({ onAddAccount, onCheckUpdate, checking, updateStatusMsg, updateStatusColor, version, commit, isProxySettings, proxyUpdate }: HeaderProps) {export function Header({ onAddAccount, onCheckUpdate, onOpenUpdateModal, checking, updateStatusMsg, updateStatusColor, version, commit, isProxySettings, hasUpdate }: HeaderProps) { const { lang, toggleLang, t } = useI18n(); const { isDark, toggle: toggleTheme } = useTheme(); const [showChangelog, setShowChangelog] = useState(false);
return ( <header class="sticky top-0 z-50 w-full bg-white dark:bg-card-dark border-b border-gray-200 dark:border-border-dark shadow-sm transition-colors">45 unmodified lines href="https://github.com/icebear0828/codex-proxy" target="_blank" rel="noopener noreferrer" class="hidden md:flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-amber-50 border border-amber-200 text-amber-700 dark:bg-amber-900/20 dark:border-amber-700/30 dark:text-amber-400 hover:bg-amber-100 dark:hover:bg-amber-900/40 transition-colors" class="hidden lg:flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-amber-50 border border-amber-200 text-amber-700 dark:bg-amber-900/20 dark:border-amber-700/30 dark:text-amber-400 hover:bg-amber-100 dark:hover:bg-amber-900/40 transition-colors" > <svg class="size-3.5" viewBox="0 0 24 24" fill="currentColor"> <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /> </svg> <span class="text-xs font-semibold">{t("starOnGithub")}</span> <span class="text-xs font-semibold inline-grid"> <span class="invisible col-start-1 row-start-1">Star on GitHub</span> <span class="col-start-1 row-start-1">{t("starOnGithub")}</span> </span> </a> {/* Check for Updates */} <button onClick={onCheckUpdate} disabled={checking} class="hidden md:flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-gray-200 dark:border-border-dark text-slate-600 dark:text-text-dim hover:bg-slate-50 dark:hover:bg-border-dark disabled:opacity-50 disabled:cursor-not-allowed transition-colors" class="hidden lg:flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-gray-200 dark:border-border-dark text-slate-600 dark:text-text-dim hover:bg-slate-50 dark:hover:bg-border-dark disabled:opacity-50 disabled:cursor-not-allowed transition-colors" > <svg class={`size-3.5 ${checking ? "animate-spin" : ""}`} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.992 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182M20.985 4.356v4.992" /> </svg> <span class="text-xs font-semibold"> {checking ? t("checkingUpdates") : t("checkForUpdates")} <span class="text-xs font-semibold inline-grid"> <span class="invisible col-start-1 row-start-1">Check for Updates</span> <span class="col-start-1 row-start-1">{checking ? t("checkingUpdates") : t("checkForUpdates")}</span> </span> </button> {/* Update status message */} {updateStatusMsg && !checking && ( <button onClick={onCheckUpdate} class={`hidden md:inline text-xs font-medium ${updateStatusColor} hover:underline`} onClick={hasUpdate && onOpenUpdateModal ? onOpenUpdateModal : onCheckUpdate} class={`hidden lg:inline text-xs font-medium ${updateStatusColor} hover:underline`} > {updateStatusMsg} </button>2 unmodified lines <button onClick={toggleLang} class="p-2 rounded-lg text-slate-500 dark:text-text-dim hover:bg-slate-100 dark:hover:bg-border-dark transition-colors" title="\u4e2d/EN" title={"\u4e2d/EN"} > <span class="text-xs font-bold inline-flex items-center justify-center w-5">{lang === "en" ? "EN" : "\u4e2d"}</span> </button>15 unmodified lines <svg class="size-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 11-3 0m3 0a1.5 1.5 0 10-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-9.75 0h9.75" /> </svg> <span class="text-xs font-semibold">{t("proxySettings")}</span> <span class="text-xs font-semibold inline-grid"> <span class="invisible col-start-1 row-start-1">Proxy Assignment</span> <span class="col-start-1 row-start-1">{t("proxySettings")}</span> </span> </a> <button onClick={onAddAccount}12 unmodified lines </div> </div> </div> {/* Expandable update panel */} {proxyUpdate && proxyUpdate.updateAvailable && ( <div class="border-t border-amber-200 dark:border-amber-700/30 bg-amber-50/80 dark:bg-amber-900/10"> <div class="px-4 md:px-8 lg:px-40 flex justify-center"> <div class="w-full max-w-[960px] py-2"> <div class="flex items-center justify-between"> <span class="text-xs font-medium text-amber-700 dark:text-amber-400"> {proxyUpdate.mode === "git" ? `${proxyUpdate.commits.length} ${t("commits")} ${t("proxyBehind")}` : `${t("newVersion")} v${proxyUpdate.release?.version}`} </span> <button onClick={() => setShowChangelog(!showChangelog)} class="text-xs font-medium text-amber-600 dark:text-amber-400 hover:underline" > {showChangelog ? t("hideChanges") : t("viewChanges")} </button> </div> {showChangelog && ( <div class="mt-2"> {proxyUpdate.mode === "git" ? ( <> <ul class="space-y-0.5 text-xs text-slate-600 dark:text-text-dim max-h-48 overflow-y-auto"> {proxyUpdate.commits.map((c) => ( <li key={c.hash} class="flex gap-2"> <code class="text-primary/70 shrink-0">{c.hash}</code> <span>{c.message}</span> </li> ))} </ul> <button onClick={proxyUpdate.onApply} disabled={proxyUpdate.applying} class="mt-2 px-3 py-1.5 text-xs font-semibold bg-primary text-white rounded-md hover:bg-primary-hover disabled:opacity-50 transition-colors" > {proxyUpdate.applying ? t("applyingUpdate") : t("updateNow")} </button> </> ) : ( <> {proxyUpdate.release && ( <pre class="text-xs text-slate-600 dark:text-text-dim whitespace-pre-wrap max-h-48 overflow-y-auto mb-2"> {proxyUpdate.release.body} </pre> )} {proxyUpdate.mode === "docker" ? ( <div class="flex items-center gap-2"> <span class="text-xs text-slate-500 dark:text-text-dim">{t("dockerUpdateCmd")}</span> <code class="text-xs bg-slate-100 dark:bg-bg-dark px-2 py-0.5 rounded font-mono select-all"> docker compose up -d --build </code> </div> ) : ( <a href={proxyUpdate.release?.url} target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-primary text-white rounded-md hover:bg-primary-hover transition-colors" > {t("downloadUpdate")} </a> )} </> )} </div> )} </div> </div> </div> )} </header> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180import { useEffect, useRef } from "preact/hooks";import { useI18n } from "../../../shared/i18n/context";
interface UpdateModalProps { open: boolean; onClose: () => void; mode: "git" | "docker" | "electron"; commits: { hash: string; message: string }[]; release: { version: string; body: string; url: string } | null; onApply: () => void; applying: boolean; restarting: boolean; restartFailed: boolean;}
export function UpdateModal({ open, onClose, mode, commits, release, onApply, applying, restarting, restartFailed,}: UpdateModalProps) { const { t } = useI18n(); const dialogRef = useRef<HTMLDialogElement>(null);
useEffect(() => { const dialog = dialogRef.current; if (!dialog) return; if (open && !dialog.open) { dialog.showModal(); } else if (!open && dialog.open) { dialog.close(); } }, [open]);
// Close on backdrop click const handleBackdropClick = (e: MouseEvent) => { if (e.target === dialogRef.current && !restarting && !applying) { onClose(); } };
// Close on Escape const handleCancel = (e: Event) => { if (restarting || applying) { e.preventDefault(); } };
if (!open) return null;
return ( <dialog ref={dialogRef} onClick={handleBackdropClick} onCancel={handleCancel} class="backdrop:bg-black/50 bg-transparent p-0 m-auto max-w-lg w-full open:flex" > <div class="w-full bg-white dark:bg-card-dark rounded-xl shadow-2xl border border-gray-200 dark:border-border-dark overflow-hidden"> {/* Header */} <div class="px-5 py-4 border-b border-gray-200 dark:border-border-dark flex items-center justify-between"> <h2 class="text-base font-bold text-slate-800 dark:text-text-main"> {t("updateTitle")} </h2> {!restarting && !applying && ( <button onClick={onClose} class="p-1 rounded-md text-slate-400 hover:text-slate-600 dark:text-text-dim dark:hover:text-text-main hover:bg-slate-100 dark:hover:bg-border-dark transition-colors" > <svg class="size-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /> </svg> </button> )} </div>
{/* Body */} <div class="px-5 py-4"> {restarting ? ( <div class="flex flex-col items-center gap-3 py-6"> <svg class="size-8 animate-spin text-primary" viewBox="0 0 24 24" fill="none"> <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" /> <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /> </svg> <span class="text-sm font-medium text-slate-600 dark:text-text-dim"> {t("updateRestarting")} </span> </div> ) : restartFailed ? ( <div class="flex flex-col items-center gap-3 py-6"> <svg class="size-8 text-red-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /> </svg> <span class="text-sm font-medium text-red-600 dark:text-red-400"> {t("restartFailed")} </span> </div> ) : mode === "git" ? ( <ul class="space-y-1 text-sm text-slate-600 dark:text-text-dim max-h-64 overflow-y-auto"> {commits.map((c) => ( <li key={c.hash} class="flex gap-2 py-0.5"> <code class="text-primary/70 text-xs shrink-0 pt-0.5">{c.hash}</code> <span class="text-xs">{c.message}</span> </li> ))} </ul> ) : ( <> {release && ( <pre class="text-xs text-slate-600 dark:text-text-dim whitespace-pre-wrap max-h-64 overflow-y-auto leading-relaxed"> {release.body} </pre> )} </> )} </div>
{/* Footer */} {!restarting && !restartFailed && ( <div class="px-5 py-3 border-t border-gray-200 dark:border-border-dark flex items-center justify-end gap-2"> <button onClick={onClose} disabled={applying} class="px-4 py-2 text-xs font-semibold text-slate-600 dark:text-text-dim hover:bg-slate-100 dark:hover:bg-border-dark rounded-lg transition-colors disabled:opacity-50" > {t("cancelBtn")} </button> {mode === "git" ? ( <button onClick={onApply} disabled={applying} class="px-4 py-2 text-xs font-semibold bg-primary text-white rounded-lg hover:bg-primary-hover disabled:opacity-50 transition-colors flex items-center gap-1.5" > {applying && ( <svg class="size-3.5 animate-spin" viewBox="0 0 24 24" fill="none"> <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" /> <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /> </svg> )} {applying ? t("applyingUpdate") : t("updateNow")} </button> ) : mode === "docker" ? ( <button onClick={() => { navigator.clipboard.writeText("docker compose up -d --build"); }} class="px-4 py-2 text-xs font-semibold bg-primary text-white rounded-lg hover:bg-primary-hover transition-colors" > {t("copy")} docker compose up -d --build </button> ) : ( <a href={release?.url} target="_blank" rel="noopener noreferrer" class="px-4 py-2 text-xs font-semibold bg-primary text-white rounded-lg hover:bg-primary-hover transition-colors inline-flex" > {t("downloadUpdate")} </a> )} </div> )}
{/* Close button for restartFailed state */} {restartFailed && ( <div class="px-5 py-3 border-t border-gray-200 dark:border-border-dark flex justify-end"> <button onClick={onClose} class="px-4 py-2 text-xs font-semibold text-slate-600 dark:text-text-dim hover:bg-slate-100 dark:hover:bg-border-dark rounded-lg transition-colors" > {t("close")} </button> </div> )} </div> </dialog> );}77 unmodified lines7879808181828384858686878889909192939194959697989697991001011021031041051061071081091101111121131141151169911711811912012112212312412577 unmodified lines window.open(data.authUrl, "oauth_add", "width=600,height=700,scrollbars=yes"); setAddVisible(true);
// Poll for new account // Poll for new account + focus/visibility detection const prevResp = await fetch("/auth/accounts"); const prevData = await prevResp.json(); const prevCount = prevData.accounts?.length || 0;
const pollTimer = setInterval(async () => { let checking = false; const checkForNewAccount = async () => { if (checking) return; checking = true; try { const r = await fetch("/auth/accounts"); const d = await r.json(); if ((d.accounts?.length || 0) > prevCount) { clearInterval(pollTimer); cleanup(); setAddVisible(false); setAddInfo("accountAdded"); await loadAccounts(); } } catch {} }, 2000); } catch {} finally { checking = false; } };
// Focus event — check immediately when window regains focus const onFocus = () => { checkForNewAccount(); }; window.addEventListener("focus", onFocus);
// Visibility change — check when tab becomes visible const onVisible = () => { if (document.visibilityState === "visible") checkForNewAccount(); }; document.addEventListener("visibilitychange", onVisible);
// Interval polling as fallback const pollTimer = setInterval(checkForNewAccount, 2000);
setTimeout(() => clearInterval(pollTimer), 5 * 60 * 1000); const cleanup = () => { clearInterval(pollTimer); window.removeEventListener("focus", onFocus); document.removeEventListener("visibilitychange", onVisible); }; setTimeout(cleanup, 5 * 60 * 1000); } catch (err) { setAddError(err instanceof Error ? err.message : "failedStartLogin"); }