feat(desktop-client): give login and main views their own BrowserWindow

Spawn a separate window per mode keyed by a ?window= query param so each surface keeps its size, devtools, and renderer state independently. Logout now persists the cleared session and switches windows before awaiting the runtime release, avoiding a stale main-window flash on the way out.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-30 20:56:03 +08:00
parent cdd63db7f1
commit ed38721feb
7 changed files with 265 additions and 95 deletions
+146 -77
View File
@@ -66,14 +66,29 @@ process.on("uncaughtException", (error) => {
}); });
let mainWindow: ElectronBrowserWindow | null = null; let mainWindow: ElectronBrowserWindow | null = null;
let loginWindow: ElectronBrowserWindow | null = null;
let mainRendererContents: ElectronWebContents | null = null; let mainRendererContents: ElectronWebContents | null = null;
let quitReleaseInFlight = false; let quitReleaseInFlight = false;
type WindowMode = "login" | "main"; type WindowMode = "login" | "main";
type WindowModeSource = "auth-state" | "login" | "logout";
const WINDOW_SIZES: Record<WindowMode, { width: number; height: number; resizable: boolean }> = { interface WindowSizePreset {
login: { width: 340, height: 540, resizable: false }, width: number;
main: { width: 1320, height: 860, resizable: true }, height: number;
minWidth: number;
minHeight: number;
resizable: boolean;
}
interface WindowModeRequest {
source?: WindowModeSource;
animate?: boolean;
}
const WINDOW_SIZES: Record<WindowMode, WindowSizePreset> = {
login: { width: 340, height: 540, minWidth: 340, minHeight: 540, resizable: false },
main: { width: 1320, height: 860, minWidth: 900, minHeight: 600, resizable: true },
}; };
function windowModePath(): string { function windowModePath(): string {
@@ -102,39 +117,20 @@ function persistWindowMode(mode: WindowMode): void {
} }
let currentWindowMode: WindowMode = "login"; let currentWindowMode: WindowMode = "login";
let windowModeApplied = false;
function applyWindowMode(window: ElectronBrowserWindow, mode: WindowMode): void { function normalizeWindowModeRequest(input: unknown): WindowModeRequest {
const isFirstApply = !windowModeApplied; if (!input || typeof input !== "object") {
const sameMode = windowModeApplied && currentWindowMode === mode; return {};
if (!sameMode) {
currentWindowMode = mode;
persistWindowMode(mode);
const target = WINDOW_SIZES[mode];
window.setResizable(true);
window.setMinimumSize(1, 1);
window.setMaximumSize(0, 0);
window.setSize(target.width, target.height, false);
window.center();
if (mode === "login") {
window.setMinimumSize(target.width, target.height);
window.setMaximumSize(target.width, target.height);
window.setResizable(false);
} else {
window.setMinimumSize(800, 600);
window.setResizable(true);
}
} }
windowModeApplied = true; const candidate = input as { source?: unknown; animate?: unknown };
return {
if (isFirstApply || !window.isVisible()) { source:
window.show(); candidate.source === "login" || candidate.source === "logout" || candidate.source === "auth-state"
window.focus(); ? candidate.source
} : undefined,
animate: candidate.animate === true,
};
} }
function currentMainWindow(): ElectronBrowserWindow | null { function currentMainWindow(): ElectronBrowserWindow | null {
@@ -143,12 +139,34 @@ function currentMainWindow(): ElectronBrowserWindow | null {
} }
if (mainWindow.isDestroyed()) { if (mainWindow.isDestroyed()) {
mainWindow = null; mainWindow = null;
windowModeApplied = false;
return null; return null;
} }
return mainWindow; return mainWindow;
} }
function currentLoginWindow(): ElectronBrowserWindow | null {
if (!loginWindow) {
return null;
}
if (loginWindow.isDestroyed()) {
loginWindow = null;
return null;
}
return loginWindow;
}
function currentActiveWindow(): ElectronBrowserWindow | null {
return currentMainWindow() ?? currentLoginWindow();
}
function closeWindowAfterIpcReturn(window: ElectronBrowserWindow): void {
setTimeout(() => {
if (!window.isDestroyed()) {
window.close();
}
}, 50);
}
function captureRuntimeSnapshot() { function captureRuntimeSnapshot() {
const snapshot = createRuntimeSnapshot(); const snapshot = createRuntimeSnapshot();
applyDesktopHealthIndicatorFromSnapshot(snapshot, currentMainWindow()); applyDesktopHealthIndicatorFromSnapshot(snapshot, currentMainWindow());
@@ -164,17 +182,29 @@ async function ensureMainWindow(): Promise<ElectronBrowserWindow> {
if (existing) { if (existing) {
return existing; return existing;
} }
const window = await createMainWindow(); const window = await createAppWindow("main");
mainWindow = window; mainWindow = window;
return window; return window;
} }
async function revealMainWindow(): Promise<void> { async function ensureLoginWindow(): Promise<ElectronBrowserWindow> {
const window = await ensureMainWindow(); const existing = currentLoginWindow();
if (existing) {
return existing;
}
const window = await createAppWindow("login");
loginWindow = window;
return window;
}
async function ensureWindow(mode: WindowMode): Promise<ElectronBrowserWindow> {
return mode === "main" ? ensureMainWindow() : ensureLoginWindow();
}
async function revealWindow(window: ElectronBrowserWindow): Promise<void> {
if (window.isMinimized()) { if (window.isMinimized()) {
window.restore(); window.restore();
} }
applyWindowMode(window, currentWindowMode);
if (!window.isVisible()) { if (!window.isVisible()) {
window.show(); window.show();
} }
@@ -182,12 +212,34 @@ async function revealMainWindow(): Promise<void> {
app.focus({ steal: true }); app.focus({ steal: true });
} }
function revealMainWindowSafely(source: string): void { async function revealActiveWindow(): Promise<void> {
void revealMainWindow().catch((error) => { const window = currentActiveWindow() ?? await ensureWindow(currentWindowMode);
console.error("[desktop-main] reveal main window failed", { source, error }); await revealWindow(window);
}
function revealActiveWindowSafely(source: string): void {
void revealActiveWindow().catch((error) => {
console.error("[desktop-main] reveal active window failed", { source, error });
}); });
} }
async function switchWindowMode(mode: WindowMode, _request: WindowModeRequest = {}): Promise<void> {
currentWindowMode = mode;
persistWindowMode(mode);
const target = await ensureWindow(mode);
const previous = mode === "main" ? currentLoginWindow() : currentMainWindow();
if (!target.isVisible()) {
target.center();
}
await revealWindow(target);
if (previous && previous !== target && !previous.isDestroyed()) {
closeWindowAfterIpcReturn(previous);
}
}
function rendererURL(): string | null { function rendererURL(): string | null {
return process.env.ELECTRON_RENDERER_URL ?? null; return process.env.ELECTRON_RENDERER_URL ?? null;
} }
@@ -196,40 +248,57 @@ function preloadPath(): string {
return join(__dirname, "../preload/bridge.cjs"); return join(__dirname, "../preload/bridge.cjs");
} }
async function mountRendererWebContents(window: ElectronBrowserWindow): Promise<void> { async function loadRenderer(window: ElectronBrowserWindow, mode: WindowMode): Promise<void> {
const contents = window.webContents;
contents.setWindowOpenHandler(() => ({ action: "deny" }));
registerRendererDevtoolsProxyTarget(contents);
registerObservedRequestRendererTarget(contents);
mainRendererContents = contents;
window.on("closed", () => {
if (mainRendererContents === contents) {
mainRendererContents = null;
}
});
const devServerURL = rendererURL(); const devServerURL = rendererURL();
if (devServerURL) { if (devServerURL) {
await contents.loadURL(devServerURL); const url = new URL(devServerURL);
contents.openDevTools({ mode: "detach" }); url.searchParams.set("window", mode);
await window.webContents.loadURL(url.toString());
if (mode === "main") {
window.webContents.openDevTools({ mode: "detach" });
}
return; return;
} }
await contents.loadFile(join(__dirname, "../renderer/index.html")); await window.webContents.loadFile(join(__dirname, "../renderer/index.html"), {
query: { window: mode },
});
} }
async function createMainWindow(): Promise<ElectronBrowserWindow> { async function mountRendererWebContents(window: ElectronBrowserWindow, mode: WindowMode): Promise<void> {
const initial = WINDOW_SIZES[currentWindowMode]; const contents = window.webContents;
contents.setWindowOpenHandler(() => ({ action: "deny" }));
if (mode === "main") {
registerRendererDevtoolsProxyTarget(contents);
registerObservedRequestRendererTarget(contents);
mainRendererContents = contents;
window.on("closed", () => {
if (mainRendererContents === contents) {
mainRendererContents = null;
}
});
}
await loadRenderer(window, mode);
}
async function createAppWindow(mode: WindowMode): Promise<ElectronBrowserWindow> {
const initial = WINDOW_SIZES[mode];
const window = new BrowserWindow({ const window = new BrowserWindow({
width: initial.width, width: initial.width,
height: initial.height, height: initial.height,
minWidth: initial.minWidth,
minHeight: initial.minHeight,
show: false, show: false,
title: "GEO Rankly Desktop", title: "GEO Rankly Desktop",
icon: createDesktopHealthIcon("normal"), icon: createDesktopHealthIcon("normal"),
titleBarStyle: "hiddenInset", titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 12, y: 14 }, trafficLightPosition: { x: 12, y: 14 },
backgroundColor: nativeTheme.shouldUseDarkColors ? "#15191a" : "#eaf2ff", resizable: initial.resizable,
maximizable: initial.resizable,
fullscreenable: initial.resizable,
backgroundColor: mode === "login" ? "#eaf2ff" : nativeTheme.shouldUseDarkColors ? "#15191a" : "#f0f2f5",
webPreferences: { webPreferences: {
preload: preloadPath(), preload: preloadPath(),
sandbox: true, sandbox: true,
@@ -238,16 +307,17 @@ async function createMainWindow(): Promise<ElectronBrowserWindow> {
}, },
}); });
const fallbackReveal = setTimeout(() => { if (!initial.resizable) {
if (!windowModeApplied && !window.isDestroyed()) { window.setMinimumSize(initial.minWidth, initial.minHeight);
applyWindowMode(window, currentWindowMode); window.setMaximumSize(initial.width, initial.height);
} }
}, 1500);
window.once("closed", () => { window.once("closed", () => {
clearTimeout(fallbackReveal); if (mode === "main" && mainWindow === window) {
if (mainWindow === window) {
mainWindow = null; mainWindow = null;
windowModeApplied = false; }
if (mode === "login" && loginWindow === window) {
loginWindow = null;
} }
}); });
@@ -271,7 +341,7 @@ async function createMainWindow(): Promise<ElectronBrowserWindow> {
}); });
}); });
await mountRendererWebContents(window); await mountRendererWebContents(window, mode);
return window; return window;
} }
@@ -391,17 +461,16 @@ function registerBridgeHandlers(): void {
await releaseRuntimeSession({ revoke: Boolean(revoke) }); await releaseRuntimeSession({ revoke: Boolean(revoke) });
return null; return null;
}); });
ipcMain.handle("desktop:set-window-mode", (_event, mode: WindowMode) => { ipcMain.handle("desktop:set-window-mode", async (_event, mode: WindowMode, request?: unknown) => {
const window = currentMainWindow(); if (mode === "login" || mode === "main") {
if (window && (mode === "login" || mode === "main")) { await switchWindowMode(mode, normalizeWindowModeRequest(request));
applyWindowMode(window, mode);
} }
return null; return null;
}); });
} }
const hasSingleInstanceLock = initSingleInstance(() => { const hasSingleInstanceLock = initSingleInstance(() => {
revealMainWindowSafely("single-instance"); revealActiveWindowSafely("single-instance");
}); });
if (!hasSingleInstanceLock) { if (!hasSingleInstanceLock) {
@@ -425,9 +494,9 @@ if (!hasSingleInstanceLock) {
} }
mainRendererContents.send("desktop:runtime-invalidated", event); mainRendererContents.send("desktop:runtime-invalidated", event);
}); });
await ensureMainWindow(); await switchWindowMode(currentWindowMode);
initTray(() => { initTray(() => {
revealMainWindowSafely("tray"); revealActiveWindowSafely("tray");
}); });
startDesktopHealthIndicator(() => currentMainWindow()); startDesktopHealthIndicator(() => currentMainWindow());
}).catch((error) => { }).catch((error) => {
@@ -435,7 +504,7 @@ if (!hasSingleInstanceLock) {
}); });
app.on("activate", () => { app.on("activate", () => {
revealMainWindowSafely("activate"); revealActiveWindowSafely("activate");
}); });
app.on("window-all-closed", () => { app.on("window-all-closed", () => {
+7 -2
View File
@@ -22,6 +22,11 @@ interface DesktopClientIDScope {
user_id: number; user_id: number;
} }
interface WindowModeRequest {
source?: "auth-state" | "login" | "logout";
animate?: boolean;
}
const rendererProxyRequestChannel = "desktop:renderer-devtools-proxy:request"; const rendererProxyRequestChannel = "desktop:renderer-devtools-proxy:request";
const rendererProxyResponseChannel = "desktop:renderer-devtools-proxy:response"; const rendererProxyResponseChannel = "desktop:renderer-devtools-proxy:response";
@@ -119,8 +124,8 @@ const desktopBridge = {
ipcRenderer.invoke("desktop:runtime-session-sync", session) as Promise<null>, ipcRenderer.invoke("desktop:runtime-session-sync", session) as Promise<null>,
releaseRuntimeSession: (revoke?: boolean) => releaseRuntimeSession: (revoke?: boolean) =>
ipcRenderer.invoke("desktop:runtime-session-release", revoke) as Promise<null>, ipcRenderer.invoke("desktop:runtime-session-release", revoke) as Promise<null>,
setWindowMode: (mode: "login" | "main") => setWindowMode: (mode: "login" | "main", request?: WindowModeRequest) =>
ipcRenderer.invoke("desktop:set-window-mode", mode) as Promise<null>, ipcRenderer.invoke("desktop:set-window-mode", mode, request) as Promise<null>,
onRuntimeInvalidated: ( onRuntimeInvalidated: (
listener: (event: { reason: "account-health"; at: number; accountId?: string }) => void, listener: (event: { reason: "account-health"; at: number; accountId?: string }) => void,
) => { ) => {
+40 -10
View File
@@ -1,14 +1,23 @@
<script setup lang="ts"> <script setup lang="ts">
import { defineAsyncComponent, onMounted, watch } from "vue"; import { computed, defineAsyncComponent, onMounted, watch } from "vue";
import { useDesktopSession } from "./composables/useDesktopSession"; import { useDesktopSession } from "./composables/useDesktopSession";
const DesktopShell = defineAsyncComponent(() => import("./components/DesktopShell.vue")); const DesktopShell = defineAsyncComponent(() => import("./components/DesktopShell.vue"));
const LoginView = defineAsyncComponent(() => import("./views/LoginView.vue")); const LoginView = defineAsyncComponent(() => import("./views/LoginView.vue"));
const { isAuthenticated, syncRuntimeSession } = useDesktopSession(); const { isAuthenticated, syncRuntimeSession } = useDesktopSession();
type RendererWindowMode = "auto" | "login" | "main";
interface WindowModeBridge { interface WindowModeBridge {
setWindowMode?: (mode: "login" | "main") => Promise<unknown>; setWindowMode?: (
mode: "login" | "main",
request?: { source?: "auth-state" | "login" | "logout"; animate?: boolean },
) => Promise<unknown>;
}
function resolveRendererWindowMode(): RendererWindowMode {
const mode = new URLSearchParams(window.location.search).get("window");
return mode === "login" || mode === "main" ? mode : "auto";
} }
function getModeBridge(): WindowModeBridge | undefined { function getModeBridge(): WindowModeBridge | undefined {
@@ -18,21 +27,42 @@ function getModeBridge(): WindowModeBridge | undefined {
} }
function syncWindowMode(authenticated: boolean): void { function syncWindowMode(authenticated: boolean): void {
void getModeBridge()?.setWindowMode?.(authenticated ? "main" : "login"); void getModeBridge()?.setWindowMode?.(authenticated ? "main" : "login", { source: "auth-state" });
} }
// Fire immediately during setup so the main process can size + reveal the const rendererWindowMode = resolveRendererWindowMode();
// window before the user sees any "wrong-sized" frame. const usesAutomaticWindowMode = rendererWindowMode === "auto";
syncWindowMode(isAuthenticated.value); const showsMainSurface = computed(() =>
watch(isAuthenticated, (next) => syncWindowMode(next)); rendererWindowMode === "main" || (rendererWindowMode === "auto" && isAuthenticated.value),
);
if (usesAutomaticWindowMode) {
syncWindowMode(isAuthenticated.value);
watch(isAuthenticated, (next) => syncWindowMode(next));
}
if (rendererWindowMode === "main") {
if (!isAuthenticated.value) {
syncWindowMode(false);
}
watch(isAuthenticated, (next) => {
if (!next) {
syncWindowMode(false);
}
});
}
onMounted(() => { onMounted(() => {
void syncRuntimeSession(); if (rendererWindowMode !== "login") {
syncWindowMode(isAuthenticated.value); void syncRuntimeSession();
}
if (usesAutomaticWindowMode) {
syncWindowMode(isAuthenticated.value);
}
}); });
</script> </script>
<template> <template>
<DesktopShell v-if="isAuthenticated" /> <DesktopShell v-if="showsMainSurface" />
<LoginView v-else /> <LoginView v-else />
</template> </template>
@@ -477,6 +477,7 @@ h1 {
.content { .content {
flex: 1; flex: 1;
min-width: 0;
height: 100vh; height: 100vh;
padding: 24px 32px; padding: 24px 32px;
overflow-y: auto; overflow-y: auto;
@@ -39,6 +39,7 @@ const apiBaseURL = shallowRef(readStoredApiBaseURL());
const pending = shallowRef(false); const pending = shallowRef(false);
const error = shallowRef<string | null>(null); const error = shallowRef<string | null>(null);
let loginPromise: Promise<void> | null = null; let loginPromise: Promise<void> | null = null;
let logoutPromise: Promise<void> | null = null;
function readStoredSession(): DesktopSession | null { function readStoredSession(): DesktopSession | null {
if (typeof window === "undefined") { if (typeof window === "undefined") {
@@ -132,6 +133,39 @@ function createAuthenticatedClient() {
}); });
} }
function createSessionBoundAuthenticatedClient(source: DesktopSession) {
let accessToken = source.accessToken;
let refreshToken = source.refreshToken;
return createApiClient({
baseURL: apiBaseURL.value,
timeoutMs: 15000,
auth: {
getAccessToken: () => accessToken,
getRefreshToken: () => refreshToken,
setTokens: (tokens: AuthTokens) => {
accessToken = tokens.accessToken;
refreshToken = tokens.refreshToken;
},
clearTokens: () => {
accessToken = null;
refreshToken = null;
},
async refresh(refreshTokenValue: string): Promise<AuthTokens> {
const next = await createPublicClient().post<RefreshResponse, { refresh_token: string }>(
"/api/auth/refresh",
{ refresh_token: refreshTokenValue },
);
return {
accessToken: next.access_token,
refreshToken: next.refresh_token,
};
},
},
});
}
function resolveFallbackPlatform(): string { function resolveFallbackPlatform(): string {
const currentNavigator = globalThis.navigator as Navigator & { const currentNavigator = globalThis.navigator as Navigator & {
userAgentData?: { platform?: string }; userAgentData?: { platform?: string };
@@ -416,10 +450,7 @@ async function enterPreview(): Promise<void> {
}); });
} }
async function logout(): Promise<void> { async function releaseSessionForLogout(current: DesktopSession | null): Promise<void> {
error.value = null;
const current = session.value;
if (current?.mode === "authenticated") { if (current?.mode === "authenticated") {
try { try {
await window.desktopBridge?.app?.releaseRuntimeSession?.(true); await window.desktopBridge?.app?.releaseRuntimeSession?.(true);
@@ -428,13 +459,43 @@ async function logout(): Promise<void> {
} }
try { try {
await createAuthenticatedClient().post<null, Record<string, never>>("/api/auth/logout", {}); await createSessionBoundAuthenticatedClient(current).post<null, Record<string, never>>("/api/auth/logout", {});
} catch (err) { } catch (err) {
console.warn("[desktop-session] auth logout failed", err); console.warn("[desktop-session] auth logout failed", err);
} }
} }
}
async function transitionWindowForLogout(): Promise<void> {
try {
await window.desktopBridge?.app?.setWindowMode?.("login", { source: "logout", animate: true });
} catch (err) {
console.warn("[desktop-session] logout window transition failed", err);
}
}
async function performLogout(): Promise<void> {
error.value = null;
const current = session.value;
const releasePromise = releaseSessionForLogout(current);
persistSession(null); persistSession(null);
await transitionWindowForLogout();
void releasePromise.catch((err) => {
console.warn("[desktop-session] background logout release failed", err);
});
}
async function logout(): Promise<void> {
if (logoutPromise) {
return logoutPromise;
}
logoutPromise = performLogout().finally(() => {
logoutPromise = null;
});
return logoutPromise;
} }
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
+4 -1
View File
@@ -42,7 +42,10 @@ declare global {
openExternalUrl(url: string): Promise<null>; openExternalUrl(url: string): Promise<null>;
syncRuntimeSession(session: DesktopRuntimeSessionSyncRequest | null): Promise<null>; syncRuntimeSession(session: DesktopRuntimeSessionSyncRequest | null): Promise<null>;
releaseRuntimeSession(revoke?: boolean): Promise<null>; releaseRuntimeSession(revoke?: boolean): Promise<null>;
setWindowMode(mode: "login" | "main"): Promise<null>; setWindowMode(mode: "login" | "main", request?: {
source?: "auth-state" | "login" | "logout";
animate?: boolean;
}): Promise<null>;
onRuntimeInvalidated( onRuntimeInvalidated(
listener: (event: { reason: "account-health"; at: number; accountId?: string }) => void, listener: (event: { reason: "account-health"; at: number; accountId?: string }) => void,
): () => void; ): () => void;
@@ -61,6 +61,7 @@ async function submitLogin() {
email: form.email, email: form.email,
password: form.password, password: form.password,
}); });
await window.desktopBridge?.app?.setWindowMode?.("main", { source: "login" });
} }
onMounted(() => { onMounted(() => {