Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-4817: open issue tabs in dedicated windows (#5462)

Jiayuan Zhangf8654b37c0e0
diff --git a/apps/desktop/src/main/auth-session-coordinator.test.ts b/apps/desktop/src/main/auth-session-coordinator.test.ts
new file mode 100644
index 0000000000..e1cd67f389
--- /dev/null
+++ b/apps/desktop/src/main/auth-session-coordinator.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ AuthSessionCoordinator,
+ parseAuthSessionUserId,
+} from "./auth-session-coordinator";
+
+describe("AuthSessionCoordinator", () => {
+ it("keeps an issue window whose account matches the main window", () => {
+ const close = vi.fn();
+ const coordinator = new AuthSessionCoordinator<string>(close);
+ coordinator.reportMain("user-a");
+ coordinator.registerIssueWindow("issue-1");
+ coordinator.reportIssue("issue-1", "user-a");
+
+ expect(close).not.toHaveBeenCalled();
+ expect(coordinator.hasActiveMainSession()).toBe(true);
+ expect(coordinator.isCurrentIssueSession("issue-1")).toBe(true);
+ });
+
+ it("closes every issue window on main logout or account switch", () => {
+ const close = vi.fn();
+ const coordinator = new AuthSessionCoordinator<string>(close);
+ coordinator.reportMain("user-a");
+ coordinator.registerIssueWindow("issue-1");
+ coordinator.registerIssueWindow("issue-2");
+
+ coordinator.reportMain("user-b");
+
+ expect(close).toHaveBeenCalledTimes(2);
+ expect(close).toHaveBeenCalledWith("issue-1");
+ expect(close).toHaveBeenCalledWith("issue-2");
+ });
+
+ it("invalidates account-scoped work once per session transition", () => {
+ const coordinator = new AuthSessionCoordinator<string>(() => {});
+
+ expect(coordinator.reportMain("user-a")).toBe(false);
+ expect(coordinator.reportMain("user-a")).toBe(false);
+ expect(coordinator.reportMain(null)).toBe(true);
+ expect(coordinator.reportMain(null)).toBe(false);
+ expect(coordinator.reportMain("user-b")).toBe(true);
+ });
+
+ it("closes an issue renderer that reports a stale or missing session", () => {
+ const close = vi.fn();
+ const coordinator = new AuthSessionCoordinator<string>(close);
+ coordinator.reportMain("user-a");
+ coordinator.registerIssueWindow("stale");
+ coordinator.registerIssueWindow("logged-out");
+
+ coordinator.reportIssue("stale", "user-b");
+ coordinator.reportIssue("logged-out", null);
+
+ expect(close).toHaveBeenCalledTimes(2);
+ expect(coordinator.isCurrentIssueSession("stale")).toBe(false);
+ });
+});
+
+describe("parseAuthSessionUserId", () => {
+ it("accepts a bounded user id or explicit logged-out state", () => {
+ expect(parseAuthSessionUserId(" user-a ")).toBe("user-a");
+ expect(parseAuthSessionUserId(null)).toBeNull();
+ expect(parseAuthSessionUserId(" ")).toBeUndefined();
+ expect(parseAuthSessionUserId(42)).toBeUndefined();
+ expect(parseAuthSessionUserId("x".repeat(257))).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/auth-session-coordinator.ts b/apps/desktop/src/main/auth-session-coordinator.ts
new file mode 100644
index 0000000000..1366e8121c
--- /dev/null
+++ b/apps/desktop/src/main/auth-session-coordinator.ts
@@ -0,0 +1,81 @@
+import type { AuthSessionUserId } from "../shared/auth-session";
+
+export {
+ AUTH_SESSION_STATE_CHANNEL,
+ parseAuthSessionUserId,
+} from "../shared/auth-session";
+
+/**
+ * Keeps dedicated issue windows bound to the main window's authenticated
+ * account. Tokens never cross renderer boundaries: only the resolved user id
+ * is compared, and stale issue windows are closed on logout/account switch.
+ */
+export class AuthSessionCoordinator<T> {
+ private mainUserId: AuthSessionUserId | undefined;
+ private readonly issueUserIds = new Map<
+ T,
+ AuthSessionUserId | undefined
+ >();
+
+ constructor(private readonly closeIssueWindow: (window: T) => void) {}
+
+ registerIssueWindow(window: T): void {
+ this.issueUserIds.set(window, undefined);
+ }
+
+ unregisterIssueWindow(window: T): void {
+ this.issueUserIds.delete(window);
+ }
+
+ hasActiveMainSession(): boolean {
+ return typeof this.mainUserId === "string";
+ }
+
+ isCurrentIssueSession(window: T): boolean {
+ return (
+ typeof this.mainUserId === "string" &&
+ this.issueUserIds.get(window) === this.mainUserId
+ );
+ }
+
+ reportMain(userId: AuthSessionUserId): boolean {
+ const becameLoggedOut = userId === null && this.mainUserId !== null;
+ const accountChanged =
+ this.mainUserId !== undefined && this.mainUserId !== userId;
+ this.mainUserId = userId;
+
+ if (userId === null || accountChanged) {
+ this.closeAllIssueWindows();
+ return becameLoggedOut || accountChanged;
+ }
+
+ for (const [window, issueUserId] of this.issueUserIds) {
+ if (issueUserId !== undefined && issueUserId !== userId) {
+ this.closeIssue(window);
+ }
+ }
+ return false;
+ }
+
+ reportIssue(window: T, userId: AuthSessionUserId): void {
+ if (!this.issueUserIds.has(window)) return;
+ this.issueUserIds.set(window, userId);
+ if (
+ userId === null ||
+ (this.mainUserId !== undefined && this.mainUserId !== userId)
+ ) {
+ this.closeIssue(window);
+ }
+ }
+
+ private closeAllIssueWindows(): void {
+ for (const window of [...this.issueUserIds.keys()]) {
+ this.closeIssue(window);
+ }
+ }
+
+ private closeIssue(window: T): void {
+ this.issueUserIds.delete(window);
+ this.closeIssueWindow(window);
+ }
+}
diff --git a/apps/desktop/src/main/freeze-breadcrumb.test.ts b/apps/desktop/src/main/freeze-breadcrumb.test.ts
index 1d2a8b4089..e24f3cc5c4 100644
--- a/apps/desktop/src/main/freeze-breadcrumb.test.ts
+++ b/apps/desktop/src/main/freeze-breadcrumb.test.ts
@@ -50,6 +50,17 @@ describe("freeze breadcrumb round-trip", () => {
clearFreezeBreadcrumb(file);
expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
});
+
+ it("only lets the window that wrote a breadcrumb clear it", () => {
+ const file = tempFile();
+ writeFreezeBreadcrumb(file, { ...sample, ownerId: "issue:2" });
+
+ clearFreezeBreadcrumb(file, "main:1");
+ expect(existsSync(file)).toBe(true);
+
+ clearFreezeBreadcrumb(file, "issue:2");
+ expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ });
});
// The breadcrumb crosses a process boundary (main writes, renderer flushes via
diff --git a/apps/desktop/src/main/freeze-breadcrumb.ts b/apps/desktop/src/main/freeze-breadcrumb.ts
index 33cb0eb9be..e49ec01239 100644
--- a/apps/desktop/src/main/freeze-breadcrumb.ts
+++ b/apps/desktop/src/main/freeze-breadcrumb.ts
@@ -35,8 +35,18 @@ export function writeFreezeBreadcrumb(filePath: string, breadcrumb: FreezeBreadc
* would double-count it AND mislabel a recovered window as `recovered: false`.
* Best-effort; a stale breadcrumb only costs one duplicate report.
*/
-export function clearFreezeBreadcrumb(filePath: string): void {
+export function clearFreezeBreadcrumb(filePath: string, ownerId?: string): void {
try {
+ if (ownerId !== undefined) {
+ const parsed = JSON.parse(readFileSync(filePath, "utf8")) as unknown;
+ if (
+ !parsed ||
+ typeof parsed !== "object" ||
+ (parsed as FreezeBreadcrumb).ownerId !== ownerId
+ ) {
+ return;
+ }
+ }
rmSync(filePath, { force: true });
} catch {
// Nothing to clear / permissions — ignore.
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index e5bacb3b12..7c517a6ad3 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -28,6 +28,26 @@ import {
readAndClearFreezeBreadcrumb,
clearFreezeBreadcrumb,
} from "./freeze-breadcrumb";
+import {
+ encodeIssueWindowArgument,
+ parseIssueWindowRequest,
+ type IssueWindowContext,
+} from "../shared/issue-window";
+import {
+ AUTH_SESSION_STATE_CHANNEL,
+ parseAuthSessionUserId,
+} from "../shared/auth-session";
+import {
+ MAIN_RENDERER_CHANNEL_STATE_CHANNEL,
+ MainRendererMessageQueue,
+ parseMainRendererChannelState,
+ type MainRendererMessageChannel,
+} from "../shared/main-renderer-messages";
+import { AuthSessionCoordinator } from "./auth-session-coordinator";
+import {
+ NotificationGate,
+ parseNativeNotificationPayload,
+} from "./notification-gate";
// Guards against registering the will-download handler more than once on the
// same session. window.webContents.session is shared, and createWindow() can
@@ -95,7 +115,21 @@ function freezeBreadcrumbPath(): string {
}
let mainWindow: BrowserWindow | null = null;
-let latestRendererRouteContext: RendererRouteContext | null = null;
+const issueWindows = new Set<BrowserWindow>();
+const authSessionCoordinator = new AuthSessionCoordinator<BrowserWindow>(
+ (window) => {
+ issueWindows.delete(window);
+ if (!window.isDestroyed()) window.close();
+ },
+);
+const notificationGate = new NotificationGate();
+const mainRendererMessages = new MainRendererMessageQueue();
+let desktopInitialized = false;
+let authSessionGeneration = 0;
+const rendererRouteContexts = new WeakMap<
+ Electron.WebContents,
+ RendererRouteContext
+>();
let runtimeConfigResult: RuntimeConfigResult = {
ok: false,
error: { message: "Runtime config has not loaded yet" },
@@ -103,6 +137,36 @@ let runtimeConfigResult: RuntimeConfigResult = {
// --- Deep link helpers ---------------------------------------------------
+function sendMainRendererMessage(
+ channel: MainRendererMessageChannel,
+ payload: unknown,
+): void {
+ const window = mainWindow;
+ if (!window || window.isDestroyed()) return;
+ window.webContents.send(channel, payload);
+}
+
+function focusMainWindow(window: BrowserWindow): void {
+ if (window.isMinimized()) window.restore();
+ window.show();
+ window.focus();
+}
+
+function ensureMainWindow(): BrowserWindow | null {
+ if (!desktopInitialized || !app.isReady()) return null;
+ if (!mainWindow || mainWindow.isDestroyed()) return createWindow();
+ return mainWindow;
+}
+
+function dispatchToMainRenderer(
+ channel: MainRendererMessageChannel,
+ payload: unknown,
+): void {
+ mainRendererMessages.enqueue(channel, payload, sendMainRendererMessage);
+ const window = ensureMainWindow();
+ if (window) focusMainWindow(window);
+}
+
function handleDeepLink(url: string): void {
try {
const parsed = new URL(url);
@@ -111,9 +175,7 @@ function handleDeepLink(url: string): void {
// multica://auth/callback?token=<jwt>
if (parsed.hostname === "auth" && parsed.pathname === "/callback") {
const token = parsed.searchParams.get("token");
- if (token && mainWindow) {
- mainWindow.webContents.send("auth:token", token);
- }
+ if (token) dispatchToMainRenderer("auth:token", token);
return;
}
@@ -123,9 +185,7 @@ function handleDeepLink(url: string): void {
// route persistence, so deep-linking the same invite twice stays safe.
if (parsed.hostname === "invite") {
const id = parsed.pathname.replace(/^\//, "");
- if (id && mainWindow) {
- mainWindow.webContents.send("invite:open", decodeURIComponent(id));
- }
+ if (id) dispatchToMainRenderer("invite:open", decodeURIComponent(id));
return;
}
} catch {
@@ -146,7 +206,77 @@ function getSystemLocale(): string {
return app.getPreferredSystemLanguages()[0] ?? "en";
}
-function createWindow(): void {
+function createRendererWebPreferences(
+ systemLocale: string,
+ additionalArguments: string[] = [],
+): Electron.WebPreferences {
+ return {
+ preload: join(__dirname, "../preload/index.js"),
+ sandbox: false,
+ webSecurity: false,
+ // Required for the Chromium PDF viewer (PDFium) to activate inside
+ // iframes — used by the attachment preview modal for application/pdf
+ // files. Default is false in Electron; without it <iframe src=*.pdf>
+ // renders blank.
+ //
+ // Security trade-off, accepted intentionally:
+ // 1. These windows already run with `webSecurity: false` +
+ // `sandbox: false`, so `plugins: true` does not meaningfully widen
+ // the renderer's attack surface beyond what is already accepted.
+ // 2. The only PDFs that reach an iframe here are signed CloudFront URLs
+ // we ourselves issued (see useDownloadAttachment); user-supplied URLs
+ // are routed through `setWindowOpenHandler` → `openExternalSafely` and
+ // cannot land in this renderer.
+ // 3. Chromium's PDFium plugin is itself sandboxed inside its own process
+ // and only handles the `application/pdf` MIME.
+ //
+ // If we ever tighten `webSecurity` / `sandbox`, revisit this by hosting
+ // the PDF viewer in a dedicated BrowserView with `plugins: true` scoped
+ // to that view, keeping the main renderer plugin-free.
+ plugins: true,
+ additionalArguments: [
+ `--multica-locale=${systemLocale}`,
+ ...additionalArguments,
+ ],
+ };
+}
+
+function loadRenderer(window: BrowserWindow): void {
+ if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
+ void window.loadURL(process.env["ELECTRON_RENDERER_URL"]);
+ } else {
+ void window.loadFile(join(__dirname, "../renderer/index.html"));
+ }
+}
+
+function installLocaleRefresh(window: BrowserWindow): void {
+ // Electron has no dedicated OS-language event. Check whenever any Multica
+ // window regains focus, then broadcast so all open windows remain aligned.
+ window.on("focus", () => {
+ const current = getSystemLocale();
+ if (current === lastKnownSystemLocale) return;
+ lastKnownSystemLocale = current;
+ for (const target of BrowserWindow.getAllWindows()) {
+ if (!target.isDestroyed()) {
+ target.webContents.send("locale:system-changed", current);
+ }
+ }
+ });
+}
+
+function installWindowShortcutHandler(window: BrowserWindow): void {
+ window.webContents.on("before-input-event", (event, input) => {
+ const result = handleAppShortcut(input, window.webContents);
+ if (result === "close-tab") {
+ event.preventDefault();
+ window.webContents.send("tab:close-active");
+ } else if (result) {
+ event.preventDefault();
+ }
+ });
+}
+
+function createWindow(): BrowserWindow {
// Pass the OS-preferred language to the renderer via additionalArguments
// instead of a sync IPC call. process.argv is available to the preload
// script before the first network request, so the renderer's i18next
@@ -154,6 +284,7 @@ function createWindow(): void {
const systemLocale = getSystemLocale();
lastKnownSystemLocale = systemLocale;
+ mainRendererMessages.resetReady();
mainWindow = new BrowserWindow({
width: 1280,
height: 800,
@@ -171,41 +302,14 @@ function createWindow(): void {
...(is.dev || process.platform === "linux"
? { icon: BUNDLED_ICON_PATH }
: {}),
- webPreferences: {
- preload: join(__dirname, "../preload/index.js"),
- sandbox: false,
- webSecurity: false,
- // Required for the Chromium PDF viewer (PDFium) to activate inside
- // iframes — used by the attachment preview modal for application/pdf
- // files. Default is false in Electron; without it <iframe src=*.pdf>
- // renders blank.
- //
- // Security trade-off, accepted intentionally:
- // 1. This window already runs with `webSecurity: false` + `sandbox: false`,
- // so `plugins: true` does NOT meaningfully widen the renderer's
- // attack surface beyond what is already accepted.
- // 2. The only PDFs that reach an iframe here are signed CloudFront URLs
- // we ourselves issued (see useDownloadAttachment); user-supplied URLs
- // are routed through `setWindowOpenHandler` → `openExternalSafely` and
- // cannot land in this renderer.
- // 3. Chromium's PDFium plugin is itself sandboxed inside its own process
- // and only handles the `application/pdf` MIME — it does not expose
- // Flash, Java, or other historical plugin surfaces.
- //
- // If we ever tighten `webSecurity` / `sandbox`, revisit this by hosting
- // the PDF viewer in a dedicated BrowserView with `plugins: true` scoped
- // to that view, keeping the main renderer plugin-free.
- plugins: true,
- additionalArguments: [`--multica-locale=${systemLocale}`],
- },
+ webPreferences: createRendererWebPreferences(systemLocale),
});
const window = mainWindow;
- latestRendererRouteContext = null;
window.on("closed", () => {
if (mainWindow === window) {
mainWindow = null;
- latestRendererRouteContext = null;
+ mainRendererMessages.resetReady();
}
});
@@ -223,17 +327,7 @@ function createWindow(): void {
window.show();
});
- // Detect OS language changes while the app is running. Electron has no
- // dedicated event for this on any platform, so we poll on focus regain —
- // catches the common case where users switch System Settings → Language
- // and bring the app back. The renderer decides whether to act (it ignores
- // the signal when the user has an explicit Settings choice).
- window.on("focus", () => {
- const current = getSystemLocale();
- if (current === lastKnownSystemLocale) return;
- lastKnownSystemLocale = current;
- window.webContents.send("locale:system-changed", current);
- });
+ installLocaleRefresh(window);
installDownloadSaveDialogHandler(window);
@@ -242,19 +336,9 @@ function createWindow(): void {
return { action: "deny" };
});
- // Window-level keyboard shortcuts. Calling preventDefault here prevents
- // both the renderer keydown AND the application menu accelerator, so
- // anything we own here (reload-block, zoom, tab-close) is the sole handler
- // for that combination — no double-fire with the macOS default View menu.
- window.webContents.on("before-input-event", (event, input) => {
- const result = handleAppShortcut(input, window.webContents);
- if (result === "close-tab") {
- event.preventDefault();
- window.webContents.send("tab:close-active");
- } else if (result) {
- event.preventDefault();
- }
- });
+ // Calling preventDefault in the shared shortcut handler prevents both the
+ // renderer keydown and the application-menu accelerator from double-firing.
+ installWindowShortcutHandler(window);
// Dev-mode renderer diagnostics. When the renderer crashes hard enough
// that DevTools can't be opened (white screen with no clickable surface),
@@ -299,12 +383,13 @@ function createWindow(): void {
showReloadPrompt: createElectronReloadPrompt((options) =>
dialog.showMessageBox(window, options),
),
- getDiagnosticContext: () => ({
- windowUrl: window.webContents.getURL(),
- ...(latestRendererRouteContext
- ? { desktopRoute: latestRendererRouteContext }
- : {}),
- }),
+ getDiagnosticContext: () => {
+ const routeContext = rendererRouteContexts.get(window.webContents);
+ return {
+ windowUrl: window.webContents.getURL(),
+ ...(routeContext ? { desktopRoute: routeContext } : {}),
+ };
+ },
// Only persist in production: a true hang/crash can't report itself, so we
// write a breadcrumb and the next renderer boot flushes it to PostHog. Dev
// is excluded to keep field telemetry clean.
@@ -312,6 +397,7 @@ function createWindow(): void {
? undefined
: (payload) =>
writeFreezeBreadcrumb(freezeBreadcrumbPath(), {
+ ownerId: `main:${window.id}`,
kind: payload.kind,
context: payload.context,
ts: Date.now(),
@@ -319,17 +405,94 @@ function createWindow(): void {
}),
clearBreadcrumb: is.dev
? undefined
- : () => clearFreezeBreadcrumb(freezeBreadcrumbPath()),
+ : () =>
+ clearFreezeBreadcrumb(freezeBreadcrumbPath(), `main:${window.id}`),
});
installContextMenu(window.webContents);
installNavigationGestures(window);
- if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
- window.loadURL(process.env["ELECTRON_RENDERER_URL"]);
- } else {
- window.loadFile(join(__dirname, "../renderer/index.html"));
+ loadRenderer(window);
+ return window;
+}
+
+function createIssueWindow(context: IssueWindowContext): void {
+ const systemLocale = getSystemLocale();
+ lastKnownSystemLocale = systemLocale;
+
+ const window = new BrowserWindow({
+ width: 960,
+ height: 760,
+ minWidth: 720,
+ minHeight: 520,
+ title: context.title,
+ titleBarStyle: "hiddenInset",
+ trafficLightPosition: { x: 16, y: 17 },
+ show: false,
+ autoHideMenuBar: true,
+ ...(is.dev || process.platform === "linux"
+ ? { icon: BUNDLED_ICON_PATH }
+ : {}),
+ webPreferences: createRendererWebPreferences(systemLocale, [
+ encodeIssueWindowArgument(context),
+ ]),
+ });
+
+ issueWindows.add(window);
+ authSessionCoordinator.registerIssueWindow(window);
+ window.on("closed", () => {
+ issueWindows.delete(window);
+ authSessionCoordinator.unregisterIssueWindow(window);
+ });
+
+ window.on("ready-to-show", () => window.show());
+ installLocaleRefresh(window);
+ installDownloadSaveDialogHandler(window);
+
+ window.webContents.setWindowOpenHandler((details) => {
+ void openExternalSafely(details.url);
+ return { action: "deny" };
+ });
+ installWindowShortcutHandler(window);
+
+ const initialRouteContext = sanitizeRendererRouteContext({
+ surface: "tab",
+ path: context.path,
+ workspaceSlug: context.workspaceSlug,
+ });
+ if (initialRouteContext) {
+ rendererRouteContexts.set(window.webContents, initialRouteContext);
}
+ installRendererRecoveryHandlers(window as unknown as RendererRecoveryWindow, {
+ isDev: is.dev,
+ showReloadPrompt: createElectronReloadPrompt((options) =>
+ dialog.showMessageBox(window, options),
+ ),
+ getDiagnosticContext: () => {
+ const routeContext = rendererRouteContexts.get(window.webContents);
+ return {
+ windowUrl: window.webContents.getURL(),
+ ...(routeContext ? { desktopRoute: routeContext } : {}),
+ };
+ },
+ persistBreadcrumb: is.dev
+ ? undefined
+ : (payload) =>
+ writeFreezeBreadcrumb(freezeBreadcrumbPath(), {
+ ownerId: `issue:${window.id}`,
+ kind: payload.kind,
+ context: payload.context,
+ ts: Date.now(),
+ version: getAppVersion(),
+ }),
+ clearBreadcrumb: is.dev
+ ? undefined
+ : () =>
+ clearFreezeBreadcrumb(freezeBreadcrumbPath(), `issue:${window.id}`),
+ });
+
+ installContextMenu(window.webContents);
+ loadRenderer(window);
}
// --- Dev / production isolation -------------------------------------------
@@ -379,18 +542,32 @@ const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
+ // Register before `ready`: macOS can deliver a cold-start URL while runtime
+ // config is still loading. handleDeepLink queues the payload until both the
+ // main window and its matching React listener exist.
+ app.on("open-url", (event, url) => {
+ event.preventDefault();
+ handleDeepLink(url);
+ });
+
// Windows/Linux: second instance passes deep link via argv
app.on("second-instance", (_event, argv) => {
- if (mainWindow) {
- if (mainWindow.isMinimized()) mainWindow.restore();
- mainWindow.focus();
- }
+ const window = ensureMainWindow();
+ if (window) focusMainWindow(window);
// On Windows the deep link URL is the last argv entry
const deepLinkUrl = argv.find((arg) => arg.startsWith(`${PROTOCOL}://`));
if (deepLinkUrl) handleDeepLink(deepLinkUrl);
});
+ // Windows/Linux cold-start deep links are safe to parse now. Delivery is
+ // queued because desktopInitialized remains false until runtime config and
+ // IPC handlers are ready.
+ const coldStartDeepLink = process.argv.find((arg) =>
+ arg.startsWith(`${PROTOCOL}://`),
+ );
+ if (coldStartDeepLink) handleDeepLink(coldStartDeepLink);
+
app.whenReady().then(async () => {
const viteEnv = import.meta.env as ImportMetaEnv & {
readonly VITE_API_URL?: string;
@@ -435,17 +612,31 @@ if (!gotTheLock) {
return openExternalSafely(url);
});
- // Renderer requests window close (e.g. Cmd+W on last tab).
- ipcMain.on("window:close", () => {
- mainWindow?.close();
+ // Renderer requests its own window close (e.g. Cmd+W on the last main
+ // tab, or Cmd+W anywhere in a dedicated issue window).
+ ipcMain.on("window:close", (event) => {
+ BrowserWindow.fromWebContents(event.sender)?.close();
});
- ipcMain.handle("file:download-url", (_event, url: string) => {
- if (!mainWindow) {
- console.warn("[download] ignored file:download-url — mainWindow torn down");
+ ipcMain.handle("window:open-issue", (event, request: unknown) => {
+ if (!BrowserWindow.fromWebContents(event.sender)) {
+ return { ok: false, reason: "invalid_request" } as const;
+ }
+ const context = parseIssueWindowRequest(request);
+ if (!context) {
+ return { ok: false, reason: "invalid_request" } as const;
+ }
+ createIssueWindow(context);
+ return { ok: true } as const;
+ });
+
+ ipcMain.handle("file:download-url", (event, url: string) => {
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender);
+ if (!sourceWindow) {
+ console.warn("[download] ignored file:download-url — source window torn down");
return;
}
- downloadURLSafely(mainWindow, url);
+ downloadURLSafely(sourceWindow, url);
});
// Sync IPC: app version + normalized OS for preload. Sync (not invoke) so
@@ -474,62 +665,102 @@ if (!gotTheLock) {
});
ipcMain.on(RENDERER_ROUTE_CONTEXT_CHANNEL, (event, context: unknown) => {
- if (!mainWindow || event.sender !== mainWindow.webContents) return;
+ if (!BrowserWindow.fromWebContents(event.sender)) return;
const sanitized = sanitizeRendererRouteContext(context);
if (!sanitized) return;
- latestRendererRouteContext = sanitized;
+ rendererRouteContexts.set(event.sender, sanitized);
+ });
+
+ // Preload announces each listener only after it has been installed by the
+ // main renderer. Ignore issue-window senders so they can never drain a
+ // payload intended for the tabbed application window.
+ ipcMain.on(
+ MAIN_RENDERER_CHANNEL_STATE_CHANNEL,
+ (event, state: unknown) => {
+ if (!mainWindow || event.sender !== mainWindow.webContents) return;
+ const parsed = parseMainRendererChannelState(state);
+ if (!parsed) return;
+ mainRendererMessages.setReady(
+ parsed.channel,
+ parsed.ready,
+ sendMainRendererMessage,
+ );
+ },
+ );
+
+ // Account identity is the only cross-renderer auth signal. Main remains
+ // authoritative and closes issue windows instead of copying credentials.
+ ipcMain.on(AUTH_SESSION_STATE_CHANNEL, (event, value: unknown) => {
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender);
+ const userId = parseAuthSessionUserId(value);
+ if (!sourceWindow || userId === undefined) return;
+
+ if (sourceWindow === mainWindow) {
+ const accountInvalidated = authSessionCoordinator.reportMain(userId);
+ if (accountInvalidated) {
+ authSessionGeneration += 1;
+ mainRendererMessages.clear("inbox:open");
+ }
+ return;
+ }
+ if (issueWindows.has(sourceWindow)) {
+ authSessionCoordinator.reportIssue(sourceWindow, userId);
+ }
});
// IPC: toggle immersive mode — hides the macOS traffic lights so full-screen
// modals (e.g. create-workspace) can place UI in the top-left corner
// without fighting the native window controls' hit-test.
- ipcMain.handle("window:setImmersive", (_event, immersive: boolean) => {
+ ipcMain.handle("window:setImmersive", (event, immersive: boolean) => {
if (process.platform !== "darwin") return;
- mainWindow?.setWindowButtonVisibility(!immersive);
+ BrowserWindow.fromWebContents(event.sender)?.setWindowButtonVisibility(
+ !immersive,
+ );
});
- // IPC: show a native OS notification for a new inbox item. The renderer
- // only fires this when the app is unfocused (it gates on
- // `document.hasFocus()`), so we don't fight macOS foreground suppression
- // here. Clicking the banner focuses the main window and routes to the
- // inbox item via a renderer-side listener.
- ipcMain.on(
- "notification:show",
- (
- _event,
- {
- slug,
- itemId,
- issueKey,
- title,
- body,
- }: {
- slug: string;
- itemId: string;
- issueKey: string;
- title: string;
- body: string;
- },
- ) => {
- if (!Notification.isSupported()) return;
- const notification = new Notification({ title, body });
- notification.on("click", () => {
- if (!mainWindow) return;
- if (mainWindow.isMinimized()) mainWindow.restore();
- mainWindow.show();
- mainWindow.focus();
- // Ship the full context back — the renderer pins the route to the
- // source workspace (slug), marks the row read (itemId), and uses
- // issueKey as the ?issue=<…> selector.
- mainWindow.webContents.send("inbox:open", {
- slug,
- itemId,
- issueKey,
- });
+ // Main owns foreground detection and item-level dedupe. Every renderer
+ // has its own WebSocket and `document.hasFocus()` only describes that one
+ // window, so renderer-only gating can emit N duplicate system banners.
+ ipcMain.on("notification:show", (event, value: unknown) => {
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender);
+ if (!sourceWindow) return;
+ if (sourceWindow === mainWindow) {
+ if (!authSessionCoordinator.hasActiveMainSession()) return;
+ } else if (
+ !issueWindows.has(sourceWindow) ||
+ !authSessionCoordinator.isCurrentIssueSession(sourceWindow)
+ ) {
+ return;
+ }
+
+ const payload = parseNativeNotificationPayload(value);
+ if (!payload || !Notification.isSupported()) return;
+ const anyWindowFocused = BrowserWindow.getAllWindows().some(
+ (window) => !window.isDestroyed() && window.isFocused(),
+ );
+ if (!notificationGate.shouldShow(payload.itemId, anyWindowFocused)) {
+ return;
+ }
+
+ const notification = new Notification({
+ title: payload.title,
+ body: payload.body,
+ });
+ const notificationSessionGeneration = authSessionGeneration;
+ notification.on("click", () => {
+ // A banner emitted for user A must not navigate after the main window
+ // logs out or switches to user B.
+ if (notificationSessionGeneration !== authSessionGeneration) return;
+ // Recreate the main window when an issue-only window outlived it, then
+ // wait for the inbox listener before delivering the navigation.
+ dispatchToMainRenderer("inbox:open", {
+ slug: payload.slug,
+ itemId: payload.itemId,
+ issueKey: payload.issueKey,
});
- notification.show();
- },
- );
+ });
+ notification.show();
+ });
// IPC: update the dock / taskbar unread badge. Values above 99 render as
// "99+". macOS is the primary target (user-visible dock badge); Linux
@@ -546,33 +777,18 @@ if (!gotTheLock) {
}
});
+ desktopInitialized = true;
createWindow();
setupAutoUpdater(() => mainWindow);
setupDaemonManager(() => mainWindow);
setupLocalDirectory(() => mainWindow);
- // macOS: deep link arrives via open-url event
- app.on("open-url", (_event, url) => {
- if (mainWindow) {
- if (mainWindow.isMinimized()) mainWindow.restore();
- mainWindow.focus();
- }
- handleDeepLink(url);
- });
-
app.on("activate", () => {
- if (BrowserWindow.getAllWindows().length === 0) createWindow();
+ const window = ensureMainWindow();
+ if (window) focusMainWindow(window);
});
});
-
- // Check argv for deep link on cold start (Windows/Linux)
- const deepLinkArg = process.argv.find((arg) =>
- arg.startsWith(`${PROTOCOL}://`),
- );
- if (deepLinkArg) {
- app.whenReady().then(() => handleDeepLink(deepLinkArg));
- }
}
app.on("window-all-closed", () => {
diff --git a/apps/desktop/src/main/local-directory.ts b/apps/desktop/src/main/local-directory.ts
index 2b9ac6884e..5e9311a447 100644
--- a/apps/desktop/src/main/local-directory.ts
+++ b/apps/desktop/src/main/local-directory.ts
@@ -62,8 +62,9 @@ export function setupLocalDirectory(
): void {
ipcMain.handle(
"local-directory:pick",
- async (_event, defaultPath?: string): Promise<PickDirectoryResult> => {
- const win = windowGetter();
+ async (event, defaultPath?: string): Promise<PickDirectoryResult> => {
+ const win =
+ BrowserWindow.fromWebContents(event.sender) ?? windowGetter();
if (!win) return { ok: false, reason: "no_window" };
try {
const result = await dialog.showOpenDialog(win, {
diff --git a/apps/desktop/src/main/notification-gate.test.ts b/apps/desktop/src/main/notification-gate.test.ts
new file mode 100644
index 0000000000..f36798234b
--- /dev/null
+++ b/apps/desktop/src/main/notification-gate.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import {
+ NotificationGate,
+ parseNativeNotificationPayload,
+} from "./notification-gate";
+
+describe("NotificationGate", () => {
+ it("suppresses native notifications while any app window is focused", () => {
+ const gate = new NotificationGate();
+ expect(gate.shouldShow("item-1", true)).toBe(false);
+ });
+
+ it("shows only the first renderer event for an inbox item", () => {
+ const gate = new NotificationGate();
+ expect(gate.shouldShow("item-1", false)).toBe(true);
+ expect(gate.shouldShow("item-1", false)).toBe(false);
+ });
+
+ it("still deduplicates an item when focus suppresses it", () => {
+ const gate = new NotificationGate();
+ expect(gate.shouldShow("item-1", true)).toBe(false);
+ expect(gate.shouldShow("item-1", false)).toBe(false);
+ });
+
+ it("bounds remembered ids without blocking newer items", () => {
+ const gate = new NotificationGate(2);
+ expect(gate.shouldShow("item-1", false)).toBe(true);
+ expect(gate.shouldShow("item-2", false)).toBe(true);
+ expect(gate.shouldShow("item-3", false)).toBe(true);
+ expect(gate.shouldShow("item-1", false)).toBe(true);
+ });
+});
+
+describe("parseNativeNotificationPayload", () => {
+ it("rejects malformed renderer payloads before native side effects", () => {
+ expect(parseNativeNotificationPayload(null)).toBeNull();
+ expect(
+ parseNativeNotificationPayload({
+ slug: "acme",
+ itemId: "item-1",
+ issueKey: "MUL-1",
+ title: "New update",
+ }),
+ ).toBeNull();
+ });
+
+ it("accepts the complete bounded payload", () => {
+ const payload = {
+ slug: "acme",
+ itemId: "item-1",
+ issueKey: "MUL-1",
+ title: "New update",
+ body: "A comment was added",
+ };
+ expect(parseNativeNotificationPayload(payload)).toEqual(payload);
+ });
+
+ it("preserves empty optional routing/body fields from legacy events", () => {
+ const payload = {
+ slug: "",
+ itemId: "item-1",
+ issueKey: "MUL-1",
+ title: "New update",
+ body: "",
+ };
+ expect(parseNativeNotificationPayload(payload)).toEqual(payload);
+ });
+});
diff --git a/apps/desktop/src/main/notification-gate.ts b/apps/desktop/src/main/notification-gate.ts
new file mode 100644
index 0000000000..c93d5420a2
--- /dev/null
+++ b/apps/desktop/src/main/notification-gate.ts
@@ -0,0 +1,59 @@
+/**
+ * Main-process authority for native notification eligibility. Renderer focus
+ * is window-local, so only main can answer whether any Multica window is in
+ * the foreground and collapse the same realtime event from N renderers.
+ */
+export class NotificationGate {
+ private readonly seenItemIds = new Set<string>();
+
+ constructor(private readonly maxRememberedItems = 1_000) {}
+
+ shouldShow(itemId: string, anyWindowFocused: boolean): boolean {
+ const normalizedItemId = itemId.trim();
+ if (!normalizedItemId) return false;
+ if (this.seenItemIds.has(normalizedItemId)) return false;
+
+ this.seenItemIds.add(normalizedItemId);
+ if (this.seenItemIds.size > this.maxRememberedItems) {
+ const oldest = this.seenItemIds.values().next().value;
+ if (typeof oldest === "string") this.seenItemIds.delete(oldest);
+ }
+ return !anyWindowFocused;
+ }
+}
+
+export interface NativeNotificationPayload {
+ slug: string;
+ itemId: string;
+ issueKey: string;
+ title: string;
+ body: string;
+}
+
+export function parseNativeNotificationPayload(
+ value: unknown,
+): NativeNotificationPayload | null {
+ if (!value || typeof value !== "object") return null;
+ const candidate = value as Record<string, unknown>;
+ const limits: Record<keyof NativeNotificationPayload, number> = {
+ slug: 256,
+ itemId: 256,
+ issueKey: 256,
+ title: 512,
+ body: 2_000,
+ };
+ const result = {} as NativeNotificationPayload;
+ for (const key of Object.keys(limits) as (keyof NativeNotificationPayload)[]) {
+ const field = candidate[key];
+ const mayBeEmpty = key === "slug" || key === "body";
+ if (
+ typeof field !== "string" ||
+ (!mayBeEmpty && !field.trim()) ||
+ field.length > limits[key]
+ ) {
+ return null;
+ }
+ result[key] = field;
+ }
+ return result;
+}
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index a5c6253cb8..2ee0949c3b 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -3,6 +3,10 @@ import type { RuntimeConfigResult } from "../shared/runtime-config";
import type { NavigationGesture } from "../shared/navigation-gestures";
import type { RendererRouteContextInput } from "../shared/renderer-route-context";
import type { FreezeBreadcrumb } from "../shared/freeze-breadcrumb";
+import type {
+ DesktopWindowContext,
+ IssueWindowRequest,
+} from "../shared/issue-window";
import type {
ManualUpdateCheckResult,
UpdaterPreferences,
@@ -20,9 +24,13 @@ interface DesktopAPI {
onSystemLocaleChanged: (callback: (locale: string) => void) => () => void;
/** Validated runtime endpoint config, or a blocking config error. */
runtimeConfig: RuntimeConfigResult;
+ /** Main tabbed window or a dedicated issue-only window. */
+ windowContext: DesktopWindowContext;
/** Read + clear any freeze/crash breadcrumb from a previous session, so the
* renderer can flush it to telemetry on boot. Null when nothing's pending. */
getLastFreeze: () => FreezeBreadcrumb | null;
+ /** Report the resolved account identity so stale issue windows can close. */
+ reportAuthSession: (userId: string | null) => void;
/** Listen for auth token delivered via deep link. Returns an unsubscribe function. */
onAuthToken: (callback: (token: string) => void) => () => void;
/** Listen for invitation IDs delivered via deep link. Returns an unsubscribe function. */
@@ -87,6 +95,10 @@ interface DesktopAPI {
onCloseActiveTab: (callback: () => void) => () => void;
/** Ask the main process to close the window. */
closeWindow: () => void;
+ /** Open an issue-detail tab in a dedicated native window. */
+ openIssueWindow: (
+ request: IssueWindowRequest,
+ ) => Promise<{ ok: true } | { ok: false; reason: "invalid_request" }>;
}
interface DaemonStatus {
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 4e8ecf874f..9d143b4617 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -15,6 +15,15 @@ import {
NAVIGATION_GESTURE_CHANNEL,
type NavigationGesture,
} from "../shared/navigation-gestures";
+import {
+ readDesktopWindowContext,
+ type IssueWindowRequest,
+} from "../shared/issue-window";
+import { AUTH_SESSION_STATE_CHANNEL } from "../shared/auth-session";
+import {
+ MAIN_RENDERER_CHANNEL_STATE_CHANNEL,
+ type MainRendererMessageChannel,
+} from "../shared/main-renderer-messages";
// Synchronously fetch app metadata from main at preload time so the renderer
// can pass it into CoreProvider during the initial render — the alternative
@@ -53,6 +62,7 @@ function fetchRuntimeConfig(): RuntimeConfigResult {
const appInfo = fetchAppInfo();
const runtimeConfig = fetchRuntimeConfig();
+const windowContext = readDesktopWindowContext(process.argv);
// Read the OS-preferred locale that main injected via additionalArguments.
// Zero IPC, zero blocking — process.argv is populated before preload runs.
@@ -63,6 +73,26 @@ function fetchSystemLocale(): string {
const systemLocale = fetchSystemLocale();
+function subscribeToMainRendererChannel<T>(
+ channel: MainRendererMessageChannel,
+ callback: (payload: T) => void,
+): () => void {
+ const handler = (_event: Electron.IpcRendererEvent, payload: T) =>
+ callback(payload);
+ ipcRenderer.on(channel, handler);
+ ipcRenderer.send(MAIN_RENDERER_CHANNEL_STATE_CHANNEL, {
+ channel,
+ ready: true,
+ });
+ return () => {
+ ipcRenderer.removeListener(channel, handler);
+ ipcRenderer.send(MAIN_RENDERER_CHANNEL_STATE_CHANNEL, {
+ channel,
+ ready: false,
+ });
+ };
+}
+
const desktopAPI = {
/** App version + normalized OS. Read once at preload time so the renderer
* can use it synchronously when initializing the API client. */
@@ -83,6 +113,9 @@ const desktopAPI = {
},
/** Validated runtime endpoint config, or a blocking config error. */
runtimeConfig,
+ /** Identifies whether this renderer owns the main tabbed window or a
+ * dedicated issue window, parsed from validated launch arguments. */
+ windowContext,
/** Read + clear any freeze/crash breadcrumb left by a previous session, so
* the renderer can flush it to telemetry on boot. Returns null when there's
* nothing pending (the normal case). */
@@ -93,24 +126,16 @@ const desktopAPI = {
return null;
}
},
+ /** Report only the resolved user id (never a token) so main can close
+ * dedicated issue windows that belong to an old account. */
+ reportAuthSession: (userId: string | null) =>
+ ipcRenderer.send(AUTH_SESSION_STATE_CHANNEL, userId),
/** Listen for auth token delivered via deep link */
- onAuthToken: (callback: (token: string) => void) => {
- const handler = (_event: Electron.IpcRendererEvent, token: string) =>
- callback(token);
- ipcRenderer.on("auth:token", handler);
- return () => {
- ipcRenderer.removeListener("auth:token", handler);
- };
- },
+ onAuthToken: (callback: (token: string) => void) =>
+ subscribeToMainRendererChannel("auth:token", callback),
/** Listen for invitation IDs delivered via deep link */
- onInviteOpen: (callback: (invitationId: string) => void) => {
- const handler = (_event: Electron.IpcRendererEvent, invitationId: string) =>
- callback(invitationId);
- ipcRenderer.on("invite:open", handler);
- return () => {
- ipcRenderer.removeListener("invite:open", handler);
- };
- },
+ onInviteOpen: (callback: (invitationId: string) => void) =>
+ subscribeToMainRendererChannel("invite:open", callback),
/** Open a URL in the default browser */
openExternal: (url: string) => ipcRenderer.invoke("shell:openExternal", url),
/** Download a file by URL through Electron's native download system.
@@ -155,16 +180,7 @@ const desktopAPI = {
itemId: string;
issueKey: string;
}) => void,
- ) => {
- const handler = (
- _event: Electron.IpcRendererEvent,
- payload: { slug: string; itemId: string; issueKey: string },
- ) => callback(payload);
- ipcRenderer.on("inbox:open", handler);
- return () => {
- ipcRenderer.removeListener("inbox:open", handler);
- };
- },
+ ) => subscribeToMainRendererChannel("inbox:open", callback),
/** Listen for native macOS back/forward swipe gestures. */
onNavigationGesture: (callback: (gesture: NavigationGesture) => void) => {
const handler = (_event: Electron.IpcRendererEvent, gesture: unknown) => {
@@ -196,6 +212,9 @@ const desktopAPI = {
},
/** Ask the main process to close the window (used after closing the last tab). */
closeWindow: () => ipcRenderer.send("window:close"),
+ /** Open a validated issue-detail route in a dedicated native window. */
+ openIssueWindow: (request: IssueWindowRequest) =>
+ ipcRenderer.invoke("window:open-issue", request),
};
interface DaemonStatus {
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index 9e53238683..bc1a587d20 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -14,6 +14,7 @@ import { Toaster } from "@multica/ui/components/ui/sonner";
import { DesktopLoginPage } from "./pages/login";
import { DesktopShell } from "./components/desktop-layout";
import { UpdateNotification } from "./components/update-notification";
+import { IssueWindow } from "./components/issue-window";
import { useTabStore } from "./stores/tab-store";
import { useWindowOverlayStore } from "./stores/window-overlay-store";
import { useDaemonIPCBridge } from "./platform/daemon-ipc-bridge";
@@ -46,6 +47,10 @@ const HTML_LANG: Record<SupportedLocale, string> = {
function useCmdWCloseTab() {
useEffect(() => {
return window.desktopAPI.onCloseActiveTab(() => {
+ if (window.desktopAPI.windowContext?.kind === "issue") {
+ window.desktopAPI.closeWindow();
+ return;
+ }
const store = useTabStore.getState();
const { activeWorkspaceSlug, byWorkspace } = store;
if (!activeWorkspaceSlug) {
@@ -65,6 +70,42 @@ function useCmdWCloseTab() {
}, []);
}
+function IssueWindowContent() {
+ const user = useAuthStore((state) => state.user);
+ const isLoading = useAuthStore((state) => state.isLoading);
+ const context = window.desktopAPI.windowContext ?? { kind: "main" as const };
+
+ if (context.kind !== "issue") return null;
+ if (isLoading) {
+ return (
+ <div className="flex h-screen items-center justify-center">
+ <MulticaIcon className="size-6 animate-pulse" />
+ </div>
+ );
+ }
+
+ return user ? <IssueWindow context={context} /> : <DesktopLoginPage />;
+}
+
+/**
+ * Keep the main process informed of the resolved account identity without
+ * sharing credentials between renderer processes. Main uses this signal to
+ * close dedicated windows on logout/account switch.
+ */
+function DesktopAuthSessionBridge() {
+ const userId = useAuthStore((state) => state.user?.id ?? null);
+ const isLoading = useAuthStore((state) => state.isLoading);
+
+ useEffect(() => {
+ if (isLoading) return;
+ // Optional chaining keeps renderer HMR safe during the brief interval in
+ // which an old preload is still attached to the refreshed React tree.
+ window.desktopAPI.reportAuthSession?.(userId);
+ }, [isLoading, userId]);
+
+ return null;
+}
+
function AppContent() {
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
@@ -301,6 +342,9 @@ function BlockingRuntimeConfigError({ message }: { message: string }) {
// useLogout clears the storage key, but the live stores stay populated until
// we explicitly reset them here.
async function handleDaemonLogout() {
+ // Report synchronously before async daemon cleanup so a rapidly closed main
+ // window cannot leave authenticated issue renderers behind.
+ window.desktopAPI.reportAuthSession?.(null);
useTabStore.getState().reset();
useWindowOverlayStore.getState().close();
// Drop any post-onboarding welcome signal so user B logging in next
@@ -322,6 +366,10 @@ export default function App() {
const { version, os } = window.desktopAPI.appInfo;
const systemLocale = window.desktopAPI.systemLocale;
const runtimeConfigResult = window.desktopAPI.runtimeConfig;
+ // The fallback keeps renderer HMR safe while a main/preload rebuild is
+ // restarting Electron; packaged builds always expose windowContext.
+ const windowContext =
+ window.desktopAPI.windowContext ?? { kind: "main" as const };
useCmdWCloseTab();
// Flush a freeze/crash breadcrumb the main process parked from a previous
@@ -395,19 +443,26 @@ export default function App() {
<CoreProvider
apiBaseUrl={runtimeConfigResult.config.apiUrl}
wsUrl={runtimeConfigResult.config.wsUrl}
- onLogout={handleDaemonLogout}
+ onLogout={
+ windowContext.kind === "main" ? handleDaemonLogout : undefined
+ }
identity={identity}
locale={locale}
resources={resources}
localeAdapter={localeAdapter}
>
- <AppContent />
+ <DesktopAuthSessionBridge />
+ {windowContext.kind === "issue" ? (
+ <IssueWindowContent />
+ ) : (
+ <AppContent />
+ )}
</CoreProvider>
) : (
<BlockingRuntimeConfigError message={runtimeConfigResult.error.message} />
)}
<Toaster />
- <UpdateNotification />
+ {windowContext.kind === "main" && <UpdateNotification />}
</ThemeProvider>
);
}
diff --git a/apps/desktop/src/renderer/src/components/issue-window.tsx b/apps/desktop/src/renderer/src/components/issue-window.tsx
new file mode 100644
index 0000000000..cbd2c370d4
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/issue-window.tsx
@@ -0,0 +1,146 @@
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ createMemoryRouter,
+ RouterProvider,
+ useParams,
+ useRouteError,
+} from "react-router-dom";
+import { AlertTriangle, RotateCw, X } from "lucide-react";
+import { useAuthStore } from "@multica/core/auth";
+import { setCurrentWorkspace } from "@multica/core/platform";
+import { WorkspaceSlugProvider } from "@multica/core/paths";
+import { workspaceBySlugOptions } from "@multica/core/workspace";
+import { Button } from "@multica/ui/components/ui/button";
+import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
+import { ModalRegistry } from "@multica/views/modals/registry";
+import { WorkspacePresencePrefetch } from "@multica/views/layout";
+import { DragStrip } from "@multica/views/platform";
+import type { IssueWindowContext } from "../../../shared/issue-window";
+import { IssueDetailPage } from "../pages/issue-detail-page";
+import { IssueWindowNavigationProvider } from "../platform/issue-window-navigation";
+
+export function IssueWindow({ context }: { context: IssueWindowContext }) {
+ const router = useMemo(
+ () =>
+ createMemoryRouter(
+ [
+ {
+ path: ":workspaceSlug/issues/:id",
+ element: <IssueWindowRoute />,
+ errorElement: <IssueWindowRouteError />,
+ },
+ ],
+ { initialEntries: [context.path] },
+ ),
+ [context.path],
+ );
+
+ return <RouterProvider router={router} />;
+}
+
+function IssueWindowRoute() {
+ const { workspaceSlug } = useParams<{ workspaceSlug: string }>();
+ const user = useAuthStore((state) => state.user);
+ const { data: workspace, isFetched } = useQuery({
+ ...workspaceBySlugOptions(workspaceSlug ?? ""),
+ enabled: !!user && !!workspaceSlug,
+ });
+
+ if (workspace && workspaceSlug) {
+ setCurrentWorkspace(workspaceSlug, workspace.id);
+ }
+
+ if (!isFetched) {
+ return (
+ <IssueWindowFrame>
+ <div className="flex min-h-0 flex-1 items-center justify-center">
+ <MulticaIcon className="size-6 animate-pulse" />
+ </div>
+ </IssueWindowFrame>
+ );
+ }
+
+ if (!workspace || !workspaceSlug) {
+ return <IssueWindowUnavailable />;
+ }
+
+ return (
+ <WorkspaceSlugProvider slug={workspaceSlug}>
+ <IssueWindowNavigationProvider>
+ <WorkspacePresencePrefetch />
+ <IssueWindowFrame>
+ <IssueDetailPage onDelete={() => window.desktopAPI.closeWindow()} />
+ </IssueWindowFrame>
+ <ModalRegistry />
+ </IssueWindowNavigationProvider>
+ </WorkspaceSlugProvider>
+ );
+}
+
+function IssueWindowFrame({ children }: { children: React.ReactNode }) {
+ return (
+ <div
+ data-dedicated-issue-window="true"
+ className="flex h-screen min-h-0 flex-col bg-page-canvas text-foreground"
+ >
+ <DragStrip />
+ <div className="flex min-h-0 flex-1 overflow-hidden">{children}</div>
+ </div>
+ );
+}
+
+function IssueWindowUnavailable() {
+ return (
+ <IssueWindowFrame>
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4 p-8 text-center">
+ <div className="rounded-full bg-muted p-3 text-muted-foreground">
+ <AlertTriangle className="size-6" aria-hidden="true" />
+ </div>
+ <div className="space-y-1">
+ <h1 className="text-lg font-semibold">Issue unavailable</h1>
+ <p className="text-sm text-muted-foreground">
+ This workspace is no longer available in your account.
+ </p>
+ </div>
+ <Button variant="outline" onClick={() => window.desktopAPI.closeWindow()}>
+ Close window
+ </Button>
+ </div>
+ </IssueWindowFrame>
+ );
+}
+
+function IssueWindowRouteError() {
+ const error = useRouteError();
+ const message = error instanceof Error ? error.message : "Unknown route error";
+
+ return (
+ <IssueWindowFrame>
+ <div
+ role="alert"
+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4 p-8 text-center"
+ >
+ <div className="rounded-full bg-destructive/10 p-3 text-destructive">
+ <AlertTriangle className="size-6" aria-hidden="true" />
+ </div>
+ <div className="space-y-1">
+ <h1 className="text-lg font-semibold">Something went wrong</h1>
+ <p className="max-w-lg truncate text-sm text-muted-foreground">
+ {message}
+ </p>
+ </div>
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={() => window.location.reload()}>
+ <RotateCw className="size-4" aria-hidden="true" />
+ Reload
+ </Button>
+ <Button variant="outline" onClick={() => window.desktopAPI.closeWindow()}>
+ <X className="size-4" aria-hidden="true" />
+ Close window
+ </Button>
+ </div>
+ </div>
+ </IssueWindowFrame>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx b/apps/desktop/src/renderer/src/components/tab-bar.test.tsx
index 5463b6c6fe..271d0c60df 100644
--- a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-bar.test.tsx
@@ -11,6 +11,7 @@ import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
type MockTab = {
id: string;
path: string;
+ url?: string;
title: string;
icon: string;
pinned: boolean;
@@ -33,6 +34,7 @@ const state = vi.hoisted(() => ({
setActiveTab: vi.fn<(tabId: string) => void>(),
moveTab: vi.fn<(from: number, to: number) => void>(),
addTab: vi.fn<(path: string, title: string, icon: string) => string>(),
+ openIssueWindow: vi.fn(),
}));
vi.mock("@/stores/tab-store", () => {
@@ -90,6 +92,7 @@ function reset() {
state.setActiveTab.mockReset();
state.moveTab.mockReset();
state.addTab.mockReset();
+ state.openIssueWindow.mockReset();
}
beforeEach(() => {
@@ -112,6 +115,9 @@ beforeEach(() => {
disconnect() {}
},
);
+ vi.stubGlobal("desktopAPI", {
+ openIssueWindow: state.openIssueWindow,
+ });
});
afterAll(() => vi.unstubAllGlobals());
@@ -397,6 +403,47 @@ describe("TabBar overflow", () => {
});
describe("TabBar context menu", () => {
+ it("opens an issue-detail tab as a dedicated window", async () => {
+ state.byWorkspace.acme.tabs = [
+ {
+ id: "tA",
+ path: "/acme/issues/issue-1",
+ url: "/acme/issues/issue-1?comment=comment-1",
+ title: "MUL-1: Fix tabs",
+ icon: "ListTodo",
+ pinned: false,
+ },
+ ];
+
+ const { findByText, getByLabelText } = render(<TabBar />);
+ fireEvent.contextMenu(getByLabelText("MUL-1: Fix tabs"));
+ fireEvent.click(await findByText("Open as new window"));
+
+ expect(state.openIssueWindow).toHaveBeenCalledWith({
+ path: "/acme/issues/issue-1?comment=comment-1",
+ title: "MUL-1: Fix tabs",
+ });
+ });
+
+ it("does not offer a dedicated window for non-issue tabs", async () => {
+ state.byWorkspace.acme.tabs = [
+ {
+ id: "tA",
+ path: "/acme/issues",
+ url: "/acme/issues",
+ title: "Issues",
+ icon: "ListTodo",
+ pinned: false,
+ },
+ ];
+
+ const { findByText, getByLabelText, queryByText } = render(<TabBar />);
+ fireEvent.contextMenu(getByLabelText("Issues"));
+ await findByText("Pin tab");
+
+ expect(queryByText("Open as new window")).toBeNull();
+ });
+
it("closes other tabs from the context menu", async () => {
state.byWorkspace.acme.tabs = [
{ id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: true },
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsx
index 5c90840a0f..a5d66211ad 100644
--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx
@@ -20,6 +20,7 @@ import {
Pin,
PinOff,
ListX,
+ AppWindow,
type LucideIcon,
} from "lucide-react";
import {
@@ -56,6 +57,7 @@ import {
type Tab,
} from "@/stores/tab-store";
import { paths } from "@multica/core/paths";
+import { parseIssueWindowPath } from "../../../shared/issue-window";
const TAB_ICONS: Record<string, LucideIcon> = {
Inbox,
@@ -190,6 +192,7 @@ function SortableTabItem({
const closeTab = useTabStore((s) => s.closeTab);
const closeOtherTabs = useTabStore((s) => s.closeOtherTabs);
const togglePin = useTabStore((s) => s.togglePin);
+ const issueWindowPath = parseIssueWindowPath(tab.url);
const {
attributes,
@@ -232,6 +235,14 @@ function SortableTabItem({
e.stopPropagation();
};
+ const handleOpenAsWindow = () => {
+ if (!issueWindowPath) return;
+ void window.desktopAPI.openIssueWindow({
+ path: issueWindowPath.path,
+ title: tab.title,
+ });
+ };
+
// Pinned tabs keep their full title (RFC §3 D1v-ii FINAL). The only visual
// differences vs. unpinned tabs are the leading Pin icon (swapped in above)
// and the suppressed X (closing requires explicit Unpin). Pin/Unpin is
@@ -353,6 +364,15 @@ function SortableTabItem({
<ContextMenu>
<ContextMenuTrigger render={tabButton} />
<ContextMenuContent>
+ {issueWindowPath && (
+ <>
+ <ContextMenuItem onClick={handleOpenAsWindow}>
+ <AppWindow />
+ Open as new window
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ </>
+ )}
<ContextMenuItem onClick={() => togglePin(tab.id)}>
{tab.pinned ? (
<>
diff --git a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx
index abfdcdd9ec..d3ad064582 100644
--- a/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx
+++ b/apps/desktop/src/renderer/src/pages/issue-detail-page.tsx
@@ -5,7 +5,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { issueDetailOptions } from "@multica/core/issues/queries";
import { useDocumentTitle } from "@/hooks/use-document-title";
-export function IssueDetailPage() {
+export function IssueDetailPage({ onDelete }: { onDelete?: () => void }) {
const { id } = useParams<{ id: string }>();
const wsId = useWorkspaceId();
const { data: issue } = useQuery(issueDetailOptions(wsId, id!));
@@ -16,5 +16,5 @@ export function IssueDetailPage() {
// Render errors bubble to the root route errorElement (DesktopRouteErrorPage),
// which contains the crash inside the tab content pane. No page-level boundary
// here — a whole-page wrapper duplicates the route-level error UI.
- return <IssueDetail issueId={id} />;
+ return <IssueDetail issueId={id} onDelete={onDelete} />;
}
diff --git a/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx
new file mode 100644
index 0000000000..95fd7ff799
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx
@@ -0,0 +1,60 @@
+import { useEffect, useMemo } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import {
+ NavigationProvider,
+ type NavigationAdapter,
+} from "@multica/views/navigation";
+import { parseIssueWindowPath } from "../../../shared/issue-window";
+
+/**
+ * Navigation bridge for a dedicated issue window. Unlike the main Desktop
+ * shell, this window owns a tiny MemoryRouter and intentionally accepts only
+ * issue-detail routes. Keeping the bridge in the platform layer preserves the
+ * MUL-4741 boundary around direct router navigation.
+ */
+export function IssueWindowNavigationProvider({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const location = useLocation();
+ const navigate = useNavigate();
+ const workspace = useCurrentWorkspace();
+ const runtimeConfig = window.desktopAPI.runtimeConfig;
+ const currentPath = `${location.pathname}${location.search}${location.hash}`;
+
+ useEffect(() => {
+ window.desktopAPI.setRendererRouteContext({
+ surface: "tab",
+ path: currentPath,
+ ...(workspace?.slug ? { workspaceSlug: workspace.slug } : {}),
+ });
+ }, [currentPath, workspace?.slug]);
+
+ const adapter = useMemo<NavigationAdapter>(() => {
+ const navigateToIssue = (path: string, replace = false) => {
+ const issuePath = parseIssueWindowPath(path);
+ if (!issuePath) return;
+ void navigate(issuePath.path, { replace });
+ };
+
+ return {
+ push: (path) => navigateToIssue(path),
+ replace: (path) => navigateToIssue(path, true),
+ back: () => void navigate(-1),
+ pathname: location.pathname,
+ searchParams: new URLSearchParams(location.search),
+ openInNewTab: (path, title) => {
+ void window.desktopAPI.openIssueWindow({
+ path,
+ title: title ?? "Issue",
+ });
+ },
+ getShareableUrl: (path) =>
+ runtimeConfig.ok ? `${runtimeConfig.config.appUrl}${path}` : path,
+ };
+ }, [location.pathname, location.search, navigate, runtimeConfig]);
+
+ return <NavigationProvider value={adapter}>{children}</NavigationProvider>;
+}
diff --git a/apps/desktop/src/shared/auth-session.ts b/apps/desktop/src/shared/auth-session.ts
new file mode 100644
index 0000000000..2f9cc3d902
--- /dev/null
+++ b/apps/desktop/src/shared/auth-session.ts
@@ -0,0 +1,13 @@
+export const AUTH_SESSION_STATE_CHANNEL = "auth:session-state";
+
+export type AuthSessionUserId = string | null;
+
+export function parseAuthSessionUserId(
+ value: unknown,
+): AuthSessionUserId | undefined {
+ if (value === null) return null;
+ if (typeof value !== "string") return undefined;
+ const userId = value.trim();
+ if (!userId || userId.length > 256) return undefined;
+ return userId;
+}
diff --git a/apps/desktop/src/shared/freeze-breadcrumb.ts b/apps/desktop/src/shared/freeze-breadcrumb.ts
index 9f3bc41115..d53c9fcec9 100644
--- a/apps/desktop/src/shared/freeze-breadcrumb.ts
+++ b/apps/desktop/src/shared/freeze-breadcrumb.ts
@@ -5,6 +5,8 @@
* read/write logic and the rationale.
*/
export interface FreezeBreadcrumb {
+ /** Window instance that owns this pending write (optional for old clients). */
+ ownerId?: string;
/** "unresponsive" (hang) or "render-process-gone" (crash). */
kind: string;
/** Diagnostic context captured at failure time (route, window url, …). */
diff --git a/apps/desktop/src/shared/issue-window.test.ts b/apps/desktop/src/shared/issue-window.test.ts
new file mode 100644
index 0000000000..9d3a472641
--- /dev/null
+++ b/apps/desktop/src/shared/issue-window.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import {
+ encodeIssueWindowArgument,
+ parseIssueWindowPath,
+ parseIssueWindowRequest,
+ readDesktopWindowContext,
+} from "./issue-window";
+
+describe("issue window request", () => {
+ it("accepts and canonicalizes a workspace-scoped issue detail path", () => {
+ expect(
+ parseIssueWindowRequest({
+ path: "/acme/issues/issue-123?comment=comment-1#activity",
+ title: " MUL-1: Fix tabs ",
+ }),
+ ).toEqual({
+ kind: "issue",
+ path: "/acme/issues/issue-123?comment=comment-1#activity",
+ title: "MUL-1: Fix tabs",
+ workspaceSlug: "acme",
+ issueId: "issue-123",
+ });
+ });
+
+ it.each([
+ "/acme/issues",
+ "/acme/projects/project-1",
+ "/acme/issues/issue-1/attachments",
+ "https://example.com/acme/issues/issue-1",
+ "//example.com/acme/issues/issue-1",
+ "/acme/issues/issue%2F1",
+ "/UPPERCASE/issues/issue-1",
+ ])("rejects non-issue or unsafe paths: %s", (path) => {
+ expect(parseIssueWindowPath(path)).toBeNull();
+ });
+
+ it("uses a safe fallback title and bounds renderer-controlled titles", () => {
+ expect(
+ parseIssueWindowRequest({ path: "/acme/issues/issue-1", title: " " }),
+ ).toMatchObject({ title: "Issue" });
+ expect(
+ parseIssueWindowRequest({
+ path: "/acme/issues/issue-1",
+ title: "x".repeat(400),
+ })?.title,
+ ).toHaveLength(256);
+ });
+
+ it("round-trips a validated request through Electron additionalArguments", () => {
+ const argument = encodeIssueWindowArgument({
+ path: "/acme/issues/issue-1",
+ title: "MUL-1: Fix tabs",
+ });
+
+ expect(readDesktopWindowContext(["electron", argument])).toEqual({
+ kind: "issue",
+ path: "/acme/issues/issue-1",
+ title: "MUL-1: Fix tabs",
+ workspaceSlug: "acme",
+ issueId: "issue-1",
+ });
+ });
+
+ it("falls back to the main window for malformed launch arguments", () => {
+ expect(
+ readDesktopWindowContext(["electron", "--multica-issue-window=%7Bbad"]),
+ ).toEqual({ kind: "main" });
+ });
+});
diff --git a/apps/desktop/src/shared/issue-window.ts b/apps/desktop/src/shared/issue-window.ts
new file mode 100644
index 0000000000..0d69d87c59
--- /dev/null
+++ b/apps/desktop/src/shared/issue-window.ts
@@ -0,0 +1,116 @@
+export const ISSUE_WINDOW_ARGUMENT_PREFIX = "--multica-issue-window=";
+
+const MAX_ISSUE_WINDOW_PATH_LENGTH = 2_048;
+const MAX_ISSUE_WINDOW_TITLE_LENGTH = 256;
+const WORKSPACE_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
+const ISSUE_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
+
+export type IssueWindowRequest = {
+ path: string;
+ title: string;
+};
+
+export type IssueWindowContext = IssueWindowRequest & {
+ kind: "issue";
+ workspaceSlug: string;
+ issueId: string;
+};
+
+export type DesktopWindowContext =
+ | { kind: "main" }
+ | IssueWindowContext;
+
+/**
+ * Validate renderer-controlled input before it can become a BrowserWindow
+ * launch argument. Dedicated windows are intentionally limited to one
+ * workspace-scoped issue-detail route; list pages and every other app route
+ * stay in the main tabbed window.
+ */
+export function parseIssueWindowRequest(value: unknown): IssueWindowContext | null {
+ if (!value || typeof value !== "object") return null;
+
+ const input = value as Record<string, unknown>;
+ if (typeof input.path !== "string") return null;
+ if (input.path.length === 0 || input.path.length > MAX_ISSUE_WINDOW_PATH_LENGTH) {
+ return null;
+ }
+
+ const parsedPath = parseIssueWindowPath(input.path);
+ if (!parsedPath) return null;
+
+ const rawTitle = typeof input.title === "string" ? input.title.trim() : "";
+ const title = rawTitle.slice(0, MAX_ISSUE_WINDOW_TITLE_LENGTH) || "Issue";
+
+ return {
+ kind: "issue",
+ path: parsedPath.path,
+ title,
+ workspaceSlug: parsedPath.workspaceSlug,
+ issueId: parsedPath.issueId,
+ };
+}
+
+/** Return a canonical issue-detail path, or null for every other URL shape. */
+export function parseIssueWindowPath(
+ value: unknown,
+): Pick<IssueWindowContext, "path" | "workspaceSlug" | "issueId"> | null {
+ if (typeof value !== "string") return null;
+ if (!value.startsWith("/") || value.startsWith("//")) return null;
+
+ let url: URL;
+ try {
+ url = new URL(value, "https://desktop.multica.invalid");
+ } catch {
+ return null;
+ }
+ if (url.origin !== "https://desktop.multica.invalid") return null;
+
+ const segments = url.pathname.split("/");
+ if (segments.length !== 4 || segments[0] !== "" || segments[2] !== "issues") {
+ return null;
+ }
+
+ let workspaceSlug: string;
+ let issueId: string;
+ try {
+ workspaceSlug = decodeURIComponent(segments[1] ?? "");
+ issueId = decodeURIComponent(segments[3] ?? "");
+ } catch {
+ return null;
+ }
+
+ if (!WORKSPACE_SLUG_PATTERN.test(workspaceSlug)) return null;
+ if (!ISSUE_REF_PATTERN.test(issueId)) return null;
+
+ const path = `/${workspaceSlug}/issues/${encodeURIComponent(issueId)}${url.search}${url.hash}`;
+ if (path.length > MAX_ISSUE_WINDOW_PATH_LENGTH) return null;
+
+ return { path, workspaceSlug, issueId };
+}
+
+export function encodeIssueWindowArgument(request: IssueWindowRequest): string {
+ const context = parseIssueWindowRequest(request);
+ if (!context) {
+ throw new Error("Invalid issue window request");
+ }
+ return `${ISSUE_WINDOW_ARGUMENT_PREFIX}${encodeURIComponent(
+ JSON.stringify({ path: context.path, title: context.title }),
+ )}`;
+}
+
+export function readDesktopWindowContext(
+ argv: readonly string[],
+): DesktopWindowContext {
+ const argument = argv.find((item) =>
+ item.startsWith(ISSUE_WINDOW_ARGUMENT_PREFIX),
+ );
+ if (!argument) return { kind: "main" };
+
+ try {
+ const encoded = argument.slice(ISSUE_WINDOW_ARGUMENT_PREFIX.length);
+ const decoded = JSON.parse(decodeURIComponent(encoded)) as unknown;
+ return parseIssueWindowRequest(decoded) ?? { kind: "main" };
+ } catch {
+ return { kind: "main" };
+ }
+}
diff --git a/apps/desktop/src/shared/main-renderer-messages.test.ts b/apps/desktop/src/shared/main-renderer-messages.test.ts
new file mode 100644
index 0000000000..010aa9b28b
--- /dev/null
+++ b/apps/desktop/src/shared/main-renderer-messages.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ MainRendererMessageQueue,
+ parseMainRendererChannelState,
+} from "./main-renderer-messages";
+
+describe("MainRendererMessageQueue", () => {
+ it("holds messages until their matching listener is ready", () => {
+ const queue = new MainRendererMessageQueue();
+ const send = vi.fn();
+
+ queue.enqueue("auth:token", "token-a", send);
+ queue.setReady("invite:open", true, send);
+ expect(send).not.toHaveBeenCalled();
+
+ queue.setReady("auth:token", true, send);
+ expect(send).toHaveBeenCalledWith("auth:token", "token-a");
+ });
+
+ it("delivers immediately while a channel is ready", () => {
+ const queue = new MainRendererMessageQueue();
+ const send = vi.fn();
+
+ queue.setReady("inbox:open", true, send);
+ queue.enqueue("inbox:open", { itemId: "item-1" }, send);
+
+ expect(send).toHaveBeenCalledOnce();
+ });
+
+ it("keeps queued work across a renderer readiness reset", () => {
+ const queue = new MainRendererMessageQueue();
+ const send = vi.fn();
+
+ queue.setReady("invite:open", true, send);
+ queue.resetReady();
+ queue.enqueue("invite:open", "invite-1", send);
+ expect(send).not.toHaveBeenCalled();
+
+ queue.setReady("invite:open", true, send);
+ expect(send).toHaveBeenCalledWith("invite:open", "invite-1");
+ });
+
+ it("can discard account-scoped pending messages", () => {
+ const queue = new MainRendererMessageQueue();
+ const send = vi.fn();
+
+ queue.enqueue("inbox:open", { itemId: "old-account-item" }, send);
+ queue.clear("inbox:open");
+ queue.setReady("inbox:open", true, send);
+
+ expect(send).not.toHaveBeenCalled();
+ });
+});
+
+describe("parseMainRendererChannelState", () => {
+ it("accepts only allowlisted channels with an explicit boolean", () => {
+ expect(
+ parseMainRendererChannelState({ channel: "auth:token", ready: true }),
+ ).toEqual({ channel: "auth:token", ready: true });
+ expect(
+ parseMainRendererChannelState({ channel: "shell:openExternal", ready: true }),
+ ).toBeNull();
+ expect(
+ parseMainRendererChannelState({ channel: "auth:token", ready: "yes" }),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/shared/main-renderer-messages.ts b/apps/desktop/src/shared/main-renderer-messages.ts
new file mode 100644
index 0000000000..7469311559
--- /dev/null
+++ b/apps/desktop/src/shared/main-renderer-messages.ts
@@ -0,0 +1,102 @@
+/**
+ * Main-process messages that must wait until the main renderer has installed
+ * the matching listener. A BrowserWindow finishing `loadURL` is not enough:
+ * React effects subscribe later, so an eager deep link can otherwise vanish.
+ */
+export const MAIN_RENDERER_CHANNEL_STATE_CHANNEL =
+ "main-renderer:channel-state";
+
+export const MAIN_RENDERER_MESSAGE_CHANNELS = [
+ "auth:token",
+ "invite:open",
+ "inbox:open",
+] as const;
+
+export type MainRendererMessageChannel =
+ (typeof MAIN_RENDERER_MESSAGE_CHANNELS)[number];
+
+export interface MainRendererChannelState {
+ channel: MainRendererMessageChannel;
+ ready: boolean;
+}
+
+const mainRendererMessageChannels = new Set<string>(
+ MAIN_RENDERER_MESSAGE_CHANNELS,
+);
+
+export function parseMainRendererChannelState(
+ value: unknown,
+): MainRendererChannelState | null {
+ if (!value || typeof value !== "object") return null;
+ const candidate = value as Record<string, unknown>;
+ if (
+ typeof candidate.channel !== "string" ||
+ !mainRendererMessageChannels.has(candidate.channel) ||
+ typeof candidate.ready !== "boolean"
+ ) {
+ return null;
+ }
+ return {
+ channel: candidate.channel as MainRendererMessageChannel,
+ ready: candidate.ready,
+ };
+}
+
+type SendMessage = (
+ channel: MainRendererMessageChannel,
+ payload: unknown,
+) => void;
+
+/**
+ * Holds renderer-bound messages until the specific React listener is ready.
+ * Readiness is per BrowserWindow lifecycle; pending messages intentionally
+ * survive a main-window close so recreating the window still delivers them.
+ */
+export class MainRendererMessageQueue {
+ private readonly readyChannels = new Set<MainRendererMessageChannel>();
+ private readonly pending = new Map<
+ MainRendererMessageChannel,
+ unknown[]
+ >();
+
+ enqueue(
+ channel: MainRendererMessageChannel,
+ payload: unknown,
+ send: SendMessage,
+ ): void {
+ if (this.readyChannels.has(channel)) {
+ send(channel, payload);
+ return;
+ }
+ const queued = this.pending.get(channel) ?? [];
+ queued.push(payload);
+ this.pending.set(channel, queued);
+ }
+
+ setReady(
+ channel: MainRendererMessageChannel,
+ ready: boolean,
+ send: SendMessage,
+ ): void {
+ if (!ready) {
+ this.readyChannels.delete(channel);
+ return;
+ }
+
+ this.readyChannels.add(channel);
+ const queued = this.pending.get(channel);
+ if (!queued) return;
+ this.pending.delete(channel);
+ for (const payload of queued) send(channel, payload);
+ }
+
+ /** Clear readiness when the main renderer is replaced, without losing work. */
+ resetReady(): void {
+ this.readyChannels.clear();
+ }
+
+ /** Drop messages that are no longer safe for the active account. */
+ clear(channel: MainRendererMessageChannel): void {
+ this.pending.delete(channel);
+ }
+}