Skip to content

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

Go

MUL-8432 feat(desktop): open each workspace in its own window (#9755)

Jiayuan Zhang631d770344b0
diff --git a/apps/desktop/src/main/auth-session-coordinator.test.ts b/apps/desktop/src/main/auth-session-coordinator.test.ts
index cf30b8e9b7..d8a1dfa2c8 100644
--- a/apps/desktop/src/main/auth-session-coordinator.test.ts
+++ b/apps/desktop/src/main/auth-session-coordinator.test.ts
@@ -5,27 +5,32 @@ import {
parseAuthSessionUserId,
} from "./auth-session-coordinator";
+function createCoordinator(mainWindows: string[] = ["main"]) {
+ const close = vi.fn();
+ const coordinator = new AuthSessionCoordinator<string>(close);
+ for (const window of mainWindows) coordinator.registerMainWindow(window);
+ return { close, 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");
+ const { close, coordinator } = createCoordinator();
+ coordinator.reportMain("main", "user-a");
coordinator.registerIssueWindow("issue-1");
coordinator.reportIssue("issue-1", "user-a");
expect(close).not.toHaveBeenCalled();
- expect(coordinator.hasActiveMainSession()).toBe(true);
+ expect(coordinator.hasActiveMainSession("main")).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");
+ const { close, coordinator } = createCoordinator();
+ coordinator.reportMain("main", "user-a");
coordinator.registerIssueWindow("issue-1");
coordinator.registerIssueWindow("issue-2");
- coordinator.reportMain("user-b");
+ coordinator.reportMain("main", "user-b");
expect(close).toHaveBeenCalledTimes(2);
expect(close).toHaveBeenCalledWith("issue-1");
@@ -33,19 +38,60 @@ describe("AuthSessionCoordinator", () => {
});
it("invalidates account-scoped work once per session transition", () => {
- const coordinator = new AuthSessionCoordinator<string>(() => {});
+ const { coordinator } = createCoordinator();
+
+ expect(coordinator.reportMain("main", "user-a")).toBe(false);
+ expect(coordinator.reportMain("main", "user-a")).toBe(false);
+ expect(coordinator.reportMain("main", null)).toBe(true);
+ expect(coordinator.reportMain("main", null)).toBe(false);
+ expect(coordinator.reportMain("main", "user-b")).toBe(true);
+ });
+
+ it("keeps main windows that share the account", () => {
+ const { close, coordinator } = createCoordinator(["work", "personal"]);
+
+ coordinator.reportMain("work", "user-a");
+ coordinator.reportMain("personal", "user-a");
+
+ expect(close).not.toHaveBeenCalled();
+ expect(coordinator.hasActiveMainSession("work")).toBe(true);
+ expect(coordinator.hasActiveMainSession("personal")).toBe(true);
+ });
+
+ it("closes every other window when any main window logs out", () => {
+ const { close, coordinator } = createCoordinator(["work", "personal"]);
+ coordinator.reportMain("work", "user-a");
+ coordinator.reportMain("personal", "user-a");
+ coordinator.registerIssueWindow("issue-1");
+
+ expect(coordinator.reportMain("personal", null)).toBe(true);
- 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);
+ expect(close).toHaveBeenCalledTimes(2);
+ expect(close).toHaveBeenCalledWith("work");
+ expect(close).toHaveBeenCalledWith("issue-1");
+ expect(coordinator.hasActiveMainSession("work")).toBe(false);
+ });
+
+ it("closes a main window that has not reported yet when another logs out", () => {
+ const { close, coordinator } = createCoordinator(["work", "restoring"]);
+
+ coordinator.reportMain("work", null);
+
+ expect(close).toHaveBeenCalledWith("restoring");
+ });
+
+ it("ignores reports from windows it does not track as main windows", () => {
+ const { close, coordinator } = createCoordinator();
+ coordinator.reportMain("main", "user-a");
+
+ expect(coordinator.reportMain("unknown", null)).toBe(false);
+ expect(close).not.toHaveBeenCalled();
+ expect(coordinator.hasActiveMainSession("main")).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");
+ const { close, coordinator } = createCoordinator();
+ coordinator.reportMain("main", "user-a");
coordinator.registerIssueWindow("stale");
coordinator.registerIssueWindow("logged-out");
diff --git a/apps/desktop/src/main/auth-session-coordinator.ts b/apps/desktop/src/main/auth-session-coordinator.ts
index 1366e8121c..55edf3ebc3 100644
--- a/apps/desktop/src/main/auth-session-coordinator.ts
+++ b/apps/desktop/src/main/auth-session-coordinator.ts
@@ -6,18 +6,29 @@ export {
} 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.
+ * Keeps every window bound to one authenticated account. Tokens never cross
+ * renderer boundaries: only the resolved user id is compared. Main windows
+ * share the session token through storage, so the latest main-window report
+ * is the account; a logout or account switch reported by any main window
+ * closes every other window instead of leaving it signed in to the old one.
*/
export class AuthSessionCoordinator<T> {
- private mainUserId: AuthSessionUserId | undefined;
+ private accountUserId: AuthSessionUserId | undefined;
+ private readonly mainUserIds = new Map<T, AuthSessionUserId | undefined>();
private readonly issueUserIds = new Map<
T,
AuthSessionUserId | undefined
>();
- constructor(private readonly closeIssueWindow: (window: T) => void) {}
+ constructor(private readonly closeWindow: (window: T) => void) {}
+
+ registerMainWindow(window: T): void {
+ this.mainUserIds.set(window, undefined);
+ }
+
+ unregisterMainWindow(window: T): void {
+ this.mainUserIds.delete(window);
+ }
registerIssueWindow(window: T): void {
this.issueUserIds.set(window, undefined);
@@ -27,31 +38,39 @@ export class AuthSessionCoordinator<T> {
this.issueUserIds.delete(window);
}
- hasActiveMainSession(): boolean {
- return typeof this.mainUserId === "string";
+ hasActiveMainSession(window: T): boolean {
+ const userId = this.mainUserIds.get(window);
+ return typeof userId === "string" && userId === this.accountUserId;
}
isCurrentIssueSession(window: T): boolean {
return (
- typeof this.mainUserId === "string" &&
- this.issueUserIds.get(window) === this.mainUserId
+ typeof this.accountUserId === "string" &&
+ this.issueUserIds.get(window) === this.accountUserId
);
}
- reportMain(userId: AuthSessionUserId): boolean {
- const becameLoggedOut = userId === null && this.mainUserId !== null;
+ reportMain(window: T, userId: AuthSessionUserId): boolean {
+ if (!this.mainUserIds.has(window)) return false;
+ const becameLoggedOut = userId === null && this.accountUserId !== null;
const accountChanged =
- this.mainUserId !== undefined && this.mainUserId !== userId;
- this.mainUserId = userId;
+ this.accountUserId !== undefined && this.accountUserId !== userId;
+ this.accountUserId = userId;
+ this.mainUserIds.set(window, userId);
if (userId === null || accountChanged) {
- this.closeAllIssueWindows();
+ this.closeAllExcept(window);
return becameLoggedOut || accountChanged;
}
- for (const [window, issueUserId] of this.issueUserIds) {
+ for (const [other, otherUserId] of [...this.mainUserIds]) {
+ if (other !== window && otherUserId !== undefined && otherUserId !== userId) {
+ this.close(other);
+ }
+ }
+ for (const [issueWindow, issueUserId] of [...this.issueUserIds]) {
if (issueUserId !== undefined && issueUserId !== userId) {
- this.closeIssue(window);
+ this.close(issueWindow);
}
}
return false;
@@ -62,20 +81,21 @@ export class AuthSessionCoordinator<T> {
this.issueUserIds.set(window, userId);
if (
userId === null ||
- (this.mainUserId !== undefined && this.mainUserId !== userId)
+ (this.accountUserId !== undefined && this.accountUserId !== userId)
) {
- this.closeIssue(window);
+ this.close(window);
}
}
- private closeAllIssueWindows(): void {
- for (const window of [...this.issueUserIds.keys()]) {
- this.closeIssue(window);
+ private closeAllExcept(keep: T): void {
+ for (const window of [...this.mainUserIds.keys(), ...this.issueUserIds.keys()]) {
+ if (window !== keep) this.close(window);
}
}
- private closeIssue(window: T): void {
+ private close(window: T): void {
+ this.mainUserIds.delete(window);
this.issueUserIds.delete(window);
- this.closeIssueWindow(window);
+ this.closeWindow(window);
}
}
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
index aad967589c..db7a41811a 100644
--- a/apps/desktop/src/main/daemon-manager.ts
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -90,8 +90,10 @@ interface ActiveProfile {
let statusPollTimer: ReturnType<typeof setInterval> | null = null;
let logTailWatcher: { path: string; listener: StatsListener } | null = null;
+let logTailOwner: Electron.WebContents | null = null;
let currentState: DaemonStatus["state"] = "installing_cli";
let getMainWindow: () => BrowserWindow | null = () => null;
+let getStatusWindows: () => readonly BrowserWindow[] = () => [];
let statusPollInProgress = false;
let cachedCliBinary: string | null | undefined = undefined;
let cliResolvePromise: Promise<string | null> | null = null;
@@ -176,8 +178,10 @@ function urlsMatch(a: string, b: string): boolean {
}
function sendStatus(status: DaemonStatus): void {
- const win = getMainWindow();
- win?.webContents.send("daemon:status", status);
+ // One daemon serves every main window, and each shows its status.
+ for (const win of getStatusWindows()) {
+ if (!win.isDestroyed()) win.webContents.send("daemon:status", status);
+ }
}
interface HealthPayload {
@@ -1319,6 +1323,7 @@ async function readLogRange(
}
function sendLines(win: BrowserWindow, text: string): void {
+ if (win.isDestroyed()) return;
const lines = text.split("\n").filter((line) => line.length > 0);
for (const line of lines) {
win.webContents.send("daemon:log-line", line);
@@ -1354,6 +1359,7 @@ function startLogTail(win: BrowserWindow, retryCount = 0): void {
const startAt = initialStats.size - windowBytes;
if (windowBytes > 0) {
const text = await readLogRange(logPath, startAt, windowBytes);
+ if (win.isDestroyed()) return;
const lines = text
.split("\n")
.filter((line) => line.length > 0)
@@ -1369,8 +1375,10 @@ function startLogTail(win: BrowserWindow, retryCount = 0): void {
}
const listener: StatsListener = (curr) => {
- const target = getMainWindow();
- if (!target) return;
+ if (win.isDestroyed()) {
+ stopLogTail();
+ return;
+ }
// File rotated/truncated — restart from the new beginning.
if (curr.size < position) position = 0;
if (curr.size === position) return;
@@ -1378,7 +1386,7 @@ function startLogTail(win: BrowserWindow, retryCount = 0): void {
const length = curr.size - from;
position = curr.size;
readLogRange(logPath, from, length)
- .then((text) => sendLines(target, text))
+ .then((text) => sendLines(win, text))
.catch((err) => {
console.warn("[daemon] log tail read failed:", err);
});
@@ -1431,10 +1439,19 @@ export function resumeDaemonAfterAbortedUpdateInstall(): void {
startPolling();
}
+/**
+ * `windowGetter` is the main window that hosts dialogs and progress;
+ * `statusWindowsGetter` lists every main window that shows daemon status.
+ */
export function setupDaemonManager(
windowGetter: () => BrowserWindow | null,
+ statusWindowsGetter: () => readonly BrowserWindow[] = () => {
+ const window = windowGetter();
+ return window ? [window] : [];
+ },
): void {
getMainWindow = windowGetter;
+ getStatusWindows = statusWindowsGetter;
ipcMain.handle("daemon:set-target-api-url", async (_e, url: string) => {
const normalized = url || null;
@@ -1543,12 +1560,18 @@ export function setupDaemonManager(
});
});
- ipcMain.on("daemon:start-log-stream", () => {
- const win = getMainWindow();
- if (win) startLogTail(win);
+ // One tail at a time, streamed to the window that opened the log view
+ // last; a window closing its view does not stop another window's stream.
+ ipcMain.on("daemon:start-log-stream", (event) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (!win) return;
+ logTailOwner = event.sender;
+ startLogTail(win);
});
- ipcMain.on("daemon:stop-log-stream", () => {
+ ipcMain.on("daemon:stop-log-stream", (event) => {
+ if (logTailOwner && logTailOwner !== event.sender) return;
+ logTailOwner = null;
stopLogTail();
});
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index c549608dda..9a1d4efb8f 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -1,4 +1,13 @@
-import { app, BrowserWindow, dialog, ipcMain, nativeImage, Notification, screen } from "electron";
+import {
+ app,
+ autoUpdater as nativeAutoUpdater,
+ BrowserWindow,
+ dialog,
+ ipcMain,
+ nativeImage,
+ Notification,
+ screen,
+} from "electron";
import { homedir } from "os";
import { join } from "path";
import { pathToFileURL } from "url";
@@ -40,17 +49,27 @@ import {
clearFreezeBreadcrumb,
} from "./freeze-breadcrumb";
import {
- loadWindowState,
+ loadWindowSession,
resolveWindowOptions,
- saveWindowStateToFile,
+ saveWindowSessionToFile,
snapshotWindowState,
windowStateFilePath,
+ type WindowState,
} from "./window-state";
import {
encodeIssueWindowArgument,
parseIssueWindowRequest,
type IssueWindowContext,
} from "../shared/issue-window";
+import {
+ encodeWorkspaceWindowArgument,
+ FOCUS_WORKSPACE_WINDOW_CHANNEL,
+ OPEN_WORKSPACE_WINDOW_CHANNEL,
+ OTHER_WINDOW_WORKSPACES_CHANNEL,
+ parseWorkspaceSlug,
+ parseWorkspaceWindowPath,
+ WINDOW_WORKSPACE_REPORT_CHANNEL,
+} from "../shared/workspace-window";
import {
AUTH_SESSION_STATE_CHANNEL,
parseAuthSessionUserId,
@@ -58,11 +77,14 @@ import {
import {
MAIN_RENDERER_CHANNEL_STATE_CHANNEL,
MainRendererMessageQueue,
+ NEW_WINDOW_SHORTCUT_CHANNEL,
parseMainRendererChannelState,
TAB_SELECTION_SHORTCUT_CHANNEL,
+ WORKSPACE_OPEN_PATH_CHANNEL,
type MainRendererMessageChannel,
} from "../shared/main-renderer-messages";
import { AuthSessionCoordinator } from "./auth-session-coordinator";
+import { MainWindowRegistry } from "./main-window-registry";
import {
NotificationGate,
parseNativeNotificationPayload,
@@ -71,7 +93,7 @@ import {
configureLinuxFileDialogs(app.commandLine);
// Guards against registering the will-download handler more than once on the
-// same session. window.webContents.session is shared, and createWindow() can
+// same session. window.webContents.session is shared, and createMainWindow() can
// be called again on macOS (app "activate" after all windows are closed).
const downloadDialogSessions = new WeakSet<Electron.Session>();
@@ -91,7 +113,7 @@ function installDownloadSaveDialogHandler(window: BrowserWindow): void {
// but Linux production needs an explicit BrowserWindow `icon` — AppImage
// direct-launch doesn't register the .desktop entry, so GNOME has no path
// from the running window to the hicolor icon and falls back to the
-// theme default. Consumed in createWindow() (all platforms in dev, Linux
+// theme default. Consumed in createMainWindow() (all platforms in dev, Linux
// in prod) and the macOS dev dock branch.
//
// `asarUnpack: resources/**` in electron-builder.yml extracts the icon to
@@ -111,7 +133,7 @@ const BUNDLED_ICON_PATH = join(__dirname, "../../resources/icon.png").replace(
// Run the user's login shell once to recover the real PATH so the bundled
// multica CLI can find agent binaries like claude/codex/opencode. Must run
// before any child_process.spawn / execFile call in the main process —
-// ES module imports are hoisted, so this block executes before createWindow
+// ES module imports are hoisted, so this block executes before createMainWindow
// or any daemon-manager spawn.
if (process.platform !== "win32") {
fixPath();
@@ -138,7 +160,7 @@ function freezeBreadcrumbPath(): string {
return join(app.getPath("userData"), "last-client-failure.json");
}
-let mainWindow: BrowserWindow | null = null;
+const mainWindows = new MainWindowRegistry<BrowserWindow>();
const issueWindows = new Set<BrowserWindow>();
const authSessionCoordinator = new AuthSessionCoordinator<BrowserWindow>(
(window) => {
@@ -147,7 +169,13 @@ const authSessionCoordinator = new AuthSessionCoordinator<BrowserWindow>(
},
);
const notificationGate = new NotificationGate();
-const mainRendererMessages = new MainRendererMessageQueue();
+const mainRendererMessages = new MainRendererMessageQueue<BrowserWindow>(
+ (window, channel, payload) => {
+ if (!window.isDestroyed()) window.webContents.send(channel, payload);
+ },
+ (window) => !window.isDestroyed() && mainWindows.has(window),
+);
+const unreadBadgeCounts = new Map<BrowserWindow, number>();
let desktopInitialized = false;
let authSessionGeneration = 0;
const rendererRouteContexts = new WeakMap<
@@ -162,34 +190,120 @@ 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 {
+function focusWindow(window: BrowserWindow): void {
if (window.isMinimized()) window.restore();
window.show();
window.focus();
}
+function windowStateFile(): string {
+ return windowStateFilePath(app.getPath("userData"));
+}
+
+/** The main window that app-level requests land in, created on demand. */
function ensureMainWindow(): BrowserWindow | null {
if (!desktopInitialized || !app.isReady()) return null;
- if (!mainWindow || mainWindow.isDestroyed()) return createWindow();
- return mainWindow;
+ return (
+ mainWindows.mostRecent() ??
+ createMainWindow(loadWindowSession(windowStateFile())[0])
+ );
}
+/**
+ * Deliver to `target` when given (a window that shows a specific workspace,
+ * or the window a shortcut came from), else to the most recently focused
+ * main window — creating one when none is open.
+ */
function dispatchToMainRenderer(
channel: MainRendererMessageChannel,
payload: unknown,
+ target: BrowserWindow | null = null,
): void {
- mainRendererMessages.enqueue(channel, payload, sendMainRendererMessage);
- const window = ensureMainWindow();
- if (window) focusMainWindow(window);
+ const window =
+ target && !target.isDestroyed() && mainWindows.has(target)
+ ? target
+ : ensureMainWindow();
+ mainRendererMessages.enqueue(window, channel, payload);
+ if (window) focusWindow(window);
+}
+
+/** Shortcuts from a dedicated issue window go to the most recent main window. */
+function mainWindowFor(window: BrowserWindow): BrowserWindow | null {
+ return mainWindows.has(window) ? window : null;
+}
+
+/**
+ * Give a workspace request from `source` to the other main window showing
+ * that workspace: open `path` there when the request has one, else focus it.
+ * Returns false when no other window shows the workspace.
+ */
+function handOffToWorkspaceWindow(
+ source: BrowserWindow | null,
+ request: unknown,
+): boolean {
+ if (!source || !mainWindows.has(source)) return false;
+ if (!request || typeof request !== "object") return false;
+ const { workspaceSlug: rawSlug, path: rawPath } = request as Record<
+ string,
+ unknown
+ >;
+ const workspaceSlug = parseWorkspaceSlug(rawSlug);
+ if (!workspaceSlug) return false;
+ const path =
+ rawPath === undefined ? null : parseWorkspaceWindowPath(workspaceSlug, rawPath);
+ if (rawPath !== undefined && !path) return false;
+ const target = mainWindows.findByWorkspace(workspaceSlug, source);
+ if (!target || target.isDestroyed()) return false;
+ if (path) {
+ dispatchToMainRenderer(WORKSPACE_OPEN_PATH_CHANNEL, path, target);
+ } else {
+ focusWindow(target);
+ }
+ return true;
+}
+
+// --- Main-window session --------------------------------------------------
+
+// Every main window's geometry and workspace, restored on the next launch.
+// Frozen once a real quit starts: windows close one by one on the way out,
+// and saving after each close would leave only the last one in the file.
+let windowSessionFrozen = false;
+let windowSessionTimer: ReturnType<typeof setTimeout> | null = null;
+
+function saveWindowSession(): void {
+ if (windowSessionTimer) {
+ clearTimeout(windowSessionTimer);
+ windowSessionTimer = null;
+ }
+ if (windowSessionFrozen || mainWindows.size === 0) return;
+ const windows: WindowState[] = [];
+ for (const window of mainWindows.all()) {
+ const snapshot = snapshotWindowState(window);
+ if (!snapshot) continue;
+ const workspaceSlug = mainWindows.workspaceOf(window);
+ windows.push(workspaceSlug ? { ...snapshot, workspaceSlug } : snapshot);
+ }
+ if (windows.length > 0) saveWindowSessionToFile(windowStateFile(), windows);
+}
+
+function scheduleWindowSessionSave(): void {
+ if (windowSessionTimer) clearTimeout(windowSessionTimer);
+ windowSessionTimer = setTimeout(saveWindowSession, 400);
+}
+
+function freezeWindowSession(): void {
+ saveWindowSession();
+ windowSessionFrozen = true;
+}
+
+function applyUnreadBadge(): void {
+ let count = 0;
+ for (const value of unreadBadgeCounts.values()) count += value;
+ if (process.platform === "darwin") {
+ app.dock?.setBadge(count === 0 ? "" : count > 99 ? "99+" : String(count));
+ } else {
+ app.setBadgeCount(count);
+ }
}
function handleDeepLink(url: string): void {
@@ -274,23 +388,39 @@ function installWindowShortcutHandler(window: BrowserWindow): void {
window.webContents.send("tab:close-active");
} else if (result === "open-settings") {
event.preventDefault();
- // Settings is a tab, so it can only live in the tabbed main window.
+ // Settings is a tab, so it can only live in a tabbed main window.
// Routing through the queue means the chord also works from a
- // dedicated issue window — and from one that outlived the main window,
- // which is recreated and only then handed the request.
- dispatchToMainRenderer("settings:open", null);
+ // dedicated issue window — and from one that outlived every main
+ // window, which is recreated and only then handed the request.
+ dispatchToMainRenderer("settings:open", null, mainWindowFor(window));
} else if (typeof result === "object" && result.action === "select-tab") {
event.preventDefault();
- // Product tabs only exist in the main window. Route there even when the
+ // Product tabs only exist in main windows. Route there even when the
// chord came from a dedicated issue window, matching Settings behavior.
- dispatchToMainRenderer(TAB_SELECTION_SHORTCUT_CHANNEL, result.key);
+ dispatchToMainRenderer(
+ TAB_SELECTION_SHORTCUT_CHANNEL,
+ result.key,
+ mainWindowFor(window),
+ );
+ } else if (result === "new-window") {
+ event.preventDefault();
+ dispatchToMainRenderer(
+ NEW_WINDOW_SHORTCUT_CHANNEL,
+ null,
+ mainWindowFor(window),
+ );
} else if (result) {
event.preventDefault();
}
});
}
-function createWindow(): BrowserWindow {
+/**
+ * A tabbed main window. `saved.workspaceSlug` pins the workspace it opens on;
+ * without one (first launch, or a pre-multi-window state file) the renderer
+ * falls back to its persisted active workspace.
+ */
+function createMainWindow(saved: WindowState = {}): 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
@@ -298,19 +428,16 @@ function createWindow(): BrowserWindow {
const systemLocale = getSystemLocale();
lastKnownSystemLocale = systemLocale;
- mainRendererMessages.resetReady();
-
// Restore prior size/position/maximized/fullscreen (#5244), constraining
// bounds to the work area of the display the window will land on.
- const stateFile = windowStateFilePath(app.getPath("userData"));
- const savedWindowState = loadWindowState(stateFile);
const windowOpts = resolveWindowOptions(
- savedWindowState,
+ saved,
screen.getAllDisplays().map((d) => d.workArea),
screen.getPrimaryDisplay().workArea,
);
+ const workspaceSlug = saved.workspaceSlug ?? null;
- mainWindow = new BrowserWindow({
+ const window = new BrowserWindow({
width: windowOpts.width,
height: windowOpts.height,
...(windowOpts.x != null && windowOpts.y != null
@@ -334,34 +461,30 @@ function createWindow(): BrowserWindow {
webPreferences: createRendererWebPreferences(
join(__dirname, "../preload/index.js"),
systemLocale,
+ workspaceSlug ? [encodeWorkspaceWindowArgument(workspaceSlug)] : [],
),
});
- const window = mainWindow;
-
- // Persist bounds on resize/move (debounced) and on close so the next
- // launch restores size/position and max/fullscreen flags. getNormalBounds
- // is used so maximized/fullscreen still saves the restore size.
- let persistTimer: ReturnType<typeof setTimeout> | null = null;
- const persistWindowState = () => {
- const snap = snapshotWindowState(window);
- if (snap) saveWindowStateToFile(stateFile, snap);
- };
- const schedulePersistWindowState = () => {
- if (persistTimer) clearTimeout(persistTimer);
- persistTimer = setTimeout(persistWindowState, 400);
- };
- window.on("resize", schedulePersistWindowState);
- window.on("move", schedulePersistWindowState);
+ mainWindows.add(window, workspaceSlug);
+ authSessionCoordinator.registerMainWindow(window);
+
+ // Persist bounds on resize/move (debounced) so the next launch restores
+ // size/position and max/fullscreen flags. getNormalBounds is used so
+ // maximized/fullscreen still saves the restore size.
+ window.on("focus", () => mainWindows.focus(window));
+ window.on("resize", scheduleWindowSessionSave);
+ window.on("move", scheduleWindowSessionSave);
window.on("close", () => {
- if (persistTimer) clearTimeout(persistTimer);
- persistWindowState();
+ // Closing the last window keeps it in the file, so the next launch (or a
+ // macOS Dock click) reopens it; closing any other window forgets it.
+ if (mainWindows.size === 1) saveWindowSession();
});
window.on("closed", () => {
- if (mainWindow === window) {
- mainWindow = null;
- mainRendererMessages.resetReady();
- }
+ mainWindows.remove(window);
+ authSessionCoordinator.unregisterMainWindow(window);
+ mainRendererMessages.release(window, mainWindows.mostRecent());
+ if (unreadBadgeCounts.delete(window)) applyUnreadBadge();
+ if (mainWindows.size > 0) saveWindowSession();
});
// Strip Origin header from WebSocket upgrade requests so the server's
@@ -610,7 +733,7 @@ if (!gotTheLock) {
// Windows/Linux: second instance passes deep link via argv
app.on("second-instance", (_event, argv) => {
const window = ensureMainWindow();
- if (window) focusMainWindow(window);
+ if (window) focusWindow(window);
// On Windows the deep link URL is the last argv entry
const deepLinkUrl = argv.find((arg) => arg.startsWith(`${PROTOCOL}://`));
@@ -737,32 +860,88 @@ if (!gotTheLock) {
rendererRouteContexts.set(event.sender, sanitized);
});
- // Preload announces each listener only after it has been installed by the
+ // Preload announces each listener only after it has been installed by a
// main renderer. Ignore issue-window senders so they can never drain a
- // payload intended for the tabbed application window.
+ // payload intended for a tabbed application window.
ipcMain.on(
MAIN_RENDERER_CHANNEL_STATE_CHANNEL,
(event, state: unknown) => {
- if (!mainWindow || event.sender !== mainWindow.webContents) return;
+ const window = BrowserWindow.fromWebContents(event.sender);
+ if (!window || !mainWindows.has(window)) return;
const parsed = parseMainRendererChannelState(state);
if (!parsed) return;
- mainRendererMessages.setReady(
- parsed.channel,
- parsed.ready,
- sendMainRendererMessage,
- );
+ mainRendererMessages.setReady(window, parsed.channel, parsed.ready);
},
);
+ // Each main window reports the workspace it shows, so routing by
+ // workspace and the restored session follow in-window switches.
+ ipcMain.on(WINDOW_WORKSPACE_REPORT_CHANNEL, (event, value: unknown) => {
+ const window = BrowserWindow.fromWebContents(event.sender);
+ if (!window || !mainWindows.has(window)) return;
+ const workspaceSlug = value === null ? null : parseWorkspaceSlug(value);
+ if (value !== null && !workspaceSlug) return;
+ if (mainWindows.setWorkspace(window, workspaceSlug)) {
+ scheduleWindowSessionSave();
+ }
+ });
+
+ // Sync IPC: the renderer reads this while deciding where a workspace
+ // link goes, inside a click handler, so it must answer synchronously.
+ ipcMain.on(OTHER_WINDOW_WORKSPACES_CHANNEL, (event) => {
+ const window = BrowserWindow.fromWebContents(event.sender);
+ event.returnValue =
+ window && mainWindows.has(window)
+ ? mainWindows.otherWorkspaces(window)
+ : [];
+ });
+
+ // Sync IPC: returns whether another main window took the request, so
+ // the caller only falls back to switching its own workspace when not.
+ // Assigning returnValue sends the reply, so it is assigned exactly once.
+ ipcMain.on(FOCUS_WORKSPACE_WINDOW_CHANNEL, (event, request: unknown) => {
+ event.returnValue = handOffToWorkspaceWindow(
+ BrowserWindow.fromWebContents(event.sender),
+ request,
+ );
+ });
+
+ // A workspace lives in at most one window: focus the window that already
+ // shows it, else open a new one cascaded from the requesting window.
+ ipcMain.handle(OPEN_WORKSPACE_WINDOW_CHANNEL, (event, value: unknown) => {
+ const source = BrowserWindow.fromWebContents(event.sender);
+ const workspaceSlug = parseWorkspaceSlug(value);
+ if (!source || !mainWindows.has(source) || !workspaceSlug) {
+ return { ok: false } as const;
+ }
+ const existing = mainWindows.findByWorkspace(workspaceSlug);
+ if (existing) {
+ focusWindow(existing);
+ return { ok: true } as const;
+ }
+ const bounds = source.getNormalBounds();
+ createMainWindow({
+ x: bounds.x + 28,
+ y: bounds.y + 28,
+ width: bounds.width,
+ height: bounds.height,
+ workspaceSlug,
+ });
+ return { ok: true } as const;
+ });
+
// Account identity is the only cross-renderer auth signal. Main remains
- // authoritative and closes issue windows instead of copying credentials.
+ // authoritative and closes 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 (mainWindows.has(sourceWindow)) {
+ const accountInvalidated = authSessionCoordinator.reportMain(
+ sourceWindow,
+ userId,
+ );
if (accountInvalidated) {
authSessionGeneration += 1;
mainRendererMessages.clear("inbox:open");
@@ -790,8 +969,8 @@ if (!gotTheLock) {
ipcMain.on("notification:show", (event, value: unknown) => {
const sourceWindow = BrowserWindow.fromWebContents(event.sender);
if (!sourceWindow) return;
- if (sourceWindow === mainWindow) {
- if (!authSessionCoordinator.hasActiveMainSession()) return;
+ if (mainWindows.has(sourceWindow)) {
+ if (!authSessionCoordinator.hasActiveMainSession(sourceWindow)) return;
} else if (
!issueWindows.has(sourceWindow) ||
!authSessionCoordinator.isCurrentIssueSession(sourceWindow)
@@ -817,13 +996,18 @@ if (!gotTheLock) {
// 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,
- });
+ // Prefer the window that shows the item's workspace. Recreate a main
+ // window when an issue-only window outlived them all, then wait for
+ // the inbox listener before delivering the navigation.
+ dispatchToMainRenderer(
+ "inbox:open",
+ {
+ slug: payload.slug,
+ itemId: payload.itemId,
+ issueKey: payload.issueKey,
+ },
+ mainWindows.findByWorkspace(payload.slug),
+ );
});
notification.show();
});
@@ -832,40 +1016,60 @@ if (!gotTheLock) {
// "99+". macOS is the primary target (user-visible dock badge); Linux
// Unity launchers also respect `setBadgeCount`. Windows' taskbar overlay
// needs a pre-rendered PNG and is deferred — the OS notification + the
- // in-app inbox sidebar cover the core UX there for now.
- ipcMain.on("badge:set", (_event, rawCount: number) => {
- const count = Math.max(0, Math.floor(rawCount));
- if (process.platform === "darwin") {
- const label = count === 0 ? "" : count > 99 ? "99+" : String(count);
- app.dock?.setBadge(label);
- } else {
- app.setBadgeCount(count);
- }
+ // in-app inbox sidebar cover the core UX there for now. Each main window
+ // counts its own workspace's unread items; the badge shows the total.
+ ipcMain.on("badge:set", (event, rawCount: unknown) => {
+ const window = BrowserWindow.fromWebContents(event.sender);
+ if (!window || !mainWindows.has(window)) return;
+ const count =
+ typeof rawCount === "number" && Number.isFinite(rawCount)
+ ? Math.max(0, Math.floor(rawCount))
+ : 0;
+ unreadBadgeCounts.set(window, count);
+ applyUnreadBadge();
});
desktopInitialized = true;
- createWindow();
+ for (const saved of loadWindowSession(windowStateFile())) {
+ createMainWindow(saved);
+ }
// Register first so the update quit gate can block daemon autoStop.
- setupAutoUpdater(() => mainWindow, {
+ setupAutoUpdater(() => mainWindows.all(), {
// Windows only (the updater ignores it elsewhere): stop the bundled
// daemon before the installer runs so multica.exe is replaced. #8823
daemonGate: {
prepare: prepareDaemonForUpdateInstall,
resumeAfterAbortedInstall: resumeDaemonAfterAbortedUpdateInstall,
- confirmInstallWhileBusy: createElectronBusyInstallPrompt((options) =>
- mainWindow && !mainWindow.isDestroyed()
- ? dialog.showMessageBox(mainWindow, options)
- : dialog.showMessageBox(options),
- ),
+ confirmInstallWhileBusy: createElectronBusyInstallPrompt((options) => {
+ const parent = mainWindows.mostRecent();
+ return parent && !parent.isDestroyed()
+ ? dialog.showMessageBox(parent, options)
+ : dialog.showMessageBox(options);
+ }),
},
});
- setupDaemonManager(() => mainWindow);
- setupLocalDirectory(() => mainWindow);
+ setupDaemonManager(
+ () => mainWindows.mostRecent(),
+ () => mainWindows.all(),
+ );
+ setupLocalDirectory(() => mainWindows.mostRecent());
+
+ // Registered after the updater and daemon gates, so a quit they hold
+ // (busy daemon, pending install) leaves the session writable; only the
+ // quit that actually proceeds freezes it.
+ app.on("before-quit", (event) => {
+ if (event.defaultPrevented) return;
+ freezeWindowSession();
+ });
+ // macOS quitAndInstall closes every window before before-quit fires.
+ if (process.platform === "darwin") {
+ nativeAutoUpdater.on("before-quit-for-update", freezeWindowSession);
+ }
app.on("activate", () => {
const window = ensureMainWindow();
- if (window) focusMainWindow(window);
+ if (window) focusWindow(window);
});
});
}
diff --git a/apps/desktop/src/main/keyboard-shortcuts.test.ts b/apps/desktop/src/main/keyboard-shortcuts.test.ts
index a496b090d5..0716b4a36d 100644
--- a/apps/desktop/src/main/keyboard-shortcuts.test.ts
+++ b/apps/desktop/src/main/keyboard-shortcuts.test.ts
@@ -358,6 +358,34 @@ describe("handleAppShortcut — open settings (Cmd/Ctrl+,)", () => {
});
});
+describe("handleAppShortcut — new window (Cmd/Ctrl+Shift+N)", () => {
+ it('returns "new-window" on Cmd+Shift+N (macOS) and Ctrl+Shift+N elsewhere', () => {
+ const wc = makeWc();
+ expect(
+ handleAppShortcut(key("N", { meta: true, shift: true }), wc, "darwin"),
+ ).toBe("new-window");
+ expect(
+ handleAppShortcut(key("N", { control: true, shift: true }), wc, "win32"),
+ ).toBe("new-window");
+ });
+
+ it("leaves the bare Cmd/Ctrl+N chord to the renderer", () => {
+ const wc = makeWc();
+ expect(handleAppShortcut(key("n", { meta: true }), wc, "darwin")).toBe(false);
+ });
+
+ it("swallows auto-repeat without opening a window per repeat", () => {
+ const wc = makeWc();
+ expect(
+ handleAppShortcut(
+ { ...key("N", { meta: true, shift: true }), isAutoRepeat: true },
+ wc,
+ "darwin",
+ ),
+ ).toBe(true);
+ });
+});
+
describe("handleAppShortcut — close tab (Cmd/Ctrl+W)", () => {
it('returns "close-tab" on Cmd+W (macOS)', () => {
const wc = makeWc();
diff --git a/apps/desktop/src/main/keyboard-shortcuts.ts b/apps/desktop/src/main/keyboard-shortcuts.ts
index 26b525805c..1697c96059 100644
--- a/apps/desktop/src/main/keyboard-shortcuts.ts
+++ b/apps/desktop/src/main/keyboard-shortcuts.ts
@@ -29,12 +29,13 @@ const ZOOM_MAX = 4.5;
* Window shortcut outcomes tell the caller whether to continue, preventDefault,
* or dispatch a renderer action. Prevent handled input from also firing the menu
* accelerator. Handle zoom here for consistent keyboard-layout behavior.
- * close-tab, open-settings, and select-tab actions route to the main window.
+ * open-settings, select-tab, and new-window actions route to a main window.
*/
export type ShortcutResult =
| boolean
| "close-tab"
| "open-settings"
+ | "new-window"
| { action: "select-tab"; key: TabSelectionShortcutKey };
export function handleAppShortcut(
@@ -109,6 +110,13 @@ export function handleAppShortcut(
return "open-settings";
}
+ // Cmd/Ctrl + Shift + N → open another workspace in a new window. The
+ // renderer owns the workspace list, so main only forwards the request.
+ if (input.key.toLowerCase() === "n" && input.shift) {
+ if (input.isAutoRepeat) return true;
+ return "new-window";
+ }
+
// Cmd/Ctrl + W → close active tab (or window if last tab).
// Cmd/Ctrl + Shift + W is reserved for "close window" — do not intercept.
// Return a signal so the caller can send IPC to the renderer.
diff --git a/apps/desktop/src/main/main-window-registry.test.ts b/apps/desktop/src/main/main-window-registry.test.ts
new file mode 100644
index 0000000000..63eaaf60b1
--- /dev/null
+++ b/apps/desktop/src/main/main-window-registry.test.ts
@@ -0,0 +1,53 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { MainWindowRegistry } from "./main-window-registry";
+
+describe("MainWindowRegistry", () => {
+ it("finds the window that shows a workspace", () => {
+ const registry = new MainWindowRegistry<string>();
+ registry.add("a", "work");
+ registry.add("b", "personal");
+
+ expect(registry.findByWorkspace("personal")).toBe("b");
+ expect(registry.findByWorkspace("personal", "b")).toBeNull();
+ expect(registry.findByWorkspace("side")).toBeNull();
+ });
+
+ it("follows workspace switches inside a window", () => {
+ const registry = new MainWindowRegistry<string>();
+ registry.add("a", "work");
+
+ expect(registry.setWorkspace("a", "personal")).toBe(true);
+ expect(registry.setWorkspace("a", "personal")).toBe(false);
+ expect(registry.setWorkspace("missing", "work")).toBe(false);
+ expect(registry.findByWorkspace("work")).toBeNull();
+ expect(registry.workspaceOf("a")).toBe("personal");
+ });
+
+ it("orders app-level targets by focus and restore by creation", () => {
+ const registry = new MainWindowRegistry<string>();
+ registry.add("a", "work");
+ registry.add("b", "personal");
+ expect(registry.mostRecent()).toBe("b");
+
+ registry.focus("a");
+ expect(registry.mostRecent()).toBe("a");
+ expect(registry.mostRecent("a")).toBe("b");
+ expect(registry.all()).toEqual(["a", "b"]);
+
+ registry.remove("a");
+ expect(registry.mostRecent()).toBe("b");
+ expect(registry.all()).toEqual(["b"]);
+ expect(registry.size).toBe(1);
+ });
+
+ it("lists the workspaces held by the other windows", () => {
+ const registry = new MainWindowRegistry<string>();
+ registry.add("a", "work");
+ registry.add("b", "personal");
+ registry.add("c", null);
+
+ expect(registry.otherWorkspaces("a")).toEqual(["personal"]);
+ expect(registry.otherWorkspaces("c")).toEqual(["work", "personal"]);
+ });
+});
diff --git a/apps/desktop/src/main/main-window-registry.ts b/apps/desktop/src/main/main-window-registry.ts
new file mode 100644
index 0000000000..7fad76a132
--- /dev/null
+++ b/apps/desktop/src/main/main-window-registry.ts
@@ -0,0 +1,79 @@
+/**
+ * Tracks the tabbed main windows and the workspace each one shows. A
+ * workspace belongs to at most one window (the VS Code folder model), so
+ * routing by workspace — notification clicks, cross-workspace links — has a
+ * single answer. Creation order is the restore order; focus order decides
+ * which window receives app-level requests that name no workspace.
+ */
+export class MainWindowRegistry<W> {
+ private readonly windows: W[] = [];
+ private readonly workspaces = new Map<W, string | null>();
+ private focusOrder: W[] = [];
+
+ get size(): number {
+ return this.windows.length;
+ }
+
+ add(window: W, workspaceSlug: string | null): void {
+ if (this.workspaces.has(window)) return;
+ this.windows.push(window);
+ this.workspaces.set(window, workspaceSlug);
+ this.focusOrder = [window, ...this.focusOrder];
+ }
+
+ remove(window: W): void {
+ if (!this.workspaces.delete(window)) return;
+ this.windows.splice(this.windows.indexOf(window), 1);
+ this.focusOrder = this.focusOrder.filter((item) => item !== window);
+ }
+
+ has(window: W): boolean {
+ return this.workspaces.has(window);
+ }
+
+ focus(window: W): void {
+ if (!this.workspaces.has(window)) return;
+ this.focusOrder = [window, ...this.focusOrder.filter((item) => item !== window)];
+ }
+
+ /** Returns whether the window's workspace actually changed. */
+ setWorkspace(window: W, workspaceSlug: string | null): boolean {
+ if (!this.workspaces.has(window)) return false;
+ if (this.workspaces.get(window) === workspaceSlug) return false;
+ this.workspaces.set(window, workspaceSlug);
+ return true;
+ }
+
+ workspaceOf(window: W): string | null {
+ return this.workspaces.get(window) ?? null;
+ }
+
+ /** The most recently focused window showing `workspaceSlug`. */
+ findByWorkspace(workspaceSlug: string, except?: W): W | null {
+ return (
+ this.focusOrder.find(
+ (window) =>
+ window !== except && this.workspaces.get(window) === workspaceSlug,
+ ) ?? null
+ );
+ }
+
+ mostRecent(except?: W): W | null {
+ return this.focusOrder.find((window) => window !== except) ?? null;
+ }
+
+ /** Windows in creation order. */
+ all(): W[] {
+ return [...this.windows];
+ }
+
+ /** Workspaces shown by every window other than `window`, deduplicated. */
+ otherWorkspaces(window: W): string[] {
+ const slugs = new Set<string>();
+ for (const other of this.windows) {
+ const slug = this.workspaces.get(other);
+ if (other !== window && slug) slugs.add(slug);
+ }
+ return [...slugs];
+ }
+}
diff --git a/apps/desktop/src/main/update-install-lifecycle.test.ts b/apps/desktop/src/main/update-install-lifecycle.test.ts
index 9aa7e8227b..646f0ff958 100644
--- a/apps/desktop/src/main/update-install-lifecycle.test.ts
+++ b/apps/desktop/src/main/update-install-lifecycle.test.ts
@@ -132,7 +132,7 @@ async function ipc(name: string) {
async function setupRealGate() {
const manager = await import("./daemon-manager");
const { setupAutoUpdater } = await import("./updater");
- setupAutoUpdater(() => null, {
+ setupAutoUpdater(() => [], {
platform: "win32",
daemonGate: {
prepare: manager.prepareDaemonForUpdateInstall,
diff --git a/apps/desktop/src/main/updater.test.ts b/apps/desktop/src/main/updater.test.ts
index 4297d17538..1750fc6f4f 100644
--- a/apps/desktop/src/main/updater.test.ts
+++ b/apps/desktop/src/main/updater.test.ts
@@ -187,7 +187,7 @@ describe("setupAutoUpdater", () => {
});
it("enables automatic background updates by default", async () => {
- setupAutoUpdater(() => null);
+ setupAutoUpdater(() => []);
await expect(invokeIpc("updater:get-preferences")).resolves.toEqual({
automaticUpdates: true,
@@ -202,7 +202,7 @@ describe("setupAutoUpdater", () => {
updaterPreferencesPath(ctx.userDataPath),
JSON.stringify({ automaticUpdates: false }),
);
- setupAutoUpdater(() => null);
+ setupAutoUpdater(() => []);
// Let the async preference load settle before advancing timers; otherwise
// the in-flight readFile can resolve after afterEach() removes the temp
@@ -216,7 +216,7 @@ describe("setupAutoUpdater", () => {
});
it("persists the automatic update preference and stops future background checks", async () => {
- setupAutoUpdater(() => null);
+ setupAutoUpdater(() => []);
await expect(
invokeIpc("updater:set-automatic-updates", false),
@@ -236,7 +236,7 @@ describe("setupAutoUpdater", () => {
updaterPreferencesPath(ctx.userDataPath),
JSON.stringify({ automaticUpdates: false }),
);
- setupAutoUpdater(() => null);
+ setupAutoUpdater(() => []);
await expect(invokeIpc("updater:check")).resolves.toMatchObject({
ok: true,
@@ -247,7 +247,7 @@ describe("setupAutoUpdater", () => {
it("forwards update progress to a live renderer", () => {
const { win, send } = makeWindow();
- setupAutoUpdater(() => win);
+ setupAutoUpdater(() => [win]);
emitUpdater("download-progress", { percent: 42 });
@@ -257,14 +257,14 @@ describe("setupAutoUpdater", () => {
});
it("skips update progress when the BrowserWindow has already been destroyed", () => {
- setupAutoUpdater(() => makeDestroyedWindow());
+ setupAutoUpdater(() => [makeDestroyedWindow()]);
expect(() => emitUpdater("download-progress", { percent: 42 })).not.toThrow();
});
it("skips update progress when the BrowserWindow webContents has already been destroyed", () => {
const { win, send } = makeWindowWithDestroyedWebContents();
- setupAutoUpdater(() => win);
+ setupAutoUpdater(() => [win]);
expect(() => emitUpdater("download-progress", { percent: 42 })).not.toThrow();
expect(send).not.toHaveBeenCalled();
@@ -274,7 +274,7 @@ describe("setupAutoUpdater", () => {
const { win, send } = makeWindowWithThrowingSend(
new TypeError("Object has been destroyed"),
);
- setupAutoUpdater(() => win);
+ setupAutoUpdater(() => [win]);
expect(() => emitUpdater("download-progress", { percent: 42 })).not.toThrow();
expect(send).toHaveBeenCalledWith("updater:download-progress", {
@@ -284,7 +284,7 @@ describe("setupAutoUpdater", () => {
it("rethrows non-destroy errors from webContents.send", () => {
const { win } = makeWindowWithThrowingSend(new Error("boom"));
- setupAutoUpdater(() => win);
+ setupAutoUpdater(() => [win]);
expect(() => emitUpdater("download-progress", { percent: 42 })).toThrow(
"boom",
@@ -330,7 +330,7 @@ describe("Windows update installation", () => {
it("keeps macOS and Linux on the existing install path", async () => {
for (const platform of ["darwin", "linux"] as const) {
const gate = makeGate();
- setupAutoUpdater(() => null, { daemonGate: gate, platform });
+ setupAutoUpdater(() => [], { daemonGate: gate, platform });
await invokeIpc("updater:install");
expect(gate.prepare).not.toHaveBeenCalled();
}
@@ -342,7 +342,7 @@ describe("Windows update installation", () => {
const gate = makeGate();
if (result === "error") gate.prepare.mockRejectedValue(new Error("probe failed"));
else gate.prepare.mockResolvedValue({ kind: result as "ready" | "timeout" });
- setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ setupAutoUpdater(() => [], { daemonGate: gate, platform: "win32" });
await invokeIpc("updater:install");
expect(ctx.quitAndInstall).toHaveBeenCalledExactlyOnceWith(false, true);
});
@@ -351,7 +351,7 @@ describe("Windows update installation", () => {
const gate = makeGate();
gate.prepare.mockResolvedValueOnce({ kind: "busy", activeTasks: 2 });
gate.confirmInstallWhileBusy.mockResolvedValue(confirmed);
- setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ setupAutoUpdater(() => [], { daemonGate: gate, platform: "win32" });
await invokeIpc("updater:install");
await vi.advanceTimersByTimeAsync(60_000);
expect(gate.confirmInstallWhileBusy).toHaveBeenCalledWith(2);
@@ -369,7 +369,7 @@ describe("Windows update installation", () => {
gate.prepare.mockResolvedValueOnce({ kind: "busy", activeTasks: 1 });
let confirm!: (choice: boolean) => void;
gate.confirmInstallWhileBusy.mockImplementation(() => new Promise((resolve) => { confirm = resolve; }));
- setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ setupAutoUpdater(() => [], { daemonGate: gate, platform: "win32" });
emitUpdater("update-downloaded", { version: "0.7.1" });
const manual = invokeIpc("updater:install");
await vi.advanceTimersByTimeAsync(0);
@@ -386,7 +386,7 @@ describe("Windows update installation", () => {
const gate = makeGate();
if (kind === "error") gate.prepare.mockRejectedValue(new Error("probe failed"));
else gate.prepare.mockResolvedValue(kind === "busy" ? { kind, activeTasks: 1 } : { kind });
- setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ setupAutoUpdater(() => [], { daemonGate: gate, platform: "win32" });
expect(emitApp("before-quit").preventDefault).not.toHaveBeenCalled();
emitUpdater("update-downloaded", { version: "0.7.1" });
expect(emitApp("before-quit").preventDefault).toHaveBeenCalled();
@@ -400,7 +400,7 @@ describe("Windows update installation", () => {
it.each([false, true])("recovers a failed install unless the app has reached will-quit (%s)", async (quitting) => {
const gate = makeGate();
- setupAutoUpdater(() => null, { daemonGate: gate, platform: "win32" });
+ setupAutoUpdater(() => [], { daemonGate: gate, platform: "win32" });
await invokeIpc("updater:install");
if (quitting) emitApp("will-quit");
await vi.advanceTimersByTimeAsync(10_000);
diff --git a/apps/desktop/src/main/updater.ts b/apps/desktop/src/main/updater.ts
index 407de03387..df416004f7 100644
--- a/apps/desktop/src/main/updater.ts
+++ b/apps/desktop/src/main/updater.ts
@@ -149,9 +149,13 @@ function checkForUpdatesOnce(): Promise<unknown> {
}
export function setupAutoUpdater(
- getMainWindow: () => BrowserWindow | null,
+ getMainWindows: () => readonly BrowserWindow[],
options: SetupAutoUpdaterOptions = {},
): void {
+ // Every main window mounts the update banner, so each one hears progress.
+ const broadcast = (channel: RendererChannel, payload: unknown) => {
+ for (const win of getMainWindows()) sendToLiveRenderer(win, channel, payload);
+ };
const platform = options.platform ?? process.platform;
// Only Windows locks a running executable against replacement; macOS and
// Linux keep their existing update path untouched.
@@ -277,21 +281,21 @@ export function setupAutoUpdater(
autoUpdater.on("update-available", (info) => {
// Forwarded for renderer-side state tracking only; the notification UI
// does not render an "available" affordance with autoDownload=true.
- sendToLiveRenderer(getMainWindow(), "updater:update-available", {
+ broadcast("updater:update-available", {
version: info.version,
releaseNotes: info.releaseNotes,
});
});
autoUpdater.on("download-progress", (progress) => {
- sendToLiveRenderer(getMainWindow(), "updater:download-progress", {
+ broadcast("updater:download-progress", {
percent: progress.percent,
});
});
autoUpdater.on("update-downloaded", (info: UpdateDownloadedEvent) => {
updateReadyToInstall = true;
- sendToLiveRenderer(getMainWindow(), "updater:update-downloaded", {
+ broadcast("updater:update-downloaded", {
version: info.version,
releaseNotes: info.releaseNotes,
});
diff --git a/apps/desktop/src/main/window-state.test.ts b/apps/desktop/src/main/window-state.test.ts
index bcc65ba81c..26020f49b3 100644
--- a/apps/desktop/src/main/window-state.test.ts
+++ b/apps/desktop/src/main/window-state.test.ts
@@ -6,8 +6,12 @@ import { join } from "node:path";
import {
parseWindowState,
+ parseWindowSession,
loadWindowState,
+ loadWindowSession,
saveWindowStateToFile,
+ saveWindowSessionToFile,
+ serializeWindowSession,
isVisibleOnSomeDisplay,
resolveWindowOptions,
snapshotWindowState,
@@ -88,6 +92,57 @@ describe("load/save window state file", () => {
});
});
+describe("window session", () => {
+ it("reads a pre-multi-window file as one window without a workspace", () => {
+ expect(parseWindowSession('{"x":10,"y":20,"width":1000,"height":700}')).toEqual([
+ { x: 10, y: 20, width: 1000, height: 700 },
+ ]);
+ });
+
+ it("round-trips every main window and its workspace through disk", () => {
+ const file = join(tempDir(), WINDOW_STATE_FILENAME);
+ const windows = [
+ { x: 0, y: 0, width: 1280, height: 800, workspaceSlug: "work" },
+ { x: 40, y: 40, width: 1100, height: 760, isMaximized: true, workspaceSlug: "personal" },
+ ];
+ saveWindowSessionToFile(file, windows);
+
+ expect(loadWindowSession(file)).toEqual(windows);
+ // The first window stays at the top level, where older builds read it.
+ expect(loadWindowState(file)).toEqual(windows[0]);
+ });
+
+ it("omits additionalWindows when a single window is open", () => {
+ expect(JSON.parse(serializeWindowSession([{ width: 1000, workspaceSlug: "work" }]))).toEqual({
+ width: 1000,
+ workspaceSlug: "work",
+ });
+ });
+
+ it("drops extra windows without a valid, distinct workspace", () => {
+ const raw = JSON.stringify({
+ workspaceSlug: "work",
+ additionalWindows: [
+ { width: 900 },
+ { width: 900, workspaceSlug: "Not A Slug" },
+ { width: 900, workspaceSlug: "work" },
+ "garbage",
+ { width: 1000, workspaceSlug: "personal" },
+ ],
+ });
+
+ expect(parseWindowSession(raw)).toEqual([
+ { workspaceSlug: "work" },
+ { width: 1000, workspaceSlug: "personal" },
+ ]);
+ });
+
+ it("falls back to one default window on a missing or corrupt file", () => {
+ expect(loadWindowSession(join(tempDir(), "missing.json"))).toEqual([{}]);
+ expect(parseWindowSession("{ broken")).toEqual([{}]);
+ });
+});
+
describe("isVisibleOnSomeDisplay", () => {
const displays = [{ x: 0, y: 0, width: 1920, height: 1080 }];
diff --git a/apps/desktop/src/main/window-state.ts b/apps/desktop/src/main/window-state.ts
index ce358c58b1..308c63ce5d 100644
--- a/apps/desktop/src/main/window-state.ts
+++ b/apps/desktop/src/main/window-state.ts
@@ -1,6 +1,17 @@
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
+// Mirrors parseWorkspaceSlug in shared/workspace-window. Kept local because
+// window-state.node-test.mjs loads this file with Node's type stripping,
+// which cannot resolve extensionless relative imports.
+const WORKSPACE_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
+
+function parseWorkspaceSlug(value: unknown): string | null {
+ return typeof value === "string" && WORKSPACE_SLUG_PATTERN.test(value)
+ ? value
+ : null;
+}
+
/** Persisted main-window geometry for the next launch (#5244). */
export type WindowState = {
x?: number;
@@ -9,6 +20,8 @@ export type WindowState = {
height?: number;
isMaximized?: boolean;
isFullScreen?: boolean;
+ /** Workspace the window showed; absent for files written before multi-window. */
+ workspaceSlug?: string;
};
export type Rectangle = {
@@ -42,26 +55,31 @@ export function windowStateFilePath(userDataPath: string): string {
*/
export function parseWindowState(raw: string): WindowState {
try {
- const parsed: unknown = JSON.parse(raw);
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
- return {};
- }
- const obj = parsed as Record<string, unknown>;
- const out: WindowState = {};
- for (const key of ["x", "y", "width", "height"] as const) {
- const v = obj[key];
- if (typeof v === "number" && Number.isFinite(v)) {
- out[key] = Math.round(v);
- }
- }
- if (typeof obj.isMaximized === "boolean") out.isMaximized = obj.isMaximized;
- if (typeof obj.isFullScreen === "boolean") out.isFullScreen = obj.isFullScreen;
- return out;
+ return windowStateFromValue(JSON.parse(raw));
} catch {
return {};
}
}
+function windowStateFromValue(parsed: unknown): WindowState {
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return {};
+ }
+ const obj = parsed as Record<string, unknown>;
+ const out: WindowState = {};
+ for (const key of ["x", "y", "width", "height"] as const) {
+ const v = obj[key];
+ if (typeof v === "number" && Number.isFinite(v)) {
+ out[key] = Math.round(v);
+ }
+ }
+ if (typeof obj.isMaximized === "boolean") out.isMaximized = obj.isMaximized;
+ if (typeof obj.isFullScreen === "boolean") out.isFullScreen = obj.isFullScreen;
+ const workspaceSlug = parseWorkspaceSlug(obj.workspaceSlug);
+ if (workspaceSlug) out.workspaceSlug = workspaceSlug;
+ return out;
+}
+
export function loadWindowState(filePath: string): WindowState {
try {
return parseWindowState(readFileSync(filePath, "utf8"));
@@ -78,6 +96,62 @@ export function saveWindowStateToFile(filePath: string, state: WindowState): voi
}
}
+/**
+ * Every main window to restore, in creation order. The first window keeps the
+ * original top-level shape so builds that predate multi-window still read its
+ * geometry; the others live under `additionalWindows` and need a workspace,
+ * since a second window without one would just duplicate the first.
+ */
+export function parseWindowSession(raw: string): WindowState[] {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ const first = windowStateFromValue(parsed);
+ const additional =
+ parsed && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>).additionalWindows
+ : undefined;
+ if (!Array.isArray(additional)) return [first];
+ const seen = new Set(first.workspaceSlug ? [first.workspaceSlug] : []);
+ const rest: WindowState[] = [];
+ for (const value of additional) {
+ const state = windowStateFromValue(value);
+ if (!state.workspaceSlug || seen.has(state.workspaceSlug)) continue;
+ seen.add(state.workspaceSlug);
+ rest.push(state);
+ }
+ return [first, ...rest];
+ } catch {
+ return [{}];
+ }
+}
+
+export function loadWindowSession(filePath: string): WindowState[] {
+ try {
+ return parseWindowSession(readFileSync(filePath, "utf8"));
+ } catch {
+ return [{}];
+ }
+}
+
+export function serializeWindowSession(windows: WindowState[]): string {
+ const [first = {}, ...rest] = windows;
+ const additionalWindows = rest.filter((state) => state.workspaceSlug);
+ return JSON.stringify(
+ additionalWindows.length > 0 ? { ...first, additionalWindows } : first,
+ );
+}
+
+export function saveWindowSessionToFile(
+ filePath: string,
+ windows: WindowState[],
+): void {
+ try {
+ writeFileSync(filePath, serializeWindowSession(windows), "utf8");
+ } catch {
+ // Disk full / permissions — drop silently; next launch uses defaults.
+ }
+}
+
/**
* True when the rectangle intersects at least one display work area.
* Prevents restoring a window onto a disconnected external monitor.
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index e8f79ade7d..14685870eb 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -120,6 +120,21 @@ interface DesktopAPI {
openIssueWindow: (
request: IssueWindowRequest,
) => Promise<{ ok: true } | { ok: false; reason: "invalid_request" }>;
+ /** Tell main which workspace this main window shows (null while none). */
+ reportWindowWorkspace: (workspaceSlug: string | null) => void;
+ /** Workspaces shown by the other main windows (synchronous). */
+ getOtherWindowWorkspaces: () => string[];
+ /** Hand a workspace (and optionally a path inside it) to the other main
+ * window that shows it. Returns false when no other window does. */
+ focusWorkspaceWindow: (workspaceSlug: string, path?: string) => boolean;
+ /** Open a workspace in its own main window, or focus the one showing it. */
+ openWorkspaceWindow: (workspaceSlug: string) => Promise<{ ok: boolean }>;
+ /** Listen for workspace paths routed here from another window.
+ * Returns an unsubscribe function. */
+ onOpenWorkspacePath: (callback: (path: string) => void) => () => void;
+ /** Listen for Cmd/Ctrl+Shift+N new-window requests. Returns an
+ * unsubscribe function. */
+ onNewWindowShortcut: (callback: () => void) => () => void;
}
type DaemonReauthResult =
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 96ae1afa98..f360d87274 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -26,11 +26,19 @@ import type {
} from "../shared/daemon-types";
import {
MAIN_RENDERER_CHANNEL_STATE_CHANNEL,
+ NEW_WINDOW_SHORTCUT_CHANNEL,
parseTabSelectionShortcutKey,
TAB_SELECTION_SHORTCUT_CHANNEL,
+ WORKSPACE_OPEN_PATH_CHANNEL,
type MainRendererMessageChannel,
type TabSelectionShortcutKey,
} from "../shared/main-renderer-messages";
+import {
+ FOCUS_WORKSPACE_WINDOW_CHANNEL,
+ OPEN_WORKSPACE_WINDOW_CHANNEL,
+ OTHER_WINDOW_WORKSPACES_CHANNEL,
+ WINDOW_WORKSPACE_REPORT_CHANNEL,
+} from "../shared/workspace-window";
// Synchronously fetch app metadata from main at preload time so the renderer
// can pass it into CoreProvider during the initial render — the alternative
@@ -243,6 +251,49 @@ const desktopAPI = {
/** Open a validated issue-detail route in a dedicated native window. */
openIssueWindow: (request: IssueWindowRequest) =>
ipcRenderer.invoke("window:open-issue", request),
+ /** Tell main which workspace this main window shows (null while none). */
+ reportWindowWorkspace: (workspaceSlug: string | null) =>
+ ipcRenderer.send(WINDOW_WORKSPACE_REPORT_CHANNEL, workspaceSlug),
+ /** Workspaces shown by the other main windows. Sync so routing decisions
+ * inside click handlers can consult it. */
+ getOtherWindowWorkspaces: (): string[] => {
+ try {
+ const slugs: unknown = ipcRenderer.sendSync(OTHER_WINDOW_WORKSPACES_CHANNEL);
+ return Array.isArray(slugs)
+ ? slugs.filter((slug): slug is string => typeof slug === "string")
+ : [];
+ } catch {
+ return [];
+ }
+ },
+ /** Hand a workspace (and optionally a path inside it) to the other main
+ * window that shows it. Returns false when no other window does. */
+ focusWorkspaceWindow: (workspaceSlug: string, path?: string): boolean => {
+ try {
+ return (
+ ipcRenderer.sendSync(FOCUS_WORKSPACE_WINDOW_CHANNEL, {
+ workspaceSlug,
+ ...(path === undefined ? {} : { path }),
+ }) === true
+ );
+ } catch {
+ return false;
+ }
+ },
+ /** Open a workspace in its own main window, or focus the one showing it. */
+ openWorkspaceWindow: (workspaceSlug: string) =>
+ ipcRenderer.invoke(OPEN_WORKSPACE_WINDOW_CHANNEL, workspaceSlug),
+ /** Listen for workspace paths routed here from another window. */
+ onOpenWorkspacePath: (callback: (path: string) => void) =>
+ subscribeToMainRendererChannel<unknown>(
+ WORKSPACE_OPEN_PATH_CHANNEL,
+ (path) => {
+ if (typeof path === "string") callback(path);
+ },
+ ),
+ /** Listen for Cmd/Ctrl+Shift+N new-window requests. */
+ onNewWindowShortcut: (callback: () => void) =>
+ subscribeToMainRendererChannel(NEW_WINDOW_SHORTCUT_CHANNEL, () => callback()),
};
type DaemonReauthResult =
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index f47e1021ce..5e101dd85c 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -29,6 +29,12 @@ import { DesktopClientUsageReporter } from "./platform/client-usage-reporter";
import { DiagnosticRouteReporter } from "./platform/diagnostic-route-reporter";
import { flushFreezeBreadcrumb } from "./freeze-flush";
import { DesktopAuthSessionBridge } from "./platform/auth-session-bridge";
+import { WorkspaceWindowBridge } from "./platform/workspace-window-bridge";
+import {
+ launchWorkspaceSlug,
+ otherWindowWorkspaces,
+ resolveWindowWorkspace,
+} from "./platform/workspace-windows";
import {
tearDownOnLogout,
tearDownOnSessionExpiry,
@@ -287,12 +293,17 @@ function AppContent() {
// while a failed background refetch retains the last successful list.
useLayoutEffect(() => {
if (!workspaceListReady) return;
- const validSlugs = new Set(workspaces.map((w) => w.slug));
- useTabStore.getState().validateWorkspaceSlugs(validSlugs);
+ const slugs = workspaces.map((w) => w.slug);
+ useTabStore.getState().validateWorkspaceSlugs(new Set(slugs));
const { activeWorkspaceSlug, switchWorkspace } = useTabStore.getState();
- if (!activeWorkspaceSlug && workspaces.length > 0) {
- switchWorkspace(workspaces[0].slug);
- }
+ if (slugs.length === 0) return;
+ const target = resolveWindowWorkspace(
+ slugs,
+ activeWorkspaceSlug,
+ launchWorkspaceSlug(),
+ otherWindowWorkspaces(),
+ );
+ if (target && target !== activeWorkspaceSlug) switchWorkspace(target);
}, [workspaces, workspaceListReady]);
// null = undecided (pre-login or list hasn't settled yet)
@@ -471,6 +482,7 @@ export default function App() {
>
<DesktopAuthSessionBridge />
{windowContext.kind === "main" && <DiagnosticRouteReporter />}
+ {windowContext.kind === "main" && <WorkspaceWindowBridge />}
{windowContext.kind === "main" && (
<DesktopClientUsageReporter
apiUrl={runtimeConfigResult.config.apiUrl}
diff --git a/apps/desktop/src/renderer/src/main.tsx b/apps/desktop/src/renderer/src/main.tsx
index fc9714d9b4..3bb7baeb0e 100644
--- a/apps/desktop/src/renderer/src/main.tsx
+++ b/apps/desktop/src/renderer/src/main.tsx
@@ -1,6 +1,8 @@
import ReactDOM from "react-dom/client";
import App from "./App";
import { AppCrashBoundary } from "./components/app-crash-boundary";
+import { launchWorkspaceSlug } from "./platform/workspace-windows";
+import { useTabStore } from "./stores/tab-store";
// Inter variable font covers all weights (100-900) in a single file.
// CJK is handled by system font fallback (see globals.css --font-sans chain).
// Keep font stack in sync with apps/web/app/layout.tsx.
@@ -41,6 +43,11 @@ if (import.meta.env.DEV && import.meta.env.VITE_REACT_GRAB) {
document.head.appendChild(grab);
}
+// A window opened for a workspace starts on it rather than on whichever
+// workspace was last active in any window.
+const launchSlug = launchWorkspaceSlug();
+if (launchSlug) useTabStore.getState().switchWorkspace(launchSlug);
+
ReactDOM.createRoot(document.getElementById("root")!).render(
<AppCrashBoundary>
<App />
diff --git a/apps/desktop/src/renderer/src/platform/navigation.test.tsx b/apps/desktop/src/renderer/src/platform/navigation.test.tsx
index feebef7600..edf0f32d35 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.test.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.test.tsx
@@ -400,3 +400,56 @@ describe("existing reserved workspace navigation", () => {
expect(getActiveTab(useTabStore.getState())?.url).toBe("/invite/issues/MUL-123");
});
});
+
+describe("workspaces shown in another window", () => {
+ function withOtherWindow(slug: string) {
+ const focusWorkspaceWindow = vi.fn(
+ (target: string, _path?: string) => target === slug,
+ );
+ Object.defineProperty(window, "desktopAPI", {
+ configurable: true,
+ value: {
+ runtimeConfig: { ok: true, config: { appUrl: "https://app.example" } },
+ windowContext: { kind: "main" },
+ focusWorkspaceWindow,
+ },
+ });
+ return focusWorkspaceWindow;
+ }
+
+ it.each(["push", "replace", "openInNewTab", "content"])(
+ "hands %s to the window that shows the workspace",
+ (action) => {
+ const focusWorkspaceWindow = withOtherWindow("butter");
+ const adapter = renderProvider();
+ act(() => {
+ if (action === "content") routeContentLinkPath("/butter/issues/BUT-1");
+ else if (action === "openInNewTab") adapter().openInNewTab!("/butter/issues/BUT-1");
+ else if (action === "replace") adapter().replace("/butter/issues/BUT-1");
+ else adapter().push("/butter/issues/BUT-1");
+ });
+
+ expect(focusWorkspaceWindow).toHaveBeenCalledWith("butter", "/butter/issues/BUT-1");
+ expect(useTabStore.getState().activeWorkspaceSlug).toBe("acme");
+ expect(useTabStore.getState().byWorkspace.butter).toBeUndefined();
+ },
+ );
+
+ it("focuses that window without a path for a workspace switcher click", () => {
+ const focusWorkspaceWindow = withOtherWindow("butter");
+ const adapter = renderProvider();
+ act(() => adapter().push("/butter/issues"));
+
+ expect(focusWorkspaceWindow).toHaveBeenCalledWith("butter", undefined);
+ expect(useTabStore.getState().activeWorkspaceSlug).toBe("acme");
+ });
+
+ it("switches in place when no other window shows the workspace", () => {
+ const focusWorkspaceWindow = withOtherWindow("butter");
+ const adapter = renderProvider();
+ act(() => adapter().push("/zebra/issues"));
+
+ expect(focusWorkspaceWindow).toHaveBeenCalledWith("zebra", undefined);
+ expect(useTabStore.getState().activeWorkspaceSlug).toBe("zebra");
+ });
+});
diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsx
index 22ad250157..e318b06bd7 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx
@@ -13,6 +13,11 @@ import {
useActiveTabUrl,
} from "@/stores/tab-store";
import { useWindowOverlayStore } from "@/stores/window-overlay-store";
+import {
+ handOffToWorkspaceWindow,
+ openWorkspaceInNewWindow,
+ otherWindowWorkspaces,
+} from "./workspace-windows";
function requireRuntimeAppUrl(scope: string): string {
const runtimeConfig = window.desktopAPI.runtimeConfig;
@@ -78,7 +83,8 @@ function tryRouteToOverlay(path: string): boolean {
*
* The target's bare Issues root (what the workspace switchers send, and where
* web lands) resumes the workspace's last active tab instead, or Issues if it
- * has none. Any deeper path opens exactly that path.
+ * has none. Any deeper path opens exactly that path. When another window
+ * already shows the target workspace, that window takes the navigation.
*/
function tryRouteToOtherWorkspace(path: string): boolean {
const targetSlug = workspaceSlugForPath(path);
@@ -86,7 +92,9 @@ function tryRouteToOtherWorkspace(path: string): boolean {
const { activeWorkspaceSlug, switchWorkspace } = useTabStore.getState();
if (targetSlug === activeWorkspaceSlug) return false;
const resume = path === paths.workspace(targetSlug).issues();
- switchWorkspace(targetSlug, resume ? undefined : path);
+ const openPath = resume ? undefined : path;
+ if (handOffToWorkspaceWindow(targetSlug, openPath)) return true;
+ switchWorkspace(targetSlug, openPath);
return true;
}
@@ -109,7 +117,7 @@ export function routeContentLinkPath(
const store = useTabStore.getState();
const slug = workspaceSlugForPath(path);
if (slug && slug !== store.activeWorkspaceSlug) {
- store.switchWorkspace(slug, path);
+ if (!handOffToWorkspaceWindow(slug, path)) store.switchWorkspace(slug, path);
return;
}
if (disposition === "push") {
@@ -234,11 +242,15 @@ export function DesktopNavigationProvider({
const slug = workspaceSlugForPath(path);
const store = useTabStore.getState();
if (slug && slug !== store.activeWorkspaceSlug) {
- store.switchWorkspace(slug, path);
+ if (!handOffToWorkspaceWindow(slug, path)) {
+ store.switchWorkspace(slug, path);
+ }
return;
}
store.openTab(path, title ?? "", { activate: opts?.activate });
},
+ openWorkspaceInNewWindow,
+ workspacesInOtherWindows: () => [...otherWindowWorkspaces()],
getShareableUrl: (path: string) => `${appUrl}${path}`,
}),
[appUrl, location],
diff --git a/apps/desktop/src/renderer/src/platform/workspace-window-bridge.tsx b/apps/desktop/src/renderer/src/platform/workspace-window-bridge.tsx
new file mode 100644
index 0000000000..a608a0c474
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/workspace-window-bridge.tsx
@@ -0,0 +1,64 @@
+import { useEffect, useRef } from "react";
+import { toast } from "sonner";
+import { useAuthStore } from "@multica/core/auth";
+import { workspaceSlugForPath } from "@multica/core/paths";
+import { useWorkspaceList } from "@multica/core/workspace";
+import { useT } from "@multica/views/i18n";
+import { useTabStore } from "@/stores/tab-store";
+import {
+ nextWorkspaceForNewWindow,
+ openWorkspaceInNewWindow,
+ otherWindowWorkspaces,
+} from "./workspace-windows";
+
+/**
+ * Main-window side of multi-window workspaces: tells main which workspace
+ * this window shows, opens paths other windows hand over, and answers
+ * Cmd/Ctrl+Shift+N. Mounted in every main-window state (login included) so
+ * a shortcut pressed before sign-in is consumed instead of replayed later.
+ */
+export function WorkspaceWindowBridge() {
+ const { t } = useT("layout");
+ const user = useAuthStore((s) => s.user);
+ const { workspaces } = useWorkspaceList({ enabled: !!user });
+ const activeWorkspaceSlug = useTabStore((s) => s.activeWorkspaceSlug);
+
+ const latest = useRef({ workspaces, t });
+ useEffect(() => {
+ latest.current = { workspaces, t };
+ }, [workspaces, t]);
+
+ useEffect(() => {
+ window.desktopAPI.reportWindowWorkspace?.(activeWorkspaceSlug);
+ }, [activeWorkspaceSlug]);
+
+ useEffect(
+ () =>
+ window.desktopAPI.onOpenWorkspacePath?.((path) => {
+ const slug = workspaceSlugForPath(path);
+ if (slug) useTabStore.getState().switchWorkspace(slug, path);
+ }),
+ [],
+ );
+
+ useEffect(
+ () =>
+ window.desktopAPI.onNewWindowShortcut?.(() => {
+ const { workspaces: list, t: translate } = latest.current;
+ if (list.length === 0) return;
+ const slug = nextWorkspaceForNewWindow(
+ list.map((workspace) => workspace.slug),
+ useTabStore.getState().activeWorkspaceSlug,
+ otherWindowWorkspaces(),
+ );
+ if (slug) {
+ openWorkspaceInNewWindow(slug);
+ } else {
+ toast(translate(($) => $.rail.all_workspaces_open));
+ }
+ }),
+ [],
+ );
+
+ return null;
+}
diff --git a/apps/desktop/src/renderer/src/platform/workspace-windows.test.ts b/apps/desktop/src/renderer/src/platform/workspace-windows.test.ts
new file mode 100644
index 0000000000..34d51222fe
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/workspace-windows.test.ts
@@ -0,0 +1,57 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import {
+ nextWorkspaceForNewWindow,
+ resolveWindowWorkspace,
+} from "./workspace-windows";
+
+describe("resolveWindowWorkspace", () => {
+ const slugs = ["work", "personal", "side"];
+
+ it("keeps a workspace no other window shows", () => {
+ expect(resolveWindowWorkspace(slugs, "personal", null, new Set(["work"]))).toBe(
+ "personal",
+ );
+ });
+
+ it("keeps the workspace a window was opened for even if another shows it", () => {
+ expect(
+ resolveWindowWorkspace(slugs, "personal", "personal", new Set(["personal"])),
+ ).toBe("personal");
+ });
+
+ it("moves an unpinned window off a workspace another window shows", () => {
+ expect(resolveWindowWorkspace(slugs, "work", null, new Set(["work"]))).toBe(
+ "personal",
+ );
+ });
+
+ it("keeps a duplicate rather than leave the window empty", () => {
+ expect(
+ resolveWindowWorkspace(["work"], "work", null, new Set(["work"])),
+ ).toBe("work");
+ });
+
+ it("picks a free workspace when the window has none", () => {
+ expect(resolveWindowWorkspace(slugs, null, null, new Set(["work"]))).toBe(
+ "personal",
+ );
+ expect(resolveWindowWorkspace(["work"], null, null, new Set(["work"]))).toBe(
+ "work",
+ );
+ });
+});
+
+describe("nextWorkspaceForNewWindow", () => {
+ it("picks the first workspace that no window shows", () => {
+ expect(
+ nextWorkspaceForNewWindow(["work", "personal", "side"], "work", new Set(["personal"])),
+ ).toBe("side");
+ });
+
+ it("returns null once every workspace has a window", () => {
+ expect(
+ nextWorkspaceForNewWindow(["work", "personal"], "work", new Set(["personal"])),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/platform/workspace-windows.ts b/apps/desktop/src/renderer/src/platform/workspace-windows.ts
new file mode 100644
index 0000000000..b3a2d72af2
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/workspace-windows.ts
@@ -0,0 +1,67 @@
+/**
+ * Desktop main windows each show one workspace (the VS Code folder model).
+ * These helpers send a workspace this window does not show to the window
+ * that does, and open other workspaces in windows of their own. Every call
+ * tolerates an older preload that lacks the multi-window bridge.
+ */
+
+function isMainWindow(): boolean {
+ return (window.desktopAPI.windowContext?.kind ?? "main") === "main";
+}
+
+/**
+ * Hand `slug` — and `path` inside it, when given — to another window that
+ * already shows that workspace. Returns false when no other window does, so
+ * the caller switches its own workspace instead.
+ */
+export function handOffToWorkspaceWindow(slug: string, path?: string): boolean {
+ if (!isMainWindow()) return false;
+ return window.desktopAPI.focusWorkspaceWindow?.(slug, path) ?? false;
+}
+
+export function openWorkspaceInNewWindow(slug: string): void {
+ void window.desktopAPI.openWorkspaceWindow?.(slug);
+}
+
+export function otherWindowWorkspaces(): Set<string> {
+ return new Set(window.desktopAPI.getOtherWindowWorkspaces?.() ?? []);
+}
+
+/** The workspace main asked this window to open, if it was opened for one. */
+export function launchWorkspaceSlug(): string | null {
+ const context = window.desktopAPI.windowContext;
+ return context?.kind === "main" ? (context.workspaceSlug ?? null) : null;
+}
+
+/** The first workspace that no window shows yet, for Cmd/Ctrl+Shift+N. */
+export function nextWorkspaceForNewWindow(
+ slugs: readonly string[],
+ activeSlug: string | null,
+ openElsewhere: ReadonlySet<string>,
+): string | null {
+ return (
+ slugs.find((slug) => slug !== activeSlug && !openElsewhere.has(slug)) ?? null
+ );
+}
+
+/**
+ * The workspace a window should show once the list is known. A window keeps
+ * its workspace unless another window already shows it and this window was
+ * not opened for it — e.g. a pre-multi-window session restoring the shared
+ * last-active workspace next to a window restored for that same workspace.
+ */
+export function resolveWindowWorkspace(
+ slugs: readonly string[],
+ activeSlug: string | null,
+ launchSlug: string | null,
+ openElsewhere: ReadonlySet<string>,
+): string | null {
+ if (
+ activeSlug &&
+ (activeSlug === launchSlug || !openElsewhere.has(activeSlug))
+ ) {
+ return activeSlug;
+ }
+ const free = slugs.find((slug) => !openElsewhere.has(slug));
+ return free ?? activeSlug ?? slugs[0] ?? null;
+}
diff --git a/apps/desktop/src/renderer/src/stores/tab-store-storage.test.ts b/apps/desktop/src/renderer/src/stores/tab-store-storage.test.ts
new file mode 100644
index 0000000000..98356164b6
--- /dev/null
+++ b/apps/desktop/src/renderer/src/stores/tab-store-storage.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { createWindowTabStorage, mergeTabGroups } from "./tab-store-storage";
+
+const KEY = "multica_tabs";
+
+function memoryStorage() {
+ const items = new Map<string, string>();
+ return {
+ getItem: (key: string) => items.get(key) ?? null,
+ setItem: (key: string, value: string) => void items.set(key, value),
+ removeItem: (key: string) => void items.delete(key),
+ };
+}
+
+function envelope(
+ byWorkspace: Record<string, unknown>,
+ activeWorkspaceSlug: string | null = Object.keys(byWorkspace)[0] ?? null,
+) {
+ return JSON.stringify({ state: { activeWorkspaceSlug, byWorkspace }, version: 5 });
+}
+
+function storedGroups(inner: ReturnType<typeof memoryStorage>) {
+ return JSON.parse(inner.getItem(KEY) ?? "null").state.byWorkspace;
+}
+
+/** Two windows that hydrated the same persisted tabs. */
+function twoWindows(initial: Record<string, unknown>) {
+ const inner = memoryStorage();
+ inner.setItem(KEY, envelope(initial));
+ const work = createWindowTabStorage(inner);
+ const personal = createWindowTabStorage(inner);
+ work.setBaseline(initial);
+ personal.setBaseline(initial);
+ return { inner, work, personal };
+}
+
+describe("createWindowTabStorage", () => {
+ it("keeps a workspace's tabs that another window opened after hydration", () => {
+ const { inner, work, personal } = twoWindows({ work: { tabs: [1] }, personal: { tabs: [1] } });
+
+ personal.setItem(KEY, envelope({ work: { tabs: [1] }, personal: { tabs: [1, 2] } }));
+ work.setItem(KEY, envelope({ work: { tabs: [1, 3] }, personal: { tabs: [1] } }));
+
+ expect(storedGroups(inner)).toEqual({
+ work: { tabs: [1, 3] },
+ personal: { tabs: [1, 2] },
+ });
+ });
+
+ it("adds a workspace group created in another window", () => {
+ const { inner, work, personal } = twoWindows({ work: { tabs: [1] } });
+
+ personal.setItem(KEY, envelope({ work: { tabs: [1] }, side: { tabs: [9] } }));
+ work.setItem(KEY, envelope({ work: { tabs: [1, 2] } }));
+
+ expect(storedGroups(inner)).toEqual({ work: { tabs: [1, 2] }, side: { tabs: [9] } });
+ });
+
+ it("drops a group this window removed, such as a workspace that is gone", () => {
+ const { inner, work } = twoWindows({ work: { tabs: [1] }, gone: { tabs: [1] } });
+
+ work.setItem(KEY, envelope({ work: { tabs: [1] } }));
+
+ expect(storedGroups(inner)).toEqual({ work: { tabs: [1] } });
+ });
+
+ it("writes an empty state as-is so logout clears every window's tabs", () => {
+ const { inner, work, personal } = twoWindows({ work: { tabs: [1] }, personal: { tabs: [1] } });
+
+ personal.setItem(KEY, envelope({ work: { tabs: [1] }, personal: { tabs: [1, 2] } }));
+ work.setItem(KEY, envelope({}, null));
+
+ expect(storedGroups(inner)).toEqual({});
+ });
+
+ it("writes through before a baseline exists (hydration migrations)", () => {
+ const inner = memoryStorage();
+ inner.setItem(KEY, envelope({ other: { tabs: [1] } }));
+ const storage = createWindowTabStorage(inner);
+
+ storage.setItem(KEY, envelope({ work: { tabs: [1] } }));
+
+ expect(storedGroups(inner)).toEqual({ work: { tabs: [1] } });
+ });
+
+ it("reads one workspace's persisted group", () => {
+ const { work, personal } = twoWindows({ work: { tabs: [1] } });
+ personal.setItem(KEY, envelope({ work: { tabs: [1] }, personal: { tabs: [4] } }));
+
+ expect(work.readStoredGroup(KEY, "personal")).toEqual({ tabs: [4] });
+ expect(work.readStoredGroup(KEY, "missing")).toBeUndefined();
+ expect(work.readStoredGroup(KEY, "constructor")).toBeUndefined();
+ });
+});
+
+describe("mergeTabGroups", () => {
+ it("prefers this window's copy when both windows changed a group", () => {
+ const baseline = new Map([["work", JSON.stringify({ tabs: [1] })]]);
+
+ expect(
+ mergeTabGroups({ work: { tabs: [1, 2] } }, { work: { tabs: [1, 3] } }, baseline),
+ ).toEqual({ work: { tabs: [1, 2] } });
+ });
+});
diff --git a/apps/desktop/src/renderer/src/stores/tab-store-storage.ts b/apps/desktop/src/renderer/src/stores/tab-store-storage.ts
new file mode 100644
index 0000000000..fa423d9514
--- /dev/null
+++ b/apps/desktop/src/renderer/src/stores/tab-store-storage.ts
@@ -0,0 +1,111 @@
+import type { StateStorage } from "zustand/middleware";
+import type { StorageAdapter } from "@multica/core/types";
+
+type SyncStorage = Pick<StorageAdapter, "getItem" | "setItem" | "removeItem">;
+
+interface PersistedEnvelope {
+ state: { activeWorkspaceSlug?: unknown; byWorkspace: Record<string, unknown> };
+ version?: number;
+}
+
+function parseEnvelope(raw: string | null): PersistedEnvelope | null {
+ if (!raw) return null;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== "object") return null;
+ const state = (parsed as { state?: unknown }).state;
+ if (!state || typeof state !== "object") return null;
+ const byWorkspace = (state as { byWorkspace?: unknown }).byWorkspace;
+ if (!byWorkspace || typeof byWorkspace !== "object" || Array.isArray(byWorkspace)) {
+ return null;
+ }
+ return parsed as PersistedEnvelope;
+ } catch {
+ return null;
+ }
+}
+
+function snapshotGroups(byWorkspace: Record<string, unknown>): Map<string, string> {
+ return new Map(
+ Object.entries(byWorkspace).map(([slug, group]) => [slug, JSON.stringify(group)]),
+ );
+}
+
+/**
+ * Three-way merge of workspace tab groups. A group this window changed or
+ * removed since `baseline` (its last write, or what it hydrated) is taken
+ * from `ours`; every other group is taken from `stored`, which may hold
+ * another window's newer copy.
+ */
+export function mergeTabGroups(
+ ours: Record<string, unknown>,
+ stored: Record<string, unknown>,
+ baseline: ReadonlyMap<string, string>,
+): Record<string, unknown> {
+ const slugs = new Set([...Object.keys(ours), ...Object.keys(stored)]);
+ const merged: [string, unknown][] = [];
+ for (const slug of slugs) {
+ const own = Object.hasOwn(ours, slug) ? ours[slug] : undefined;
+ const ownSnapshot = own === undefined ? undefined : JSON.stringify(own);
+ const group =
+ ownSnapshot !== baseline.get(slug)
+ ? own
+ : Object.hasOwn(stored, slug)
+ ? stored[slug]
+ : undefined;
+ if (group !== undefined) merged.push([slug, group]);
+ }
+ return Object.fromEntries(merged);
+}
+
+export interface WindowTabStorage extends StateStorage {
+ /** Record the groups this window holds once hydration has finished. */
+ setBaseline(byWorkspace: Record<string, unknown>): void;
+ /** The persisted copy of one workspace's group, as last written by any window. */
+ readStoredGroup(name: string, slug: string): unknown;
+}
+
+/**
+ * Every main window persists its tabs under the same key, and each holds a
+ * stale copy of the workspaces it is not showing. Writing whole snapshots
+ * would let one window erase the tabs another just opened, so each write
+ * merges per workspace group. An empty state (logout) is written as-is.
+ */
+export function createWindowTabStorage(inner: SyncStorage): WindowTabStorage {
+ let baseline: Map<string, string> | null = null;
+
+ return {
+ getItem: (name) => inner.getItem(name),
+ removeItem: (name) => inner.removeItem(name),
+ setItem(name, value) {
+ const ours = parseEnvelope(value);
+ if (!ours) {
+ inner.setItem(name, value);
+ return;
+ }
+ const ownGroups = ours.state.byWorkspace;
+ const isEmpty =
+ ours.state.activeWorkspaceSlug == null && Object.keys(ownGroups).length === 0;
+ const stored = baseline && !isEmpty ? parseEnvelope(inner.getItem(name)) : null;
+ const next =
+ baseline && stored && stored.version === ours.version
+ ? JSON.stringify({
+ ...ours,
+ state: {
+ ...ours.state,
+ byWorkspace: mergeTabGroups(ownGroups, stored.state.byWorkspace, baseline),
+ },
+ })
+ : value;
+ baseline = snapshotGroups(ownGroups);
+ inner.setItem(name, next);
+ },
+ setBaseline(byWorkspace) {
+ baseline = snapshotGroups(byWorkspace);
+ },
+ readStoredGroup(name, slug) {
+ const groups = parseEnvelope(inner.getItem(name))?.state.byWorkspace;
+ return groups && Object.hasOwn(groups, slug) ? groups[slug] : undefined;
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
index b431b2681a..a9ea5e3324 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
@@ -1643,3 +1643,51 @@ describe("reserved workspace restoration", () => {
expect(useTabStore.getState().byWorkspace.dingtalk).toBeUndefined();
});
});
+
+describe("tabs shared with other windows", () => {
+ /** Rewrite one persisted group the way another window's write would. */
+ function writeFromOtherWindow(slug: string, urls: string[]) {
+ const stored = JSON.parse(localStorage.getItem("multica_tabs") ?? "null");
+ const tabs = urls.map((url, index) => ({
+ id: `${slug}-other-${index}`,
+ url,
+ title: "Issues",
+ pinned: false,
+ history: { stack: [url], index: 0 },
+ }));
+ stored.state.byWorkspace[slug] = {
+ activeTabId: tabs[tabs.length - 1].id,
+ recentTabIds: [],
+ browsingHistory: urls,
+ tabs,
+ };
+ localStorage.setItem("multica_tabs", JSON.stringify(stored));
+ }
+
+ it("picks up tabs another window opened when switching to that workspace", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ store.switchWorkspace("beta");
+ writeFromOtherWindow("acme", ["/acme/issues", "/acme/projects"]);
+
+ useTabStore.getState().switchWorkspace("acme");
+
+ const group = useTabStore.getState().byWorkspace.acme;
+ expect(group.tabs.map((tab) => tab.url)).toEqual(["/acme/issues", "/acme/projects"]);
+ expect(group.activeTabId).toBe("acme-other-1");
+ });
+
+ it("does not overwrite another window's group when this window writes", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ store.switchWorkspace("beta");
+ writeFromOtherWindow("acme", ["/acme/issues", "/acme/projects"]);
+
+ useTabStore.getState().openTab("/beta/projects", "Projects");
+
+ const stored = JSON.parse(localStorage.getItem("multica_tabs") ?? "null");
+ expect(
+ stored.state.byWorkspace.acme.tabs.map((tab: { url: string }) => tab.url),
+ ).toEqual(["/acme/issues", "/acme/projects"]);
+ });
+});
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index b545be6e9a..ed65f60a27 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -1,7 +1,11 @@
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { arrayMove } from "@dnd-kit/sortable";
-import { createPersistStorage, defaultStorage } from "@multica/core/platform";
+import { defaultStorage } from "@multica/core/platform";
+import {
+ createWindowTabStorage,
+ type WindowTabStorage,
+} from "./tab-store-storage";
import { createSafeId } from "@multica/core/utils";
import { workspaceSlugForPath } from "@multica/core/paths";
@@ -701,6 +705,11 @@ function buildCloseOtherTabsResult(
// Store
+const TAB_STORE_KEY = "multica_tabs";
+// Built inside createJSONStorage's getter, which turns persistence off
+// instead of throwing when storage is unavailable.
+let tabStorage = null as WindowTabStorage | null;
+
export const useTabStore = create<TabStore>()(
persist(
(set, get) => ({
@@ -713,7 +722,16 @@ export const useTabStore = create<TabStore>()(
// NavigationAdapter's path-parser should already have filtered
// these, but belt-and-braces keeps garbage out of the store.
if (!slug) return;
- const { byWorkspace } = get();
+ const current = get();
+ // Another window may have shown this workspace since this window
+ // last did; pick up its tabs instead of reviving a stale copy.
+ const refreshed =
+ slug !== current.activeWorkspaceSlug
+ ? storedGroupIfNewer(slug, current.byWorkspace[slug])
+ : undefined;
+ const byWorkspace = refreshed
+ ? { ...current.byWorkspace, [slug]: refreshed }
+ : current.byWorkspace;
const existing = byWorkspace[slug];
// Decide the desired active path for this workspace.
@@ -786,7 +804,11 @@ export const useTabStore = create<TabStore>()(
}
// No openPath (or openPath was rejected) — just restore the group.
- set({ activeWorkspaceSlug: slug });
+ set(
+ refreshed
+ ? { activeWorkspaceSlug: slug, byWorkspace }
+ : { activeWorkspaceSlug: slug },
+ );
},
openTab(path, title, opts) {
@@ -1255,9 +1277,11 @@ export const useTabStore = create<TabStore>()(
},
}),
{
- name: "multica_tabs",
+ name: TAB_STORE_KEY,
version: 5,
- storage: createJSONStorage(() => createPersistStorage(defaultStorage)),
+ storage: createJSONStorage(
+ () => (tabStorage = createWindowTabStorage(defaultStorage)),
+ ),
migrate: (persistedState, version) => {
// v1 → v2: flat `tabs` array → per-workspace grouping.
// Tabs whose path isn't workspace-scoped (root `/`, login, etc.)
@@ -1286,39 +1310,70 @@ export const useTabStore = create<TabStore>()(
}
return state as V5Persisted;
},
- partialize: (state) => ({
- activeWorkspaceSlug: state.activeWorkspaceSlug,
- // mountGeneration is deliberately excluded: reload pressure must
- // never persist across restarts.
- byWorkspace: Object.fromEntries(
- Object.entries(state.byWorkspace).map(([slug, group]) => [
- slug,
- {
- activeTabId: group.activeTabId,
- // Persisted so the first close after a restart still lands on
- // the tab you were last looking at rather than falling back to
- // the positional neighbour.
- recentTabIds: group.recentTabIds,
- browsingHistory: group.browsingHistory,
- browsingHistoryTitles: group.browsingHistoryTitles,
- tabs: group.tabs.map((t) => ({
- id: t.id,
- url: t.url,
- title: t.title,
- pinned: t.pinned,
- history: t.history,
- memento: t.memento,
- })),
- },
- ]),
- ),
- }),
+ partialize: (state) => partializeTabs(state),
merge: (persistedState, currentState) =>
mergePersistedTabs(persistedState, currentState),
},
),
);
+// Hydration from localStorage is synchronous, so by now the store holds
+// exactly what this window loaded; later writes merge against it.
+tabStorage?.setBaseline(partializeTabs(useTabStore.getState()).byWorkspace);
+
+function partializeTabs(state: PersistedTabState) {
+ return {
+ activeWorkspaceSlug: state.activeWorkspaceSlug,
+ // mountGeneration is deliberately excluded: reload pressure must
+ // never persist across restarts.
+ byWorkspace: Object.fromEntries(
+ Object.entries(state.byWorkspace).map(([slug, group]) => [
+ slug,
+ {
+ activeTabId: group.activeTabId,
+ // Persisted so the first close after a restart still lands on
+ // the tab you were last looking at rather than falling back to
+ // the positional neighbour.
+ recentTabIds: group.recentTabIds,
+ browsingHistory: group.browsingHistory,
+ browsingHistoryTitles: group.browsingHistoryTitles,
+ tabs: group.tabs.map((t) => ({
+ id: t.id,
+ url: t.url,
+ title: t.title,
+ pinned: t.pinned,
+ history: t.history,
+ memento: t.memento,
+ })),
+ },
+ ]),
+ ),
+ };
+}
+
+/**
+ * The newest persisted copy of `slug`'s group when another window changed
+ * it since this window last held it, normalized like a hydrated group.
+ */
+function storedGroupIfNewer(
+ slug: string,
+ current: WorkspaceTabGroup | undefined,
+): WorkspaceTabGroup | undefined {
+ const stored = tabStorage?.readStoredGroup(TAB_STORE_KEY, slug);
+ if (stored === undefined) return undefined;
+ if (current) {
+ const own = partializeTabs({
+ activeWorkspaceSlug: slug,
+ byWorkspace: { [slug]: current },
+ }).byWorkspace[slug];
+ if (JSON.stringify(own) === JSON.stringify(stored)) return undefined;
+ }
+ return mergePersistedTabs(
+ { activeWorkspaceSlug: slug, byWorkspace: { [slug]: stored } },
+ { activeWorkspaceSlug: null, byWorkspace: {} } as PersistedTabState,
+ ).byWorkspace[slug];
+}
+
/** The persisted slice of the store — what `merge` reads and rebuilds. */
interface PersistedTabState {
activeWorkspaceSlug: string | null;
diff --git a/apps/desktop/src/shared/issue-window.ts b/apps/desktop/src/shared/issue-window.ts
index 0d69d87c59..e394d59ea3 100644
--- a/apps/desktop/src/shared/issue-window.ts
+++ b/apps/desktop/src/shared/issue-window.ts
@@ -1,8 +1,12 @@
+import {
+ parseWorkspaceSlug,
+ readWorkspaceWindowSlug,
+} from "./workspace-window";
+
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 = {
@@ -16,9 +20,13 @@ export type IssueWindowContext = IssueWindowRequest & {
issueId: string;
};
-export type DesktopWindowContext =
- | { kind: "main" }
- | IssueWindowContext;
+/**
+ * A tabbed main window. `workspaceSlug` is the workspace it was opened or
+ * restored for; without it the window resumes the persisted active workspace.
+ */
+export type MainWindowContext = { kind: "main"; workspaceSlug?: string };
+
+export type DesktopWindowContext = MainWindowContext | IssueWindowContext;
/**
* Validate renderer-controlled input before it can become a BrowserWindow
@@ -79,7 +87,7 @@ export function parseIssueWindowPath(
return null;
}
- if (!WORKSPACE_SLUG_PATTERN.test(workspaceSlug)) return null;
+ if (!parseWorkspaceSlug(workspaceSlug)) return null;
if (!ISSUE_REF_PATTERN.test(issueId)) return null;
const path = `/${workspaceSlug}/issues/${encodeURIComponent(issueId)}${url.search}${url.hash}`;
@@ -101,16 +109,20 @@ export function encodeIssueWindowArgument(request: IssueWindowRequest): string {
export function readDesktopWindowContext(
argv: readonly string[],
): DesktopWindowContext {
+ const workspaceSlug = readWorkspaceWindowSlug(argv);
+ const main: MainWindowContext = workspaceSlug
+ ? { kind: "main", workspaceSlug }
+ : { kind: "main" };
const argument = argv.find((item) =>
item.startsWith(ISSUE_WINDOW_ARGUMENT_PREFIX),
);
- if (!argument) return { kind: "main" };
+ if (!argument) return main;
try {
const encoded = argument.slice(ISSUE_WINDOW_ARGUMENT_PREFIX.length);
const decoded = JSON.parse(decodeURIComponent(encoded)) as unknown;
- return parseIssueWindowRequest(decoded) ?? { kind: "main" };
+ return parseIssueWindowRequest(decoded) ?? main;
} catch {
- return { kind: "main" };
+ return main;
}
}
diff --git a/apps/desktop/src/shared/main-renderer-messages.test.ts b/apps/desktop/src/shared/main-renderer-messages.test.ts
index 07093e017c..28b47f546c 100644
--- a/apps/desktop/src/shared/main-renderer-messages.test.ts
+++ b/apps/desktop/src/shared/main-renderer-messages.test.ts
@@ -7,49 +7,89 @@ import {
TAB_SELECTION_SHORTCUT_CHANNEL,
} from "./main-renderer-messages";
+function createQueue(live: Set<string> = new Set(["a", "b"])) {
+ const send = vi.fn();
+ const queue = new MainRendererMessageQueue<string>(send, (window) =>
+ live.has(window),
+ );
+ return { queue, send, live };
+}
+
describe("MainRendererMessageQueue", () => {
it("holds messages until their matching listener is ready", () => {
- const queue = new MainRendererMessageQueue();
- const send = vi.fn();
+ const { queue, send } = createQueue();
- queue.enqueue("auth:token", "token-a", send);
- queue.setReady("invite:open", true, send);
+ queue.enqueue("a", "auth:token", "token-a");
+ queue.setReady("a", "invite:open", true);
expect(send).not.toHaveBeenCalled();
- queue.setReady("auth:token", true, send);
- expect(send).toHaveBeenCalledWith("auth:token", "token-a");
+ queue.setReady("a", "auth:token", true);
+ expect(send).toHaveBeenCalledWith("a", "auth:token", "token-a");
});
- it("delivers immediately while a channel is ready", () => {
- const queue = new MainRendererMessageQueue();
- const send = vi.fn();
+ it("delivers immediately while the target's channel is ready", () => {
+ const { queue, send } = createQueue();
- queue.setReady("inbox:open", true, send);
- queue.enqueue("inbox:open", { itemId: "item-1" }, send);
+ queue.setReady("a", "inbox:open", true);
+ queue.enqueue("a", "inbox:open", { itemId: "item-1" });
expect(send).toHaveBeenCalledOnce();
});
- it("keeps queued work across a renderer readiness reset", () => {
- const queue = new MainRendererMessageQueue();
- const send = vi.fn();
+ it("keeps a message for its own window when another window becomes ready", () => {
+ const { queue, send } = createQueue();
+
+ queue.enqueue("a", "settings:open", null);
+ queue.setReady("b", "settings:open", true);
+ expect(send).not.toHaveBeenCalled();
+
+ queue.setReady("a", "settings:open", true);
+ expect(send).toHaveBeenCalledWith("a", "settings:open", null);
+ });
+
+ it("hands a closed window's pending messages to its successor", () => {
+ const { queue, send, live } = createQueue();
+
+ queue.setReady("b", "inbox:open", true);
+ queue.enqueue("a", "inbox:open", { itemId: "item-1" });
+ live.delete("a");
+ queue.release("a", "b");
+
+ expect(send).toHaveBeenCalledWith("b", "inbox:open", { itemId: "item-1" });
+ });
+
+ it("delivers to a recreated window when the target closed with no successor", () => {
+ const { queue, send, live } = createQueue(new Set(["a"]));
+
+ queue.setReady("a", "invite:open", true);
+ live.delete("a");
+ queue.release("a", null);
+ queue.enqueue("a", "invite:open", "invite-1");
+ expect(send).not.toHaveBeenCalled();
+
+ live.add("c");
+ queue.setReady("c", "invite:open", true);
+ expect(send).toHaveBeenCalledWith("c", "invite:open", "invite-1");
+ });
+
+ it("delivers an untargeted message to the first window that becomes ready", () => {
+ const { queue, send } = createQueue();
- queue.setReady("invite:open", true, send);
- queue.resetReady();
- queue.enqueue("invite:open", "invite-1", send);
+ queue.enqueue(null, "auth:token", "token-1");
expect(send).not.toHaveBeenCalled();
- queue.setReady("invite:open", true, send);
- expect(send).toHaveBeenCalledWith("invite:open", "invite-1");
+ queue.setReady("b", "auth:token", true);
+ queue.setReady("a", "auth:token", true);
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(send).toHaveBeenCalledWith("b", "auth:token", "token-1");
});
it("can discard account-scoped pending messages", () => {
- const queue = new MainRendererMessageQueue();
- const send = vi.fn();
+ const { queue, send } = createQueue();
- queue.enqueue("inbox:open", { itemId: "old-account-item" }, send);
+ queue.enqueue("a", "inbox:open", { itemId: "old-account-item" });
queue.clear("inbox:open");
- queue.setReady("inbox:open", true, send);
+ queue.setReady("a", "inbox:open", true);
expect(send).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/shared/main-renderer-messages.ts b/apps/desktop/src/shared/main-renderer-messages.ts
index c02e1e05d1..46bbb8a254 100644
--- a/apps/desktop/src/shared/main-renderer-messages.ts
+++ b/apps/desktop/src/shared/main-renderer-messages.ts
@@ -1,5 +1,5 @@
/**
- * Main-process messages that must wait until the main renderer has installed
+ * Main-process messages that must wait until a 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.
*/
@@ -22,12 +22,19 @@ export function parseTabSelectionShortcutKey(
: null;
}
+/** Open a workspace-scoped path in the window that shows that workspace. */
+export const WORKSPACE_OPEN_PATH_CHANNEL = "workspace:open-path";
+/** Cmd/Ctrl+Shift+N: the renderer picks which workspace gets the new window. */
+export const NEW_WINDOW_SHORTCUT_CHANNEL = "window:new-by-shortcut";
+
export const MAIN_RENDERER_MESSAGE_CHANNELS = [
"auth:token",
"invite:open",
"inbox:open",
"settings:open",
TAB_SELECTION_SHORTCUT_CHANNEL,
+ WORKSPACE_OPEN_PATH_CHANNEL,
+ NEW_WINDOW_SHORTCUT_CHANNEL,
] as const;
export type MainRendererMessageChannel =
@@ -60,57 +67,83 @@ export function parseMainRendererChannelState(
};
}
-type SendMessage = (
+type SendMessage<W> = (
+ target: W,
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.
+ * Holds renderer-bound messages until the specific React listener in the
+ * target main window is ready. Readiness is per window lifecycle; a message
+ * with no target (sent before any window exists), or whose target closed
+ * before it was delivered, goes to the next main window that becomes ready,
+ * so recreating a window still delivers it.
*/
-export class MainRendererMessageQueue {
- private readonly readyChannels = new Set<MainRendererMessageChannel>();
+export class MainRendererMessageQueue<W> {
+ private readonly readyChannels = new Map<W, Set<MainRendererMessageChannel>>();
private readonly pending = new Map<
MainRendererMessageChannel,
- unknown[]
+ { target: W | null; payload: unknown }[]
>();
+ constructor(
+ private readonly send: SendMessage<W>,
+ private readonly isLive: (window: W) => boolean,
+ ) {}
+
enqueue(
+ target: W | null,
channel: MainRendererMessageChannel,
payload: unknown,
- send: SendMessage,
): void {
- if (this.readyChannels.has(channel)) {
- send(channel, payload);
+ if (target !== null && this.readyChannels.get(target)?.has(channel)) {
+ this.send(target, channel, payload);
return;
}
const queued = this.pending.get(channel) ?? [];
- queued.push(payload);
+ queued.push({ target, payload });
this.pending.set(channel, queued);
}
- setReady(
- channel: MainRendererMessageChannel,
- ready: boolean,
- send: SendMessage,
- ): void {
+ setReady(window: W, channel: MainRendererMessageChannel, ready: boolean): void {
if (!ready) {
- this.readyChannels.delete(channel);
+ this.readyChannels.get(window)?.delete(channel);
return;
}
- this.readyChannels.add(channel);
+ const channels = this.readyChannels.get(window) ?? new Set();
+ channels.add(channel);
+ this.readyChannels.set(window, channels);
const queued = this.pending.get(channel);
if (!queued) return;
- this.pending.delete(channel);
- for (const payload of queued) send(channel, payload);
+ const deliver = queued.filter(
+ (entry) =>
+ entry.target === window ||
+ entry.target === null ||
+ !this.isLive(entry.target),
+ );
+ const keep = queued.filter((entry) => !deliver.includes(entry));
+ if (keep.length > 0) this.pending.set(channel, keep);
+ else this.pending.delete(channel);
+ for (const entry of deliver) this.send(window, channel, entry.payload);
}
- /** Clear readiness when the main renderer is replaced, without losing work. */
- resetReady(): void {
- this.readyChannels.clear();
+ /**
+ * Forget a window's readiness when its renderer goes away and hand its
+ * undelivered messages to `successor`, when another main window exists.
+ */
+ release(window: W, successor: W | null): void {
+ this.readyChannels.delete(window);
+ if (!successor) return;
+ for (const [channel, queued] of [...this.pending]) {
+ const moved = queued.filter((entry) => entry.target === window);
+ if (moved.length === 0) continue;
+ const keep = queued.filter((entry) => entry.target !== window);
+ if (keep.length > 0) this.pending.set(channel, keep);
+ else this.pending.delete(channel);
+ for (const entry of moved) this.enqueue(successor, channel, entry.payload);
+ }
}
/** Drop messages that are no longer safe for the active account. */
diff --git a/apps/desktop/src/shared/workspace-window.ts b/apps/desktop/src/shared/workspace-window.ts
new file mode 100644
index 0000000000..d3cfe06f24
--- /dev/null
+++ b/apps/desktop/src/shared/workspace-window.ts
@@ -0,0 +1,54 @@
+export const WORKSPACE_WINDOW_ARGUMENT_PREFIX = "--multica-workspace-window=";
+
+/** Renderer → main: the workspace this main window is showing (or null). */
+export const WINDOW_WORKSPACE_REPORT_CHANNEL = "window:report-workspace";
+/** Renderer → main (sync): workspaces shown by every other main window. */
+export const OTHER_WINDOW_WORKSPACES_CHANNEL = "window:other-workspaces";
+/** Renderer → main (sync): focus the window showing a workspace, if any. */
+export const FOCUS_WORKSPACE_WINDOW_CHANNEL = "window:focus-workspace";
+/** Renderer → main: open a workspace in its own main window. */
+export const OPEN_WORKSPACE_WINDOW_CHANNEL = "window:open-workspace";
+
+const WORKSPACE_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
+const MAX_WORKSPACE_PATH_LENGTH = 2_048;
+
+export function parseWorkspaceSlug(value: unknown): string | null {
+ return typeof value === "string" && WORKSPACE_SLUG_PATTERN.test(value)
+ ? value
+ : null;
+}
+
+/**
+ * Accept a renderer-supplied path only when it stays inside `slug`'s routes,
+ * so focusing another window can never hand it a foreign or absolute URL.
+ */
+export function parseWorkspaceWindowPath(
+ slug: string,
+ value: unknown,
+): string | null {
+ if (typeof value !== "string") return null;
+ if (value.length === 0 || value.length > MAX_WORKSPACE_PATH_LENGTH) {
+ return null;
+ }
+ const prefix = `/${slug}`;
+ if (!value.startsWith(prefix)) return null;
+ const rest = value.slice(prefix.length);
+ return rest === "" || /^[/?#]/.test(rest) ? value : null;
+}
+
+export function encodeWorkspaceWindowArgument(slug: string): string {
+ const valid = parseWorkspaceSlug(slug);
+ if (!valid) throw new Error("Invalid workspace window slug");
+ return `${WORKSPACE_WINDOW_ARGUMENT_PREFIX}${valid}`;
+}
+
+/** The workspace a main window was launched for, or null when unspecified. */
+export function readWorkspaceWindowSlug(argv: readonly string[]): string | null {
+ const argument = argv.find((item) =>
+ item.startsWith(WORKSPACE_WINDOW_ARGUMENT_PREFIX),
+ );
+ if (!argument) return null;
+ return parseWorkspaceSlug(
+ argument.slice(WORKSPACE_WINDOW_ARGUMENT_PREFIX.length),
+ );
+}
diff --git a/packages/views/layout/rail-workspaces.test.tsx b/packages/views/layout/rail-workspaces.test.tsx
index f0fe167a73..3146b18239 100644
--- a/packages/views/layout/rail-workspaces.test.tsx
+++ b/packages/views/layout/rail-workspaces.test.tsx
@@ -1,6 +1,6 @@
import type { ReactNode } from "react";
import { fireEvent, screen, within } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
import { renderWithI18n } from "../test/i18n";
import { RailWorkspaces } from "./rail-workspaces";
@@ -15,6 +15,8 @@ const state = vi.hoisted(() => ({
invalidateQueries: vi.fn(),
mutations: [] as Array<Record<string, unknown>>,
workspaceCreationDisabled: false,
+ openWorkspaceInNewWindow: undefined as undefined | Mock<(slug: string) => void>,
+ workspacesInOtherWindows: undefined as undefined | (() => string[]),
}));
vi.mock("@multica/core/config", () => ({
@@ -28,7 +30,12 @@ vi.mock("../navigation", () => ({
{children}
</a>
),
- useNavigation: () => ({ pathname: "/active/issues", push: vi.fn() }),
+ useNavigation: () => ({
+ pathname: "/active/issues",
+ push: vi.fn(),
+ openWorkspaceInNewWindow: state.openWorkspaceInNewWindow,
+ workspacesInOtherWindows: state.workspacesInOtherWindows,
+ }),
}));
vi.mock("@multica/core/paths", async (importOriginal) => ({
...(await importOriginal<typeof import("@multica/core/paths")>()),
@@ -89,6 +96,8 @@ beforeEach(() => {
state.summary = [];
state.mutations.length = 0;
state.workspaceCreationDisabled = false;
+ state.openWorkspaceInNewWindow = undefined;
+ state.workspacesInOtherWindows = undefined;
});
describe("RailWorkspaces", () => {
@@ -140,6 +149,70 @@ describe("RailWorkspaces", () => {
renderWithI18n(<RailWorkspaces />);
expect(within(await openMenu()).queryByRole("menuitem", { name: "Create workspace" })).toBeNull();
});
+
+ describe("new windows", () => {
+ const row = (menu: HTMLElement, name: RegExp) => within(menu).getByRole("menuitem", { name });
+
+ beforeEach(() => {
+ state.openWorkspaceInNewWindow = vi.fn();
+ state.workspaces = [ws(1), ws(2), ws(3)];
+ });
+
+ it("opens a workspace in a new window from its row button without following the row link", async () => {
+ renderWithI18n(<RailWorkspaces />);
+ const menu = await openMenu();
+ const button = within(row(menu, /WS 3/)).getByRole("button", { name: "Open in new window" });
+ const notPrevented = fireEvent.click(button);
+
+ expect(state.openWorkspaceInNewWindow).toHaveBeenCalledWith("ws3");
+ expect(notPrevented).toBe(false);
+ });
+
+ it("opens a workspace in a new window on shift-click", async () => {
+ renderWithI18n(<RailWorkspaces />);
+ const menu = await openMenu();
+ const target = row(menu, /WS 2/);
+ const notPrevented = fireEvent.click(target, { shiftKey: true });
+
+ expect(state.openWorkspaceInNewWindow).toHaveBeenCalledWith("ws2");
+ expect(notPrevented).toBe(false);
+ });
+
+ it("leaves a plain or cmd+shift click to the row link", async () => {
+ renderWithI18n(<RailWorkspaces />);
+ const menu = await openMenu();
+ fireEvent.click(row(menu, /WS 2/));
+ fireEvent.click(row(menu, /WS 2/), { shiftKey: true, metaKey: true });
+ expect(state.openWorkspaceInNewWindow).not.toHaveBeenCalled();
+ });
+
+ it("marks a workspace another window shows instead of offering a new window for it", async () => {
+ state.workspacesInOtherWindows = () => ["ws2"];
+ renderWithI18n(<RailWorkspaces />);
+ const menu = await openMenu();
+
+ const shown = row(menu, /WS 2/);
+ expect(within(shown).getByText("Other window")).toBeInTheDocument();
+ expect(within(row(menu, /WS 3/)).queryByText("Other window")).toBeNull();
+ expect(within(shown).queryByRole("button")).toBeNull();
+ expect(within(row(menu, /WS 3/)).getByRole("button", { name: "Open in new window" })).toBeInTheDocument();
+ fireEvent.click(shown, { shiftKey: true });
+ expect(state.openWorkspaceInNewWindow).not.toHaveBeenCalled();
+ });
+
+ it("offers no new window for the current workspace", async () => {
+ renderWithI18n(<RailWorkspaces />);
+ const menu = await openMenu();
+ expect(within(row(menu, /Active WS/)).queryByRole("button")).toBeNull();
+ });
+
+ it("offers no new windows on web", async () => {
+ state.openWorkspaceInNewWindow = undefined;
+ renderWithI18n(<RailWorkspaces />);
+ const menu = await openMenu();
+ expect(within(menu).queryByRole("button", { name: "Open in new window" })).toBeNull();
+ });
+ });
});
describe("pending invitation self-heal", () => {
diff --git a/packages/views/layout/rail-workspaces.tsx b/packages/views/layout/rail-workspaces.tsx
index 7d1e521428..41c2322c50 100644
--- a/packages/views/layout/rail-workspaces.tsx
+++ b/packages/views/layout/rail-workspaces.tsx
@@ -1,8 +1,8 @@
"use client";
-import { useMemo } from "react";
+import { useMemo, useState, type MouseEvent } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Check, Plus } from "@multica/ui/icons";
+import { AppWindow, ArrowBigUp, Check, Plus } from "@multica/ui/icons";
import { api } from "@multica/core/api";
import { useConfigStore } from "@multica/core/config";
import {
@@ -30,6 +30,7 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
+import { Kbd, KbdGroup } from "@multica/ui/components/ui/kbd";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../i18n";
import { AppLink, useNavigation } from "../navigation";
@@ -39,11 +40,68 @@ import { WorkspaceAvatar } from "../workspace/workspace-avatar";
const EMPTY_WORKSPACES: Workspace[] = [];
const EMPTY_INVITATIONS: Invitation[] = [];
const EMPTY_INBOX_SUMMARY: Awaited<ReturnType<typeof api.getInboxUnreadSummary>> = [];
+const EMPTY_SLUGS: ReadonlySet<string> = new Set();
function UnreadDot({ className }: { className?: string }) {
return <span aria-hidden className={cn("size-2 shrink-0 rounded-full bg-brand", className)} />;
}
+// Shift alone, the browser's "open in new window" gesture. Cmd/Ctrl+Shift
+// stays the foreground-tab gesture AppLink already handles.
+function isNewWindowClick(event: MouseEvent) {
+ return event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey;
+}
+
+/**
+ * Trailing row button that opens the workspace in a new window. It sits
+ * inside the row link, so its click cancels the link's navigation and still
+ * reaches the menu item, which closes the menu.
+ */
+function NewWindowButton({ onOpen }: { onOpen: () => void }) {
+ const { t } = useT("layout");
+ const label = t(($) => $.rail.open_in_new_window);
+ return (
+ <TooltipHint
+ label={label}
+ side="right"
+ shortcut={
+ <KbdGroup>
+ <Kbd>
+ <ArrowBigUp />
+ </Kbd>
+ <Kbd>{t(($) => $.rail.open_in_new_window_click)}</Kbd>
+ </KbdGroup>
+ }
+ >
+ <button
+ type="button"
+ tabIndex={-1}
+ aria-label={label}
+ className="-my-1 -mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground opacity-0 group-hover/workspace:opacity-100 group-data-highlighted/workspace:opacity-100 hover:bg-surface-selected hover:text-foreground"
+ onClick={(event) => {
+ event.preventDefault();
+ onOpen();
+ }}
+ >
+ <AppWindow />
+ </button>
+ </TooltipHint>
+ );
+}
+
+// A text tag rather than a window glyph, so it never reads as the row
+// button that opens a new window.
+function OtherWindowMarker() {
+ const { t } = useT("layout");
+ return (
+ <TooltipHint label={t(($) => $.rail.open_in_other_window)} side="right">
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {t(($) => $.rail.in_other_window)}
+ </span>
+ </TooltipHint>
+ );
+}
+
function useInvitationActions(invitations: Invitation[]) {
const queryClient = useQueryClient();
const { push } = useNavigation();
@@ -136,6 +194,9 @@ export function RailWorkspaces() {
});
const unreadIds = useMemo(() => unreadWorkspaceIds(unreadSummary), [unreadSummary]);
const actions = useInvitationActions(invitations);
+ const { openWorkspaceInNewWindow, workspacesInOtherWindows } = useNavigation();
+ // Read when the menu opens: other windows switch workspaces independently.
+ const [inOtherWindows, setInOtherWindows] = useState(EMPTY_SLUGS);
const current = workspaces.find((ws) => ws.id === wsId) ?? workspace;
if (!current) return null;
@@ -143,7 +204,13 @@ export function RailWorkspaces() {
const label = t(($) => $.rail.switch_workspace);
return (
- <DropdownMenu>
+ <DropdownMenu
+ onOpenChange={(open) => {
+ if (open && workspacesInOtherWindows) {
+ setInOtherWindows(new Set(workspacesInOtherWindows()));
+ }
+ }}
+ >
<TooltipHint label={current.name} side="right">
<DropdownMenuTrigger
aria-label={label}
@@ -166,15 +233,34 @@ export function RailWorkspaces() {
</DropdownMenuLabel>
{workspaces.map((ws) => {
const isCurrent = ws.id === wsId;
+ // A workspace shown by another window is focused there by a
+ // plain click, so it offers no new window of its own.
+ const inOtherWindow = !isCurrent && inOtherWindows.has(ws.slug);
+ const openInNewWindow =
+ openWorkspaceInNewWindow && !isCurrent && !inOtherWindow
+ ? () => openWorkspaceInNewWindow(ws.slug)
+ : null;
return (
<DropdownMenuItem
key={ws.id}
aria-current={isCurrent ? "page" : undefined}
+ className="group/workspace"
+ onClick={
+ openInNewWindow
+ ? (event: MouseEvent) => {
+ if (event.defaultPrevented || !isNewWindowClick(event)) return;
+ event.preventDefault();
+ openInNewWindow();
+ }
+ : undefined
+ }
render={<AppLink href={paths.workspace(ws.slug).issues()} />}
>
<WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />
<span className="min-w-0 flex-1 truncate">{ws.name}</span>
{isCurrent ? <Check /> : unreadIds.has(ws.id) && <UnreadDot />}
+ {inOtherWindow && <OtherWindowMarker />}
+ {openInNewWindow && <NewWindowButton onOpen={openInNewWindow} />}
</DropdownMenuItem>
);
})}
diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.json
index 053962e5f5..83caf56036 100644
--- a/packages/views/locales/en/layout.json
+++ b/packages/views/locales/en/layout.json
@@ -76,7 +76,12 @@
"chat": "Chat",
"autopilots": "Auto",
"switch_workspace": "Switch workspace",
- "invitation_from": "{{name}} invited you"
+ "invitation_from": "{{name}} invited you",
+ "open_in_new_window": "Open in new window",
+ "open_in_new_window_click": "Click",
+ "open_in_other_window": "Already open in another window",
+ "in_other_window": "Other window",
+ "all_workspaces_open": "Every workspace is already open in a window"
},
"panels": {
"work": {
diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.json
index c4681b270c..6a0f5ae0c4 100644
--- a/packages/views/locales/fr/layout.json
+++ b/packages/views/locales/fr/layout.json
@@ -76,7 +76,12 @@
"chat": "Chat",
"autopilots": "Auto",
"switch_workspace": "Changer d'espace de travail",
- "invitation_from": "{{name}} vous a invité"
+ "invitation_from": "{{name}} vous a invité",
+ "open_in_new_window": "Ouvrir dans une nouvelle fenêtre",
+ "open_in_new_window_click": "Clic",
+ "open_in_other_window": "Déjà ouvert dans une autre fenêtre",
+ "in_other_window": "Autre fenêtre",
+ "all_workspaces_open": "Chaque espace de travail est déjà ouvert dans une fenêtre"
},
"panels": {
"work": {
diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.json
index 5839060472..d36d88d9f6 100644
--- a/packages/views/locales/ja/layout.json
+++ b/packages/views/locales/ja/layout.json
@@ -76,7 +76,12 @@
"chat": "チャット",
"autopilots": "自動化",
"switch_workspace": "ワークスペースを切り替え",
- "invitation_from": "{{name}} さんから招待されています"
+ "invitation_from": "{{name}} さんから招待されています",
+ "open_in_new_window": "新しいウィンドウで開く",
+ "open_in_new_window_click": "クリック",
+ "open_in_other_window": "別のウィンドウで開いています",
+ "in_other_window": "別ウィンドウ",
+ "all_workspaces_open": "すべてのワークスペースがすでにウィンドウで開いています"
},
"panels": {
"work": {
diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.json
index f787abe9be..27fc957a70 100644
--- a/packages/views/locales/ko/layout.json
+++ b/packages/views/locales/ko/layout.json
@@ -76,7 +76,12 @@
"chat": "채팅",
"autopilots": "자동화",
"switch_workspace": "워크스페이스 전환",
- "invitation_from": "{{name}} 님이 초대했습니다"
+ "invitation_from": "{{name}} 님이 초대했습니다",
+ "open_in_new_window": "새 창에서 열기",
+ "open_in_new_window_click": "클릭",
+ "open_in_other_window": "다른 창에서 열려 있음",
+ "in_other_window": "다른 창",
+ "all_workspaces_open": "모든 워크스페이스가 이미 창에 열려 있습니다"
},
"panels": {
"work": {
diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.json
index 1f6ac3844b..5b2fece980 100644
--- a/packages/views/locales/zh-Hans/layout.json
+++ b/packages/views/locales/zh-Hans/layout.json
@@ -76,7 +76,12 @@
"chat": "聊天",
"autopilots": "自动化",
"switch_workspace": "切换工作区",
- "invitation_from": "{{name}} 邀请你加入"
+ "invitation_from": "{{name}} 邀请你加入",
+ "open_in_new_window": "在新窗口打开",
+ "open_in_new_window_click": "点击",
+ "open_in_other_window": "已在其他窗口打开",
+ "in_other_window": "其他窗口",
+ "all_workspaces_open": "所有工作区都已在窗口中打开"
},
"panels": {
"work": {
diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.json
index 6319f9eaa8..02ec3395ac 100644
--- a/packages/views/locales/zh-Hant/layout.json
+++ b/packages/views/locales/zh-Hant/layout.json
@@ -76,7 +76,12 @@
"chat": "聊天",
"autopilots": "自動化",
"switch_workspace": "切換工作區",
- "invitation_from": "{{name}} 邀請你加入"
+ "invitation_from": "{{name}} 邀請你加入",
+ "open_in_new_window": "在新視窗開啟",
+ "open_in_new_window_click": "點擊",
+ "open_in_other_window": "已在其他視窗開啟",
+ "in_other_window": "其他視窗",
+ "all_workspaces_open": "所有工作區都已在視窗中開啟"
},
"panels": {
"work": {
diff --git a/packages/views/navigation/types.ts b/packages/views/navigation/types.ts
index 6e13fc4b06..6893bb4534 100644
--- a/packages/views/navigation/types.ts
+++ b/packages/views/navigation/types.ts
@@ -28,6 +28,13 @@ export interface NavigationAdapter {
title?: string,
opts?: { activate?: boolean },
) => void;
+ /**
+ * Desktop only: show a workspace in its own window, or focus the window
+ * that already shows it.
+ */
+ openWorkspaceInNewWindow?: (slug: string) => void;
+ /** Desktop only: slugs of the workspaces other windows currently show. */
+ workspacesInOtherWindows?: () => readonly string[];
/** Return a shareable URL for a path. Web: origin + path. Desktop: public web URL of the connected environment. */
getShareableUrl: (path: string) => string;
/**