From 98acf8f5e14b0892b3cfd9c5088a7fadca1be4fe Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 22:32:08 -0500 Subject: [PATCH 01/21] feat(desktop): open more windows that share the main window's connection Secondary windows are thin clients: the main window's renderer is a hub that relays each environment's RPC over a MessagePort and shares its subscription streams, so a new window opens without its own sockets or auth. The desktop shell opens them from New Window (command palette, Window menu, and mod+alt+shift+n), trusts IPC from every app window, scopes preview tabs to the window that shows them, and keeps the main window hidden rather than closed while it serves other windows. Windows merge their shared UI state and composer drafts instead of overwriting each other's saves. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app/DesktopLifecycle.test.ts | 7 +- .../src/backend/DesktopBackendPool.test.ts | 5 +- apps/desktop/src/electron/ElectronWindow.ts | 41 +- apps/desktop/src/i18n/translations/de.json | 1 + apps/desktop/src/i18n/translations/en.json | 1 + apps/desktop/src/i18n/translations/es.json | 1 + apps/desktop/src/i18n/translations/fr.json | 1 + apps/desktop/src/i18n/translations/ja.json | 1 + apps/desktop/src/i18n/translations/ko.json | 1 + apps/desktop/src/i18n/translations/pt-BR.json | 1 + apps/desktop/src/i18n/translations/ru.json | 1 + apps/desktop/src/i18n/translations/sv.json | 1 + apps/desktop/src/i18n/translations/zh.json | 1 + apps/desktop/src/ipc/DesktopIpc.test.ts | 28 +- apps/desktop/src/ipc/DesktopIpc.ts | 63 ++- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 8 + apps/desktop/src/ipc/channels.ts | 12 + .../desktop/src/ipc/methods/clientSettings.ts | 7 + apps/desktop/src/ipc/methods/fileDrag.test.ts | 2 +- apps/desktop/src/ipc/methods/fileDrag.ts | 10 +- apps/desktop/src/ipc/methods/preview.test.ts | 85 ++- apps/desktop/src/ipc/methods/preview.ts | 104 +++- apps/desktop/src/ipc/methods/snapShot.test.ts | 10 +- apps/desktop/src/ipc/methods/snapShot.ts | 12 +- apps/desktop/src/ipc/methods/window.test.ts | 32 +- apps/desktop/src/ipc/methods/window.ts | 79 +-- apps/desktop/src/ipc/methods/windows.ts | 58 ++ apps/desktop/src/preload.ts | 66 +++ apps/desktop/src/preview/Manager.test.ts | 80 +++ apps/desktop/src/preview/Manager.ts | 152 +++-- .../src/ssh/DesktopSshPasswordPrompts.test.ts | 4 +- .../desktop/src/updates/updatesTestHarness.ts | 4 +- .../src/window/BackgroundThrottling.ts | 21 + .../src/window/DesktopApplicationMenu.test.ts | 32 +- .../src/window/DesktopApplicationMenu.ts | 20 +- .../src/window/DesktopHubLinks.test.ts | 66 +++ apps/desktop/src/window/DesktopHubLinks.ts | 55 ++ apps/desktop/src/window/DesktopWindow.test.ts | 70 ++- apps/desktop/src/window/DesktopWindow.ts | 397 ++++++++++--- .../src/window/DesktopWindowProfiles.test.ts | 26 + .../src/window/DesktopWindowProfiles.ts | 41 ++ apps/web/src/appInit.tsx | 23 +- apps/web/src/browser/ElectronBrowserHost.tsx | 28 +- apps/web/src/components/CommandPalette.tsx | 3 + .../components/CommandPaletteWindowItems.tsx | 25 + .../settings/KeybindingsSettings.logic.ts | 1 + apps/web/src/composerDraftStore.test.ts | 51 ++ apps/web/src/composerDraftStore.ts | 140 +++++ apps/web/src/connection/runtime.ts | 18 +- apps/web/src/hooks/useSettings.ts | 17 +- apps/web/src/i18n/translations/de.json | 2 + apps/web/src/i18n/translations/en.json | 2 + apps/web/src/i18n/translations/es.json | 2 + apps/web/src/i18n/translations/fr.json | 2 + apps/web/src/i18n/translations/ja.json | 2 + apps/web/src/i18n/translations/ko.json | 2 + apps/web/src/i18n/translations/pt-BR.json | 2 + apps/web/src/i18n/translations/ru.json | 2 + apps/web/src/i18n/translations/sv.json | 2 + apps/web/src/i18n/translations/zh.json | 2 + apps/web/src/keybindings.test.ts | 27 + apps/web/src/multiWindow/hub.ts | 126 +++++ apps/web/src/multiWindow/hubLink.ts | 66 +++ .../src/multiWindow/previewHosting.test.ts | 21 + apps/web/src/multiWindow/previewHosting.ts | 104 ++++ apps/web/src/multiWindow/secondary.ts | 170 ++++++ apps/web/src/multiWindow/ui/windowActions.ts | 41 ++ apps/web/src/multiWindow/windowContext.ts | 24 + apps/web/src/multiWindow/windowsState.ts | 46 ++ apps/web/src/routes/__root.tsx | 7 +- apps/web/src/uiStateStore.test.ts | 30 + apps/web/src/uiStateStore.ts | 115 +++- docs/README.md | 1 + docs/user/keybindings.md | 3 + docs/user/multiple-windows.md | 14 + .../client-runtime/src/connection/hub.test.ts | 37 ++ packages/client-runtime/src/connection/hub.ts | 195 +++++++ .../client-runtime/src/connection/index.ts | 1 + .../client-runtime/src/connection/layer.ts | 19 +- packages/client-runtime/src/rpc/index.ts | 1 + packages/client-runtime/src/rpc/relay.ts | 357 ++++++++++++ .../client-runtime/src/rpc/session.test.ts | 512 +++++++++++++++++ packages/client-runtime/src/rpc/session.ts | 122 +++- .../client-runtime/src/rpc/sharedStreams.ts | 529 ++++++++++++++++++ packages/contracts/src/desktopWindows.ts | 46 ++ packages/contracts/src/index.ts | 1 + packages/contracts/src/ipc.ts | 5 + packages/contracts/src/keybindings.ts | 1 + packages/shared/src/keybindings.ts | 1 + 89 files changed, 4238 insertions(+), 317 deletions(-) create mode 100644 apps/desktop/src/ipc/methods/windows.ts create mode 100644 apps/desktop/src/window/BackgroundThrottling.ts create mode 100644 apps/desktop/src/window/DesktopHubLinks.test.ts create mode 100644 apps/desktop/src/window/DesktopHubLinks.ts create mode 100644 apps/desktop/src/window/DesktopWindowProfiles.test.ts create mode 100644 apps/desktop/src/window/DesktopWindowProfiles.ts create mode 100644 apps/web/src/components/CommandPaletteWindowItems.tsx create mode 100644 apps/web/src/multiWindow/hub.ts create mode 100644 apps/web/src/multiWindow/hubLink.ts create mode 100644 apps/web/src/multiWindow/previewHosting.test.ts create mode 100644 apps/web/src/multiWindow/previewHosting.ts create mode 100644 apps/web/src/multiWindow/secondary.ts create mode 100644 apps/web/src/multiWindow/ui/windowActions.ts create mode 100644 apps/web/src/multiWindow/windowContext.ts create mode 100644 apps/web/src/multiWindow/windowsState.ts create mode 100644 docs/user/multiple-windows.md create mode 100644 packages/client-runtime/src/connection/hub.test.ts create mode 100644 packages/client-runtime/src/connection/hub.ts create mode 100644 packages/client-runtime/src/rpc/relay.ts create mode 100644 packages/client-runtime/src/rpc/sharedStreams.ts create mode 100644 packages/contracts/src/desktopWindows.ts diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index e11e946dd41ba..772379b964374 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -73,7 +73,9 @@ function layerElectronWindow(destroyAll: Effect.Effect = Effect.void) { create: () => Effect.die("unexpected window creation"), main: Effect.die("unexpected main window read"), currentMainOrFirst: Effect.die("unexpected current window read"), - focusedMainOrFirst: Effect.die("unexpected focused window read"), + apps: Effect.succeed([]), + focusedApp: Effect.succeedNone, + registerApp: () => Effect.void, setMain: () => Effect.void, clearMain: () => Effect.void, prepareReveal: () => Effect.succeed(false), @@ -90,7 +92,7 @@ function layerDesktopWindow( readonly flushMainWindowBounds?: Effect.Effect; } = {}, ) { - return Layer.succeed(DesktopWindow.DesktopWindow, { + return Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected window creation"), ensureMain: Effect.die("unexpected window creation"), revealOrCreateMain: Effect.die("unexpected window creation"), @@ -103,7 +105,6 @@ function layerDesktopWindow( prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.void, dispatchSnapShotEvent: () => Effect.void, - zoomMain: () => Effect.void, runMainContentsCommand: () => Effect.void, syncAppearance: Effect.void, }); diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 005a1cde1224a..1be204cb02354 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -203,7 +203,7 @@ function layerPool( showErrorBox: () => Effect.void, } satisfies ElectronDialog.ElectronDialog["Service"]), ElectronApp.layer, - Layer.succeed(DesktopWindow.DesktopWindow, { + Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected window create"), ensureMain: Effect.die("unexpected window ensure"), revealOrCreateMain: Effect.die("unexpected window reveal"), @@ -216,11 +216,10 @@ function layerPool( prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.die("unexpected menu action"), dispatchSnapShotEvent: () => Effect.void, - zoomMain: () => Effect.die("unexpected zoom"), runMainContentsCommand: options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")), syncAppearance: Effect.void, - } satisfies DesktopWindow.DesktopWindow["Service"]), + }), ), ), ); diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts index b5f89969e66c7..098e9191328f2 100644 --- a/apps/desktop/src/electron/ElectronWindow.ts +++ b/apps/desktop/src/electron/ElectronWindow.ts @@ -117,7 +117,11 @@ export class ElectronWindow extends Context.Service< ) => Effect.Effect; readonly main: Effect.Effect>; readonly currentMainOrFirst: Effect.Effect>; - readonly focusedMainOrFirst: Effect.Effect>; + /** Windows that load the app renderer: the main window first, then secondary windows. */ + readonly apps: Effect.Effect>; + /** The focused app window, else the main window; never a popup or auxiliary window. */ + readonly focusedApp: Effect.Effect>; + readonly registerApp: (window: Electron.BrowserWindow) => Effect.Effect; readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect; readonly clearMain: (window: Option.Option) => Effect.Effect; readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect; @@ -148,6 +152,7 @@ export const make = Effect.gen(function* () { yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close())); const mainWindowRef = yield* Ref.make>(Option.none()); const auxiliaryWindows = new WeakSet(); + const appWindows = new Set(); const titleBarOverlayWindows = new WeakSet(); const listWindows = Effect.try({ @@ -198,9 +203,22 @@ export const make = Effect.gen(function* () { return first; }); - const focusedMainOrFirst = Effect.gen(function* () { + const liveApps = Effect.gen(function* () { + const main = yield* liveMain; + const apps: Electron.BrowserWindow[] = Option.isSome(main) ? [main.value] : []; + for (const window of appWindows) { + if (yield* isWindowDestroyed(window)) { + appWindows.delete(window); + } else if (!apps.includes(window)) { + apps.push(window); + } + } + return apps; + }); + + const focusedApp = Effect.gen(function* () { const focused = yield* Effect.try({ - try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null), + try: () => Electron.BrowserWindow.getFocusedWindow(), catch: (cause) => new ElectronWindowOperationError({ operation: "get-focused-window", @@ -210,10 +228,9 @@ export const make = Effect.gen(function* () { cause, }), }).pipe(Effect.orDie); - if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) { - return focused; - } - return yield* currentMainOrFirst; + const apps = yield* liveApps; + if (focused !== null && apps.includes(focused)) return Option.some(focused); + return yield* liveMain; }); return ElectronWindow.of({ @@ -255,9 +272,15 @@ export const make = Effect.gen(function* () { }), main: liveMain, currentMainOrFirst, - focusedMainOrFirst, + apps: liveApps, + focusedApp, + registerApp: Effect.fn("ElectronWindow.registerApp")(function (window) { + return Effect.sync(() => void appWindows.add(window)); + }), setMain: Effect.fn("ElectronWindow.setMain")(function (window) { - return Ref.set(mainWindowRef, Option.some(window)); + return Ref.set(mainWindowRef, Option.some(window)).pipe( + Effect.andThen(Effect.sync(() => void appWindows.add(window))), + ); }), clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) { return Ref.update(mainWindowRef, (current) => { diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json index 8e39e7585f60d..55145c7cda1eb 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Verkleinern", "50fe114d093a5bc7": "Vollbildmodus ein/aus", "d8c6d6d9845353da": "Fenster", + "c015841b7b2523c6": "Neues Fenster", "f184aa190588625e": "Minimieren", "c20a9deaed71bd1c": "Zoomen", "d207ba3a23f94223": "Alle nach vorne bringen", diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 9a07ef060cbc9..578c3a86c961e 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Zoom Out", "50fe114d093a5bc7": "Toggle Full Screen", "d8c6d6d9845353da": "Window", + "c015841b7b2523c6": "New Window", "f184aa190588625e": "Minimize", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Bring All to Front", diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index f891e9eaf850b..155d2d7e22e48 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Alejar", "50fe114d093a5bc7": "Activar/desactivar pantalla completa", "d8c6d6d9845353da": "Ventana", + "c015841b7b2523c6": "Nueva ventana", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Traer todo al frente", diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 0bb5a47518581..9312fb6c77f57 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Zoom arrière", "50fe114d093a5bc7": "Activer/désactiver le plein écran", "d8c6d6d9845353da": "Fenêtre", + "c015841b7b2523c6": "Nouvelle fenêtre", "f184aa190588625e": "Réduire", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Tout ramener au premier plan", diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index df89efe466261..46759a18b9b1c 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "縮小", "50fe114d093a5bc7": "フルスクリーンに切り替え", "d8c6d6d9845353da": "ウインドウ", + "c015841b7b2523c6": "新規ウインドウ", "f184aa190588625e": "しまう", "c20a9deaed71bd1c": "拡大/縮小", "d207ba3a23f94223": "すべてを手前に移動", diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index 566724b9b91c1..eac165f0b91ce 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "축소", "50fe114d093a5bc7": "전체 화면 전환", "d8c6d6d9845353da": "윈도우", + "c015841b7b2523c6": "새 윈도우", "f184aa190588625e": "최소화", "c20a9deaed71bd1c": "확대/축소", "d207ba3a23f94223": "모두 앞으로 가져오기", diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 67f4eefd1c9ec..7d39c2e2bb2ee 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Diminuir zoom", "50fe114d093a5bc7": "Alternar tela cheia", "d8c6d6d9845353da": "Janela", + "c015841b7b2523c6": "Nova janela", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Trazer tudo para a frente", diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index 46364dfabe488..2f56fc560ab1b 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Уменьшить", "50fe114d093a5bc7": "Полноэкранный режим", "d8c6d6d9845353da": "Окно", + "c015841b7b2523c6": "Новое окно", "f184aa190588625e": "Свернуть", "c20a9deaed71bd1c": "Масштаб", "d207ba3a23f94223": "Все окна на передний план", diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index 67bcaf6a380aa..e161a7f984dfc 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Zooma ut", "50fe114d093a5bc7": "Växla helskärm", "d8c6d6d9845353da": "Fönster", + "c015841b7b2523c6": "Nytt fönster", "f184aa190588625e": "Minimera", "c20a9deaed71bd1c": "Zooma", "d207ba3a23f94223": "Lägg alla överst", diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index 72122de01df62..b414c5fd1f0df 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "缩小", "50fe114d093a5bc7": "切换全屏", "d8c6d6d9845353da": "窗口", + "c015841b7b2523c6": "新建窗口", "f184aa190588625e": "最小化", "c20a9deaed71bd1c": "缩放", "d207ba3a23f94223": "前置全部窗口", diff --git a/apps/desktop/src/ipc/DesktopIpc.test.ts b/apps/desktop/src/ipc/DesktopIpc.test.ts index 1973ab49cefeb..36defff9eb9ea 100644 --- a/apps/desktop/src/ipc/DesktopIpc.test.ts +++ b/apps/desktop/src/ipc/DesktopIpc.test.ts @@ -9,9 +9,12 @@ vi.mock("electron", () => ({})); import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as DesktopIpc from "./DesktopIpc.ts"; -it.effect("answers only the main window's top frame", () => +it.effect("answers only app windows' top frames and tells handlers which window sent", () => Effect.gen(function* () { const mainFrame = {}; + const secondaryFrame = {}; + const mainWindow = { id: 10, webContents: { id: 1, mainFrame } }; + const secondaryWindow = { id: 11, webContents: { id: 3, mainFrame: secondaryFrame } }; const invoke = new Map(); const sync = new Map(); const ipc = yield* DesktopIpc.DesktopIpc.pipe( @@ -24,9 +27,11 @@ it.effect("answers only the main window's top frame", () => }).pipe( Layer.provide( Layer.mock(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ - webContents: { id: 1, mainFrame }, - } as unknown as Electron.BrowserWindow), + main: Effect.succeedSome(mainWindow as unknown as Electron.BrowserWindow), + apps: Effect.succeed([ + mainWindow, + secondaryWindow, + ] as unknown as ReadonlyArray), }), ), ), @@ -37,13 +42,21 @@ it.effect("answers only the main window's top frame", () => channel: "token", payload: Schema.Void, result: Schema.String, - handler: () => Effect.succeed("secret"), + handler: () => + Effect.map( + DesktopIpc.DesktopIpcSender, + ({ window, isMain }) => `secret-${window.id}${isMain ? "-main" : ""}`, + ), }), ); - yield* ipc.handleSync({ channel: "token-sync", handler: () => Effect.succeed("secret") }); + yield* ipc.handleSync({ + channel: "token-sync", + handler: () => Effect.map(DesktopIpc.DesktopIpcSender, ({ window }) => `secret-${window.id}`), + }); const senders = { app: { sender: { id: 1 }, senderFrame: mainFrame }, + secondary: { sender: { id: 3 }, senderFrame: secondaryFrame }, appSubframe: { sender: { id: 1 }, senderFrame: {} }, previewGuest: { sender: { id: 2 }, senderFrame: {} }, }; @@ -59,7 +72,8 @@ it.effect("answers only the main window's top frame", () => ]; } assert.deepEqual(results, { - app: ["secret", "secret"], + app: ["secret-10-main", "secret-10"], + secondary: ["secret-11", "secret-11"], appSubframe: ["rejected", undefined], previewGuest: ["rejected", undefined], }); diff --git a/apps/desktop/src/ipc/DesktopIpc.ts b/apps/desktop/src/ipc/DesktopIpc.ts index 69d4f70c15a0e..16a5e01bae121 100644 --- a/apps/desktop/src/ipc/DesktopIpc.ts +++ b/apps/desktop/src/ipc/DesktopIpc.ts @@ -5,6 +5,8 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import type * as Electron from "electron"; + import * as ElectronWindow from "../electron/ElectronWindow.ts"; export interface DesktopIpcInvokeEvent { @@ -16,7 +18,16 @@ export interface DesktopIpcSyncEvent extends DesktopIpcInvokeEvent { returnValue: unknown; } -export type DesktopIpcSenderGuard = (event: DesktopIpcInvokeEvent) => Effect.Effect; +/** The app window that sent the IPC call being handled. */ +export class DesktopIpcSender extends Context.Service< + DesktopIpcSender, + { readonly window: Electron.BrowserWindow; readonly isMain: boolean } +>()("@t3tools/desktop/ipc/DesktopIpc/DesktopIpcSender") {} + +/** Resolves the app window whose top frame sent the event; none rejects the call. */ +export type DesktopIpcSenderGuard = ( + event: DesktopIpcInvokeEvent, +) => Effect.Effect>; export type DesktopIpcHandleListener = ( event: DesktopIpcInvokeEvent, @@ -83,15 +94,17 @@ export interface DesktopSyncIpcMethod { readonly handler: () => Effect.Effect; } +type HandlerServices = Exclude; + export class DesktopIpc extends Context.Service< DesktopIpc, { readonly handle: ( input: DesktopIpcMethod, - ) => Effect.Effect; + ) => Effect.Effect | Scope.Scope>; readonly handleSync: ( input: DesktopSyncIpcMethod, - ) => Effect.Effect; + ) => Effect.Effect | Scope.Scope>; } >()("@t3tools/desktop/ipc/DesktopIpc") {} @@ -106,7 +119,7 @@ export const make = ( handler, }: DesktopIpcMethod) { yield* Effect.annotateCurrentSpan({ channel }); - const context = yield* Effect.context(); + const context = yield* Effect.context>(); const runPromise = Effect.runPromiseWith(context); yield* Effect.acquireRelease( @@ -117,10 +130,13 @@ export const make = ( runPromise( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); - if (!(yield* isTrustedSender(event))) { + const sender = yield* isTrustedSender(event); + if (Option.isNone(sender)) { return yield* new DesktopIpcUntrustedSenderError({ channel }); } - return yield* handler(raw, event); + return yield* handler(raw, event).pipe( + Effect.provideService(DesktopIpcSender, sender.value), + ); }).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")), ), ); @@ -142,7 +158,7 @@ export const make = ( handler, }: DesktopSyncIpcMethod) { yield* Effect.annotateCurrentSpan({ channel }); - const context = yield* Effect.context(); + const context = yield* Effect.context>(); const runSync = Effect.runSyncWith(context); yield* Effect.acquireRelease( @@ -154,11 +170,14 @@ export const make = ( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); // Throwing here would surface as an uncaught main-process exception. - if (!(yield* isTrustedSender(event))) { + const sender = yield* isTrustedSender(event); + if (Option.isNone(sender)) { yield* Effect.logWarning("Rejected sync IPC from an untrusted sender."); return undefined; } - return yield* handler(); + return yield* handler().pipe( + Effect.provideService(DesktopIpcSender, sender.value), + ); }).pipe( Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync"), @@ -184,22 +203,30 @@ export const layer = (ipcMain: DesktopIpcMain) => DesktopIpc, Effect.gen(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; + // Only an app window's top frame is trusted, never a preview guest or subframe. return make(ipcMain, (event) => - Effect.map( - electronWindow.main, - (main) => - Option.isSome(main) && - main.value.webContents.id === event.sender.id && - main.value.webContents.mainFrame === event.senderFrame, - ), + Effect.gen(function* () { + const main = yield* electronWindow.main; + const window = (yield* electronWindow.apps).find( + (candidate) => + candidate.webContents.id === event.sender.id && + candidate.webContents.mainFrame === event.senderFrame, + ); + return window === undefined + ? Option.none() + : Option.some({ window, isMain: Option.contains(main, window) }); + }), ); }), ); -export const layerTest = (ipcMain: DesktopIpcMain) => +export const layerTest = ( + ipcMain: DesktopIpcMain, + sender: DesktopIpcSender["Service"] = { window: {} as Electron.BrowserWindow, isMain: true }, +) => Layer.succeed( DesktopIpc, - make(ipcMain, () => Effect.succeed(true)), + make(ipcMain, () => Effect.succeedSome(sender)), ); export interface DesktopIpcMethodRegistration< diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index c88ddd0827df0..099ae312c7c12 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -79,6 +79,7 @@ import { setSnapShotShortcutSuppressed, } from "./methods/snapShot.ts"; import * as PreviewIpc from "./methods/preview.ts"; +import * as WindowsIpc from "./methods/windows.ts"; import * as AppActivationIpc from "./methods/appActivation.ts"; import * as WebLinksIpc from "./methods/webLinks.ts"; import { @@ -189,6 +190,13 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" Effect.Services> >(previewMethod); } + yield* ipc.handleSync(WindowsIpc.getContext); + for (const windowsMethod of WindowsIpc.methods) { + yield* ipc.handle< + Effect.Error>, + Effect.Services> + >(windowsMethod); + } yield* ipc.handle(PreviewIpc.listBrowserImportSources); yield* ipc.handle(PreviewIpc.importBrowserCookies); }); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 71d272333fdc7..072915f952e48 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -154,3 +154,15 @@ export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-lo export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; export const START_FILE_DRAG_CHANNEL = "desktop:start-file-drag"; + +export const CLIENT_SETTINGS_CHANGED_CHANNEL = "desktop:client-settings-changed"; + +export const WINDOWS_GET_CONTEXT_CHANNEL = "desktop:windows-get-context"; +export const WINDOWS_GET_STATE_CHANNEL = "desktop:windows-get-state"; +export const WINDOWS_STATE_CHANNEL = "desktop:windows-state"; +export const WINDOWS_OPEN_NEW_CHANNEL = "desktop:windows-open-new"; +export const WINDOWS_REGISTER_HUB_CHANNEL = "desktop:windows-register-hub"; +export const WINDOWS_REQUEST_HUB_LINK_CHANNEL = "desktop:windows-request-hub-link"; +export const WINDOWS_HUB_LINK_CHANNEL = "desktop:windows-hub-link"; +export const WINDOWS_HUB_PEER_GONE_CHANNEL = "desktop:windows-hub-peer-gone"; +export const WINDOWS_HUB_RESET_CHANNEL = "desktop:windows-hub-reset"; diff --git a/apps/desktop/src/ipc/methods/clientSettings.ts b/apps/desktop/src/ipc/methods/clientSettings.ts index 56e861944871d..cf8da650564fa 100644 --- a/apps/desktop/src/ipc/methods/clientSettings.ts +++ b/apps/desktop/src/ipc/methods/clientSettings.ts @@ -4,6 +4,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { applyLanguage } from "../../i18n/messages.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts"; import * as IpcChannels from "../channels.ts"; @@ -29,5 +30,11 @@ export const setClientSettings = DesktopIpc.makeIpcMethod({ yield* clientSettings.set(settings); yield* snapShot.configure(settings); yield* applyLanguage(settings.language); + const sender = yield* DesktopIpc.DesktopIpcSender; + for (const window of yield* (yield* ElectronWindow.ElectronWindow).apps) { + if (window !== sender.window && !window.isDestroyed()) { + window.webContents.send(IpcChannels.CLIENT_SETTINGS_CHANGED_CHANNEL); + } + } }), }); diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts index 7e140f9db5445..b10d8f58beab6 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.test.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -33,7 +33,7 @@ it.effect("only drags existing absolute paths from the host environment and app platform, } as DesktopEnvironment.DesktopEnvironment["Service"]), Effect.provideService(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 1, startDrag } }), + apps: Effect.succeed([{ webContents: { id: 1, startDrag } }]), } as unknown as ElectronWindow.ElectronWindow["Service"]), ); assert.isFalse(yield* run("remote", filePath)); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts index 227849c5935be..f3a3f3ab1a25b 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -1,6 +1,5 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Electron from "electron"; @@ -20,14 +19,17 @@ export const startFileDrag = makeIpcMethod({ if (!environment.path.isAbsolute(input.path)) return false; const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; - const window = yield* (yield* ElectronWindow.ElectronWindow).main; - if (Option.isNone(window) || event?.sender.id !== window.value.webContents.id) return false; + // Drags start from whichever app window asked. + const window = (yield* (yield* ElectronWindow.ElectronWindow).apps).find( + (candidate) => event !== undefined && candidate.webContents.id === event.sender.id, + ); + if (window === undefined) return false; const fs = yield* FileSystem.FileSystem; if (!(yield* fs.exists(input.path))) return false; return yield* Effect.promise(async () => { try { const icon = await Electron.app.getFileIcon(input.path, { size: "normal" }); - window.value.webContents.startDrag({ file: input.path, icon }); + window.webContents.startDrag({ file: input.path, icon }); return true; } catch { return false; diff --git a/apps/desktop/src/ipc/methods/preview.test.ts b/apps/desktop/src/ipc/methods/preview.test.ts index bd7e44bec8307..a971eedc45c88 100644 --- a/apps/desktop/src/ipc/methods/preview.test.ts +++ b/apps/desktop/src/ipc/methods/preview.test.ts @@ -6,13 +6,17 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as LoopbackTunnel from "../../preview/LoopbackTunnel.ts"; import * as PreviewManager from "../../preview/Manager.ts"; import * as PreviewIpc from "./preview.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; +import * as IpcChannels from "../channels.ts"; const { fromPartition } = vi.hoisted(() => ({ fromPartition: vi.fn(() => { @@ -51,7 +55,7 @@ describe("preview IPC methods", () => { removeAllListeners: vi.fn(), on: vi.fn(), }, - () => Effect.succeed(true), + () => Effect.succeedSome({ window: {} as Electron.BrowserWindow, isMain: true }), ); yield* ipc.handle(method); return yield* Effect.promise(async () => @@ -110,6 +114,85 @@ describe("preview IPC methods", () => { }), ); + effectIt.effect( + "scopes a secondary window's tabs and sends their events only to it, unscoped", + () => + Effect.scoped( + Effect.gen(function* () { + const appWindow = (id: number) => + ({ + id, + isDestroyed: () => false, + webContents: { send: vi.fn() }, + }) as unknown as Electron.BrowserWindow; + const main = appWindow(1); + const secondary = appWindow(3); + const created: unknown[] = []; + let emitState: + | Parameters[0] + | undefined; + const manager = { + createTab: (tabId, _defaults, owner) => + Effect.sync(() => { + created.push({ tabId, owner }); + return {} as never; + }), + tabRoute: (tabId) => + Effect.succeed( + tabId === "w3:tab" + ? { window: Option.some(secondary), rendererTabId: "tab" } + : { window: Option.some(main), rendererTabId: tabId }, + ), + subscribeStateChanges: (listener) => + Effect.sync(() => { + emitState = listener; + }), + subscribeRecordingInputs: () => Effect.void, + subscribePointerEvents: () => Effect.void, + subscribeOpenLinks: () => Effect.void, + subscribeFindResults: () => Effect.void, + } satisfies Partial; + let listener: DesktopIpc.DesktopIpcHandleListener | undefined; + const ipc = DesktopIpc.make( + { + removeHandler: vi.fn(), + handle: (_channel, registered) => { + listener = registered; + }, + removeAllListeners: vi.fn(), + on: vi.fn(), + }, + () => Effect.succeedSome({ window: secondary, isMain: false }), + ); + yield* Effect.gen(function* () { + yield* ipc.handle(PreviewIpc.createTab); + yield* PreviewIpc.installPreviewEventForwarding(); + yield* Effect.promise(async () => listener!({ sender: { id: 3 } }, { tabId: "tab" })); + yield* emitState!("w3:tab", { tabId: "w3:tab" } as never); + }).pipe( + Effect.provideService( + PreviewManager.PreviewManager, + manager as unknown as PreviewManager.PreviewManager["Service"], + ), + Effect.provideService(ElectronWindow.ElectronWindow, { + sendAll: () => Effect.void, + } as unknown as ElectronWindow.ElectronWindow["Service"]), + Effect.provideService(LoopbackTunnel.LoopbackTunnel, { + subscribeForwards: () => Effect.void, + } as unknown as LoopbackTunnel.LoopbackTunnel["Service"]), + ); + + expect(created).toEqual([ + { tabId: "w3:tab", owner: { window: secondary, rendererTabId: "tab" } }, + ]); + expect(vi.mocked(secondary.webContents.send).mock.calls).toEqual([ + [IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, "tab", { tabId: "tab" }], + ]); + expect(vi.mocked(main.webContents.send)).not.toHaveBeenCalled(); + }), + ), + ); + beforeEach(() => { fromPartition.mockClear(); }); diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 9dc0465c1e55a..7690cad20f0fd 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -39,6 +39,8 @@ import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; import * as NodeURL from "node:url"; +import type * as Electron from "electron"; + import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts"; import * as LoopbackTunnel from "../../preview/LoopbackTunnel.ts"; @@ -49,25 +51,70 @@ import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts import * as IpcChannels from "../channels.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; +/** + * A secondary window's tab ids are scoped to that window, so two windows can each show the + * same thread's preview. The main window keeps its ids as they are. + */ +function scopePreviewTabId(tabId: string, secondaryWindowId: number | null): string { + return secondaryWindowId === null ? tabId : `w${secondaryWindowId}:${tabId}`; +} + +const senderTabId = (tabId: string) => + Effect.map(DesktopIpc.DesktopIpcSender, ({ window, isMain }) => + scopePreviewTabId(tabId, isMain ? null : window.id), + ); + +const withRendererTabId = (value: A, rendererTabId: string): A => + typeof value === "object" && value !== null && "tabId" in value + ? { ...value, tabId: rendererTabId } + : value; + +/** Per-tab events go only to the window that shows the tab, under the id it knows. */ export const installPreviewEventForwarding = Effect.fn( "desktop.ipc.preview.installEventForwarding", )(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; const manager = yield* PreviewManager.PreviewManager; + // Pointer and recording-input events stream per frame, so routing them adds no span. + const sendToOwner = Effect.fnUntraced(function* ( + tabId: string, + send: (contents: Electron.WebContents, rendererTabId: string) => void, + ) { + const { window, rendererTabId } = yield* manager.tabRoute(tabId); + if (Option.isNone(window) || window.value.isDestroyed()) return; + send(window.value.webContents, rendererTabId); + }); yield* manager.subscribeStateChanges((tabId, state) => - electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state), + sendToOwner(tabId, (contents, rendererTabId) => + contents.send( + IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, + rendererTabId, + withRendererTabId(state, rendererTabId), + ), + ), ); yield* manager.subscribeRecordingInputs((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, { + ...event, + tabId: rendererTabId, + }), + ), ); yield* manager.subscribePointerEvents((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, { ...event, tabId: rendererTabId }), + ), ); yield* manager.subscribeOpenLinks((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, { ...event, tabId: rendererTabId }), + ), ); yield* manager.subscribeFindResults((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, { ...event, tabId: rendererTabId }), + ), ); const tunnel = yield* LoopbackTunnel.LoopbackTunnel; yield* tunnel.subscribeForwards((forwards) => @@ -85,7 +132,7 @@ const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ }), }); -const createTab = DesktopIpc.makeIpcMethod({ +export const createTab = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, payload: DesktopPreviewCreateTabInputSchema, result: Schema.Void, @@ -96,7 +143,12 @@ const createTab = DesktopIpc.makeIpcMethod({ serverTab, }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.createTab(tabId, { zoomFactor, colorScheme, serverTab }); + const sender = yield* DesktopIpc.DesktopIpcSender; + yield* manager.createTab( + yield* senderTabId(tabId), + { zoomFactor, colorScheme, serverTab }, + sender.isMain ? undefined : { window: sender.window, rendererTabId: tabId }, + ); }), }); @@ -106,7 +158,7 @@ const closeTab = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.closeTab(tabId); + yield* manager.closeTab(yield* senderTabId(tabId)); }), }); @@ -116,7 +168,7 @@ const registerWebview = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.registerWebview(tabId, webContentsId); + yield* manager.registerWebview(yield* senderTabId(tabId), webContentsId); }), }); @@ -126,7 +178,7 @@ const navigate = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.navigate(tabId, url); + yield* manager.navigate(yield* senderTabId(tabId), url); }), }); @@ -141,7 +193,7 @@ const findInPage = DesktopIpc.makeIpcMethod({ newSession, }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.findInPage(tabId, text, { forward, newSession }); + yield* manager.findInPage(yield* senderTabId(tabId), text, { forward, newSession }); }), }); @@ -159,7 +211,7 @@ const tabMethod = ( result: Schema.Void, handler: Effect.fn(name)(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; - yield* invoke(manager, tabId); + yield* invoke(manager, yield* senderTabId(tabId)); }), }); @@ -214,7 +266,7 @@ const setZoomFactor = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setZoomFactor")(function* ({ tabId, zoomFactor }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setZoomFactor(tabId, zoomFactor); + yield* manager.setZoomFactor(yield* senderTabId(tabId), zoomFactor); }), }); const setColorScheme = DesktopIpc.makeIpcMethod({ @@ -223,7 +275,7 @@ const setColorScheme = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setColorScheme")(function* ({ tabId, colorScheme }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setColorScheme(tabId, colorScheme); + yield* manager.setColorScheme(yield* senderTabId(tabId), colorScheme); }), }); const setAudioMuted = DesktopIpc.makeIpcMethod({ @@ -232,7 +284,7 @@ const setAudioMuted = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setAudioMuted")(function* ({ tabId, audioMuted }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setAudioMuted(tabId, audioMuted); + yield* manager.setAudioMuted(yield* senderTabId(tabId), audioMuted); }), }); const setShown = DesktopIpc.makeIpcMethod({ @@ -241,7 +293,7 @@ const setShown = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setShown")(function* ({ tabId, shown }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setShown(tabId, shown); + yield* manager.setShown(yield* senderTabId(tabId), shown); }), }); const setCaptureDrawn = DesktopIpc.makeIpcMethod({ @@ -250,7 +302,7 @@ const setCaptureDrawn = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setCaptureDrawn")(function* ({ tabId, drawn }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setCaptureDrawn(tabId, drawn); + yield* manager.setCaptureDrawn(yield* senderTabId(tabId), drawn); }), }); const openDevTools = tabMethod( @@ -277,7 +329,7 @@ export const startRecording = DesktopIpc.makeIpcMethod({ showMousePresses: value.browserRecordingShowMousePresses, })); return yield* manager - .startRecording(tabId, Option.getOrUndefined(options)) + .startRecording(yield* senderTabId(tabId), Option.getOrUndefined(options)) .pipe( Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "recording-start"))), ); @@ -474,7 +526,7 @@ const pickElement = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema), handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId, voice }) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager.pickElement(tabId, voice); + return yield* manager.pickElement(yield* senderTabId(tabId), voice); }), }); @@ -484,7 +536,7 @@ const updateAnnotationVoice = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.updateAnnotationVoice")(function* (state) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.updateAnnotationVoice(state); + yield* manager.updateAnnotationVoice({ ...state, tabId: yield* senderTabId(state.tabId) }); }), }); @@ -497,7 +549,7 @@ const setAnnotationSendEnabled = DesktopIpc.makeIpcMethod({ enabled, }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setAnnotationSendEnabled(tabId, enabled); + yield* manager.setAnnotationSendEnabled(yield* senderTabId(tabId), enabled); }), }); @@ -507,9 +559,10 @@ export const captureScreenshot = DesktopIpc.makeIpcMethod({ result: Schema.Union([DesktopPreviewScreenshotArtifactSchema, PreviewCaptureFailure]), handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager - .captureScreenshot(tabId) - .pipe(Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot")))); + return yield* manager.captureScreenshot(yield* senderTabId(tabId)).pipe( + Effect.map((artifact) => withRendererTabId(artifact, tabId)), + Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot"))), + ); }), }); @@ -539,7 +592,8 @@ const saveRecording = DesktopIpc.makeIpcMethod({ result: DesktopPreviewRecordingArtifactSchema, handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager.saveRecording(tabId, mimeType, data); + const artifact = yield* manager.saveRecording(yield* senderTabId(tabId), mimeType, data); + return withRendererTabId(artifact, tabId); }), }); diff --git a/apps/desktop/src/ipc/methods/snapShot.test.ts b/apps/desktop/src/ipc/methods/snapShot.test.ts index 7e1ae602f979d..04cfc193b6d14 100644 --- a/apps/desktop/src/ipc/methods/snapShot.test.ts +++ b/apps/desktop/src/ipc/methods/snapShot.test.ts @@ -44,8 +44,8 @@ describe("window capture IPC", () => { Effect.provide( Layer.mergeAll( Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), + apps: Effect.succeed([{ webContents: { id: 7 } }]), + } as unknown as ElectronWindow.ElectronWindow["Service"]), Layer.succeed(DesktopSnapShot.DesktopSnapShot, { previewConfig: () => Effect.sync(() => { @@ -67,7 +67,7 @@ describe("window capture IPC", () => { ); }); - it.effect("allows capture setup only from the trusted main renderer", () => { + it.effect("allows capture setup only from a trusted app renderer", () => { const actions: string[] = []; return Effect.gen(function* () { yield* setupSnapShot.handler("install-extension", { sender: { id: 7 } }); @@ -81,8 +81,8 @@ describe("window capture IPC", () => { Effect.provide( Layer.mergeAll( Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), + apps: Effect.succeed([{ webContents: { id: 7 } }]), + } as unknown as ElectronWindow.ElectronWindow["Service"]), Layer.succeed(DesktopSnapShot.DesktopSnapShot, { setup: (action: string) => Effect.sync(() => { diff --git a/apps/desktop/src/ipc/methods/snapShot.ts b/apps/desktop/src/ipc/methods/snapShot.ts index 1a37882f4871e..1cb62a28fd132 100644 --- a/apps/desktop/src/ipc/methods/snapShot.ts +++ b/apps/desktop/src/ipc/methods/snapShot.ts @@ -35,15 +35,13 @@ class SnapShotIpcUnauthorizedSenderError extends Schema.TaggedError event !== undefined && candidate.webContents.id === event.sender.id, + ); + if (window === undefined) { return yield* new SnapShotIpcUnauthorizedSenderError(); } - return main.value; + return window; }, ); diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index 9c50501a1bdfd..56aa3bb14a4ac 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -33,7 +33,6 @@ import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; -import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as IpcChannels from "../channels.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; import { @@ -314,7 +313,7 @@ describe("installRelayTelemetryEnabled", () => { }); describe("readMedia", () => { - it.effect("reads http(s) media only for the main window", () => + it.effect("reads only http(s) media, through the sending window's session", () => Effect.gen(function* () { const mib = new Uint8Array(1024 * 1024); const fetch = vi.fn(async (url: string) => { @@ -327,32 +326,30 @@ describe("readMedia", () => { }); return new Response(huge); }); - const main = { + const sender = { + isDestroyed: () => false, webContents: { id: 1, session: { fetch } }, } as unknown as Electron.BrowserWindow; - const read = (url: string, senderId: number) => + const read = (url: string) => readMedia - .handler(url, { sender: { id: senderId } }) + .handler(url) .pipe( - Effect.provide( - Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(main) }), - ), + Effect.provideService(DesktopIpc.DesktopIpcSender, { window: sender, isMain: false }), ); - assert.strictEqual(yield* read("https://example.com/a.png", 2), null); - assert.strictEqual(yield* read("file:///etc/passwd", 1), null); + assert.strictEqual(yield* read("file:///etc/passwd"), null); assert.strictEqual(fetch.mock.calls.length, 0); - assert.deepEqual(yield* read("https://example.com/small.png", 1), { + assert.deepEqual(yield* read("https://example.com/small.png"), { status: 200, mimeType: "", data: Buffer.from([1, 2]), }); - assert.deepEqual(yield* read("https://example.com/missing.png", 1), { + assert.deepEqual(yield* read("https://example.com/missing.png"), { status: 404, mimeType: "text/plain;charset=UTF-8", data: new Uint8Array(), }); - assert.deepEqual(yield* read("https://example.com/huge.mp4", 1), { + assert.deepEqual(yield* read("https://example.com/huge.mp4"), { status: 413, mimeType: "", data: new Uint8Array(), @@ -362,15 +359,14 @@ describe("readMedia", () => { }); describe("pickProjectFavicon", () => { + const pickerOwner = { id: 3 } as Electron.BrowserWindow; const pickerLayer = ( pickFiles: () => Effect.Effect>, settings?: DesktopAppSettings.DesktopSettings, ) => Layer.mergeAll( Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }), - Layer.mock(ElectronWindow.ElectronWindow)({ - focusedMainOrFirst: Effect.succeedNone, - }), + Layer.succeed(DesktopIpc.DesktopIpcSender, { window: pickerOwner, isMain: true }), DesktopAppSettings.layerTest(settings), ); @@ -385,7 +381,7 @@ describe("pickProjectFavicon", () => { assert.deepEqual(pickFiles.mock.calls, [ [ { - owner: Option.none(), + owner: Option.some(pickerOwner), defaultPath: Option.some("/project"), multiple: false, filters: [ @@ -465,7 +461,7 @@ describe("syncHtmlFullscreen", () => { if (event === "leave-full-screen") leaveListeners.push(listener); }, } as unknown as Electron.BrowserWindow; - const layer = Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(window) }); + const layer = Layer.succeed(DesktopIpc.DesktopIpcSender, { window, isMain: true }); return { window, setFullScreen, finishExit, layer }; }; const fromMainRenderer = { sender: { id: 1 } }; diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index c6ad0bef18c81..d5e491710dd25 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -142,9 +142,8 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL, result: Schema.Boolean, handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.currentMainOrFirst; - return Option.isSome(window) && window.value.isFullScreen(); + const { window } = yield* DesktopIpc.DesktopIpcSender; + return !window.isDestroyed() && window.isFullScreen(); }), }); @@ -237,7 +236,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const environment = yield* DesktopEnvironment.DesktopEnvironment; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; @@ -268,7 +267,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ ) : environment.resolvePickFolderDefaultPath(options); const selectedPath = yield* dialog.pickFolder({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath, }); if (Option.isNone(selectedPath)) { @@ -306,13 +305,13 @@ export const pickProjectFavicon = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; if (!(yield* appSettings.get).localEnvironmentEnabled) { return null; } const paths = yield* dialog.pickFiles({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath: Option.fromNullishOr(initialPath), multiple: false, filters: [ @@ -342,14 +341,13 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) { const electronMenu = yield* ElectronMenu.ElectronMenu; - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.focusedMainOrFirst; - if (Option.isNone(window)) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return null; } const selectedItemId = yield* electronMenu.showContextMenu({ - window: window.value, + window, items: input.items, position: Option.fromNullishOr(input.position), source: Option.fromNullishOr(input.source), @@ -381,17 +379,12 @@ export const readMedia = DesktopIpc.makeIpcMethod({ channel: IpcChannels.READ_MEDIA_CHANNEL, payload: Schema.String, result: Schema.NullOr(DesktopMediaReadSchema), - handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) { - const window = yield* (yield* ElectronWindow.ElectronWindow).main; - if ( - event === undefined || - Option.isNone(window) || - window.value.webContents.id !== event.sender.id || - !/^https?:$/.test(URL.parse(url)?.protocol ?? "") - ) { + handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed() || !/^https?:$/.test(URL.parse(url)?.protocol ?? "")) { return null; } - const session = window.value.webContents.session; + const session = window.webContents.session; return yield* Effect.tryPromise({ try: async () => { // Like an , send the session's cookies. @@ -463,22 +456,16 @@ export const pasteAsText = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PASTE_AS_TEXT_CHANNEL, payload: Schema.Undefined, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(window) || - window.value.isDestroyed() || - window.value.webContents.id !== event.sender.id - ) { + handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return; } const focused = Electron.webContents.getFocusedWebContents(); if ( focused && !focused.isDestroyed() && - Electron.BrowserWindow.fromWebContents(focused) === window.value + Electron.BrowserWindow.fromWebContents(focused) === window ) { focused.paste(); } @@ -489,17 +476,10 @@ export const revealWindow = DesktopIpc.makeIpcMethod({ channel: IpcChannels.REVEAL_WINDOW_CHANNEL, payload: Schema.Undefined, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) { + handler: Effect.fn("desktop.ipc.window.revealWindow")(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(window) || - window.value.webContents.id !== event.sender.id - ) { - return; - } - yield* electronWindow.reveal(window.value); + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* electronWindow.reveal(window); }), }); @@ -521,24 +501,17 @@ const htmlFullscreenState = (window: Electron.BrowserWindow) => { return state; }; -// The main window keeps HTML fullscreen inside itself so preview guests stay in their webview, +// App windows keep HTML fullscreen inside themselves so preview guests stay in their webview, // so the app's own fullscreen elements, such as chat videos, take the screen here. export const syncHtmlFullscreen = DesktopIpc.makeIpcMethod({ channel: IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL, payload: Schema.Boolean, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen, event) { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const main = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(main) || - main.value.isDestroyed() || - main.value.webContents.id !== event.sender.id - ) { + handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return; } - const window = main.value; const state = htmlFullscreenState(window); if (fullscreen) { // macOS reports fullscreen until its exit animation ends, and Electron queues the re-entry. @@ -561,7 +534,7 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)), handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions"); @@ -569,7 +542,7 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({ .exists(extensionsDir) .pipe(Effect.orElseSucceed(() => false)); const paths = yield* dialog.pickFiles({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(), filters: [{ name: "JSON", extensions: ["json"] }], multiple: true, diff --git a/apps/desktop/src/ipc/methods/windows.ts b/apps/desktop/src/ipc/methods/windows.ts new file mode 100644 index 0000000000000..a2ce8200510a4 --- /dev/null +++ b/apps/desktop/src/ipc/methods/windows.ts @@ -0,0 +1,58 @@ +import { DesktopWindowContextSchema, DesktopWindowsStateSchema } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as DesktopWindow from "../../window/DesktopWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; + +export const getContext = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.WINDOWS_GET_CONTEXT_CHANNEL, + result: Schema.NullOr(DesktopWindowContextSchema), + handler: Effect.fn("desktop.ipc.windows.getContext")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + const desktopWindow = yield* DesktopWindow.DesktopWindow; + return Option.getOrNull(yield* desktopWindow.windowContext(window)); + }), +}); + +const getState = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_GET_STATE_CHANNEL, + payload: Schema.Void, + result: DesktopWindowsStateSchema, + handler: Effect.fn("desktop.ipc.windows.getState")(function* () { + return yield* (yield* DesktopWindow.DesktopWindow).windowsState; + }), +}); + +const openNew = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_OPEN_NEW_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openNew")(function* () { + yield* (yield* DesktopWindow.DesktopWindow).openNewWindow; + }), +}); + +const registerHub = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.registerHub")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).registerHub(window); + }), +}); + +const requestHubLink = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_REQUEST_HUB_LINK_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.requestHubLink")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).requestHubLink(window); + }), +}); + +export const methods = [getState, openNew, registerHub, requestHubLink] as const; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ac52fbc73d868..65c714f87dbdb 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -1,5 +1,7 @@ import type { + DESKTOP_HUB_LINK_MESSAGE_TYPE, DesktopBridge, + DesktopHubLinkMessage, DesktopPreviewAnnotationVoiceEvent, DesktopPreviewFindResultEvent, DesktopPreviewOpenLinkEvent, @@ -7,6 +9,9 @@ import type { DesktopPreviewRecordingInputEvent, DesktopPreviewTabState, DesktopSnapShotEvent, + DesktopWindowContext, + DesktopWindowsBridge, + DesktopWindowsState, } from "@t3tools/contracts"; import { exposeClerkBridge } from "@clerk/electron/preload"; import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron"; @@ -87,6 +92,64 @@ if (!primaryPasteEnabled) { ); } +// Typed against the contract's constant so they cannot drift; importing it would bundle contracts. +const HUB_LINK_MESSAGE_TYPE: typeof DESKTOP_HUB_LINK_MESSAGE_TYPE = "t3code:desktop-hub-link"; + +const windowContext = ((): DesktopWindowContext => { + try { + const result: unknown = ipcRenderer.sendSync(IpcChannels.WINDOWS_GET_CONTEXT_CHANNEL); + if (typeof result === "object" && result !== null) return result as DesktopWindowContext; + } catch {} + return { windowId: -1, isMain: true }; +})(); + +// A MessagePort cannot cross the context bridge, so the page receives it as a window message. +ipcRenderer.on(IpcChannels.WINDOWS_HUB_LINK_CHANNEL, (event, message: unknown) => { + const peerWindowId = + typeof message === "object" && message !== null && "peerWindowId" in message + ? message.peerWindowId + : undefined; + if (typeof peerWindowId !== "number" || event.ports.length === 0) return; + window.postMessage( + { type: HUB_LINK_MESSAGE_TYPE, peerWindowId } satisfies DesktopHubLinkMessage, + "*", + event.ports, + ); +}); + +const subscribe = + (channel: string, decode: (value: unknown) => A | undefined) => + (listener: (value: A) => void) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, value: unknown) => { + const decoded = decode(value); + if (decoded !== undefined) listener(decoded); + }; + ipcRenderer.on(channel, wrappedListener); + return () => { + ipcRenderer.removeListener(channel, wrappedListener); + }; + }; + +const windows: DesktopWindowsBridge = { + getContext: () => windowContext, + getState: () => ipcRenderer.invoke(IpcChannels.WINDOWS_GET_STATE_CHANNEL), + onState: subscribe(IpcChannels.WINDOWS_STATE_CHANNEL, (state) => + typeof state === "object" && state !== null ? (state as DesktopWindowsState) : undefined, + ), + openNew: () => ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_NEW_CHANNEL), + registerHub: () => { + void ipcRenderer.invoke(IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL).catch(() => undefined); + }, + requestHubLink: () => { + void ipcRenderer.invoke(IpcChannels.WINDOWS_REQUEST_HUB_LINK_CHANNEL).catch(() => undefined); + }, + onHubPeerGone: subscribe(IpcChannels.WINDOWS_HUB_PEER_GONE_CHANNEL, (windowId) => + typeof windowId === "number" ? windowId : undefined, + ), + onHubReset: (listener) => + subscribe(IpcChannels.WINDOWS_HUB_RESET_CHANNEL, () => true)(() => listener()), +}; + function unwrapEnsureSshEnvironmentResult(result: unknown) { if ( typeof result === "object" && @@ -164,6 +227,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL), setClientSettings: (settings) => ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings), + onClientSettingsChanged: (listener) => + subscribe(IpcChannels.CLIENT_SETTINGS_CHANGED_CHANNEL, () => true)(() => listener()), requestSnapShotPermissions: (includeAccessibility) => ipcRenderer.invoke(IpcChannels.REQUEST_SNAP_SHOT_PERMISSIONS_CHANNEL, includeAccessibility), getSnapShotState: () => ipcRenderer.invoke(IpcChannels.GET_SNAP_SHOT_STATE_CHANNEL), @@ -570,4 +635,5 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.removeListener(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, wrappedListener); }, }, + windows, } satisfies DesktopBridge); diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 9c15a0e0a4a95..4abd3e61487de 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -2289,6 +2289,86 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("keeps a secondary window's preview tab to that window until it closes", () => + withManager((manager) => + Effect.gen(function* () { + let closeSecondaryWindow: (() => void) | undefined; + let secondaryDestroyed = false; + const mainThrottling = vi.fn(); + const secondaryHost = Object.assign(makeTestHostWebContents(), { + id: 9, + setBackgroundThrottling: vi.fn(), + }); + const secondaryWindow = { + id: 3, + isDestroyed: () => secondaryDestroyed, + once: vi.fn((event: string, listener: () => void) => { + if (event === "closed") closeSecondaryWindow = listener; + }), + webContents: secondaryHost, + } as unknown as Electron.BrowserWindow; + const capturePage = vi.fn(async () => ({ + toJPEG: () => Buffer.from("recording-frame"), + getSize: () => ({ width: 1280, height: 720 }), + })); + const mainHost = makeTestHostWebContents(); + const webContentsById = new Map([ + [42, makeTestPreviewWebContents(capturePage, 42, mainHost)], + [43, makeTestPreviewWebContents(capturePage, 43, secondaryHost)], + ]); + fromId.mockImplementation((id) => + id === undefined ? null : (webContentsById.get(id) ?? null), + ); + yield* manager.setMainWindow({ + isDestroyed: () => false, + once: vi.fn(), + webContents: Object.assign(mainHost, { setBackgroundThrottling: mainThrottling }), + } as never); + yield* manager.registerSecondaryWindow(secondaryWindow); + const tabClosed = yield* Deferred.make(); + yield* manager.subscribeStateChanges((tabId, state) => + secondaryDestroyed && tabId === "w3:tab" && state.webContentsId === null + ? Deferred.succeed(tabClosed, undefined).pipe(Effect.asVoid) + : Effect.void, + ); + + yield* manager.createTab("w3:tab", undefined, { + window: secondaryWindow, + rendererTabId: "tab", + }); + const route = yield* manager.tabRoute("w3:tab"); + expect(Option.getOrNull(route.window)).toBe(secondaryWindow); + expect(route.rendererTabId).toBe("tab"); + + // A guest that the main window hosts cannot take over the secondary window's tab. + const hijack = yield* Effect.exit(manager.registerWebview("w3:tab", 42)); + expect(Exit.isFailure(hijack)).toBe(true); + if (Exit.isFailure(hijack)) { + expect(Option.getOrThrow(Cause.findErrorOption(hijack.cause))).toMatchObject({ + _tag: "PreviewWebContentsNotFoundError", + }); + } + yield* manager.registerWebview("w3:tab", 43); + + yield* manager.startRecording("w3:tab"); + expect(secondaryHost.setBackgroundThrottling.mock.calls).toEqual([[false]]); + expect(mainThrottling).not.toHaveBeenCalled(); + + secondaryDestroyed = true; + closeSecondaryWindow?.(); + yield* Deferred.await(tabClosed); + const afterClose = yield* Effect.exit(manager.startRecording("w3:tab")); + expect(Exit.isFailure(afterClose)).toBe(true); + if (Exit.isFailure(afterClose)) { + expect(Option.getOrThrow(Cause.findErrorOption(afterClose.cause))).toMatchObject({ + _tag: "PreviewTabNotFoundError", + }); + } + expect(mainThrottling).not.toHaveBeenCalled(); + }), + ), + ); + effectIt.effect("releases frame capture when the main window closes", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 531e269a07f11..e420093e8765a 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -94,6 +94,7 @@ import { import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS, type RecordingInputOptions } from "./RecordingInput.ts"; +import { setUnthrottledHold } from "../window/BackgroundThrottling.ts"; export type PreviewNavStatus = | { kind: "Idle" } @@ -407,6 +408,16 @@ interface PictureInPictureSession { readonly initializationScope: Scope.Closeable; } +export interface PreviewTabOwner { + readonly window: BrowserWindow; + readonly rendererTabId: string; +} + +export interface PreviewTabRoute { + readonly window: Option.Option; + readonly rendererTabId: string; +} + interface PendingRecording { readonly tabId: string; readonly webContents: Electron.WebContents; @@ -581,6 +592,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const annotationThemeRef = yield* Ref.make(DEFAULT_ANNOTATION_THEME); const annotationSendEnabled = new Map(); const mainWindowRef = yield* Ref.make>(Option.none()); + // Tabs created by a secondary app window; every other tab belongs to the main window. + const secondaryTabOwners = new Map(); const tabsRef = yield* SynchronizedRef.make>(new Map()); const attachedRef = yield* Ref.make>(new Map()); const listenersRef = yield* Ref.make>(new Set()); @@ -702,13 +715,29 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { if (window.isDestroyed()) return; yield* attempt({ operation: "frameCapture.setBackgroundThrottling" }, () => - window.webContents.setBackgroundThrottling(enabled), + setUnthrottledHold(window, "preview-frame-capture", !enabled), ); }); - const setFrameCaptureBackgroundThrottling = Effect.fnUntraced(function* (enabled: boolean) { - const mainWindow = yield* Ref.get(mainWindowRef); - if (Option.isNone(mainWindow)) return; - yield* setWindowBackgroundThrottling(mainWindow.value, enabled); + const ownerWindowOf = (tabId: string) => + Effect.map(Ref.get(mainWindowRef), (mainWindow) => { + const owner = secondaryTabOwners.get(tabId); + return owner === undefined ? mainWindow : Option.some(owner.window); + }); + const sameOwner = (left: string, right: string) => + secondaryTabOwners.get(left)?.window === secondaryTabOwners.get(right)?.window; + const ownerHasFrameCapture = (sessions: ReadonlyMap, tabId: string) => + [...sessions.keys()].some((sessionTabId) => sameOwner(sessionTabId, tabId)); + const ownerWindowOpen = (tabId: string) => { + const owner = secondaryTabOwners.get(tabId); + return owner === undefined ? frameCaptureWindowOpen : !owner.window.isDestroyed(); + }; + const setFrameCaptureBackgroundThrottling = Effect.fnUntraced(function* ( + tabId: string, + enabled: boolean, + ) { + const window = yield* ownerWindowOf(tabId); + if (Option.isNone(window)) return; + yield* setWindowBackgroundThrottling(window.value, enabled); }); const setFrameCaptureWebContentsBackgroundThrottling = Effect.fnUntraced(function* ( wc: Electron.WebContents, @@ -826,8 +855,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* restoreFrameCaptureWebContentsBackgroundThrottling( current.unthrottledWebContentsIds, ); - if (remainingSessions.size === 0) { - yield* setFrameCaptureBackgroundThrottling(true).pipe( + if (!ownerHasFrameCapture(remainingSessions, tabId)) { + yield* setFrameCaptureBackgroundThrottling(tabId, true).pipe( Effect.retry({ times: 2 }), Effect.catch((error) => Effect.logWarning("Failed to restore preview frame capture throttling.", { error }), @@ -844,14 +873,19 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); - const stopAllRecordings = Effect.fn("PreviewManager.stopAllRecordings")(function* () { - pendingRecording = null; - const sessions = yield* SynchronizedRef.get(frameCaptureSessionsRef); - yield* Effect.forEach(sessions.keys(), (tabId) => stopFrameCapture(tabId, "recording"), { - concurrency: "unbounded", - discard: true, - }); - }); + const stopMainWindowRecordings = Effect.fn("PreviewManager.stopMainWindowRecordings")( + function* () { + if (pendingRecording !== null && !secondaryTabOwners.has(pendingRecording.tabId)) { + pendingRecording = null; + } + const sessions = yield* SynchronizedRef.get(frameCaptureSessionsRef); + yield* Effect.forEach( + [...sessions.keys()].filter((tabId) => !secondaryTabOwners.has(tabId)), + (tabId) => stopFrameCapture(tabId, "recording"), + { concurrency: "unbounded", discard: true }, + ); + }, + ); const deliverEvent = ( eventKind: "state-change" | "recording-input" | "pointer-event" | "open-link" | "find-result", @@ -1727,7 +1761,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function Effect.gen(function* () { // Cleanup or lock acquisition can outlive the replacement window. if (window.isDestroyed()) return [undefined, sessions] as const; - if (sessions.size > 0) { + if ([...sessions.keys()].some((tabId) => !secondaryTabOwners.has(tabId))) { yield* setWindowBackgroundThrottling(window, false); } yield* Ref.set(mainWindowRef, Option.some(window)); @@ -1738,7 +1772,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function currentMainWindow = undefined; frameCaptureWindowOpen = false; mainWindowCleanupFiber = runFork( - Effect.all([closeAllPictureInPicture(), stopAllRecordings()], { + Effect.all([closeMainWindowPictureInPicture(), stopMainWindowRecordings()], { concurrency: "unbounded", discard: true, }).pipe(Effect.ignore), @@ -1749,9 +1783,35 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ).pipe(Effect.uninterruptible); }); + // Closing the window closes its tabs, which also ends their picture-in-picture and recordings. + const registerSecondaryWindow = Effect.fn("PreviewManager.registerSecondaryWindow")(function* ( + window: BrowserWindow, + ) { + yield* Effect.sync(() => + window.once("closed", () => { + const owned = [...secondaryTabOwners] + .filter(([, owner]) => owner.window === window) + .map(([tabId]) => tabId); + runFork( + Effect.forEach(owned, (tabId) => closeTab(tabId).pipe(Effect.ignore), { + concurrency: "unbounded", + discard: true, + }), + ); + }), + ); + }); + + const tabRoute = (tabId: string): Effect.Effect => + Effect.map(ownerWindowOf(tabId), (window) => ({ + window, + rendererTabId: secondaryTabOwners.get(tabId)?.rendererTabId ?? tabId, + })); + const createTabUnlocked = Effect.fn("PreviewManager.createTabUnlocked")(function* ( tabId: string, defaults?: DesktopPreviewTabDefaults, + owner?: PreviewTabOwner, ) { const updatedAt = yield* currentIso; const result = yield* SynchronizedRef.modify( @@ -1790,6 +1850,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); if (result.created) { tabLifecycleGenerations.set(tabId, (tabLifecycleGenerations.get(tabId) ?? 0) + 1); + if (owner !== undefined) secondaryTabOwners.set(tabId, owner); } yield* emit(tabId, result.state); return result.state; @@ -1798,8 +1859,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const createTab = Effect.fn("PreviewManager.createTab")(function* ( tabId: string, defaults?: DesktopPreviewTabDefaults, + owner?: PreviewTabOwner, ) { - return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId, defaults)); + return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId, defaults, owner)); }); const closeTabUnlocked = Effect.fn("PreviewManager.closeTabUnlocked")(function* (tabId: string) { @@ -1859,6 +1921,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function updatedAt, }; yield* emit(tabId, closed); + secondaryTabOwners.delete(tabId); }); const closeTab = Effect.fn("PreviewManager.closeTab")(function* (tabId: string) { @@ -1893,12 +1956,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function return yield* new PreviewTabNotFoundError({ tabId }); } const wc = webContents.fromId(webContentsId); - const mainWindow = yield* Ref.get(mainWindowRef); + // A guest must be hosted by the window that owns its tab, not by another app window. + const ownerWindow = yield* ownerWindowOf(tabId); if ( !wc || wc.isDestroyed() || wc.getType() !== "webview" || - (Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents) + (Option.isSome(ownerWindow) && wc.hostWebContents !== ownerWindow.value.webContents) ) { return yield* new PreviewWebContentsNotFoundError({ tabId, webContentsId }); } @@ -2461,12 +2525,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (decoded.value.sessionId !== voice.sessionId) return; runFork( Effect.gen(function* () { - const window = yield* Ref.get(mainWindowRef); + const { window, rendererTabId } = yield* tabRoute(tabId); if (Option.isNone(window) || window.value.isDestroyed()) return; yield* attempt({ operation: "annotationVoice.forward", tabId }, () => window.value.webContents.send( PREVIEW_ANNOTATION_VOICE_EVENT_CHANNEL, - tabId, + rendererTabId, decoded.value, ), ).pipe(Effect.ignore); @@ -2997,7 +3061,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function frameCaptureSessionsRef, (sessions) => { return Effect.gen(function* () { - if (!frameCaptureWindowOpen) { + if (!ownerWindowOpen(tabId)) { return yield* new PreviewMainWindowClosedError({ tabId }); } const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); @@ -3030,14 +3094,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), ] as const; } - if (sessions.size === 0) { - yield* setFrameCaptureBackgroundThrottling(false); + const ownerAlreadyUnthrottled = ownerHasFrameCapture(sessions, tabId); + if (!ownerAlreadyUnthrottled) { + yield* setFrameCaptureBackgroundThrottling(tabId, false); } yield* setFrameCaptureWebContentsBackgroundThrottling(wc, false).pipe( Effect.onError(() => - sessions.size === 0 - ? setFrameCaptureBackgroundThrottling(true).pipe(Effect.ignore) - : Effect.void, + ownerAlreadyUnthrottled + ? Effect.void + : setFrameCaptureBackgroundThrottling(tabId, true).pipe(Effect.ignore), ), ); const scope = @@ -3130,15 +3195,16 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* pictureInPictureMutationSemaphore.withPermit(closePictureInPictureUnlocked(tabId)); }); - const closeAllPictureInPicture = Effect.fn("PreviewManager.closeAllPictureInPicture")( - function* () { - const sessions = yield* SynchronizedRef.get(pictureInPictureSessionsRef); - yield* Effect.forEach(sessions.keys(), closePictureInPicture, { - concurrency: "unbounded", - discard: true, - }); - }, - ); + const closeMainWindowPictureInPicture = Effect.fn( + "PreviewManager.closeMainWindowPictureInPicture", + )(function* () { + const sessions = yield* SynchronizedRef.get(pictureInPictureSessionsRef); + yield* Effect.forEach( + [...sessions.keys()].filter((tabId) => !secondaryTabOwners.has(tabId)), + closePictureInPicture, + { concurrency: "unbounded", discard: true }, + ); + }); const openPictureInPicture = Effect.fn("PreviewManager.openPictureInPicture")(function* ( tabId: string, @@ -3488,7 +3554,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function webContentsId: wc.id, }); } - if (!frameCaptureWindowOpen || requestWebContents.isDestroyed()) { + if (!ownerWindowOpen(tabId) || requestWebContents.isDestroyed()) { return yield* new PreviewMainWindowClosedError({ tabId }); } installDisplayMediaRequestHandler(requestWebContents.session); @@ -3771,6 +3837,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function setCaptureDrawn, setColorScheme, setMainWindow, + registerSecondaryWindow, + tabRoute, setForwardedShortcuts: (shortcuts: ReadonlyArray) => Effect.sync(() => { forwardedShortcuts = shortcuts; @@ -3937,6 +4005,10 @@ export class PreviewManager extends Context.Service< PreviewManager, { readonly setMainWindow: (window: BrowserWindow) => Effect.Effect; + /** Closes the tabs a secondary app window created once that window closes. */ + readonly registerSecondaryWindow: (window: BrowserWindow) => Effect.Effect; + /** The app window that shows a tab and the id its renderer knows the tab by. */ + readonly tabRoute: (tabId: string) => Effect.Effect; readonly setForwardedShortcuts: ( shortcuts: ReadonlyArray, ) => Effect.Effect; @@ -3946,9 +4018,11 @@ export class PreviewManager extends Context.Service< namespace?: BrowserSession.BrowserSessionPartitionNamespace, ) => Effect.Effect; readonly isBrowserPartition: (partition: string) => boolean; + /** Without an owner the tab belongs to the main window. */ readonly createTab: ( tabId: string, defaults?: DesktopPreviewTabDefaults, + owner?: PreviewTabOwner, ) => Effect.Effect; readonly closeTab: (tabId: string) => Effect.Effect; readonly registerWebview: ( @@ -4112,6 +4186,8 @@ export const make = Effect.gen(function* PreviewManagerMake() { return PreviewManager.of({ setMainWindow: operations.setMainWindow, + registerSecondaryWindow: operations.registerSecondaryWindow, + tabRoute: operations.tabRoute, setForwardedShortcuts: operations.setForwardedShortcuts, getBrowserSession: Effect.fn("PreviewManager.getBrowserSession")( function* (scope, persistent, namespace) { diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts index 15977b34f398b..792d23697fad5 100644 --- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts +++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts @@ -96,7 +96,9 @@ function layerElectronWindow(window: ReturnType["window"] create: () => Effect.die("unexpected BrowserWindow creation"), main: Effect.succeedSome(window as Electron.BrowserWindow), currentMainOrFirst: Effect.succeedSome(window as Electron.BrowserWindow), - focusedMainOrFirst: Effect.succeedSome(window as Electron.BrowserWindow), + apps: Effect.succeed([]), + focusedApp: Effect.succeedNone, + registerApp: () => Effect.void, setMain: () => Effect.void, clearMain: () => Effect.void, prepareReveal: () => Effect.succeed(false), diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index b118d15ced674..480a4496553b7 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -122,7 +122,9 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { create: () => Effect.die("unexpected BrowserWindow creation"), main: Effect.succeedNone, currentMainOrFirst: Effect.succeedNone, - focusedMainOrFirst: Effect.succeedNone, + apps: Effect.succeed([]), + focusedApp: Effect.succeedNone, + registerApp: () => Effect.void, setMain: () => Effect.void, clearMain: () => Effect.void, prepareReveal: () => Effect.succeed(false), diff --git a/apps/desktop/src/window/BackgroundThrottling.ts b/apps/desktop/src/window/BackgroundThrottling.ts new file mode 100644 index 0000000000000..41f4200d691b5 --- /dev/null +++ b/apps/desktop/src/window/BackgroundThrottling.ts @@ -0,0 +1,21 @@ +import type * as Electron from "electron"; + +const holds = new WeakMap>(); + +/** + * Preview frame capture and the hub's secondary windows can each need a renderer unthrottled; + * it throttles again only once every holder releases. + */ +export function setUnthrottledHold( + window: Pick, + reason: string, + held: boolean, +): void { + if (window.isDestroyed()) return; + const contents = window.webContents; + const reasons = holds.get(contents) ?? new Set(); + if (held) reasons.add(reason); + else reasons.delete(reason); + holds.set(contents, reasons); + contents.setBackgroundThrottling(reasons.size === 0); +} diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 8b2c4317bd20f..2166d7c9cb97d 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -92,7 +92,7 @@ const layerDesktopUpdates = ({ checkResult }: MenuServices) => } satisfies DesktopUpdates.DesktopUpdates["Service"]); const layerDesktopWindow = (selectedAction: Deferred.Deferred) => - Layer.succeed(DesktopWindow.DesktopWindow, { + Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected createMain"), ensureMain: Effect.die("unexpected ensureMain"), revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"), @@ -105,12 +105,12 @@ const layerDesktopWindow = (selectedAction: Deferred.Deferred) => prepareCaptureReveal: Effect.void, dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid), dispatchSnapShotEvent: () => Effect.void, - zoomMain: (direction) => + zoomFocused: (direction) => Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid), - runMainContentsCommand: (command) => + runFocusedContentsCommand: (command) => Deferred.succeed(selectedAction, `main-${command}`).pipe(Effect.asVoid), syncAppearance: Effect.void, - } satisfies DesktopWindow.DesktopWindow["Service"]); + }); const layerElectronMenu = ( applicationMenuTemplate: Deferred.Deferred, @@ -347,6 +347,30 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); + it.effect("leads the Window menu with New Window and leaves its chord to the renderer", () => + Effect.gen(function* () { + const selectedAction = yield* Deferred.make(); + const applicationMenuTemplate = + yield* Deferred.make(); + yield* configureMenu(selectedAction, applicationMenuTemplate); + + const windowMenu = (yield* Deferred.await(applicationMenuTemplate)).find( + (item) => item.role === "windowMenu", + ); + if (!Array.isArray(windowMenu?.submenu)) { + throw new Error("Expected the Window menu submenu to be an array."); + } + const [newWindow] = windowMenu.submenu; + assert.deepEqual( + { label: newWindow?.label, accelerator: newWindow?.accelerator }, + { label: "New Window", accelerator: "CmdOrCtrl+Alt+Shift+N" }, + ); + assert.equal(newWindow?.registerAccelerator, false); + newWindow?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + assert.equal(yield* Deferred.await(selectedAction), "new-window"); + }), + ); + it.effect("tells the user which update the menu check found", () => Effect.gen(function* () { const dialog = yield* checkForUpdatesFromMacMenu({ diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 543d8d245731b..524471920374b 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -55,18 +55,18 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function }); }); -const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* ( +const zoomFocusedWindow = Effect.fn("desktop.menu.zoomFocusedWindow")(function* ( direction: DesktopWindow.MainWindowZoomDirection, ): Effect.fn.Return { const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.zoomMain(direction); + yield* desktopWindow.zoomFocused(direction); }); -const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(function* ( +const runFocusedContentsCommand = Effect.fn("desktop.menu.runFocusedContentsCommand")(function* ( command: DesktopWindow.MainWindowContentsCommand, ): Effect.fn.Return { const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.runMainContentsCommand(command); + yield* desktopWindow.runFocusedContentsCommand(command); }); const trackLabel = (channel: DesktopUpdateChannel) => @@ -224,10 +224,10 @@ export const make = Effect.gen(function* () { runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text")); }; const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => { - runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction)); + runMenuEffect(`zoom-${direction}`, zoomFocusedWindow(direction)); }; const mainContentsClick = (command: DesktopWindow.MainWindowContentsCommand) => () => { - runMenuEffect(command, runMainContentsCommand(command)); + runMenuEffect(command, runFocusedContentsCommand(command)); }; const template: Electron.MenuItemConstructorOptions[] = []; @@ -396,6 +396,14 @@ export const make = Effect.gen(function* () { role: "windowMenu", label: m(msg("Window", { $context: "menu bar title" })), submenu: [ + { + label: m(msg("New Window", { $context: "Window menu item" })), + // The renderer's window.new keybinding owns the chord. + accelerator: "CmdOrCtrl+Alt+Shift+N", + registerAccelerator: false, + click: () => runMenuEffect("new-window", dispatchMenuAction("new-window")), + }, + { type: "separator" }, { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) }, { role: "zoom", diff --git a/apps/desktop/src/window/DesktopHubLinks.test.ts b/apps/desktop/src/window/DesktopHubLinks.test.ts new file mode 100644 index 0000000000000..af4d8ce49dd3f --- /dev/null +++ b/apps/desktop/src/window/DesktopHubLinks.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; + +const setup = () => { + let channels = 0; + const deliveries: Array<{ to: number; port: string; peerWindowId: number }> = []; + const broker = new HubLinkBroker(() => { + channels += 1; + return { port1: `hub-end-${channels}`, port2: `window-end-${channels}` }; + }); + const peer = (windowId: number): HubLinkPeer => ({ + windowId, + deliver: (port, peerWindowId) => deliveries.push({ to: windowId, port, peerWindowId }), + }); + return { broker, deliveries, peer }; +}; + +describe("HubLinkBroker", () => { + it("holds requests until the hub registers, once per window", () => { + const { broker, deliveries, peer } = setup(); + broker.request(peer(2)); + broker.request(peer(2)); + broker.request(peer(3)); + expect(deliveries).toEqual([]); + + broker.registerHub(peer(1)); + expect(deliveries).toEqual([ + { to: 1, port: "hub-end-1", peerWindowId: 2 }, + { to: 2, port: "window-end-1", peerWindowId: 1 }, + { to: 1, port: "hub-end-2", peerWindowId: 3 }, + { to: 3, port: "window-end-2", peerWindowId: 1 }, + ]); + }); + + it("links at once while the hub is ready and makes windows relink after it resets", () => { + const { broker, deliveries, peer } = setup(); + broker.registerHub(peer(1)); + broker.request(peer(2)); + expect(deliveries).toHaveLength(2); + + expect(broker.resetHub()).toBe(true); + expect(broker.resetHub()).toBe(false); + expect(broker.peerGone(2)).toBe(false); + broker.request(peer(2)); + expect(deliveries).toHaveLength(2); + + broker.registerHub(peer(1)); + expect(deliveries.slice(2)).toEqual([ + { to: 1, port: "hub-end-2", peerWindowId: 2 }, + { to: 2, port: "window-end-2", peerWindowId: 1 }, + ]); + }); + + it("tells the hub about a gone window only when it held links to it", () => { + const { broker, deliveries, peer } = setup(); + broker.request(peer(4)); + expect(broker.peerGone(4)).toBe(false); + broker.registerHub(peer(1)); + expect(deliveries).toEqual([]); + + broker.request(peer(2)); + expect(broker.peerGone(2)).toBe(true); + expect(broker.peerGone(2)).toBe(false); + }); +}); diff --git a/apps/desktop/src/window/DesktopHubLinks.ts b/apps/desktop/src/window/DesktopHubLinks.ts new file mode 100644 index 0000000000000..e0e91197c0411 --- /dev/null +++ b/apps/desktop/src/window/DesktopHubLinks.ts @@ -0,0 +1,55 @@ +export interface HubLinkPeer { + readonly windowId: number; + readonly deliver: (port: Port, peerWindowId: number) => void; +} + +/** + * Pairs secondary windows with the main window's renderer, which owns every environment + * connection. Requests made before the hub registers wait for it. + */ +export class HubLinkBroker { + private hub: HubLinkPeer | null = null; + private readonly pending = new Map>(); + private readonly linked = new Set(); + private readonly createChannel: () => { port1: Port; port2: Port }; + + constructor(createChannel: () => { port1: Port; port2: Port }) { + this.createChannel = createChannel; + } + + registerHub(hub: HubLinkPeer): void { + this.hub = hub; + const waiting = [...this.pending.values()]; + this.pending.clear(); + for (const peer of waiting) this.link(hub, peer); + } + + /** Returns whether the hub had been serving; its secondary windows must then relink. */ + resetHub(): boolean { + if (this.hub === null) return false; + this.hub = null; + this.linked.clear(); + return true; + } + + request(peer: HubLinkPeer): void { + if (this.hub === null) { + this.pending.set(peer.windowId, peer); + return; + } + this.link(this.hub, peer); + } + + /** Returns whether the hub held links to the peer and must drop them. */ + peerGone(windowId: number): boolean { + this.pending.delete(windowId); + return this.linked.delete(windowId) && this.hub !== null; + } + + private link(hub: HubLinkPeer, peer: HubLinkPeer): void { + const { port1, port2 } = this.createChannel(); + hub.deliver(port1, peer.windowId); + peer.deliver(port2, hub.windowId); + this.linked.add(peer.windowId); + } +} diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index e4e426b1975ae..3d812c82aa5f8 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -69,6 +69,8 @@ const environmentInput = { runningUnderArm64Translation: false, } satisfies DesktopEnvironment.MakeDesktopEnvironmentInput; +let nextFakeWindowId = 1; + function makeFakeBrowserWindow() { const windowListeners = new Map void>(); const webContentsListeners = new Map void>(); @@ -112,7 +114,9 @@ function makeFakeBrowserWindow() { }; const window = { + id: nextFakeWindowId++, close: vi.fn(), + hide: vi.fn(), focus: vi.fn(), getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })), getNormalBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })), @@ -167,6 +171,8 @@ function makeFakeBrowserWindow() { webContentsListeners, webContentsOnce: webContents.once, windowListeners, + close: window.close, + hide: window.hide, }; } @@ -252,6 +258,8 @@ function layerTest(input: { readonly onPopupTemplate?: (input: ElectronMenu.ElectronMenuTemplateInput) => Effect.Effect; readonly previewZoomReapplies?: number[]; readonly onReveal?: (window: Electron.BrowserWindow) => void; + /** Windows to hand out in creation order; `window` once these run out. */ + readonly createdWindows?: Electron.BrowserWindow[]; readonly focusedWindow?: Electron.BrowserWindow; readonly fallbackWindow?: Electron.BrowserWindow; readonly platform?: NodeJS.Platform; @@ -304,16 +312,20 @@ function layerTest(input: { }).pipe( Effect.andThen(Ref.update(input.createCount, (count) => count + 1)), Effect.andThen(input.onWindowCreate ?? Effect.void), - Effect.as(input.window), + Effect.map(() => input.createdWindows?.shift() ?? input.window), ), main: Ref.get(input.mainWindow), currentMainOrFirst: Ref.get(input.mainWindow).pipe( Effect.map(Option.orElse(() => Option.fromNullishOr(input.fallbackWindow ?? null))), ), - focusedMainOrFirst: - input.focusedWindow === undefined - ? Ref.get(input.mainWindow) - : Effect.succeedSome(input.focusedWindow), + apps: Effect.map(Ref.get(input.mainWindow), Option.toArray), + // Popups and auxiliary windows are never app windows, so focus falls back to main. + focusedApp: Effect.map(Ref.get(input.mainWindow), (main) => + input.focusedWindow !== undefined && Option.contains(main, input.focusedWindow) + ? Option.some(input.focusedWindow) + : main, + ), + registerApp: () => Effect.void, setMain: (window) => Ref.set(input.mainWindow, Option.some(window)), clearMain: () => Ref.set(input.mainWindow, Option.none()), prepareReveal: () => Effect.succeed(false), @@ -374,6 +386,7 @@ function layerTest(input: { Layer.mock(PreviewManager.PreviewManager)({ getBrowserSession: () => Effect.succeed({} as Electron.Session), setMainWindow: input.setPreviewMainWindow ?? (() => Effect.void), + registerSecondaryWindow: () => Effect.void, prepareWebview: () => Effect.void, isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"), getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"), @@ -443,7 +456,9 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n }), main: Ref.get(mainWindow), currentMainOrFirst, - focusedMainOrFirst: currentMainOrFirst, + apps: Effect.map(Ref.get(mainWindow), Option.toArray), + focusedApp: Ref.get(mainWindow), + registerApp: () => Effect.void, setMain: (window) => Ref.set(mainWindow, Option.some(window)), clearMain: () => Ref.set(mainWindow, Option.none()), prepareReveal: () => Effect.succeed(false), @@ -807,10 +822,10 @@ describe("DesktopWindow", () => { const desktopWindow = yield* DesktopWindow.DesktopWindow; yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - yield* desktopWindow.zoomMain("out"); - yield* desktopWindow.zoomMain("out"); - yield* desktopWindow.zoomMain("in"); - yield* desktopWindow.zoomMain("reset"); + yield* desktopWindow.zoomFocused("out"); + yield* desktopWindow.zoomFocused("out"); + yield* desktopWindow.zoomFocused("in"); + yield* desktopWindow.zoomFocused("reset"); assert.deepEqual( fakeWindow.setZoomLevel.mock.calls.map(([level]) => level), @@ -1470,6 +1485,41 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens a secondary window, keeping the main window hidden while it serves it", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const secondary = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, secondary.window], + createCount, + mainWindow, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* windows.openNewWindow; + assert.equal(yield* Ref.get(createCount), 2); + assert.deepEqual(Option.getOrThrow(yield* windows.windowContext(secondary.window)), { + windowId: secondary.window.id, + isMain: false, + }); + assert.deepEqual((yield* windows.windowsState).windows, [ + { windowId: main.window.id, isMain: true }, + { windowId: secondary.window.id, isMain: false }, + ]); + + const preventMainClose = vi.fn(); + main.windowListeners.get("close")?.({ preventDefault: preventMainClose }); + assert.equal(preventMainClose.mock.calls.length, 1); + assert.equal(main.hide.mock.calls.length, 1); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("persists the current main window bounds before the window closes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index c99fbb52c49e2..6b3aa5b82e655 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -11,7 +11,12 @@ import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; import { msg } from "gt-i18n"; -import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; +import { + type DesktopSnapShotEvent, + type DesktopWindowContext, + type DesktopWindowsState, + DEFAULT_CLIENT_SETTINGS, +} from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; import * as DesktopClerk from "../app/DesktopClerk.ts"; @@ -31,6 +36,10 @@ import { TRACKPAD_SCROLL_BEGIN_CHANNEL, TRACKPAD_SCROLL_END_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL, + WINDOWS_HUB_LINK_CHANNEL, + WINDOWS_HUB_PEER_GONE_CHANNEL, + WINDOWS_HUB_RESET_CHANNEL, + WINDOWS_STATE_CHANNEL, } from "../ipc/channels.ts"; import { PASSKEY_BRIDGE_ARGUMENT, @@ -46,6 +55,9 @@ import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts" import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; +import { setUnthrottledHold } from "./BackgroundThrottling.ts"; +import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; +import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; const TITLEBAR_HEIGHT = 40; @@ -96,6 +108,7 @@ const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500; const RENDERER_RECOVERY_MAX_ATTEMPTS = 3; const RENDERER_RECOVERY_WINDOW_MS = 60_000; const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]); +const HUB_UNTHROTTLED_REASON = "hub-serving-windows"; type WindowTitleBarOptions = Pick< Electron.BrowserWindowConstructorOptions, @@ -143,10 +156,18 @@ export class DesktopWindow extends Context.Service< readonly dispatchSnapShotEvent: ( event: DesktopSnapShotEvent, ) => Effect.Effect; - // Electron zoom roles target focused guests; zoomMain must always target the app. - readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect; + // Electron zoom roles target focused guests; this must always target an app window. + readonly zoomFocused: (direction: MainWindowZoomDirection) => Effect.Effect; readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; + readonly runFocusedContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; readonly syncAppearance: Effect.Effect; + readonly windowsState: Effect.Effect; + readonly windowContext: ( + window: Electron.BrowserWindow, + ) => Effect.Effect>; + readonly openNewWindow: Effect.Effect; + readonly registerHub: (window: Electron.BrowserWindow) => Effect.Effect; + readonly requestHubLink: (window: Electron.BrowserWindow) => Effect.Effect; } >()("@t3tools/desktop/window/DesktopWindow") {} @@ -381,6 +402,20 @@ function bindFirstRevealTrigger( } } +type AppWindowSpec = + | { readonly role: "main" } + | { readonly role: "secondary"; readonly anchorBounds: DisplayBounds | null }; + +interface AppWindowEntry { + readonly window: Electron.BrowserWindow; + readonly windowId: number; + readonly isMain: boolean; + rendererLive: boolean; + hubUnthrottled: boolean; +} + +const serializeWindowsState = (state: DesktopWindowsState) => JSON.stringify(state); + /** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -404,6 +439,7 @@ export const make = Effect.gen(function* () { const context = yield* Effect.context(); const runFork = Effect.runForkWith(context); const runPromise = Effect.runPromiseWith(context); + const runSync = Effect.runSyncWith(context); const mainWindowMutex = yield* Semaphore.make(1); const pendingMainReveals = new WeakMap>(); const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) => @@ -411,6 +447,21 @@ export const make = Effect.gen(function* () { ); let flushMainWindowBounds: Effect.Effect = Effect.void; let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; + const entries = new Map(); + let lastBroadcastState = ""; + const hubLinks = new HubLinkBroker( + () => new Electron.MessageChannelMain(), + ); + + const liveEntries = () => [...entries.values()].filter((entry) => !entry.window.isDestroyed()); + const mainEntry = () => liveEntries().find((entry) => entry.isMain); + const secondaryEntries = () => liveEntries().filter((entry) => !entry.isMain); + const entryOf = (window: Electron.BrowserWindow) => { + const entry = entries.get(window.id); + return entry !== undefined && entry.window === window && !window.isDestroyed() + ? entry + : undefined; + }; const dismissConnectingSplash = Effect.gen(function* () { const splash = yield* Ref.getAndSet(splashWindowRef, Option.none()); @@ -444,18 +495,60 @@ export const make = Effect.gen(function* () { yield* previewManager.reapplyZoom(); }); - const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return< - Option.Option, - DesktopWindowError - > { - if (yield* Ref.get(desktopState.quitting)) return Option.none(); - yield* previewManager.getBrowserSession(); - const applicationUrl = getDesktopUrl(environment.isDevelopment); - const iconPaths = yield* assets.iconPaths; - const iconOption = getIconOption(iconPaths, environment.platform); - const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; - const persistedSettings = yield* desktopSettings.get; - const persistedBounds = persistedSettings.mainWindowBounds; + const computeWindowsState = Effect.sync((): DesktopWindowsState => ({ + windows: liveEntries() + .sort((left, right) => Number(right.isMain) - Number(left.isMain)) + .map(({ windowId, isMain }) => ({ windowId, isMain })), + })); + + // The hub must keep serving secondary windows while it is hidden or minimized. + const syncHubThrottling = () => { + const main = mainEntry(); + if (main === undefined) return; + const held = secondaryEntries().length > 0; + if (held === main.hubUnthrottled) return; + main.hubUnthrottled = held; + setUnthrottledHold(main.window, HUB_UNTHROTTLED_REASON, held); + }; + + // Throttling and every renderer's list of open windows follow from the open windows. + const syncWindows = Effect.fn("desktop.window.syncWindows")(function* () { + syncHubThrottling(); + const state = yield* computeWindowsState; + const serialized = serializeWindowsState(state); + if (serialized === lastBroadcastState) return; + lastBroadcastState = serialized; + for (const entry of liveEntries()) { + if (entry.rendererLive) entry.window.webContents.send(WINDOWS_STATE_CHANNEL, state); + } + }); + const requestSync = () => { + runFork(syncWindows()); + }; + + const notifyHubReset = () => { + if (!hubLinks.resetHub()) return; + for (const entry of secondaryEntries()) { + if (entry.rendererLive) entry.window.webContents.send(WINDOWS_HUB_RESET_CHANNEL); + } + }; + const notifyHubPeerGone = (windowId: number) => { + if (!hubLinks.peerGone(windowId)) return; + const main = mainEntry(); + if (main !== undefined) main.window.webContents.send(WINDOWS_HUB_PEER_GONE_CHANNEL, windowId); + }; + const hubPeer = (entry: AppWindowEntry): HubLinkPeer => ({ + windowId: entry.windowId, + deliver: (port, peerWindowId) => { + if (entry.window.isDestroyed()) { + port.close(); + return; + } + entry.window.webContents.postMessage(WINDOWS_HUB_LINK_CHANNEL, { peerWindowId }, [port]); + }, + }); + + const readDisplayBounds = Effect.gen(function* () { const displayBoundsResult = yield* Effect.sync(() => { try { return { @@ -466,17 +559,41 @@ export const make = Effect.gen(function* () { return { _tag: "Failure" as const, cause }; } }); - const displayBounds = - displayBoundsResult._tag === "Success" - ? displayBoundsResult.bounds - : yield* logWindowWarning("failed to read connected displays; using defaults", { - cause: displayBoundsResult.cause, - }).pipe(Effect.as([])); - const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds); - const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds; - if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) { + return displayBoundsResult._tag === "Success" + ? displayBoundsResult.bounds + : yield* logWindowWarning("failed to read connected displays; using defaults", { + cause: displayBoundsResult.cause, + }).pipe(Effect.as([])); + }); + + const buildAppWindow = Effect.fn("desktop.window.createWindow")(function* ( + spec: AppWindowSpec, + ): Effect.fn.Return, DesktopWindowError> { + if (yield* Ref.get(desktopState.quitting)) return Option.none(); + const isMain = spec.role === "main"; + yield* previewManager.getBrowserSession(); + const applicationUrl = getDesktopUrl(environment.isDevelopment); + const iconPaths = yield* assets.iconPaths; + const iconOption = getIconOption(iconPaths, environment.platform); + const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; + const persistedSettings = yield* desktopSettings.get; + // Only the main window keeps its placement. + const persistedBounds = isMain ? persistedSettings.mainWindowBounds : null; + const displayBounds = yield* readDisplayBounds; + const restorableBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds); + const restoredPersistedBounds = + persistedBounds !== null && restorableBounds === persistedBounds; + if (persistedBounds !== null && !restoredPersistedBounds) { yield* logWindowWarning("saved main window bounds could not be restored; using defaults"); } + const initialBounds = + spec.role === "secondary" + ? cascadeWindowBounds({ + anchor: spec.anchorBounds, + size: DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, + displays: displayBounds, + }) + : restorableBounds; if (yield* Ref.get(desktopState.quitting)) return Option.none(); const window = yield* electronWindow.create({ ...initialBounds, @@ -507,11 +624,19 @@ export const make = Effect.gen(function* () { return Option.none(); } - pendingMainReveals.set(window, Effect.void); + if (isMain) pendingMainReveals.set(window, Effect.void); + setUnthrottledHold(window, "first-reveal", true); yield* rendererHistory.register(window.webContents, { surface: "main" }); if (environment.platform === "darwin") { window.setAutoHideCursor(false); } + const entry: AppWindowEntry = { + window, + windowId: window.id, + isMain, + rendererLive: false, + hubUnthrottled: false, + }; let boundsPersistFiber: Fiber.Fiber | undefined; let pendingBoundsPersistFiber: Fiber.Fiber | undefined; let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds; @@ -552,7 +677,7 @@ export const make = Effect.gen(function* () { : (readPersistableState()?.bounds ?? null); const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { - if (!boundsPersistenceEnabled) { + if (!isMain || !boundsPersistenceEnabled) { return pendingBoundsPersistFiber; } const state = readPersistableState(); @@ -615,9 +740,13 @@ export const make = Effect.gen(function* () { fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid), ), ); - flushMainWindowBounds = flushBoundsPersist; + if (isMain) flushMainWindowBounds = flushBoundsPersist; - yield* previewManager.setMainWindow(window); + if (isMain) { + yield* previewManager.setMainWindow(window); + } else { + yield* previewManager.registerSecondaryWindow(window); + } if (yield* Ref.get(desktopState.quitting)) { yield* electronWindow.destroyAll; return Option.none(); @@ -794,6 +923,16 @@ export const make = Effect.gen(function* () { void runPromise(electronShell.openExternal(url)); } }); + // A new document drops the old renderer's hub links. + const rendererGone = () => { + entry.rendererLive = false; + if (isMain) notifyHubReset(); + else notifyHubPeerGone(entry.windowId); + }; + window.webContents.on("did-start-navigation", (event) => { + if (event.isMainFrame && !event.isSameDocument) rendererGone(); + }); + window.webContents.on("destroyed", rendererGone); const quitShortcutHandler = makeQuitShortcutHandler({ platform: environment.platform, @@ -860,7 +999,13 @@ export const make = Effect.gen(function* () { window.on("move", scheduleBoundsPersist); window.on("maximize", scheduleBoundsPersist); window.on("unmaximize", scheduleBoundsPersist); - window.on("close", () => { + window.on("close", (event) => { + // Hidden, the main window keeps serving the secondary windows' connections. + if (isMain && secondaryEntries().length > 0 && !runSync(Ref.get(desktopState.quitting))) { + event.preventDefault(); + window.hide(); + return; + } runFork(flushBoundsPersist); }); @@ -936,6 +1081,11 @@ export const make = Effect.gen(function* () { clearDevelopmentLoadRetry(); developmentLoadRetryIndex = 0; if (environment.platform === "darwin") syncMacosWindowButtons(window); + entry.rendererLive = true; + if (entries.size > 1 || !isMain) { + lastBroadcastState = ""; + requestSync(); + } }); window.webContents.on( "did-fail-load", @@ -954,7 +1104,8 @@ export const make = Effect.gen(function* () { ? scheduleDevelopmentLoadRetry() : undefined; void runPromise( - logWindowWarning("main window failed to load", { + logWindowWarning("app window failed to load", { + role: spec.role, errorCode, errorDescription, url: validatedURL, @@ -964,6 +1115,7 @@ export const make = Effect.gen(function* () { }, ); window.webContents.on("render-process-gone", (_event, details) => { + rendererGone(); const recoverable = details.reason === "crashed" || details.reason === "oom" || @@ -992,7 +1144,8 @@ export const make = Effect.gen(function* () { RENDERER_RECOVERY_RELOAD_DELAY_MS, oldestAttempt + RENDERER_RECOVERY_WINDOW_MS - now, ); - yield* logWindowWarning("main window render process gone", { + yield* logWindowWarning("app window render process gone", { + role: spec.role, reason: details.reason, exitCode: details.exitCode, recovering: shouldRecover, @@ -1026,53 +1179,69 @@ export const make = Effect.gen(function* () { return; firstRevealComplete = true; pendingMainReveals.delete(window); - window.webContents.setBackgroundThrottling(true); - if (persistedSettings.mainWindowMaximized) window.maximize(); + setUnthrottledHold(window, "first-reveal", false); + if (isMain && persistedSettings.mainWindowMaximized) window.maximize(); yield* electronWindow.reveal(window); - yield* dismissConnectingSplash; + if (isMain) yield* dismissConnectingSplash; }); - pendingMainReveals.set(window, revealWhenReady); + if (isMain) pendingMainReveals.set(window, revealWhenReady); bindFirstRevealTrigger(revealSubscribers, () => { rendererReady = true; void runPromise(revealWhenReady); }); - // Desktop IPC only answers the main window, so register it before its renderer can call in. - yield* electronWindow.setMain(window); - remoteRequestHeaderOwner = window; - const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( - window.webContents.session, - { - desktopOrigin: getDesktopOrigin(environment.isDevelopment), - mainWebContentsId: window.webContents.id, - clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, - devServerOrigin: Option.getOrUndefined( - Option.map(environment.devServerUrl, (url) => url.origin), - ), - isDevelopment: environment.isDevelopment, - }, - ); + entries.set(window.id, entry); + // Desktop IPC only answers app windows, so register this one before its renderer can call in. + let detachRemoteRequestHeaders = () => {}; + if (isMain) { + yield* electronWindow.setMain(window); + // App windows share one session, whose single header listener follows the main window. + remoteRequestHeaderOwner = window; + detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( + window.webContents.session, + { + desktopOrigin: getDesktopOrigin(environment.isDevelopment), + mainWebContentsId: window.webContents.id, + clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, + devServerOrigin: Option.getOrUndefined( + Option.map(environment.devServerUrl, (url) => url.origin), + ), + isDevelopment: environment.isDevelopment, + }, + ); + } else { + yield* electronWindow.registerApp(window); + } + yield* syncWindows(); loadApplication(); - if (environment.isDevelopment) { + if (isMain && environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); } window.on("closed", () => { - if (!backendHasStarted) mainClosedDuringStartup = true; + if (entries.get(window.id) === entry) entries.delete(window.id); clearDevelopmentLoadRetry(); clearBoundsPersist(); if (remoteRequestHeaderOwner === window) { remoteRequestHeaderOwner = null; detachRemoteRequestHeaders(); } - void runPromise(electronWindow.clearMain(Option.some(window))); + if (isMain) { + if (!backendHasStarted) mainClosedDuringStartup = true; + notifyHubReset(); + void runPromise(electronWindow.clearMain(Option.some(window))); + } else { + notifyHubPeerGone(entry.windowId); + runFork(handleSecondaryClosed); + } + requestSync(); }); return Option.some(window); }); const createMain = Effect.gen(function* () { - const window = yield* createWindow(); + const window = yield* buildAppWindow({ role: "main" }); if (Option.isSome(window)) { mainClosedDuringStartup = false; yield* logWindowInfo("main window created"); @@ -1101,6 +1270,26 @@ export const make = Effect.gen(function* () { return window; }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain")); + const openSecondary = Effect.gen(function* () { + // Secondary windows reach environments through the main window's renderer. + if (Option.isNone(yield* ensureMain)) return; + const anchor = yield* electronWindow.focusedApp; + yield* buildAppWindow({ + role: "secondary", + anchorBounds: + Option.isSome(anchor) && !anchor.value.isDestroyed() ? anchor.value.getBounds() : null, + }); + }).pipe(Effect.withSpan("desktop.window.openSecondary")); + + const handleSecondaryClosed = Effect.gen(function* () { + if (yield* Ref.get(desktopState.quitting)) return; + const main = mainEntry(); + if (secondaryEntries().length > 0 || main === undefined || main.window.isVisible()) return; + // The hidden main window kept the app alive for its secondary windows; without them, quit + // as closing the last window always has. macOS apps outlive their windows. + if (environment.platform !== "darwin") main.window.close(); + }).pipe(Effect.withSpan("desktop.window.handleSecondaryClosed")); + const waitingForBackend = Effect.gen(function* () { if (yield* Ref.get(backendReadyRef)) return false; return (yield* desktopSettings.get).localEnvironmentEnabled; @@ -1166,14 +1355,22 @@ export const make = Effect.gen(function* () { const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* ( channel: string, payload: unknown, - { reveal = true }: { readonly reveal?: boolean } = {}, - ) { - if (yield* Ref.get(desktopState.quitting)) return; - // Only the main renderer loads the app preload that listens on these channels. - const existingWindow = yield* electronWindow.main; - if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return; + { + reveal = true, + target, + }: { readonly reveal?: boolean; readonly target?: Electron.BrowserWindow } = {}, + ): Effect.fn.Return, DesktopWindowError> { + if (yield* Ref.get(desktopState.quitting)) return Option.none(); + // Only app renderers load the preload that listens on these channels; the focused one acts. + const existingWindow = + target !== undefined && !target.isDestroyed() + ? Option.some(target) + : yield* electronWindow.focusedApp; + if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) { + return Option.none(); + } const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain; - if (Option.isNone(window) || window.value.isDestroyed()) return; + if (Option.isNone(window) || window.value.isDestroyed()) return Option.none(); const targetWindow = window.value; const send = Effect.sync(() => { if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload); @@ -1184,17 +1381,35 @@ export const make = Effect.gen(function* () { : send; if (targetWindow.webContents.isLoadingMainFrame()) { targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch)); - return; + return window; } yield* dispatch; + return window; }); + // A capture finishes in the window it started in, even if focus moved meanwhile. + const captureWindows = new Map(); + + const runContentsCommand = ( + window: Electron.BrowserWindow, + command: MainWindowContentsCommand, + ) => { + if (window.isDestroyed()) return; + const webContents = window.webContents; + if (command === "reload") webContents.reload(); + else if (command === "forceReload") webContents.reloadIgnoringCache(); + else webContents.toggleDevTools(); + }; return DesktopWindow.of({ createMain: createMain.pipe(Effect.flatMap(requireWindow)), ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)), revealOrCreateMain, prepareCaptureReveal: Effect.gen(function* () { - const existingWindow = yield* currentMainWindow; + // The capture lands in the focused app window, so that is the one to bring forward. + const focusedWindow = yield* electronWindow.focusedApp; + const existingWindow = Option.isSome(focusedWindow) + ? focusedWindow + : yield* currentMainWindow; if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) { yield* electronWindow.prepareReveal(existingWindow.value); } @@ -1243,13 +1458,26 @@ export const make = Effect.gen(function* () { event: event.type, captureId: "id" in event ? (event.id ?? null) : null, }); - yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, { + if (event.type === "shortcut-changed") { + for (const entry of entries.values()) { + if (!entry.window.isDestroyed()) + entry.window.webContents.send(SNAP_SHOT_EVENT_CHANNEL, event); + } + return; + } + const id = event.id; + const started = id === undefined ? undefined : captureWindows.get(id); + const delivered = yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, { reveal: event.type === "started", + ...(started === undefined ? {} : { target: started }), }); + if (id === undefined) return; + if (event.type === "ready" || event.type === "failed") captureWindows.delete(id); + else if (Option.isSome(delivered)) captureWindows.set(id, delivered.value); }), - zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) { + zoomFocused: Effect.fn("desktop.window.zoomFocused")(function* (direction) { yield* Effect.annotateCurrentSpan({ direction }); - const window = yield* electronWindow.main; + const window = yield* electronWindow.focusedApp; if (Option.isNone(window) || window.value.isDestroyed()) { return; } @@ -1257,20 +1485,45 @@ export const make = Effect.gen(function* () { }), runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) { yield* Effect.annotateCurrentSpan({ command }); - // A focused OAuth popup must not receive the app's Reload command. const window = yield* electronWindow.main; - if (Option.isNone(window) || window.value.isDestroyed()) return; - const webContents = window.value.webContents; - if (command === "reload") webContents.reload(); - else if (command === "forceReload") webContents.reloadIgnoringCache(); - else webContents.toggleDevTools(); + if (Option.isSome(window)) runContentsCommand(window.value, command); }), + runFocusedContentsCommand: Effect.fn("desktop.window.runFocusedContentsCommand")( + function* (command) { + yield* Effect.annotateCurrentSpan({ command }); + // A focused OAuth popup must not receive the app's Reload command. + const window = yield* electronWindow.focusedApp; + if (Option.isSome(window)) runContentsCommand(window.value, command); + }, + ), syncAppearance: Effect.gen(function* () { const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) => syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform), ); }).pipe(Effect.withSpan("desktop.window.syncAppearance")), + windowsState: computeWindowsState, + windowContext: Effect.fn("desktop.window.windowContext")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + return entry === undefined + ? Option.none() + : Option.some({ windowId: entry.windowId, isMain: entry.isMain }); + }); + }), + openNewWindow: openSecondary, + registerHub: Effect.fn("desktop.window.registerHub")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + if (entry !== undefined && entry.isMain) hubLinks.registerHub(hubPeer(entry)); + }); + }), + requestHubLink: Effect.fn("desktop.window.requestHubLink")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + if (entry !== undefined && !entry.isMain) hubLinks.request(hubPeer(entry)); + }); + }), }); }); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.test.ts b/apps/desktop/src/window/DesktopWindowProfiles.test.ts new file mode 100644 index 0000000000000..f1a8a93b10634 --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; + +describe("cascadeWindowBounds", () => { + const display = { x: 0, y: 0, width: 1920, height: 1080 }; + + it("offsets from the opener and wraps back inside its display", () => { + const size = { width: 1100, height: 780 }; + expect( + cascadeWindowBounds({ + anchor: { x: 100, y: 100, width: 1100, height: 780 }, + size, + displays: [display], + }), + ).toEqual({ x: 128, y: 128, width: 1100, height: 780 }); + expect( + cascadeWindowBounds({ + anchor: { x: 900, y: 290, width: 1100, height: 780 }, + size, + displays: [display], + }), + ).toEqual({ x: 28, y: 28, width: 1100, height: 780 }); + expect(cascadeWindowBounds({ anchor: null, size, displays: [display] })).toEqual(size); + }); +}); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.ts b/apps/desktop/src/window/DesktopWindowProfiles.ts new file mode 100644 index 0000000000000..9e0e07c757bf4 --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.ts @@ -0,0 +1,41 @@ +interface Rectangle { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +const CASCADE_OFFSET_PX = 28; + +/** Places a new window down and right of the window it opened from, wrapping inside that display. */ +export function cascadeWindowBounds(input: { + readonly anchor: Rectangle | null; + readonly size: { readonly width: number; readonly height: number }; + readonly displays: readonly Rectangle[]; +}): Rectangle | { readonly width: number; readonly height: number } { + const { anchor } = input; + if (anchor === null) return input.size; + const display = + input.displays.find( + (candidate) => + anchor.x >= candidate.x && + anchor.y >= candidate.y && + anchor.x < candidate.x + candidate.width && + anchor.y < candidate.y + candidate.height, + ) ?? input.displays[0]; + if (display === undefined) return input.size; + const width = Math.min(input.size.width, display.width); + const height = Math.min(input.size.height, display.height); + let x = anchor.x + CASCADE_OFFSET_PX; + let y = anchor.y + CASCADE_OFFSET_PX; + if (x + width > display.x + display.width || y + height > display.y + display.height) { + x = display.x + CASCADE_OFFSET_PX; + y = display.y + CASCADE_OFFSET_PX; + } + return { + x: Math.round(Math.min(x, display.x + display.width - width)), + y: Math.round(Math.min(y, display.y + display.height - height)), + width, + height, + }; +} diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index cce59f08f6d12..f63de9c4818b0 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -48,6 +48,9 @@ import { import { syncBrowserChromeTheme } from "./hooks/useTheme"; import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration"; import { installDesktopPasteAsText } from "./lib/desktopPasteAsText"; +import { startDesktopWindowHub } from "./multiWindow/hub"; +import { registerDesktopWindowCommands } from "./multiWindow/ui/windowActions"; +import { isSecondaryDesktopWindow } from "./multiWindow/windowContext"; import { syncDocumentElectronPlatformClasses, syncDocumentWindowControlsOverlayClass, @@ -259,6 +262,8 @@ export function startAppServices(): AppRouter { // Ahead of the history: the provider auth code must leave the address before anything reads it. startProviderAuthDelivery(); + // App-wide duties run once, in the main window: secondary desktop windows only host UI. + const appWideWindow = !isSecondaryDesktopWindow(); // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues. const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory()); @@ -278,14 +283,15 @@ export function startAppServices(): AppRouter { startThemeBackground(); startBrowserChromeThemeSync(router); startDefaultThemeAdoption(); - startModelPreferencesMigration(); - startAgentOpenedPreviews(); + if (appWideWindow) startModelPreferencesMigration(); + if (appWideWindow) startAgentOpenedPreviews(); if (isElectron) startElectronBrowserHost(); startPreviewTitleRecording(); - startBrowserProfileReporting(); + if (appWideWindow) startBrowserProfileReporting(); installChatRouteCommands(router); installCommandPaletteCommands(router); registerOpenFavoriteEditorCommand(); + registerDesktopWindowCommands(); startThreadOverlayRetention(router); // Drafts promote as their server threads arrive, wherever the user is. subscribeDraftThreadPromotion({ @@ -303,7 +309,7 @@ export function startAppServices(): AppRouter { startMainAppLocationTracking(router); startWorkspaceFocus(router); startBackgroundThreadAnnouncements(appAtomRegistry, router); - startThreadVisitedMigration(appAtomRegistry); + if (appWideWindow) startThreadVisitedMigration(appAtomRegistry); startSshPasswordPromptQueue(); startKeybindingsUpdateToasts(); @@ -311,9 +317,12 @@ export function startAppServices(): AppRouter { startHostFreezeToasts(); startLegacyThreadMigrationToast(); startPermissionUpdateNotices(router); - startThreadNotifications(appAtomRegistry, router); - startGuideRunNotifications(appAtomRegistry, router); - if (isElectron) startDesktopUpdateLaunchNotice(); + if (appWideWindow) { + startThreadNotifications(appAtomRegistry, router); + startGuideRunNotifications(appAtomRegistry, router); + if (isElectron) startDesktopUpdateLaunchNotice(); + } + startDesktopWindowHub(); return router; } diff --git a/apps/web/src/browser/ElectronBrowserHost.tsx b/apps/web/src/browser/ElectronBrowserHost.tsx index e818b4b400dc1..ad9f60ff173dd 100644 --- a/apps/web/src/browser/ElectronBrowserHost.tsx +++ b/apps/web/src/browser/ElectronBrowserHost.tsx @@ -1,4 +1,4 @@ -import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; +import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { AuthPreviewOperateScope, type DesktopPreviewBridge, @@ -8,9 +8,14 @@ import { } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; -import { type ComponentProps, useState } from "react"; +import { type ComponentProps, useEffect, useState } from "react"; import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment"; +import { + publishHostedPreviewThreads, + useThreadsHostedElsewhere, +} from "~/multiWindow/previewHosting"; +import { isSecondaryDesktopWindow } from "~/multiWindow/windowContext"; import { isElectron } from "~/env"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; @@ -134,8 +139,23 @@ export function startElectronBrowserHost(): () => void { export function ElectronBrowserHost() { const previewByThreadKey = useActivePreviewSessions(); const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom); - useDesktopHostedPreviewSessions(primaryEnvironmentId); - const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId); + // Background previews belong to the main window; a secondary one hosts only what it shows. + const [secondaryWindow] = useState(isSecondaryDesktopWindow); + useDesktopHostedPreviewSessions(secondaryWindow ? null : primaryEnvironmentId); + const hostedElsewhere = useThreadsHostedElsewhere(); + const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId).filter( + (session) => !hostedElsewhere.has(scopedThreadKey(session.threadRef)), + ); + const hostedThreadKeys = secondaryWindow + ? [...new Set(sessions.map((session) => scopedThreadKey(session.threadRef)))] + .toSorted() + .join("\n") + : ""; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this window's hosted previews to the main window through shared storage + useEffect(() => { + if (!secondaryWindow) return; + return publishHostedPreviewThreads(hostedThreadKeys === "" ? [] : hostedThreadKeys.split("\n")); + }, [secondaryWindow, hostedThreadKeys]); if (!isElectron) return null; return ( diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 4610ef7542890..3745ed9b83d50 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -257,6 +257,7 @@ import { } from "./CommandPaletteAddProject"; import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems"; import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems"; +import { useCommandPaletteWindowItems } from "./CommandPaletteWindowItems"; import { PORT_FORWARD_GROUP_PREFIX, useCommandPalettePortForwardItem, @@ -558,6 +559,7 @@ function OpenCommandPaletteDialog(props: { activeThread: activeThread ?? null, query: deferredQuery, }); + const windowItems = useCommandPaletteWindowItems(); const currentView = viewStack.at(-1)?.view ?? null; const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : ""; const [browseGeneration, setBrowseGeneration] = useState(0); @@ -1678,6 +1680,7 @@ function OpenCommandPaletteDialog(props: { actionItems.push(changeAppearanceItem); actionItems.push(themeEditorItem); + actionItems.push(...windowItems); if (environments.some((environment) => environment.serverConfig !== null)) { actionItems.push({ diff --git a/apps/web/src/components/CommandPaletteWindowItems.tsx b/apps/web/src/components/CommandPaletteWindowItems.tsx new file mode 100644 index 0000000000000..f38e3ecb476f9 --- /dev/null +++ b/apps/web/src/components/CommandPaletteWindowItems.tsx @@ -0,0 +1,25 @@ +import { useGT } from "gt-react"; +import { AppWindowIcon } from "lucide-react"; +import { useState } from "react"; + +import { desktopWindowsBridge } from "../multiWindow/windowContext"; +import { openNewDesktopWindow } from "../multiWindow/ui/windowActions"; +import { ITEM_ICON_CLASS, type CommandPaletteActionItem } from "./CommandPalette.logic"; + +/** Desktop multi-window actions; empty on the web and in shells without multi-window support. */ +export function useCommandPaletteWindowItems(): ReadonlyArray { + const [bridge] = useState(desktopWindowsBridge); + const gt = useGT(); + if (bridge === null) return []; + return [ + { + kind: "action", + value: "action:window-new", + title: gt("New Window"), + searchTerms: ["new window", "window", "open window", "multiple windows"], + icon: , + shortcutCommand: "window.new", + run: async () => openNewDesktopWindow(bridge), + }, + ]; +} diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 9d03b7ab72e48..9907448c60914 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -517,6 +517,7 @@ const USAGE_COMMAND_LABELS: Record< const LATE_COMMAND_LABELS: Partial> = { "view.reopenClosed": msg("Reopen Closed Tab"), + "window.new": msg("New Window"), "preview.focusUrl": msg("Preview: Focus URL"), "preview.find": msg("Preview: Find on Page"), }; diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index c6942b7e01c88..d9bd98498b1d3 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -756,6 +756,57 @@ describe("composerDraftStore context persistence", () => { vi.resetModules(); } }); + + it("shows a draft another desktop window saved, without reverting it on its next save", async () => { + const sharedStorage = createMemoryStorage(); + vi.stubGlobal("localStorage", sharedStorage); + const context = { windowId: 2, isMain: false }; + vi.stubGlobal( + "window", + Object.assign(new EventTarget(), { + desktopBridge: { windows: { getContext: () => context } }, + }), + ); + vi.useFakeTimers(); + vi.resetModules(); + try { + const thisWindow = await import("./composerDraftStore"); + vi.resetModules(); + const otherWindow = await import("./composerDraftStore"); + const alphaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("alpha-window-thread")); + const betaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("beta-window-thread")); + const announceSave = () => + window.dispatchEvent( + Object.assign(new Event("storage"), { + key: COMPOSER_DRAFT_STORAGE_KEY, + newValue: sharedStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY), + }), + ); + + thisWindow.useComposerDraftStore.getState().setPrompt(alphaRef, "alpha draft"); + await vi.advanceTimersByTimeAsync(300); + otherWindow.useComposerDraftStore.getState().setPrompt(betaRef, "beta draft"); + await vi.advanceTimersByTimeAsync(300); + announceSave(); + + const drafts = thisWindow.useComposerDraftStore.getState().draftsByThreadKey; + expect(drafts[scopedThreadKey(betaRef)]?.prompt).toBe("beta draft"); + expect(drafts[scopedThreadKey(alphaRef)]?.prompt).toBe("alpha draft"); + + otherWindow.useComposerDraftStore.getState().setPrompt(betaRef, "beta edited"); + await vi.advanceTimersByTimeAsync(300); + thisWindow.useComposerDraftStore.getState().setPrompt(alphaRef, "alpha edited"); + await vi.advanceTimersByTimeAsync(300); + + const saved = JSON.parse(sharedStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) as string); + expect(saved.state.draftsByThreadKey[scopedThreadKey(betaRef)]?.prompt).toBe("beta edited"); + expect(saved.state.draftsByThreadKey[scopedThreadKey(alphaRef)]?.prompt).toBe("alpha edited"); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); }); describe("composerDraftStore thread contexts", () => { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 07eca76db05f3..629638b690c5e 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -97,6 +97,7 @@ import { persist, type PersistStorage, type StorageValue } from "zustand/middlew import { useShallow } from "zustand/react/shallow"; import { draftModelSelectionApplies } from "./lib/chatThreadActions"; import { createDeferredStorage, createMemoryStorage } from "./lib/storage"; +import { readDesktopWindowContext } from "./multiWindow/windowContext"; import { getDefaultServerModel } from "./providerModels"; import { replaceComposerContextReferences, @@ -4580,6 +4581,145 @@ composerDraftLoadedState = partializeComposerDraftStoreState(composerDraftStore. export const useComposerDraftStore = composerDraftStore; +type DraftRecordKey = + | "draftsByThreadKey" + | "draftThreadsByThreadKey" + | "logicalProjectDraftThreadKeyByLogicalProjectKey"; +const DRAFT_RECORD_KEYS: ReadonlyArray = [ + "draftsByThreadKey", + "draftThreadsByThreadKey", + "logicalProjectDraftThreadKeyByLogicalProjectKey", +]; +const DRAFT_STICKY_KEYS = [ + "stickyModelSelectionByProvider", + "stickyOptionsByModelByProvider", + "stickyActiveProvider", +] as const; + +interface AdoptedComposerDrafts { + /** Entries another window saved that this window had not changed; undefined removes one. */ + readonly records: { readonly [K in DraftRecordKey]: Record }; + readonly sticky: Partial< + Pick + >; + /** The baseline the next write merges against, now including the adopted entries. */ + readonly baseline: PersistedComposerDraftStoreState; + readonly changed: boolean; +} + +/** + * The read side of `mergeComposerDraftStates`: what another window saved since `baseline` + * replaces this window's entry only where this window has not changed it since. + */ +function adoptStoredComposerDrafts( + stored: PersistedComposerDraftStoreState, + local: PersistedComposerDraftStoreState, + baseline: PersistedComposerDraftStoreState, +): AdoptedComposerDrafts { + let changed = false; + const nextBaseline: Record = { ...baseline }; + const records = {} as Record>; + for (const field of DRAFT_RECORD_KEYS) { + const storedRecord: Readonly> = stored[field]; + const localRecord: Readonly> = local[field]; + const baselineRecord: Readonly> = baseline[field]; + const adopted: Record = {}; + const nextBaselineRecord: Record = { ...baselineRecord }; + for (const key of new Set([...Object.keys(storedRecord), ...Object.keys(baselineRecord)])) { + if (Equal.equals(storedRecord[key], baselineRecord[key])) continue; + if (!Equal.equals(localRecord[key], baselineRecord[key])) continue; + adopted[key] = storedRecord[key]; + if (storedRecord[key] === undefined) delete nextBaselineRecord[key]; + else nextBaselineRecord[key] = storedRecord[key]; + changed = true; + } + records[field] = adopted; + nextBaseline[field] = nextBaselineRecord; + } + const sticky: Record = {}; + for (const field of DRAFT_STICKY_KEYS) { + if (Equal.equals(stored[field], baseline[field])) continue; + if (!Equal.equals(local[field], baseline[field])) continue; + sticky[field] = stored[field]; + nextBaseline[field] = stored[field]; + changed = true; + } + return { + records, + sticky, + baseline: nextBaseline as PersistedComposerDraftStoreState, + changed, + }; +} + +function applyRecordChanges( + current: Readonly>, + adopted: Readonly>, + hydrate: (value: never) => V, +): Record { + const next = { ...current }; + for (const [key, value] of Object.entries(adopted)) { + if (value === undefined) delete next[key]; + else next[key] = hydrate(value as never); + } + return next; +} + +function adoptOtherWindowDrafts(text: string): void { + let parsed: StorageValue; + try { + parsed = JSON.parse(text) as StorageValue; + } catch { + return; + } + if (parsed.version !== COMPOSER_DRAFT_STORAGE_VERSION) return; + const baseline = composerDraftLastWrite?.local ?? composerDraftLoadedState; + if (baseline === null) return; + const stored = normalizeCurrentPersistedComposerDraftStoreState(parsed.state); + const adopted = adoptStoredComposerDrafts( + stored, + partializeComposerDraftStoreState(composerDraftStore.getState()), + baseline, + ); + composerDraftLastWrite = { text, local: adopted.baseline, merged: stored }; + if (!adopted.changed) return; + composerDraftStore.setState((state) => ({ + draftsByThreadKey: applyRecordChanges( + state.draftsByThreadKey, + adopted.records.draftsByThreadKey, + toHydratedThreadDraft, + ), + draftThreadsByThreadKey: applyRecordChanges( + state.draftThreadsByThreadKey, + adopted.records.draftThreadsByThreadKey, + toHydratedDraftThreadState, + ) as Record, + logicalProjectDraftThreadKeyByLogicalProjectKey: applyRecordChanges( + state.logicalProjectDraftThreadKeyByLogicalProjectKey, + adopted.records.logicalProjectDraftThreadKeyByLogicalProjectKey, + (value: string) => value, + ), + ...("stickyModelSelectionByProvider" in adopted.sticky + ? { stickyModelSelectionByProvider: adopted.sticky.stickyModelSelectionByProvider ?? {} } + : {}), + ...("stickyOptionsByModelByProvider" in adopted.sticky + ? { stickyOptionsByModelByProvider: adopted.sticky.stickyOptionsByModelByProvider ?? {} } + : {}), + ...("stickyActiveProvider" in adopted.sticky + ? { stickyActiveProvider: adopted.sticky.stickyActiveProvider ?? null } + : {}), + })); +} + +// Desktop windows share drafts through storage; each picks up what the others save. +if (readDesktopWindowContext() !== null && typeof window !== "undefined") { + window.addEventListener("storage", (event) => { + if (event.key === COMPOSER_DRAFT_STORAGE_KEY && event.newValue !== null) { + adoptOtherWindowDrafts(event.newValue); + } + }); +} + export function subscribeComposerDraftModelReconciliation(input: { readonly registry: AtomRegistry.AtomRegistry; readonly threadRefsAtom: Atom.Atom>; diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.ts index 6a3cc4acb43f3..2490d2d397940 100644 --- a/apps/web/src/connection/runtime.ts +++ b/apps/web/src/connection/runtime.ts @@ -10,6 +10,8 @@ import * as Layer from "effect/Layer"; import { Atom } from "effect/reactivity"; import { isGuestPage } from "../guestPage"; +import { isSecondaryDesktopWindow, readDesktopWindowContext } from "../multiWindow/windowContext"; +import { layerHubLeaseSource } from "../multiWindow/secondary"; import * as Runtime from "../lib/runtime"; import * as BackgroundActivityReporter from "../lib/backgroundActivityReporter"; @@ -34,11 +36,17 @@ type ConnectionLayerSource = const layerProvidedClientConnection = layerSnapshotLoader.pipe( Layer.provideMerge( - Connection.layerWithOptions({ - environmentThemes: true, - usageLimitSources: true, - usageLimitsCommand: true, - }), + Connection.layerWithOptions( + { + environmentThemes: true, + usageLimitSources: true, + usageLimitsCommand: true, + // The main desktop window serves other windows, which share its subscriptions. + shareStreams: readDesktopWindowContext()?.isMain === true, + }, + // A secondary desktop window shares the main window's sockets. + isSecondaryDesktopWindow() ? layerHubLeaseSource : undefined, + ), ), Layer.provideMerge( Layer.mergeAll( diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 9cb27b4cc2611..14a14d7129c4f 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -157,9 +157,7 @@ async function hydrateClientSettings(): Promise { if (persistedSettings) { replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings }); } - unsubscribeOtherTabClientSettings ??= subscribeBrowserClientSettingsWrites( - refreshClientSettingsFromOtherTab, - ); + unsubscribeOtherTabClientSettings ??= subscribeOtherWindowClientSettingsWrites(); setClientSettingsHydrationStatus("ready"); } catch (error) { if (hydrationGeneration === clientSettingsHydrationGeneration) { @@ -183,6 +181,19 @@ async function hydrateClientSettings(): Promise { return clientSettingsHydrationPromise; } +/** Browser tabs share storage events; desktop windows hear of the desktop's settings file writes. */ +function subscribeOtherWindowClientSettingsWrites(): () => void { + const unsubscribeTabs = subscribeBrowserClientSettingsWrites(refreshClientSettingsFromOtherTab); + const unsubscribeWindows = + typeof window === "undefined" + ? undefined + : window.desktopBridge?.onClientSettingsChanged?.(refreshClientSettingsFromOtherTab); + return () => { + unsubscribeTabs(); + unsubscribeWindows?.(); + }; +} + function refreshClientSettingsFromOtherTab(): void { void enqueueClientSettingsPersistence(async () => { const persistedSettings = await ensureLocalApi().persistence.getClientSettings(); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7900e73186091..6604147270dd5 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1969,6 +1969,7 @@ "9c6962c66efa5668": "Darstellung ändern", "074c1660aac1c7cf": "Design-Editor umschalten", "02c340f8d0bb7649": "Aktuell", + "9268423936e5989f": "Neues Fenster", "b8ec049821ce511c": "Berechtigungen: {label}", "f0d4573b2e03e2a7": "Berechtigungen", "38695f22426981d6": "Vorschau von {path}", @@ -12669,6 +12670,7 @@ "0e4b49c8203aae81": "Zeitüberschreitung beim Warten auf eine authentifizierte Sitzung nach dem Bootstrap.", "d7ffde2874d60d4f": "Gib ein Kopplungstoken ein, um fortzufahren.", "5d18537f82794deb": "Die lokale Umgebung ist deaktiviert.", + "67b874ad1deb2ab5": "Neues Fenster konnte nicht geöffnet werden", "d5ef094f40aedece": "Terminal-Eingabe", "f7046b10d49caab6": "Terminal-Verlauf", "24de858bbcf05f40": "Folie {number}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 5bdd7c383d319..c9cc4bbd6d72b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Change appearance", "074c1660aac1c7cf": "Toggle theme editor", "02c340f8d0bb7649": "Current", + "9268423936e5989f": "New Window", "b8ec049821ce511c": "Permissions: {label}", "f0d4573b2e03e2a7": "Permissions", "38695f22426981d6": "Preview {path}", @@ -12677,6 +12678,7 @@ "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", "d7ffde2874d60d4f": "Enter a pairing token to continue.", "5d18537f82794deb": "The local environment is disabled.", + "67b874ad1deb2ab5": "Couldn't open a new window", "d5ef094f40aedece": "Terminal input", "f7046b10d49caab6": "Terminal scrollback", "24de858bbcf05f40": "Slide {number}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 91dbb2b07f50f..a48a6e84a0947 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Cambiar apariencia", "074c1660aac1c7cf": "Mostrar u ocultar el editor de temas", "02c340f8d0bb7649": "Actual", + "9268423936e5989f": "Nueva ventana", "b8ec049821ce511c": "Permisos: {label}", "f0d4573b2e03e2a7": "Permisos", "38695f22426981d6": "Vista previa de {path}", @@ -12662,6 +12663,7 @@ "0e4b49c8203aae81": "Se agotó el tiempo de espera de la sesión autenticada tras el arranque.", "d7ffde2874d60d4f": "Introduce un token de emparejamiento para continuar.", "5d18537f82794deb": "El entorno local está desactivado.", + "67b874ad1deb2ab5": "No se pudo abrir una ventana nueva", "d5ef094f40aedece": "Entrada de la terminal", "f7046b10d49caab6": "Historial de desplazamiento de la terminal", "24de858bbcf05f40": "Diapositiva {number}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f5cf7e62a4744..ac59673409150 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Changer l’apparence", "074c1660aac1c7cf": "Afficher/masquer l’éditeur de thème", "02c340f8d0bb7649": "Actuel", + "9268423936e5989f": "Nouvelle fenêtre", "b8ec049821ce511c": "Autorisations : {label}", "f0d4573b2e03e2a7": "Autorisations", "38695f22426981d6": "Aperçu de {path}", @@ -12667,6 +12668,7 @@ "0e4b49c8203aae81": "Délai dépassé en attendant la session authentifiée après l’amorçage.", "d7ffde2874d60d4f": "Saisissez un jeton d’appairage pour continuer.", "5d18537f82794deb": "L’environnement local est désactivé.", + "67b874ad1deb2ab5": "Impossible d’ouvrir une nouvelle fenêtre", "d5ef094f40aedece": "Saisie du terminal", "f7046b10d49caab6": "Historique du terminal", "24de858bbcf05f40": "Diapositive {number}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 7e3be343b068b..baf98a6bfc3da 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1968,6 +1968,7 @@ "9c6962c66efa5668": "外観を変更", "074c1660aac1c7cf": "テーマエディターの切り替え", "02c340f8d0bb7649": "使用中", + "9268423936e5989f": "新しいウィンドウ", "b8ec049821ce511c": "権限: {label}", "f0d4573b2e03e2a7": "権限", "38695f22426981d6": "{path} をプレビュー", @@ -12610,6 +12611,7 @@ "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", "d7ffde2874d60d4f": "続行するにはペアリングトークンを入力してください。", "5d18537f82794deb": "ローカル環境は無効になっています。", + "67b874ad1deb2ab5": "新しいウィンドウを開けませんでした", "d5ef094f40aedece": "ターミナルの入力", "f7046b10d49caab6": "ターミナルのスクロールバック", "24de858bbcf05f40": "スライド {number}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index ef69858aead11..0976d4d356dd2 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "모양 변경", "074c1660aac1c7cf": "테마 편집기 전환", "02c340f8d0bb7649": "현재", + "9268423936e5989f": "새 창", "b8ec049821ce511c": "권한: {label}", "f0d4573b2e03e2a7": "권한", "38695f22426981d6": "{path} 미리 보기", @@ -12607,6 +12608,7 @@ "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", "d7ffde2874d60d4f": "계속하려면 페어링 토큰을 입력하세요.", "5d18537f82794deb": "로컬 환경이 꺼져 있습니다.", + "67b874ad1deb2ab5": "새 창을 열 수 없습니다", "d5ef094f40aedece": "터미널 입력", "f7046b10d49caab6": "터미널 스크롤백", "24de858bbcf05f40": "슬라이드 {number}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2f82a27a416..17e5bfff912da 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Mudar aparência", "074c1660aac1c7cf": "Alternar editor de temas", "02c340f8d0bb7649": "Atual", + "9268423936e5989f": "Nova janela", "b8ec049821ce511c": "Permissões: {label}", "f0d4573b2e03e2a7": "Permissões", "38695f22426981d6": "Pré-visualizar {path}", @@ -12667,6 +12668,7 @@ "0e4b49c8203aae81": "Tempo esgotado aguardando a sessão autenticada após a inicialização.", "d7ffde2874d60d4f": "Informe um token de pareamento para continuar.", "5d18537f82794deb": "O ambiente local está desativado.", + "67b874ad1deb2ab5": "Não foi possível abrir uma nova janela", "d5ef094f40aedece": "Entrada do terminal", "f7046b10d49caab6": "Histórico de rolagem do terminal", "24de858bbcf05f40": "Slide {number}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 2891cb8165d7c..b331b4d57cd8f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Изменить оформление", "074c1660aac1c7cf": "Показать/скрыть редактор темы", "02c340f8d0bb7649": "Текущая", + "9268423936e5989f": "Новое окно", "b8ec049821ce511c": "Разрешения: {label}", "f0d4573b2e03e2a7": "Разрешения", "38695f22426981d6": "Предпросмотр {path}", @@ -12668,6 +12669,7 @@ "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", "d7ffde2874d60d4f": "Введите токен сопряжения, чтобы продолжить.", "5d18537f82794deb": "Локальное окружение отключено.", + "67b874ad1deb2ab5": "Не удалось открыть новое окно", "d5ef094f40aedece": "Ввод терминала", "f7046b10d49caab6": "Прокрутка терминала", "24de858bbcf05f40": "Слайд {number}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c792d6fb4a981..f641de70d4dc3 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Ändra utseende", "074c1660aac1c7cf": "Växla temaredigerare", "02c340f8d0bb7649": "Aktuellt", + "9268423936e5989f": "Nytt fönster", "b8ec049821ce511c": "Behörigheter: {label}", "f0d4573b2e03e2a7": "Behörigheter", "38695f22426981d6": "Förhandsvisa {path}", @@ -12675,6 +12676,7 @@ "0e4b49c8203aae81": "Tidsgränsen överskreds i väntan på en autentiserad session efter uppstart.", "d7ffde2874d60d4f": "Ange en parkopplingstoken för att fortsätta.", "5d18537f82794deb": "Den lokala miljön är inaktiverad.", + "67b874ad1deb2ab5": "Kunde inte öppna ett nytt fönster", "d5ef094f40aedece": "Terminalinmatning", "f7046b10d49caab6": "Terminalens rullningshistorik", "24de858bbcf05f40": "Bild {number}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cd80e9a35102a..c3490a202ed1c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1971,6 +1971,7 @@ "9c6962c66efa5668": "切换外观", "074c1660aac1c7cf": "开关主题编辑器", "02c340f8d0bb7649": "当前", + "9268423936e5989f": "新建窗口", "b8ec049821ce511c": "权限:{label}", "f0d4573b2e03e2a7": "权限", "38695f22426981d6": "预览 {path}", @@ -12686,6 +12687,7 @@ "0e4b49c8203aae81": "引导完成后等待登录状态超时。", "d7ffde2874d60d4f": "请输入配对 token 以继续。", "5d18537f82794deb": "本地环境已停用。", + "67b874ad1deb2ab5": "无法打开新窗口", "d5ef094f40aedece": "终端输入", "f7046b10d49caab6": "终端回滚缓冲", "24de858bbcf05f40": "幻灯片 {number}", diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 84463efc3abfd..2ce2fe870540c 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -400,6 +400,33 @@ describe("thread navigation helpers", () => { }); }); +describe("new window shortcut", () => { + it("opens a window only in the desktop app, apart from the no-project thread shortcut", () => { + const newWindow = event({ key: "n", ctrlKey: true, altKey: true, shiftKey: true }); + assert.strictEqual( + resolveShortcutCommand(newWindow, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context: { isDesktop: true }, + }), + "window.new", + ); + assert.isNull( + resolveShortcutCommand(newWindow, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context: { isDesktop: false }, + }), + ); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "n", ctrlKey: true, altKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { platform: "Linux", context: { isDesktop: true } }, + ), + "chat.newWithoutProject", + ); + }); +}); + describe("model picker navigation helpers", () => { it("keeps default model jumps off the web even while the picker is open", () => { const input = event({ key: "3", metaKey: true }); diff --git a/apps/web/src/multiWindow/hub.ts b/apps/web/src/multiWindow/hub.ts new file mode 100644 index 0000000000000..bcd356bc7b6a7 --- /dev/null +++ b/apps/web/src/multiWindow/hub.ts @@ -0,0 +1,126 @@ +import { EnvironmentRegistry, HubConnection } from "@t3tools/client-runtime/connection"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import { Atom } from "effect/reactivity"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { + type HubLinkRequest, + type HubLinkResponse, + isHubLinkRequest, + onHubLinkPort, + toRpcPort, +} from "./hubLink"; +import { desktopWindowsBridge, readDesktopWindowContext } from "./windowContext"; + +/** + * Serves secondary windows' environment connections from this window's own + * sessions. Each link is one secondary window; each lease relays one + * environment's RPC traffic over a dedicated port until that window releases it. + */ +const hubAtom = connectionAtomRuntime + .atom( + Effect.gen(function* () { + const bridge = desktopWindowsBridge(); + if (bridge === null) return; + const hubScope = yield* Effect.scope; + const runFork = Effect.runForkWith( + yield* Effect.context(), + ); + const links = new Map(); + + const serveLease = Effect.fn("DesktopWindowHub.serveLease")(function* ( + link: MessagePort, + linkScope: Scope.Scope, + leases: Map, + request: Extract, + ) { + const leaseScope = yield* Scope.fork(linkScope); + leases.set(request.leaseId, leaseScope); + const channel = new MessageChannel(); + const respond = (response: HubLinkResponse, transfer: Transferable[] = []) => + Effect.sync(() => link.postMessage(response, transfer)); + yield* HubConnection.serveHubLease( + EnvironmentId.make(request.environmentId), + toRpcPort(channel.port1), + ).pipe( + Scope.provide(leaseScope), + Effect.matchEffect({ + onSuccess: (prepared) => + respond( + { + type: "leased", + leaseId: request.leaseId, + prepared: HubConnection.encodePreparedConnection(prepared), + }, + [channel.port2], + ), + onFailure: (error) => + respond({ + type: "leaseFailed", + leaseId: request.leaseId, + error: HubConnection.encodeConnectionAttemptError(error), + }).pipe(Effect.andThen(Scope.close(leaseScope, Exit.void))), + }), + Effect.forkIn(leaseScope), + ); + }); + + const openLink = (port: MessagePort, peerWindowId: number) => { + const previous = links.get(peerWindowId); + if (previous !== undefined) runFork(Scope.close(previous, Exit.void)); + const linkScope = Scope.forkUnsafe(hubScope); + links.set(peerWindowId, linkScope); + const leases = new Map(); + const handle = (event: MessageEvent) => { + const request: unknown = event.data; + if (!isHubLinkRequest(request)) return; + if (request.type === "release") { + const lease = leases.get(request.leaseId); + leases.delete(request.leaseId); + if (lease !== undefined) runFork(Scope.close(lease, Exit.void)); + return; + } + runFork(serveLease(port, linkScope, leases, request)); + }; + port.addEventListener("message", handle); + port.start(); + runFork( + Scope.addFinalizer( + linkScope, + Effect.sync(() => { + port.removeEventListener("message", handle); + port.close(); + if (links.get(peerWindowId) === linkScope) links.delete(peerWindowId); + }), + ), + ); + }; + + const closeLink = (peerWindowId: number) => { + const link = links.get(peerWindowId); + if (link !== undefined) runFork(Scope.close(link, Exit.void)); + }; + + const stopListening = onHubLinkPort(openLink); + const stopPeerGone = bridge.onHubPeerGone(closeLink); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + stopListening(); + stopPeerGone(); + }), + ); + bridge.registerHub(); + return yield* Effect.never; + }), + ) + .pipe(Atom.keepAlive, Atom.withLabel("desktop-window-hub")); + +/** The main window serves every other window's connections for the life of the page. */ +export function startDesktopWindowHub(): void { + if (readDesktopWindowContext()?.isMain !== true) return; + appAtomRegistry.mount(hubAtom); +} diff --git a/apps/web/src/multiWindow/hubLink.ts b/apps/web/src/multiWindow/hubLink.ts new file mode 100644 index 0000000000000..d359fd22baeec --- /dev/null +++ b/apps/web/src/multiWindow/hubLink.ts @@ -0,0 +1,66 @@ +import { DESKTOP_HUB_LINK_MESSAGE_TYPE, type DesktopHubLinkMessage } from "@t3tools/contracts"; +import type { RpcPort } from "@t3tools/client-runtime/rpc"; +import * as Schema from "effect/Schema"; + +/** Messages a secondary window sends the hub over its link port. */ +const HubLinkRequest = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("lease"), + leaseId: Schema.Number, + environmentId: Schema.String, + }), + Schema.Struct({ type: Schema.Literal("release"), leaseId: Schema.Number }), +]); +export type HubLinkRequest = typeof HubLinkRequest.Type; +export const isHubLinkRequest = Schema.is(HubLinkRequest); + +/** The hub's answers. A `leased` message transfers the lease's session port. */ +const HubLinkResponse = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("leased"), + leaseId: Schema.Number, + prepared: Schema.Unknown, + }), + Schema.Struct({ + type: Schema.Literal("leaseFailed"), + leaseId: Schema.Number, + error: Schema.Unknown, + }), +]); +export type HubLinkResponse = typeof HubLinkResponse.Type; +export const isHubLinkResponse = Schema.is(HubLinkResponse); + +export function toRpcPort(port: MessagePort): RpcPort { + return { + postMessage: (message) => port.postMessage(message), + onMessage: (listener) => { + const handle = (event: MessageEvent) => listener(event.data); + port.addEventListener("message", handle); + port.start(); + return () => port.removeEventListener("message", handle); + }, + close: () => port.close(), + }; +} + +function isHubLinkMessage(data: unknown): data is DesktopHubLinkMessage { + return ( + typeof data === "object" && + data !== null && + (data as { readonly type?: unknown }).type === DESKTOP_HUB_LINK_MESSAGE_TYPE && + typeof (data as { readonly peerWindowId?: unknown }).peerWindowId === "number" + ); +} + +/** The preload hands link ports to the page with `window.postMessage`, as ports cannot cross the bridge. */ +export function onHubLinkPort( + listener: (port: MessagePort, peerWindowId: number) => void, +): () => void { + const handle = (event: MessageEvent) => { + const port = event.ports[0]; + if (event.source !== window || port === undefined || !isHubLinkMessage(event.data)) return; + listener(port, event.data.peerWindowId); + }; + window.addEventListener("message", handle); + return () => window.removeEventListener("message", handle); +} diff --git a/apps/web/src/multiWindow/previewHosting.test.ts b/apps/web/src/multiWindow/previewHosting.test.ts new file mode 100644 index 0000000000000..69882a0ea1f2d --- /dev/null +++ b/apps/web/src/multiWindow/previewHosting.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { threadsHostedByOtherWindows } from "./previewHosting"; + +describe("threadsHostedByOtherWindows", () => { + it("collects open secondary windows' threads and ignores its own, closed and broken lists", () => { + const hosted = threadsHostedByOtherWindows( + [ + ["t3code:desktop-window-previews:2", JSON.stringify(["env:a", "env:b"])], + ["t3code:desktop-window-previews:3", JSON.stringify(["env:c"])], + ["t3code:desktop-window-previews:1", JSON.stringify(["env:own"])], + ["t3code:desktop-window-previews:4", "not json"], + ["t3code:other", JSON.stringify(["env:x"])], + ], + new Set([1, 2, 4]), + 1, + ); + + expect([...hosted].toSorted()).toEqual(["env:a", "env:b"]); + }); +}); diff --git a/apps/web/src/multiWindow/previewHosting.ts b/apps/web/src/multiWindow/previewHosting.ts new file mode 100644 index 0000000000000..5ade60d32e6f5 --- /dev/null +++ b/apps/web/src/multiWindow/previewHosting.ts @@ -0,0 +1,104 @@ +import { useSyncExternalStore } from "react"; + +import { readDesktopWindowContext } from "./windowContext"; +import { readDesktopWindowsState, subscribeDesktopWindowsState } from "./windowsState"; + +const KEY_PREFIX = "t3code:desktop-window-previews:"; + +/** + * Threads whose previews another open window hosts, from each window's published list. + * Lists from windows that are no longer open are ignored, since a crash leaves them behind. + */ +export function threadsHostedByOtherWindows( + entries: ReadonlyArray, + openWindowIds: ReadonlySet, + ownWindowId: number, +): ReadonlySet { + const hosted = new Set(); + for (const [key, value] of entries) { + if (!key.startsWith(KEY_PREFIX) || value === null) continue; + const windowId = Number(key.slice(KEY_PREFIX.length)); + if (windowId === ownWindowId || !openWindowIds.has(windowId)) continue; + try { + const threadKeys: unknown = JSON.parse(value); + if (!Array.isArray(threadKeys)) continue; + for (const threadKey of threadKeys) if (typeof threadKey === "string") hosted.add(threadKey); + } catch {} + } + return hosted; +} + +/** A secondary window announces the threads whose previews it shows, so the main window skips them. */ +export function publishHostedPreviewThreads(threadKeys: ReadonlyArray): () => void { + const context = readDesktopWindowContext(); + if (context === null || context.isMain) return () => {}; + const key = `${KEY_PREFIX}${context.windowId}`; + try { + if (threadKeys.length === 0) window.localStorage.removeItem(key); + else window.localStorage.setItem(key, JSON.stringify(threadKeys)); + } catch {} + return () => { + try { + window.localStorage.removeItem(key); + } catch {} + }; +} + +const EMPTY: ReadonlySet = new Set(); +let cachedSignature = ""; +let cachedHosted: ReadonlySet = EMPTY; +// React reads the snapshot every render; storage is scanned only after a change. +let stale = true; + +function readHostedElsewhere(): ReadonlySet { + if (!stale) return cachedHosted; + stale = false; + const context = readDesktopWindowContext(); + const state = readDesktopWindowsState(); + if (context === null || !context.isMain || state === null || state.windows.length < 2) { + cachedSignature = ""; + cachedHosted = EMPTY; + return EMPTY; + } + const entries: Array = []; + try { + for (let index = 0; index < window.localStorage.length; index++) { + const key = window.localStorage.key(index); + if (key?.startsWith(KEY_PREFIX)) entries.push([key, window.localStorage.getItem(key)]); + } + } catch { + return EMPTY; + } + const hosted = threadsHostedByOtherWindows( + entries, + new Set(state.windows.map((open) => open.windowId)), + context.windowId, + ); + const signature = [...hosted].toSorted().join("\n"); + if (signature !== cachedSignature) { + cachedSignature = signature; + cachedHosted = hosted; + } + return cachedHosted; +} + +function subscribeHostedElsewhere(listener: () => void): () => void { + const changed = () => { + stale = true; + listener(); + }; + const onStorage = (event: StorageEvent) => { + if (event.key === null || event.key.startsWith(KEY_PREFIX)) changed(); + }; + window.addEventListener("storage", onStorage); + const unsubscribeWindows = subscribeDesktopWindowsState(changed); + return () => { + window.removeEventListener("storage", onStorage); + unsubscribeWindows(); + }; +} + +/** In the main window: threads a secondary window shows, whose previews it hosts instead. */ +export function useThreadsHostedElsewhere(): ReadonlySet { + return useSyncExternalStore(subscribeHostedElsewhere, readHostedElsewhere, () => EMPTY); +} diff --git a/apps/web/src/multiWindow/secondary.ts b/apps/web/src/multiWindow/secondary.ts new file mode 100644 index 0000000000000..9feb25fe05c8a --- /dev/null +++ b/apps/web/src/multiWindow/secondary.ts @@ -0,0 +1,170 @@ +import { + type ConnectionAttemptError, + ConnectionTransientError, + HubConnection, +} from "@t3tools/client-runtime/connection"; +import type { RpcPort } from "@t3tools/client-runtime/rpc"; +import type { DesktopWindowsBridge, EnvironmentId } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { type HubLinkRequest, isHubLinkResponse, onHubLinkPort, toRpcPort } from "./hubLink"; +import { desktopWindowsBridge } from "./windowContext"; + +const hubGone = (detail: string) => + new ConnectionTransientError({ reason: "transport", detail, hop: "device" }); + +const sendToHub = (port: MessagePort, request: HubLinkRequest) => port.postMessage(request); + +interface ActiveLease { + readonly result: Deferred.Deferred; + /** Ends the lease's session as if the relay had closed it. */ + end: (detail: string) => void; +} + +interface Link { + readonly port: MessagePort; + readonly leases: Map; +} + +/** A session port that can also be ended locally when the hub disappears without a word. */ +function endableRpcPort(port: MessagePort): { + readonly port: RpcPort; + readonly end: (detail: string) => void; +} { + const base = toRpcPort(port); + const listeners = new Set<(message: unknown) => void>(); + return { + port: { + ...base, + onMessage: (listener) => { + listeners.add(listener); + const stop = base.onMessage(listener); + return () => { + listeners.delete(listener); + stop(); + }; + }, + }, + end: (detail) => { + for (const listener of listeners) listener({ _tag: "RelayClosed", detail }); + }, + }; +} + +function makeLeaseSource(bridge: DesktopWindowsBridge) { + let link: Link | null = null; + let linkWaiters: Array<(link: Link) => void> = []; + let linkRequested = false; + let nextLeaseId = 1; + + const onResponse = (current: Link) => (event: MessageEvent) => { + const response: unknown = event.data; + if (!isHubLinkResponse(response)) return; + const lease = current.leases.get(response.leaseId); + if (lease === undefined) return; + if (response.type === "leaseFailed") { + current.leases.delete(response.leaseId); + Deferred.doneUnsafe( + lease.result, + Effect.fail(HubConnection.decodeConnectionAttemptError(response.error)), + ); + return; + } + const sessionPort = event.ports[0]; + if (sessionPort === undefined) return; + const endable = endableRpcPort(sessionPort); + lease.end = endable.end; + Deferred.doneUnsafe( + lease.result, + Effect.succeed({ + prepared: HubConnection.decodePreparedConnection(response.prepared), + port: endable.port, + }), + ); + }; + + onHubLinkPort((port) => { + dropLink("The main window replaced this window's link."); + const next: Link = { port, leases: new Map() }; + link = next; + linkRequested = false; + port.addEventListener("message", onResponse(next)); + port.start(); + const waiters = linkWaiters; + linkWaiters = []; + for (const waiter of waiters) waiter(next); + }); + + const dropLink = (detail: string) => { + const current = link; + link = null; + if (current === null) return; + for (const lease of current.leases.values()) { + Deferred.doneUnsafe(lease.result, Effect.fail(hubGone(detail))); + lease.end(detail); + } + current.leases.clear(); + current.port.close(); + }; + + bridge.onHubReset(() => { + linkRequested = false; + dropLink("The main window reloaded."); + // Sessions waiting on the old link reconnect through a fresh one. + if (linkWaiters.length > 0) { + linkRequested = true; + bridge.requestHubLink(); + } + }); + + const awaitLink = Effect.callback((resume) => { + if (link !== null) { + resume(Effect.succeed(link)); + return; + } + const waiter = (ready: Link) => resume(Effect.succeed(ready)); + linkWaiters.push(waiter); + if (!linkRequested) { + linkRequested = true; + bridge.requestHubLink(); + } + return Effect.sync(() => { + linkWaiters = linkWaiters.filter((candidate) => candidate !== waiter); + }); + }); + + return HubConnection.HubLeaseSource.of({ + lease: Effect.fn("DesktopHubLeaseSource.lease")(function* (environmentId: EnvironmentId) { + const current = yield* awaitLink; + const leaseId = nextLeaseId++; + const lease: ActiveLease = { + result: yield* Deferred.make(), + end: () => undefined, + }; + current.leases.set(leaseId, lease); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + current.leases.delete(leaseId); + if (link === current) { + sendToHub(current.port, { type: "release", leaseId }); + } + }), + ); + sendToHub(current.port, { type: "lease", leaseId, environmentId }); + return yield* Deferred.await(lease.result); + }), + }); +} + +/** Secondary windows connect every environment through the main window's sessions. */ +export const layerHubLeaseSource = Layer.effect( + HubConnection.HubLeaseSource, + Effect.suspend(() => { + const bridge = desktopWindowsBridge(); + return bridge === null + ? Effect.die(new Error("Secondary windows need the desktop windows bridge.")) + : Effect.succeed(makeLeaseSource(bridge)); + }), +); diff --git a/apps/web/src/multiWindow/ui/windowActions.ts b/apps/web/src/multiWindow/ui/windowActions.ts new file mode 100644 index 0000000000000..c8d75683481f7 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowActions.ts @@ -0,0 +1,41 @@ +import type { DesktopWindowsBridge } from "@t3tools/contracts"; +import { msg } from "gt-react"; + +import { toastManager } from "../../components/ui/toast"; +import { m } from "../../i18n/messages"; +import { registerCommands, registerMenuAction } from "../../shortcuts/dispatcher"; +import { desktopWindowsBridge } from "../windowContext"; + +function notifyWindowActionFailure(title: string, cause: unknown): void { + console.error(title, cause); + toastManager.add({ + type: "error", + title, + description: cause instanceof Error ? cause.message : undefined, + }); +} + +export function openNewDesktopWindow(bridge: DesktopWindowsBridge): void { + bridge.openNew().catch((cause: unknown) => { + notifyWindowActionFailure(m(msg("Couldn't open a new window")), cause); + }); +} + +/** The New Window shortcut and menu item; a no-op outside a multi-window desktop shell. */ +export function registerDesktopWindowCommands(): () => void { + const bridge = desktopWindowsBridge(); + if (bridge === null) return () => {}; + const disposers = [ + registerCommands({ + "window.new": (event) => { + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) openNewDesktopWindow(bridge); + }, + }), + registerMenuAction("new-window", () => openNewDesktopWindow(bridge)), + ]; + return () => { + for (const dispose of disposers) dispose(); + }; +} diff --git a/apps/web/src/multiWindow/windowContext.ts b/apps/web/src/multiWindow/windowContext.ts new file mode 100644 index 0000000000000..c686fb0203787 --- /dev/null +++ b/apps/web/src/multiWindow/windowContext.ts @@ -0,0 +1,24 @@ +import type { DesktopWindowContext, DesktopWindowsBridge } from "@t3tools/contracts"; + +export function desktopWindowsBridge(): DesktopWindowsBridge | null { + if (typeof window === "undefined") return null; + return window.desktopBridge?.windows ?? null; +} + +let cachedContext: DesktopWindowContext | null | undefined; + +/** Null outside a desktop shell with multi-window support. */ +export function readDesktopWindowContext(): DesktopWindowContext | null { + if (cachedContext !== undefined) return cachedContext; + try { + cachedContext = desktopWindowsBridge()?.getContext() ?? null; + } catch { + cachedContext = null; + } + return cachedContext; +} + +/** A secondary window hosts UI only; the main window's renderer owns its connections. */ +export function isSecondaryDesktopWindow(): boolean { + return readDesktopWindowContext()?.isMain === false; +} diff --git a/apps/web/src/multiWindow/windowsState.ts b/apps/web/src/multiWindow/windowsState.ts new file mode 100644 index 0000000000000..dba46d1ddb4e4 --- /dev/null +++ b/apps/web/src/multiWindow/windowsState.ts @@ -0,0 +1,46 @@ +import type { DesktopWindowsState } from "@t3tools/contracts"; + +import { desktopWindowsBridge } from "./windowContext"; + +let state: DesktopWindowsState | null = null; +let started = false; +const listeners = new Set<() => void>(); + +function publish(next: DesktopWindowsState): void { + state = next; + for (const listener of listeners) listener(); +} + +function ensureStarted(): void { + if (started) return; + const bridge = desktopWindowsBridge(); + if (bridge === null) return; + started = true; + let pushed = false; + bridge.onState((next) => { + pushed = true; + publish(next); + }); + // A push that lands first is newer than this snapshot. + void bridge.getState().then( + (next) => { + if (!pushed) publish(next); + }, + (cause: unknown) => { + console.error("Failed to read desktop windows state.", cause); + }, + ); +} + +export function readDesktopWindowsState(): DesktopWindowsState | null { + ensureStarted(); + return state; +} + +export function subscribeDesktopWindowsState(listener: () => void): () => void { + ensureStarted(); + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 3cbef77306c8e..17cbcddc4b1d3 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -61,6 +61,7 @@ import { readProject } from "../state/entities"; import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; +import { isSecondaryDesktopWindow } from "../multiWindow/windowContext"; export const Route = createRootRoute({ beforeLoad: async ({ location }) => { @@ -160,6 +161,7 @@ function RootRouteBranch() { const hostedPromptLinkLanding = useHostedPromptLinkLanding( authGateState.status === "hosted-static", ); + const secondaryWindow = isSecondaryDesktopWindow(); if (pathname === GUEST_PAGE_PATH) return ; @@ -186,13 +188,14 @@ function RootRouteBranch() { // first-run gate and the event router, whose first navigation would leave the page. const appHosts = ( <> - {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? ( + {/* The desktop routes activations and web links to the main window, which also keeps the app awake. */} + {(primaryEnvironmentAuthenticated || localEnvironmentDisabled) && !secondaryWindow ? ( <> ) : null} - {isElectron ? : null} + {isElectron && !secondaryWindow ? : null} diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 804757e78307a..a4a80a7d58e58 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -5,6 +5,7 @@ import { legacyProjectCwdPreferenceKey, markThreadUnread, markThreadVisited, + mergeSharedUiState, parsePersistedState, PERSISTED_STATE_KEY, type PersistedUiState, @@ -94,6 +95,35 @@ describe("uiStateStore pure functions", () => { }); }); +describe("mergeSharedUiState", () => { + it("keeps this window's changes over another window's save and takes the rest", () => { + const { sidebarProjectScopeKeys: _baselineScope, ...baseline } = makeUiState({ + projectExpandedById: { a: true, b: true }, + projectOrder: ["a", "b"], + threadLastVisitedAtById: { t1: "2026-01-01T00:00:00.000Z" }, + }); + const { sidebarProjectScopeKeys: _localScope, ...local } = makeUiState({ + projectExpandedById: { a: false, b: true }, + projectOrder: ["a", "b"], + threadLastVisitedAtById: { t1: "2026-01-01T00:00:00.000Z" }, + }); + const { sidebarProjectScopeKeys: _storedScope, ...stored } = makeUiState({ + projectExpandedById: { a: true, b: false }, + projectOrder: ["b", "a"], + threadLastVisitedAtById: { + t1: "2026-01-01T00:00:00.000Z", + t2: "2026-01-02T00:00:00.000Z", + }, + pullRequestMergeMethod: "squash", + }); + + expect(mergeSharedUiState(stored, local, baseline)).toEqual({ + ...stored, + projectExpandedById: { a: false, b: false }, + }); + }); +}); + describe("parsePersistedState", () => { it("hydrates raw UI-owned state without server entities", () => { const parsed = parsePersistedState({ diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index b2ac1a508c7a6..c8ce7db1ea1db 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -4,6 +4,8 @@ import * as Schema from "effect/Schema"; import { create } from "zustand"; import { normalizeProjectPathForComparison } from "@t3tools/client-runtime/state/projects"; +import { readDesktopWindowContext } from "./multiWindow/windowContext"; + export const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; const THREAD_CHANGED_FILES_EXPANSION_VERSION = 2; const LEGACY_PERSISTED_STATE_KEYS = [ @@ -209,11 +211,101 @@ function sanitizePersistedThreadChangedFilesExpanded( return nextState; } -export function persistState(state: UiState): void { +type SharedUiState = Omit; + +function sameValue(left: unknown, right: unknown): boolean { + return left === right || JSON.stringify(left) === JSON.stringify(right); +} + +function mergeRecord( + stored: Readonly>, + local: Readonly>, + baseline: Readonly>, +): Record { + const merged = { ...stored }; + for (const key of new Set([...Object.keys(local), ...Object.keys(baseline)])) { + if (sameValue(local[key], baseline[key])) continue; + const value = local[key]; + if (value === undefined) delete merged[key]; + else merged[key] = value; + } + return merged; +} + +/** + * Keeps what this window changed since `baseline` (the state it last read or wrote) over + * what other windows saved since. The project filter belongs to each window, so it is left out. + */ +export function mergeSharedUiState( + stored: SharedUiState, + local: SharedUiState, + baseline: SharedUiState, +): SharedUiState { + const pick = (key: K): SharedUiState[K] => + sameValue(local[key], baseline[key]) ? stored[key] : local[key]; + return { + projectExpandedById: mergeRecord( + stored.projectExpandedById, + local.projectExpandedById, + baseline.projectExpandedById, + ), + projectOrder: pick("projectOrder"), + threadLastVisitedAtById: mergeRecord( + stored.threadLastVisitedAtById, + local.threadLastVisitedAtById, + baseline.threadLastVisitedAtById, + ), + threadChangedFilesExpandedById: mergeRecord( + stored.threadChangedFilesExpandedById, + local.threadChangedFilesExpandedById, + baseline.threadChangedFilesExpandedById, + ), + defaultAdvertisedEndpointKey: pick("defaultAdvertisedEndpointKey"), + pullRequestMergeMethod: pick("pullRequestMergeMethod"), + }; +} + +function sharedStateChanged(left: SharedUiState, right: SharedUiState): boolean { + return (Object.keys(right) as Array).some( + (key) => !sameValue(left[key], right[key]), + ); +} + +// Desktop windows share this storage; null outside a multi-window desktop shell. +const windowContext = readDesktopWindowContext(); +let persistedBaseline: UiState | null = null; + +function readStoredState(): UiState | null { + try { + const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); + return raw ? parsePersistedState(JSON.parse(raw) as PersistedUiState) : null; + } catch { + return null; + } +} + +/** What this window writes: its own changes over other windows' saves, and only its own filter. */ +function resolveStateToPersist(state: UiState): UiState { + if (windowContext === null) return state; + const stored = readStoredState(); + if (stored === null) return state; + const merged = mergeSharedUiState(stored, state, persistedBaseline ?? stored); + return { + ...merged, + // A secondary window's filter is its own, never the main window's state. + sidebarProjectScopeKeys: windowContext.isMain + ? state.sidebarProjectScopeKeys + : stored.sidebarProjectScopeKeys, + }; +} + +export function persistState(current: UiState): void { if (typeof window === "undefined") { return; } try { + const state = resolveStateToPersist(current); + persistedBaseline = state; window.localStorage.setItem( PERSISTED_STATE_KEY, JSON.stringify({ @@ -437,8 +529,14 @@ interface UiStateStore extends UiState { ) => void; } +function readInitialState(): UiState { + const state = readPersistedState(); + persistedBaseline = state; + return state; +} + export const useUiStateStore = create((set) => ({ - ...readPersistedState(), + ...readInitialState(), markThreadVisited: (threadId, visitedAt) => set((state) => markThreadVisited(state, threadId, visitedAt)), markThreadUnread: (threadId, latestTurnCompletedAt) => @@ -460,6 +558,19 @@ export const useUiStateStore = create((set) => ({ useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state)); +if (windowContext !== null && typeof window !== "undefined") { + // Another window saved: take its changes to state this window has not changed since. + window.addEventListener("storage", (event) => { + if (event.key !== PERSISTED_STATE_KEY || event.newValue === null) return; + const stored = readStoredState(); + if (stored === null) return; + const local = useUiStateStore.getState(); + const merged = mergeSharedUiState(stored, local, persistedBaseline ?? stored); + persistedBaseline = stored; + if (sharedStateChanged(local, merged)) useUiStateStore.setState(merged); + }); +} + if (typeof window !== "undefined" && typeof window.addEventListener === "function") { window.addEventListener("beforeunload", () => { debouncedPersistState.flush(); diff --git a/docs/README.md b/docs/README.md index 622d31096da05..e1cb610ab8982 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,6 +5,7 @@ - [Install T3 Code](./user/install.md) - [Messages and context](./user/composer.md) - [Working with threads](./user/thread-sidebar.md) +- [Multiple windows](./user/multiple-windows.md) - [Permission modes](./user/permission-modes.md) - [Terminal history](./user/terminal.md) - [Source control](./user/source-control.md) diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index eab9e88ec98f0..b77939bbb6c3b 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -195,6 +195,9 @@ through the pages you have visited, like a browser's back and forward buttons. [new-thread defaults](./thread-sidebar.md#start-a-thread). `chat.newWithoutProject` (`mod+alt+n`) starts a thread [without a project](./thread-sidebar.md#start-without-a-project). +`window.new` (`mod+alt+shift+n`) opens another window in the desktop app. See +[Multiple windows](./multiple-windows.md). + ## Reserved shortcuts In the desktop app, `mod+w` closes the focused terminal or the active right-panel diff --git a/docs/user/multiple-windows.md b/docs/user/multiple-windows.md new file mode 100644 index 0000000000000..7a4934b817309 --- /dev/null +++ b/docs/user/multiple-windows.md @@ -0,0 +1,14 @@ +# Multiple windows + +The desktop app can open more than one window, so you can keep different threads side by side. All +windows share the same environments, threads, and settings. The web app and mobile app use a single +window. + +## Open a window + +Choose **New Window** in the command palette or the app menu, or press **Cmd+Option+Shift+N** on +macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. Change the shortcut under +**Settings → Keybindings** (`window.new`). + +Closing the main window while others are open hides it instead, since the other windows connect +through it. It closes once the last other window does. diff --git a/packages/client-runtime/src/connection/hub.test.ts b/packages/client-runtime/src/connection/hub.test.ts new file mode 100644 index 0000000000000..1b40ab6b9177d --- /dev/null +++ b/packages/client-runtime/src/connection/hub.test.ts @@ -0,0 +1,37 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; + +import { + decodeConnectionAttemptError, + decodePreparedConnection, + encodeConnectionAttemptError, + encodePreparedConnection, +} from "./hub.ts"; +import { ConnectionBlockedError, RelayConnectionTarget, type PreparedConnection } from "./model.ts"; + +describe("HubConnection window boundary", () => { + it("rebuilds a lease's connection and failures after a structured clone", () => { + const prepared: PreparedConnection = { + environmentId: EnvironmentId.make("environment-1"), + label: "Remote", + httpBaseUrl: "https://remote.example.test", + socketUrl: "wss://remote.example.test/ws", + httpAuthorization: { _tag: "Dpop", accessToken: "token", expiresAtEpochMs: 1 }, + target: new RelayConnectionTarget({ + environmentId: EnvironmentId.make("environment-1"), + label: "Remote", + }), + }; + const error = new ConnectionBlockedError({ reason: "permission", detail: "No access." }); + + const received = decodePreparedConnection(structuredClone(encodePreparedConnection(prepared))); + const failure = decodeConnectionAttemptError( + structuredClone(encodeConnectionAttemptError(error)), + ); + + expect(received).toEqual(prepared); + expect(received.target).toBeInstanceOf(RelayConnectionTarget); + expect(failure).toBeInstanceOf(ConnectionBlockedError); + expect(failure.message).toBe("No access."); + }); +}); diff --git a/packages/client-runtime/src/connection/hub.ts b/packages/client-runtime/src/connection/hub.ts new file mode 100644 index 0000000000000..c6b48ca50dd39 --- /dev/null +++ b/packages/client-runtime/src/connection/hub.ts @@ -0,0 +1,195 @@ +import { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import * as ConnectionDriver from "./driver.ts"; +import { + type ConnectionAttemptError, + ConnectionBlockedError, + ConnectionTarget, + ConnectionTransientError, + type PreparedConnection, +} from "./model.ts"; +import * as EnvironmentRegistry from "./registry.ts"; +import * as EnvironmentSupervisor from "./supervisor.ts"; +import type { RpcPort } from "../rpc/relay.ts"; +import * as RpcSession from "../rpc/session.ts"; + +const PreparedHttpAuthorization = Schema.Union([ + Schema.TaggedStruct("Bearer", { token: Schema.String }), + Schema.TaggedStruct("Dpop", { accessToken: Schema.String, expiresAtEpochMs: Schema.Number }), +]); + +const PreparedConnectionSchema = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + httpBaseUrl: Schema.String, + socketUrl: Schema.String, + httpAuthorization: Schema.NullOr(PreparedHttpAuthorization), + target: ConnectionTarget, + descriptor: Schema.optionalKey(ExecutionEnvironmentDescriptor), +}); + +const ConnectionAttemptErrorSchema = Schema.Union([ + ConnectionTransientError, + ConnectionBlockedError, +]); + +/** Plain values for crossing a window boundary, where class instances lose their prototype. */ +export const encodePreparedConnection = Schema.encodeSync( + Schema.toCodecJson(PreparedConnectionSchema), +); +export const decodePreparedConnection = Schema.decodeUnknownSync( + Schema.toCodecJson(PreparedConnectionSchema), +); +export const encodeConnectionAttemptError = Schema.encodeSync( + Schema.toCodecJson(ConnectionAttemptErrorSchema), +); +export const decodeConnectionAttemptError = Schema.decodeUnknownSync( + Schema.toCodecJson(ConnectionAttemptErrorSchema), +); + +export interface HubLease { + readonly prepared: PreparedConnection; + readonly port: RpcPort; +} + +/** How a secondary window asks the hub window for one environment's connection. */ +export class HubLeaseSource extends Context.Service< + HubLeaseSource, + { + /** The lease ends, and the hub stops relaying, when the scope closes. */ + readonly lease: ( + environmentId: EnvironmentId, + ) => Effect.Effect; + } +>()("@t3tools/client-runtime/connection/hub/HubLeaseSource") {} + +/** + * The connection driver of a secondary window: every environment connects + * through the hub window's existing session instead of a socket of its own. + */ +const makeHubDriver = Effect.gen(function* () { + const hub = yield* HubLeaseSource; + const sessions = yield* RpcSession.RpcSessionFactory; + return ConnectionDriver.ConnectionDriver.of({ + connect: Effect.fn("HubConnectionDriver.connect")(function* (entry, reportProgress) { + yield* Effect.annotateCurrentSpan({ + "connection.environment.id": entry.target.environmentId, + }); + yield* reportProgress({ stage: "preparing" }); + const { prepared, port } = yield* hub.lease(entry.target.environmentId); + yield* reportProgress({ stage: "opening", prepared }); + const session = yield* sessions.connectOverPort(prepared, port); + yield* reportProgress({ stage: "synchronizing", prepared }); + yield* session.ready; + // The hub owns route choice, so it alone reports refused routes. + return { + prepared, + session, + refusedRouteIds: [], + } satisfies ConnectionDriver.EnvironmentConnectionLease; + }), + // Route choice belongs to the hub, which owns the socket. + preflight: Effect.fn("HubConnectionDriver.preflight")(function* () { + return yield* Effect.succeed("unchecked" as const); + }), + checkHost: Effect.fn("HubConnectionDriver.checkHost")(function* () { + return yield* Effect.succeed("answered" as const); + }), + }); +}); + +export const layerHubDriver = Layer.effect(ConnectionDriver.ConnectionDriver, makeHubDriver); + +type HubSessionState = + | { + readonly _tag: "Ready"; + readonly prepared: PreparedConnection; + readonly session: RpcSession.RpcSession; + } + | { readonly _tag: "Blocked"; readonly error: ConnectionAttemptError }; + +const hubSessionStates = Stream.unwrap( + Effect.gen(function* () { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + return Stream.merge( + SubscriptionRef.changes(supervisor.session), + SubscriptionRef.changes(supervisor.state), + ).pipe( + Stream.mapEffect(() => + Effect.all([ + SubscriptionRef.get(supervisor.session), + SubscriptionRef.get(supervisor.prepared), + SubscriptionRef.get(supervisor.state), + ]), + ), + Stream.map(([session, prepared, state]): Option.Option => { + if (Option.isSome(session) && Option.isSome(prepared)) { + return Option.some({ _tag: "Ready", prepared: prepared.value, session: session.value }); + } + if (state.phase === "blocked" && state.lastFailure !== null) { + return Option.some({ _tag: "Blocked", error: state.lastFailure }); + } + return Option.none(); + }), + Stream.filter(Option.isSome), + Stream.map((state) => state.value), + ); + }), +); + +/** + * The hub's side of a lease: waits for this window's own session to the + * environment, then relays `port` through it until the scope closes or the + * session ends. A blocked environment fails the lease with its own error. + */ +export const serveHubLease = Effect.fn("HubConnection.serveLease")(function* ( + environmentId: EnvironmentId, + port: RpcPort, +) { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + const head = yield* registry.followStream(environmentId, hubSessionStates).pipe(Stream.runHead); + if (Option.isNone(head)) { + return yield* new ConnectionTransientError({ + reason: "endpoint-unavailable", + detail: "The main window no longer has this environment.", + }); + } + const state = head.value; + if (state._tag === "Blocked") return yield* state.error; + const { prepared, session } = state; + if (session.relay === undefined) { + return yield* new ConnectionTransientError({ + reason: "transport", + detail: `${prepared.label} cannot be shared with another window.`, + }); + } + const relay = yield* session.relay(port); + // A session that ends or is replaced takes its relays with it, so the window reconnects at once. + const supervisor = yield* registry + .run(environmentId, EnvironmentSupervisor.EnvironmentSupervisor) + .pipe( + Effect.mapError( + () => + new ConnectionTransientError({ + reason: "endpoint-unavailable", + detail: "The main window no longer has this environment.", + }), + ), + ); + yield* Effect.raceFirst( + session.closed.pipe(Effect.ignore), + SubscriptionRef.changes(supervisor.session).pipe( + Stream.filter((current) => Option.getOrNull(current) !== session), + Stream.runHead, + ), + ).pipe(Effect.andThen(relay.close("The main window's connection ended.")), Effect.forkScoped); + return prepared; +}); diff --git a/packages/client-runtime/src/connection/index.ts b/packages/client-runtime/src/connection/index.ts index 02a30adb57fae..7c7c6d8fe9388 100644 --- a/packages/client-runtime/src/connection/index.ts +++ b/packages/client-runtime/src/connection/index.ts @@ -17,6 +17,7 @@ export * as EnvironmentRegistry from "./registry.ts"; // Flat so consumers' inferred types can name them. export { EnvironmentNotRegisteredError, PlatformEnvironmentRemovalError } from "./registry.ts"; export * as EnvironmentSupervisor from "./supervisor.ts"; +export * as HubConnection from "./hub.ts"; export * as Wakeups from "./wakeups.ts"; export { orchestrationProtocolCompatibilityError } from "./compatibility.ts"; diff --git a/packages/client-runtime/src/connection/layer.ts b/packages/client-runtime/src/connection/layer.ts index 0ab9e0d2f96b1..dd6ada5dddef0 100644 --- a/packages/client-runtime/src/connection/layer.ts +++ b/packages/client-runtime/src/connection/layer.ts @@ -8,6 +8,7 @@ import { orchestrationProtocolCompatibilityError } from "./compatibility.ts"; import * as ConnectionResolver from "./resolver.ts"; import * as ConnectionDriver from "./driver.ts"; +import * as HubConnection from "./hub.ts"; import * as EnvironmentRegistry from "./registry.ts"; import * as ConnectionOnboarding from "./onboarding.ts"; import { connectionRoutes, hasRelayRoute } from "./routes.ts"; @@ -71,10 +72,22 @@ export const watchDiscoveredCompatibility = Effect.fn("connection.watchDiscovere }, ); -export function layerWithOptions(options: RpcSession.RpcSessionOptions) { - const layerDriver = ConnectionDriver.layer.pipe( - Layer.provide(Layer.mergeAll(ConnectionResolver.layer, RpcSession.layer(options))), +/** + * With `hubLeases`, environments connect through another window's sessions + * (see `HubConnection`) instead of opening sockets of their own. + */ +export function layerWithOptions( + options: RpcSession.RpcSessionOptions, + hubLeases?: Layer.Layer, +) { + const layerSessions = RpcSession.layer(options); + const layerSocketDriver = ConnectionDriver.layer.pipe( + Layer.provide(Layer.mergeAll(ConnectionResolver.layer, layerSessions)), ); + const layerDriver: typeof layerSocketDriver = + hubLeases === undefined + ? layerSocketDriver + : HubConnection.layerHubDriver.pipe(Layer.provide(Layer.mergeAll(layerSessions, hubLeases))); const layerRegistry = EnvironmentRegistry.layer.pipe(Layer.provide(layerDriver)); const layerOnboarding = ConnectionOnboarding.layer.pipe(Layer.provide(layerRegistry)); const layerConnectionServices = Layer.mergeAll( diff --git a/packages/client-runtime/src/rpc/index.ts b/packages/client-runtime/src/rpc/index.ts index e0e269bdfa8ad..1e970329e9116 100644 --- a/packages/client-runtime/src/rpc/index.ts +++ b/packages/client-runtime/src/rpc/index.ts @@ -2,3 +2,4 @@ export * from "./client.ts"; export * from "./http.ts"; export type { WsRpcProtocolClient } from "./protocol.ts"; export { type RpcSession } from "./session.ts"; +export { type RpcPort } from "./relay.ts"; diff --git a/packages/client-runtime/src/rpc/relay.ts b/packages/client-runtime/src/rpc/relay.ts new file mode 100644 index 0000000000000..cbceb3682a5b8 --- /dev/null +++ b/packages/client-runtime/src/rpc/relay.ts @@ -0,0 +1,357 @@ +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import * as RpcClient from "effect/rpc/RpcClient"; +import * as RpcClientError from "effect/rpc/RpcClientError"; +import type { FromClientEncoded, FromServerEncoded, RequestEncoded } from "effect/rpc/RpcMessage"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; + +/** + * One end of a message channel carrying encoded RPC messages, such as a DOM + * `MessagePort` between two windows. Messages are plain JSON-compatible values. + */ +export interface RpcPort { + readonly postMessage: (message: unknown) => void; + readonly onMessage: (listener: (message: unknown) => void) => () => void; + readonly close: () => void; +} + +/** Sent by the relay instead of forwarding a transport failure, then the port closes. */ +export interface RelayClosedMessage { + readonly _tag: "RelayClosed"; + readonly detail: string; +} + +/** Fails only these requests, which then resubscribe; the relay stays open. */ +interface RelayRequestsFailedMessage { + readonly _tag: "RelayRequestsFailed"; + readonly requestIds: ReadonlyArray; + readonly detail: string; +} + +const relayTag = (message: unknown): unknown => + typeof message === "object" && message !== null + ? (message as { readonly _tag?: unknown })._tag + : undefined; +const isRelayClosedMessage = (message: unknown): message is RelayClosedMessage => + relayTag(message) === "RelayClosed"; +const isRelayRequestsFailedMessage = (message: unknown): message is RelayRequestsFailedMessage => + relayTag(message) === "RelayRequestsFailed"; + +export interface RelayHandle { + /** Ends the relay now; the secondary's session closes and reconnects. */ + readonly close: (detail: string) => Effect.Effect; +} + +/** + * A stream the relay serves from state the hub already holds instead of + * opening another subscription on the server. `encode` turns a chunk of + * `items` into the RPC's encoded chunk values. + */ +export interface SharedRelayStream { + readonly tag: string; + readonly matches: (payload: unknown) => boolean; + readonly items: Stream.Stream; + readonly encode: (values: ReadonlyArray) => Effect.Effect; +} + +/** Runs port messages one at a time and in arrival order, like a socket's frames. */ +const makeSerialRunner = ( + runFork: (effect: Effect.Effect) => unknown, + handle: (message: A) => Effect.Effect, +) => { + const queue: Array = []; + let draining = false; + const drain = Effect.gen(function* () { + while (queue.length > 0) { + yield* handle(queue.shift()!); + } + }).pipe( + Effect.ensuring( + Effect.sync(() => { + draining = false; + }), + ), + ); + return (message: A) => { + queue.push(message); + if (draining) return; + draining = true; + runFork(drain); + }; +}; + +// RpcClient numbers its clients from 0 within one JavaScript realm, so relay +// clients sharing the hub's protocol start far above any realistic count. +let nextRelayClientId = 1_000_000_000; + +/** + * Serves a secondary window's RpcClient over `port` through the hub's socket. + * Request ids are renamed on the way in and restored on the way out: each + * window numbers requests from its own counter, and the server keys them per socket. + */ +export const serveRelay = Effect.fnUntraced(function* (options: { + readonly protocol: RpcClient.Protocol["Service"]; + readonly port: RpcPort; + readonly shared?: ReadonlyArray; +}): Effect.fn.Return { + const { protocol, port } = options; + const runFork = Effect.runForkWith(yield* Effect.context()); + const clientId = nextRelayClientId++; + const prefix = `relay${clientId}:`; + // Hub id -> the secondary's original id, whose type the secondary's client keys on. + const forwarded = new Map(); + const sharedFibers = new Map>(); + let closed = false; + + const toHubId = (id: string | number) => `${prefix}${String(id)}`; + + // The port itself closes with the scope: closing right after the last post could drop it. + const close = (detail: string) => + Effect.sync(() => { + if (closed) return; + closed = true; + try { + port.postMessage({ _tag: "RelayClosed", detail } satisfies RelayClosedMessage); + } catch {} + }); + + const post = (message: FromServerEncoded) => + Effect.sync(() => { + if (!closed) port.postMessage(message); + }); + + const restore = (requestId: string | number) => + typeof requestId === "string" ? forwarded.get(requestId) : undefined; + + yield* protocol + .run(clientId, (response) => { + switch (response._tag) { + case "Chunk": + case "Exit": { + const original = restore(response.requestId); + if (original === undefined) return Effect.void; + if (response._tag === "Exit") forwarded.delete(String(response.requestId)); + return post({ ...response, requestId: original }); + } + case "ClientProtocolError": { + if (response.requestIds === undefined) return close(response.error.message); + const requestIds = response.requestIds.flatMap((requestId) => { + const original = restore(requestId); + if (original === undefined) return []; + forwarded.delete(String(requestId)); + return [original]; + }); + if (requestIds.length === 0) return Effect.void; + return Effect.sync(() => { + if (closed) return; + port.postMessage({ + _tag: "RelayRequestsFailed", + requestIds, + detail: response.error.message, + } satisfies RelayRequestsFailedMessage); + }); + } + case "Pong": + return Effect.void; + default: + return post(response); + } + }) + .pipe(Effect.forkScoped); + + const serveShared = (shared: SharedRelayStream, request: RequestEncoded) => { + const fiber = shared.items.pipe( + Stream.runForEachArray((values) => + values.length === 0 + ? Effect.void + : shared + .encode(values) + .pipe( + Effect.flatMap((encoded) => + post({ _tag: "Chunk", requestId: request.id, values: encoded as never }), + ), + ), + ), + // Shared streams outlive any one subscriber, so their end means the hub's session ended. + Effect.matchCauseEffect({ + onSuccess: () => close("The main window's shared subscription ended."), + onFailure: (cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : close("The main window's shared subscription failed."), + }), + Effect.ensuring(Effect.sync(() => sharedFibers.delete(request.id))), + ); + sharedFibers.set(request.id, runFork(fiber)); + }; + + const handle = (message: FromClientEncoded): Effect.Effect => { + switch (message._tag) { + case "Request": { + const shared = options.shared?.find( + (candidate) => candidate.tag === message.tag && candidate.matches(message.payload), + ); + if (shared !== undefined) { + serveShared(shared, message); + return Effect.void; + } + const hubId = toHubId(message.id); + forwarded.set(hubId, message.id); + return protocol.send(clientId, { ...message, id: hubId }).pipe( + Effect.catch((error: RpcClientError.RpcClientError) => { + forwarded.delete(hubId); + return close(error.message); + }), + ); + } + case "Ack": + case "Interrupt": { + const fiber = sharedFibers.get(message.requestId); + if (fiber !== undefined) { + return message._tag === "Interrupt" ? Fiber.interrupt(fiber) : Effect.void; + } + const hubId = toHubId(message.requestId); + if (!forwarded.has(hubId)) return Effect.void; + if (message._tag === "Interrupt") forwarded.delete(hubId); + return protocol + .send(clientId, { ...message, requestId: hubId }) + .pipe(Effect.catch((error) => close(error.message))); + } + default: + return Effect.void; + } + }; + + const enqueue = makeSerialRunner(runFork, handle); + const stopListening = port.onMessage((message) => { + if (!closed) enqueue(message as FromClientEncoded); + }); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + stopListening(); + for (const fiber of sharedFibers.values()) yield* Fiber.interrupt(fiber); + // The server keeps streaming to an abandoned id until it hears an interrupt. + for (const hubId of forwarded.keys()) { + yield* protocol.send(clientId, { _tag: "Interrupt", requestId: hubId }).pipe(Effect.ignore); + } + forwarded.clear(); + yield* close("The main window closed this connection."); + port.close(); + }), + ); + + return { + close: Effect.fn("RelayHandle.close")(function* (detail: string) { + for (const fiber of sharedFibers.values()) yield* Fiber.interrupt(fiber); + yield* close(detail); + }), + } satisfies RelayHandle; +}); + +/** + * The secondary window's end: an RpcClient protocol whose requests travel over + * `port` to a relay in the hub. `onClosed` runs once when the relay goes away. + */ +export const makePortProtocol = (options: { + readonly port: RpcPort; + readonly onMessage?: () => void; + readonly onClosed: (detail: string) => Effect.Effect; +}): Effect.Effect => + RpcClient.Protocol.make( + Effect.fnUntraced(function* (writeResponse, clientIds) { + const { port } = options; + const runFork = Effect.runForkWith(yield* Effect.context()); + const requestClients = new Map(); + let closedError: RpcClientError.RpcClientError | undefined; + + const broadcast = (response: FromServerEncoded) => + Effect.forEach(Array.from(clientIds), (clientId) => writeResponse(clientId, response), { + discard: true, + }); + + const fail = (detail: string) => + Effect.suspend(() => { + if (closedError !== undefined) return Effect.void; + closedError = new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ message: detail, cause: undefined }), + }); + requestClients.clear(); + return broadcast({ _tag: "ClientProtocolError", error: closedError }).pipe( + Effect.uninterruptible, + Effect.andThen(options.onClosed(detail)), + ); + }); + + const receive = (message: unknown): Effect.Effect => { + if (isRelayClosedMessage(message)) return fail(message.detail); + if (isRelayRequestsFailedMessage(message)) { + const error = new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: message.detail, + cause: undefined, + }), + }); + return Effect.forEach( + message.requestIds, + (requestId) => { + const clientId = requestClients.get(requestId); + requestClients.delete(requestId); + return clientId === undefined + ? Effect.void + : writeResponse(clientId, { + _tag: "ClientProtocolError", + error, + requestIds: [requestId], + }); + }, + { discard: true }, + ); + } + const response = message as FromServerEncoded; + if ("requestId" in response) { + const clientId = requestClients.get(response.requestId); + if (clientId === undefined) return Effect.void; + if (response._tag === "Exit") requestClients.delete(response.requestId); + return writeResponse(clientId, response); + } + return broadcast(response); + }; + + const enqueue = makeSerialRunner(runFork, receive); + const stopListening = port.onMessage((message) => { + options.onMessage?.(); + enqueue(message); + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + stopListening(); + port.close(); + }), + ); + + return { + send: (_clientId, request) => { + if (closedError !== undefined) return Effect.fail(closedError); + switch (request._tag) { + case "Request": + requestClients.set(request.id, _clientId); + break; + case "Interrupt": + requestClients.delete(request.requestId); + break; + case "Ping": + case "Eof": + return Effect.void; + } + return Effect.sync(() => port.postMessage(request)); + }, + supportsAck: true, + supportsTransferables: false, + codecFor: RpcSerialization.json.codecFor, + }; + }), + ); diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 27bb60f567e10..d7e0fb326e2c8 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -1,6 +1,10 @@ import { DEFAULT_SERVER_SETTINGS, EnvironmentId, + ORCHESTRATION_V2_WS_METHODS, + type OrchestrationV2SubscribeShellInput, + type OrchestrationV2SubscribeThreadInput, + ThreadId, ServerConfig, type ServerConfig as ServerConfigType, ServerConfigStreamEvent, @@ -20,6 +24,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Socket from "effect/socket/Socket"; @@ -34,7 +39,9 @@ import { } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as Persistence from "../platform/persistence.ts"; +import type { RpcPort } from "./relay.ts"; import * as RpcSession from "./session.ts"; +import { AHEAD_CURSOR_GRACE, SLOW_SUBSCRIBER_TIMEOUT } from "./sharedStreams.ts"; import { toServerClock } from "../clock.ts"; import { makeEnvironmentServerConfigState } from "../state/server.ts"; import { applyServerConfigProjection } from "../state/serverConfigProjection.ts"; @@ -1229,3 +1236,508 @@ describe("RpcSessionFactory", () => { }), ); }); + +/** An in-memory MessageChannel: delivery is async and structured-cloned, like a real port. */ +function makePortPair(): readonly [RpcPort, RpcPort] { + const listeners = [new Set<(message: unknown) => void>(), new Set<(message: unknown) => void>()]; + let closed = false; + const end = (self: 0 | 1): RpcPort => ({ + postMessage: (message) => { + if (closed) return; + const copy = structuredClone(message); + queueMicrotask(() => { + for (const listener of listeners[self === 0 ? 1 : 0]!) listener(copy); + }); + }, + onMessage: (listener) => { + listeners[self]!.add(listener); + return () => listeners[self]!.delete(listener); + }, + close: () => { + closed = true; + }, + }); + return [end(0), end(1)]; +} + +const connectHubAndWindows = Effect.fn("TestRpcSessionFactory.connectHubAndWindows")(function* ( + count: number, +) { + const { factory, sockets } = yield* makeFactory({ shareStreams: true }); + const hub = yield* factory.connect(PREPARED); + const hubReady = yield* Effect.forkChild(hub.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(hubReady); + const windows: Array = []; + for (let index = 0; index < count; index++) { + const [hubPort, windowPort] = makePortPair(); + yield* hub.relay!(hubPort); + const secondary = yield* factory.connectOverPort(PREPARED, windowPort); + yield* secondary.ready; + windows.push(secondary); + } + return { hub, windows, socket, sockets }; +}); + +const connectHubAndWindow = Effect.fn("TestRpcSessionFactory.connectHubAndWindow")(function* () { + const { hub, windows, socket, sockets } = yield* connectHubAndWindows(1); + return { hub, secondary: windows[0]!, socket, sockets }; +}); + +const sentRequests = (socket: TestWebSocket) => + socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest); + +const LEGACY_MIGRATION_EVENT = { + version: 1, + sequence: 1, + type: "legacyThreadMigration", + payload: { status: "running", totalThreadCount: 3 }, +}; + +describe("hub relay", () => { + it.effect("serves a window's config from the hub's replay without a second subscription", () => + Effect.gen(function* () { + const { secondary, socket, sockets } = yield* connectHubAndWindow(); + + expect(yield* secondary.initialConfig).toEqual(SERVER_CONFIG); + expect(sentRequests(socket).map((request) => request.tag)).toEqual([ + WS_METHODS.subscribeServerConfig, + ]); + expect(sockets).toHaveLength(1); + }).pipe(Effect.scoped), + ); + + it.effect("sends a window's requests over the hub's socket under ids the hub cannot reuse", () => + Effect.gen(function* () { + const { hub, secondary, socket } = yield* connectHubAndWindow(); + + const windowProbe = yield* Effect.forkChild(secondary.probe); + const relayed = yield* awaitRequest(socket, 1); + const hubProbe = yield* Effect.forkChild(hub.probe); + const native = yield* awaitRequest(socket, 2); + + expect(relayed.tag).toBe(WS_METHODS.serverProbe); + expect(String(relayed.id)).toMatch(/^relay\d+:/); + expect(relayed.id).not.toEqual(native.id); + socket.serverMessage( + encodeJson({ _tag: "Exit", requestId: relayed.id, exit: { _tag: "Success", value: {} } }), + ); + yield* Fiber.join(windowProbe); + expect(hubProbe.pollUnsafe()).toBeUndefined(); + socket.serverMessage( + encodeJson({ _tag: "Exit", requestId: native.id, exit: { _tag: "Success", value: {} } }), + ); + yield* Fiber.join(hubProbe); + }).pipe(Effect.scoped), + ); + + it.effect("forwards stream chunks, acks and interrupts under the relayed id", () => + Effect.gen(function* () { + const { secondary, socket } = yield* connectHubAndWindow(); + const received = yield* Queue.unbounded(); + const subscription = yield* secondary.client[WS_METHODS.subscribeServerLifecycle]({}).pipe( + Stream.runForEach((event) => Queue.offer(received, event)), + Effect.forkChild, + ); + const request = yield* awaitRequest(socket, 1); + socket.serverMessage( + encodeJson({ _tag: "Chunk", requestId: request.id, values: [LEGACY_MIGRATION_EVENT] }), + ); + + expect(yield* Queue.take(received)).toEqual(LEGACY_MIGRATION_EVENT); + const sentAfter = (tag: string) => + socket.sent + .map((message) => decodeJson(message) as { _tag: string; requestId?: unknown }) + .filter((message) => message._tag === tag && message.requestId === request.id); + while (sentAfter("Ack").length === 0) yield* Queue.take(socket.sentChanges); + expect(sentAfter("Ack")).toEqual([{ _tag: "Ack", requestId: request.id }]); + + yield* Fiber.interrupt(subscription); + while (sentAfter("Interrupt").length === 0) yield* Queue.take(socket.sentChanges); + expect(sentAfter("Interrupt")).toEqual([{ _tag: "Interrupt", requestId: request.id }]); + }).pipe(Effect.scoped), + ); + + it.effect("closes the window's session when the hub's socket drops", () => + Effect.gen(function* () { + const { secondary, socket } = yield* connectHubAndWindow(); + const pending = yield* Effect.forkChild(Effect.flip(secondary.probe)); + yield* awaitRequest(socket, 1); + + socket.close(1006); + + expect(yield* Effect.flip(secondary.closed)).toBeInstanceOf(ConnectionTransientError); + expect(yield* Fiber.join(pending)).toBeInstanceOf(ConnectionTransientError); + }).pipe(Effect.scoped), + ); + + it.effect("interrupts a window's open streams on the server when the relay ends", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const hub = yield* factory.connect(PREPARED); + const hubReady = yield* Effect.forkChild(hub.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(hubReady); + const [hubPort, windowPort] = makePortPair(); + const relayScope = yield* Scope.make(); + yield* hub.relay!(hubPort).pipe(Scope.provide(relayScope)); + const secondary = yield* factory.connectOverPort(PREPARED, windowPort); + yield* secondary.ready; + yield* secondary.client[WS_METHODS.subscribeServerLifecycle]({}).pipe( + Stream.runDrain, + Effect.forkChild, + ); + const request = yield* awaitRequest(socket, 1); + + yield* Scope.close(relayScope, Exit.void); + + expect( + socket.sent + .map((message) => decodeJson(message) as { _tag: string }) + .filter((message) => message._tag === "Interrupt"), + ).toEqual([{ _tag: "Interrupt", requestId: request.id }]); + expect(yield* Effect.flip(secondary.closed)).toBeInstanceOf(ConnectionTransientError); + }).pipe(Effect.scoped), + ); +}); + +const shellEvent = (sequence: number) => ({ + kind: "project.removed", + sequence, + projectId: `project-${sequence}`, +}); +const threadEvent = (sequence: number) => ({ + kind: "event", + sequence, + event: { type: "test.unknown-event" }, +}); +const SYNCHRONIZED = { kind: "synchronized" }; +const THREAD_ID = ThreadId.make("thread-1"); + +const followShell = Effect.fn("TestSharedStreams.followShell")(function* ( + session: RpcSession.RpcSession, + input: OrchestrationV2SubscribeShellInput, +) { + const items = yield* Queue.unbounded(); + const fiber = yield* session.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell](input).pipe( + Stream.runForEach((item) => Queue.offer(items, item)), + Effect.forkChild, + ); + return { items, fiber }; +}); + +const followThread = Effect.fn("TestSharedStreams.followThread")(function* ( + session: RpcSession.RpcSession, + input: OrchestrationV2SubscribeThreadInput, +) { + const items = yield* Queue.unbounded(); + const fiber = yield* session.client[ORCHESTRATION_V2_WS_METHODS.subscribeThread](input).pipe( + Stream.runForEach((item) => Queue.offer(items, item)), + Effect.forkChild, + ); + return { items, fiber }; +}); + +const takeItems = Effect.fn("TestSharedStreams.takeItems")(function* ( + items: Queue.Queue, + count: number, +) { + const taken: Array = []; + for (let index = 0; index < count; index++) taken.push(yield* Queue.take(items)); + return taken; +}); + +const serverChunk = (socket: TestWebSocket, requestId: unknown, values: ReadonlyArray) => + socket.serverMessage(encodeJson({ _tag: "Chunk", requestId, values })); + +const sentMessages = (socket: TestWebSocket) => + socket.sent.map((message) => decodeJson(message) as { _tag: string; requestId?: unknown }); + +const shellRequests = (socket: TestWebSocket) => + sentRequests(socket).filter( + (request) => request.tag === ORCHESTRATION_V2_WS_METHODS.subscribeShell, + ); +const activeUpstreams = (socket: TestWebSocket, tag: string) => { + const interrupted = new Set( + sentMessages(socket) + .filter((message) => message._tag === "Interrupt") + .map((message) => message.requestId), + ); + return sentRequests(socket).filter( + (request) => request.tag === tag && !interrupted.has(request.id), + ); +}; +const awaitShellRequest = Effect.fn("TestSharedStreams.awaitShellRequest")(function* ( + socket: TestWebSocket, + index: number, +) { + for (;;) { + const request = shellRequests(socket)[index]; + if (request) return request; + yield* Queue.take(socket.sentChanges); + } +}); +const acksFor = (socket: TestWebSocket, requestId: unknown) => + sentMessages(socket).filter( + (message) => message._tag === "Ack" && message.requestId === requestId, + ).length; +const awaitAcks = Effect.fn("TestSharedStreams.awaitAcks")(function* ( + socket: TestWebSocket, + requestId: unknown, + count: number, +) { + while (acksFor(socket, requestId) < count) yield* Queue.take(socket.sentChanges); +}); +const enrichment = (snapshotSequence: number) => ({ + kind: "snapshot", + snapshot: { schemaVersion: 1, snapshotSequence, threads: [], archivedThreads: [], projects: [] }, + resolvedRepositoryIdentityRoots: [], +}); +const authoritativeShell = (snapshotSequence: number) => ({ + kind: "snapshot", + snapshot: { schemaVersion: 1, snapshotSequence, threads: [], archivedThreads: [], projects: [] }, +}); + +describe("shared hub subscriptions", () => { + it.effect("leaves web and mobile sessions, and a lone subscriber, untouched", () => + Effect.gen(function* () { + const plain = yield* makeFactory(); + const session = yield* plain.factory.connect(PREPARED); + const plainSocket = yield* awaitSocket(plain.sockets); + plainSocket.open(); + yield* completeInitialConfig(plainSocket); + yield* followShell(session, { afterSequence: 5 }); + expect(typeof (yield* awaitRequest(plainSocket, 1)).id).toBe("number"); + + const { hub, socket } = yield* connectHubAndWindows(0); + const payload = { + afterSequence: 5, + httpSnapshotFallback: true, + knownProjectIdentities: "identities", + requestCompletionMarker: true, + } as const; + const lone = yield* followShell(hub, payload); + const request = yield* awaitShellRequest(socket, 0); + expect(request.payload).toEqual(payload); + serverChunk(socket, request.id, [shellEvent(6), SYNCHRONIZED]); + expect(yield* takeItems(lone.items, 2)).toMatchObject([{ sequence: 6 }, SYNCHRONIZED]); + yield* awaitAcks(socket, request.id, 1); + }).pipe(Effect.scoped), + ); + + it.effect("holds one shell and one thread subscription for the hub and two windows", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(2); + const [first, second] = [windows[0]!, windows[1]!]; + + const hubShell = yield* followShell(hub, { afterSequence: 5, requestCompletionMarker: true }); + const lone = yield* awaitShellRequest(socket, 0); + serverChunk(socket, lone.id, [shellEvent(6), shellEvent(7), SYNCHRONIZED]); + yield* takeItems(hubShell.items, 3); + + const firstShell = yield* followShell(first, { + afterSequence: 6, + requestCompletionMarker: true, + }); + const shared = yield* awaitShellRequest(socket, 1); + expect(shared.payload).toEqual({ afterSequence: 6, requestCompletionMarker: true }); + serverChunk(socket, shared.id, [shellEvent(7), SYNCHRONIZED]); + expect(yield* takeItems(firstShell.items, 2)).toMatchObject([{ sequence: 7 }, SYNCHRONIZED]); + + const secondShell = yield* followShell(second, { afterSequence: 7 }); + const reshared = yield* awaitShellRequest(socket, 2); + expect(reshared.payload).toEqual({ afterSequence: 7, requestCompletionMarker: true }); + serverChunk(socket, reshared.id, [SYNCHRONIZED]); + + const hubThread = yield* followThread(hub, { + threadId: THREAD_ID, + afterSequence: 1, + requestCompletionMarker: true, + }); + const loneThread = yield* awaitRequest(socket, 4); + serverChunk(socket, loneThread.id, [threadEvent(2), SYNCHRONIZED]); + yield* takeItems(hubThread.items, 2); + const firstThread = yield* followThread(first, { + threadId: THREAD_ID, + afterSequence: 1, + requestCompletionMarker: true, + }); + const sharedThread = yield* awaitRequest(socket, 5); + serverChunk(socket, sharedThread.id, [threadEvent(2), SYNCHRONIZED]); + expect(yield* takeItems(firstThread.items, 2)).toMatchObject([ + { kind: "unknown-event", sequence: 2 }, + SYNCHRONIZED, + ]); + + serverChunk(socket, reshared.id, [shellEvent(8)]); + serverChunk(socket, sharedThread.id, [threadEvent(3)]); + for (const shell of [hubShell, firstShell, secondShell]) { + expect(yield* Queue.take(shell.items)).toMatchObject({ sequence: 8 }); + } + for (const thread of [hubThread, firstThread]) { + expect(yield* Queue.take(thread.items)).toMatchObject({ sequence: 3 }); + } + // Nothing was delivered twice: the hub's replayed 7 and 2 were skipped. + expect(Queue.sizeUnsafe(hubShell.items)).toBe(0); + expect(Queue.sizeUnsafe(hubThread.items)).toBe(0); + expect(activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeShell)).toHaveLength(1); + expect(activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeThread)).toHaveLength(1); + }).pipe(Effect.scoped), + ); + + it.effect("keeps a resume replay that follows a project enrichment snapshot", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(1); + const hubShell = yield* followShell(hub, { afterSequence: 5 }); + yield* awaitShellRequest(socket, 0); + const late = yield* followShell(windows[0]!, { + afterSequence: 5, + requestCompletionMarker: true, + }); + const shared = yield* awaitShellRequest(socket, 1); + + serverChunk(socket, shared.id, [enrichment(9), shellEvent(6), shellEvent(7), SYNCHRONIZED]); + + expect(yield* takeItems(late.items, 4)).toMatchObject([ + { kind: "snapshot", resolvedRepositoryIdentityRoots: [] }, + { sequence: 6 }, + { sequence: 7 }, + SYNCHRONIZED, + ]); + expect(yield* takeItems(hubShell.items, 3)).toMatchObject([ + { kind: "snapshot" }, + { sequence: 6 }, + { sequence: 7 }, + ]); + }).pipe(Effect.scoped), + ); + + it.effect("gives a window that wants a fresh snapshot one, never snapshot-required", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(1); + yield* followShell(hub, { + afterSequence: 5, + httpSnapshotFallback: true, + requestCompletionMarker: true, + }); + yield* awaitShellRequest(socket, 0); + const fresh = yield* followShell(windows[0]!, { requestCompletionMarker: true }); + const shared = yield* awaitShellRequest(socket, 1); + + expect(shared.payload).toEqual({ requestCompletionMarker: true }); + serverChunk(socket, shared.id, [authoritativeShell(20), SYNCHRONIZED]); + expect(yield* takeItems(fresh.items, 2)).toMatchObject([ + { kind: "snapshot", snapshot: { snapshotSequence: 20 } }, + SYNCHRONIZED, + ]); + }).pipe(Effect.scoped), + ); + + it.effect("starts everyone over when a window's cursor is beyond the server's history", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(1); + yield* followShell(hub, { afterSequence: 5, requestCompletionMarker: true }); + const lone = yield* awaitShellRequest(socket, 0); + serverChunk(socket, lone.id, [shellEvent(6), SYNCHRONIZED]); + const ahead = yield* followShell(windows[0]!, { + afterSequence: 100, + requestCompletionMarker: true, + }); + const shared = yield* awaitShellRequest(socket, 1); + expect(shared.payload).toEqual({ afterSequence: 6, requestCompletionMarker: true }); + serverChunk(socket, shared.id, [SYNCHRONIZED]); + + yield* TestClock.adjust(AHEAD_CURSOR_GRACE); + const restarted = yield* awaitShellRequest(socket, 2); + expect(restarted.payload).toEqual({ requestCompletionMarker: true }); + serverChunk(socket, restarted.id, [authoritativeShell(7), SYNCHRONIZED]); + expect(yield* takeItems(ahead.items, 2)).toMatchObject([ + { kind: "snapshot", snapshot: { snapshotSequence: 7 } }, + SYNCHRONIZED, + ]); + }).pipe(Effect.scoped), + ); + + it.effect("acks upstream for the slowest subscriber and resyncs one that stays behind", () => + Effect.gen(function* () { + const { hub, socket } = yield* connectHubAndWindows(0); + const fast = yield* followShell(hub, { afterSequence: 1 }); + yield* awaitShellRequest(socket, 0); + const slow = yield* hub.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]( + { afterSequence: 1 }, + { asQueue: true, streamBufferSize: 1 }, + ); + const shared = yield* awaitShellRequest(socket, 1); + + serverChunk(socket, shared.id, [shellEvent(2)]); + yield* Queue.take(fast.items); + yield* awaitAcks(socket, shared.id, 1); + serverChunk(socket, shared.id, [shellEvent(3)]); + yield* Queue.take(fast.items); + yield* Effect.yieldNow; + expect(acksFor(socket, shared.id)).toBe(1); + + yield* TestClock.adjust(SLOW_SUBSCRIBER_TIMEOUT); + yield* awaitAcks(socket, shared.id, 2); + expect(yield* Stream.fromQueue(slow).pipe(Stream.runDrain, Effect.flip)).toMatchObject({ + _tag: "RpcClientError", + }); + serverChunk(socket, shared.id, [shellEvent(4)]); + expect(yield* Queue.take(fast.items)).toMatchObject({ sequence: 4 }); + }).pipe(Effect.scoped), + ); + + it.effect("keeps the stream for others when one leaves and closes it with the last", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(2); + const hubShell = yield* followShell(hub, { afterSequence: 1 }); + yield* awaitShellRequest(socket, 0); + const firstShell = yield* followShell(windows[0]!, { afterSequence: 1 }); + yield* awaitShellRequest(socket, 1); + const secondShell = yield* followShell(windows[1]!, { afterSequence: 1 }); + const shared = yield* awaitShellRequest(socket, 2); + serverChunk(socket, shared.id, [shellEvent(2)]); + for (const shell of [hubShell, firstShell, secondShell]) yield* Queue.take(shell.items); + + yield* Fiber.interrupt(firstShell.fiber); + yield* Fiber.interrupt(hubShell.fiber); + serverChunk(socket, shared.id, [shellEvent(3)]); + + expect(yield* Queue.take(secondShell.items)).toMatchObject({ sequence: 3 }); + expect(activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeShell)).toHaveLength(1); + + yield* Fiber.interrupt(secondShell.fiber); + while (activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeShell).length > 0) { + yield* Queue.take(socket.sentChanges); + } + }).pipe(Effect.scoped), + ); + + it.effect("ends a window's relay and its config stream when the hub closes it", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory({ shareStreams: true }); + const hub = yield* factory.connect(PREPARED); + const hubReady = yield* Effect.forkChild(hub.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(hubReady); + const [hubPort, windowPort] = makePortPair(); + const relay = yield* hub.relay!(hubPort); + const secondary = yield* factory.connectOverPort(PREPARED, windowPort); + yield* secondary.ready; + const config = yield* secondary + .subscribeServerConfig() + .pipe(Stream.runDrain, Effect.forkChild); + + yield* relay.close("The main window's connection ended."); + + expect(yield* Effect.flip(secondary.closed)).toBeInstanceOf(ConnectionTransientError); + expect((yield* Fiber.await(config))._tag).toBe("Failure"); + }).pipe(Effect.scoped), + ); +}); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 148005df2124d..cbfa81ac1204a 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -2,7 +2,7 @@ import { msg } from "gt-i18n"; import { translatableDetail } from "../errors/translatable.ts"; import { type ServerConfig, - type ServerConfigStreamEvent, + ServerConfigStreamEvent, WsSubscribeServerConfigRpc, WS_METHODS, } from "@t3tools/contracts"; @@ -18,6 +18,7 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; +import { identity } from "effect/Function"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; @@ -33,6 +34,8 @@ import * as RpcSerialization from "effect/rpc/RpcSerialization"; import * as Socket from "effect/socket/Socket"; import { makeWsRpcProtocolClient, PING_TIMEOUT, type WsRpcProtocolClient } from "./protocol.ts"; +import { makePortProtocol, type RelayHandle, type RpcPort, serveRelay } from "./relay.ts"; +import { canonicalJson, makeSharedStreamProtocol } from "./sharedStreams.ts"; import { NETWORK_BLOCKING_HINT, UNRESPONSIVE_HOST_HINT } from "../errors/network.ts"; import type { ConnectionAttemptError, @@ -64,6 +67,8 @@ export interface RpcSession { /** Frames received so far: proof the socket is alive that needs no reply. */ readonly inboundFrames: Effect.Effect; readonly closed: Effect.Effect; + /** Serves another window's RpcClient over `port` through this session's socket. */ + readonly relay?: (port: RpcPort) => Effect.Effect; } export interface RpcSessionOptions { @@ -73,6 +78,8 @@ export interface RpcSessionOptions { readonly providerCatalogsOnDemand?: boolean; readonly providerCatalogDigests?: boolean; readonly providerStatusDeltas?: boolean; + /** Desktop hub only: clients of one session share identical subscriptions. */ + readonly shareStreams?: boolean; } export class RpcSessionFactory extends Context.Service< @@ -81,6 +88,11 @@ export class RpcSessionFactory extends Context.Service< readonly connect: ( connection: PreparedConnection, ) => Effect.Effect; + /** A session whose requests travel over `port` to a hub window's `relay`. */ + readonly connectOverPort: ( + connection: PreparedConnection, + port: RpcPort, + ) => Effect.Effect; } >()("@t3tools/client-runtime/rpc/session/RpcSessionFactory") {} @@ -178,6 +190,13 @@ function socketFailureLocation(via: "relay" | "direct") { return { hop: via === "relay" ? "tunnel" : "server", via } as const; } +const encodeServerConfigPayload = Schema.encodeUnknownSync( + Schema.toCodecJson(WsSubscribeServerConfigRpc.payloadSchema), +); +const encodeServerConfigEvents = Schema.encodeUnknownEffect( + Schema.toCodecJson(Schema.Array(ServerConfigStreamEvent)), +); + /** @public */ export const make = Effect.fn("RpcSessionFactory.make")(function* ( options: RpcSessionOptions = {}, @@ -196,6 +215,9 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ...input, workspaceSnapshotsOnDemand: true, }); + const sharedConfigInputKey = canonicalJson( + encodeServerConfigPayload(onDemandSnapshots(serverConfigInput)), + ); const connect = Effect.fnUntraced(function* (connection: PreparedConnection) { const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct"; @@ -275,13 +297,15 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( // Teardown sends an interrupt per open stream, and a write to a closed // socket waits out the client's 1s interrupt timeout before reconnecting. // Requests still go through, so they fail with the protocol error. - Effect.map((protocol) => ({ + Effect.map((protocol): RpcClient.Protocol["Service"] => ({ ...protocol, send: (clientId, request, transferables) => request._tag !== "Request" && Deferred.isDoneUnsafe(disconnected) ? Effect.void : protocol.send(clientId, request, transferables), })), + // A desktop hub's own client and every relayed window share each subscription. + options.shareStreams === true ? Effect.flatMap(makeSharedStreamProtocol) : identity, ), ).pipe( Layer.provide( @@ -303,6 +327,29 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( Effect.ignore, Effect.forkScoped, ); + return yield* finishSession({ + connection, + protocolContext, + via, + inboundFrames: Effect.sync(() => inboundFrames), + mapRpcError, + relayable: true, + }); + }); + + const finishSession = Effect.fnUntraced(function* (input: { + readonly connection: PreparedConnection; + readonly protocolContext: Context.Context; + readonly via: "relay" | "direct"; + /** Port sessions only: fails when the hub's relay goes away. */ + readonly relayClosed?: Effect.Effect; + readonly inboundFrames: Effect.Effect; + readonly mapRpcError: ( + error: Parameters[0], + ) => ConnectionAttemptError; + readonly relayable: boolean; + }) { + const { connection, protocolContext, via, mapRpcError } = input; const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); const initialConfigDeferred = yield* Deferred.make(); const serverConfigExit = yield* Deferred.make< @@ -538,13 +585,78 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( subscribeServerConfig, ready: initialConfig.pipe(Effect.asVoid), probe, - inboundFrames: Effect.sync(() => inboundFrames), + inboundFrames: input.inboundFrames, // The config stream also fails on disconnect, and only it can report a decode failure. - closed: Deferred.await(configSubscriptionClosed), + closed: + input.relayClosed === undefined + ? Deferred.await(configSubscriptionClosed) + : Effect.raceFirst(input.relayClosed, Deferred.await(configSubscriptionClosed)), + ...(input.relayable + ? { + relay: (port: RpcPort) => + serveRelay({ + protocol: Context.get(protocolContext, RpcClient.Protocol), + port, + // Every window subscribes with the same options, so the hub's + // replaying config stream answers them all. + shared: [ + { + tag: WS_METHODS.subscribeServerConfig, + matches: (payload) => canonicalJson(payload) === sharedConfigInputKey, + items: subscribeServerConfig().pipe(Stream.orDie), + encode: (events) => encodeServerConfigEvents(events).pipe(Effect.orDie), + }, + ], + }), + } + : {}), } satisfies RpcSession; }); - return RpcSessionFactory.of({ connect }); + const connectOverPort = Effect.fnUntraced(function* ( + connection: PreparedConnection, + port: RpcPort, + ) { + yield* Effect.annotateCurrentSpan({ + "connection.environment.id": connection.environmentId, + }); + const disconnected = yield* Deferred.make(); + let inboundMessages = 0; + const protocol = yield* makePortProtocol({ + port, + onMessage: () => { + inboundMessages += 1; + }, + onClosed: (detail) => + Deferred.fail( + disconnected, + new ConnectionTransientErrorClass({ + reason: "transport", + detail: `${connection.label}: ${detail}`, + }), + ).pipe(Effect.asVoid), + }); + return yield* finishSession({ + connection, + protocolContext: Context.make(RpcClient.Protocol, protocol), + via: "direct", + relayClosed: Deferred.await(disconnected), + inboundFrames: Effect.sync(() => inboundMessages), + mapRpcError: (error) => + mapSessionRpcError( + error, + "direct", + () => + new ConnectionTransientErrorClass({ + reason: "transport", + ...translatableDetail(msg("{host} disconnected.", { host: connection.label })), + }), + ), + relayable: false, + }); + }); + + return RpcSessionFactory.of({ connect, connectOverPort }); }); export const layer = (options: RpcSessionOptions) => Layer.effect(RpcSessionFactory, make(options)); diff --git a/packages/client-runtime/src/rpc/sharedStreams.ts b/packages/client-runtime/src/rpc/sharedStreams.ts new file mode 100644 index 0000000000000..a60a3fdf0fdca --- /dev/null +++ b/packages/client-runtime/src/rpc/sharedStreams.ts @@ -0,0 +1,529 @@ +import { ORCHESTRATION_V2_WS_METHODS, WS_METHODS } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import type * as Scope from "effect/Scope"; +import * as RpcClient from "effect/rpc/RpcClient"; +import * as RpcClientError from "effect/rpc/RpcClientError"; +import type { FromClientEncoded, FromServerEncoded, RequestEncoded } from "effect/rpc/RpcMessage"; + +type EncodedItem = { readonly [key: string]: unknown }; + +/** + * How a subscription is reopened when another subscriber joins it. Nothing is + * retained: the server replays from the earliest subscriber's cursor, or starts + * over from current state, and each subscriber skips what it already has. + */ +type ShareStrategy = + | { + readonly _tag: "sequenced"; + /** Payload fields that position one subscriber; they never split a shared stream. */ + readonly cursorFields: ReadonlyArray; + /** The sequence of a snapshot that replaces all state; null for anything else. */ + readonly authoritativeSnapshot: (item: EncodedItem) => number | null; + readonly eventSequence: (item: EncodedItem) => number | null; + } + /** A fresh subscription starts with the whole current state. */ + | { readonly _tag: "restartable" }; + +const numberField = (value: unknown): number | null => (typeof value === "number" ? value : null); +const SHELL_EVENT_KINDS = new Set([ + "project.updated", + "project.removed", + "thread.updated", + "thread.removed", +]); + +const STRATEGIES: ReadonlyMap = new Map([ + [ + ORCHESTRATION_V2_WS_METHODS.subscribeShell, + { + _tag: "sequenced", + cursorFields: [ + "afterSequence", + "requestCompletionMarker", + "httpSnapshotFallback", + "knownProjectIdentities", + ], + // Snapshots with resolved identity roots only enrich projects (see the ws.ts shell resume). + authoritativeSnapshot: (item) => + item.kind === "snapshot" && item.resolvedRepositoryIdentityRoots === undefined + ? numberField((item.snapshot as EncodedItem | undefined)?.snapshotSequence) + : null, + eventSequence: (item) => + SHELL_EVENT_KINDS.has(String(item.kind)) ? numberField(item.sequence) : null, + }, + ], + [ + ORCHESTRATION_V2_WS_METHODS.subscribeThread, + { + _tag: "sequenced", + cursorFields: ["afterSequence", "requestCompletionMarker"], + authoritativeSnapshot: (item) => + item.kind === "snapshot" ? numberField(item.snapshotSequence) : null, + eventSequence: (item) => (item.kind === "event" ? numberField(item.sequence) : null), + }, + ], + ...[ + WS_METHODS.subscribeVcsStatus, + WS_METHODS.subscribeAuthAccess, + WS_METHODS.subscribeTerminalMetadata, + ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput, + WS_METHODS.providerAuthSubscribe, + WS_METHODS.providerInstallSubscribe, + WS_METHODS.scheduledTasksSubscribe, + WS_METHODS.subscribeDiscoveredLocalServers, + WS_METHODS.subscribeDeviceState, + WS_METHODS.subscribeResourceTelemetry, + WS_METHODS.subscribeVcsBranch, + WS_METHODS.subscribeProjectClones, + WS_METHODS.subscribeWorktreeSetup, + WS_METHODS.pullRequestsSubscribeRefreshes, + WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes, + ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion, + ].map((tag): [string, ShareStrategy] => [tag, { _tag: "restartable" }]), +]); + +/** A subscriber that leaves a chunk unacknowledged this long resubscribes instead of stalling others. */ +export const SLOW_SUBSCRIBER_TIMEOUT = Duration.seconds(10); +/** How long a cursor ahead of the stream may wait for in-flight events before everyone resyncs. */ +export const AHEAD_CURSOR_GRACE = Duration.seconds(5); + +export function canonicalJson(value: unknown, omit: ReadonlyArray = []): string { + if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(",")}]`; + if (typeof value !== "object" || value === null) return JSON.stringify(value) ?? "null"; + const entries = Object.entries(value) + .filter(([key, entry]) => entry !== undefined && !omit.includes(key)) + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)); + return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; +} + +type RequestId = string | number; + +interface PendingAck { + readonly waiting: Set; + timer: Fiber.Fiber | null; +} + +interface Consumer { + readonly clientId: number; + readonly requestId: RequestId; + readonly wantsMarker: boolean; + markerSent: boolean; + /** Last sequence this subscriber has; null while it waits for a snapshot. */ + position: number | null; + /** Chunks delivered and not yet acknowledged, oldest first; null for a replaced upstream's. */ + readonly unacked: Array; + aheadTimer: Fiber.Fiber | null; +} + +interface Group { + readonly key: string; + readonly strategy: ShareStrategy; + readonly template: RequestEncoded; + readonly consumers: Map; + upstreamId: string; + /** One subscriber whose own request is the upstream: chunks and acks pass straight through. */ + passThrough: boolean; + head: number | null; + /** The current upstream has sent its completion marker. */ + live: boolean; + readonly pendingAcks: Array; +} + +let nextInstance = 0; + +/** + * One server subscription per stream and arguments for all clients of a desktop hub + * session. A lone subscriber passes through; a joiner reopens the upstream from the + * earliest cursor, so nothing is retained. Acks wait for the slowest subscriber. + */ +export const makeSharedStreamProtocol = ( + inner: RpcClient.Protocol["Service"], +): Effect.Effect => + RpcClient.Protocol.make( + Effect.fnUntraced(function* (writeResponse, clientIds) { + const runFork = Effect.runForkWith(yield* Effect.context()); + const instance = nextInstance++; + // Every client shares one inner client; request ids are unique in this realm. + const innerClientId = 2_000_000_000 + instance; + let nextUpstream = 0; + const routes = new Map(); + const groups = new Map(); + const groupsByUpstream = new Map(); + const consumerGroups = new Map(); + const outboxes = new Map>(); + let failure: RpcClientError.RpcClientError | undefined; + + // Per client and in order, so a chunk never overtakes an earlier one. + const deliver = (clientId: number, message: FromServerEncoded) => { + const existing = outboxes.get(clientId); + if (existing !== undefined) { + existing.push(message); + return; + } + const queue = [message]; + outboxes.set(clientId, queue); + runFork( + Effect.gen(function* () { + while (queue.length > 0) yield* writeResponse(clientId, queue.shift()!); + }).pipe(Effect.ensuring(Effect.sync(() => outboxes.delete(clientId)))), + ); + }; + const sendInner = (message: FromClientEncoded) => + runFork(inner.send(innerClientId, message).pipe(Effect.ignore)); + const newUpstreamId = () => `shared:${instance}:${nextUpstream++}`; + const cancelTimer = (fiber: Fiber.Fiber | null) => { + if (fiber !== null) runFork(Fiber.interrupt(fiber)); + }; + + const ackUpstream = (group: Group) => { + while (group.pendingAcks.length > 0 && group.pendingAcks[0]!.waiting.size === 0) { + cancelTimer(group.pendingAcks.shift()!.timer); + sendInner({ _tag: "Ack", requestId: group.upstreamId }); + } + }; + + const forgetConsumer = (group: Group, consumer: Consumer) => { + group.consumers.delete(consumer.requestId); + consumerGroups.delete(consumer.requestId); + cancelTimer(consumer.aheadTimer); + for (const pending of consumer.unacked) pending?.waiting.delete(consumer); + consumer.unacked.length = 0; + }; + + const closeGroup = (group: Group) => { + groups.delete(group.key); + groupsByUpstream.delete(group.upstreamId); + for (const consumer of group.consumers.values()) forgetConsumer(group, consumer); + for (const pending of group.pendingAcks) cancelTimer(pending.timer); + group.pendingAcks.length = 0; + }; + + const leave = (group: Group, consumer: Consumer) => { + forgetConsumer(group, consumer); + if (group.consumers.size === 0) { + sendInner({ _tag: "Interrupt", requestId: group.upstreamId }); + closeGroup(group); + return; + } + ackUpstream(group); + }; + + /** Fails only this subscriber's request; it resubscribes from its own cursor. */ + const resync = (group: Group, consumer: Consumer, detail: string) => { + leave(group, consumer); + deliver(consumer.clientId, { + _tag: "ClientProtocolError", + error: new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ message: detail, cause: undefined }), + }), + requestIds: [consumer.requestId], + }); + }; + + /** Replaces the upstream with one every current subscriber can resume from. */ + const reopen = (group: Group, fromScratch: boolean) => { + sendInner({ _tag: "Interrupt", requestId: group.upstreamId }); + groupsByUpstream.delete(group.upstreamId); + for (const pending of group.pendingAcks) cancelTimer(pending.timer); + group.pendingAcks.length = 0; + for (const consumer of group.consumers.values()) consumer.unacked.fill(null); + group.passThrough = false; + group.live = false; + group.upstreamId = newUpstreamId(); + groupsByUpstream.set(group.upstreamId, group); + const strategy = group.strategy; + if (strategy._tag === "restartable") { + sendInner({ ...group.template, id: group.upstreamId }); + return; + } + const positions = Array.from(group.consumers.values(), (consumer) => consumer.position); + const cursor = + fromScratch || positions.includes(null) + ? null + : Math.min(...positions.filter((position) => position !== null)); + group.head = cursor; + if (fromScratch) { + for (const consumer of group.consumers.values()) { + consumer.position = null; + cancelTimer(consumer.aheadTimer); + consumer.aheadTimer = null; + } + } + const base = Object.fromEntries( + Object.entries(group.template.payload as EncodedItem).filter( + ([key]) => !strategy.cursorFields.includes(key), + ), + ); + sendInner({ + ...group.template, + id: group.upstreamId, + // Without `httpSnapshotFallback`: a gap answers with a snapshot every subscriber can use. + payload: { + ...base, + ...(cursor === null ? {} : { afterSequence: cursor }), + requestCompletionMarker: true, + }, + }); + }; + + const watchAhead = (group: Group, consumer: Consumer) => { + cancelTimer(consumer.aheadTimer); + consumer.aheadTimer = runFork( + Effect.sleep(AHEAD_CURSOR_GRACE).pipe( + Effect.andThen( + Effect.sync(() => { + consumer.aheadTimer = null; + if (!group.consumers.has(consumer.requestId) || consumer.position === null) return; + // The server never reached this cursor, so it lost history: everyone starts over. + if ((group.head ?? -1) < consumer.position) reopen(group, true); + }), + ), + ), + ); + }; + + const subscribe = (clientId: number, request: RequestEncoded, strategy: ShareStrategy) => { + const payload = request.payload as EncodedItem | null; + const key = `${request.tag}\u0000${canonicalJson( + request.payload, + strategy._tag === "sequenced" ? strategy.cursorFields : [], + )}`; + const consumer: Consumer = { + clientId, + requestId: request.id, + wantsMarker: payload?.requestCompletionMarker === true, + markerSent: false, + position: strategy._tag === "sequenced" ? numberField(payload?.afterSequence) : null, + unacked: [], + aheadTimer: null, + }; + const existing = groups.get(key); + if (existing === undefined) { + const group: Group = { + key, + strategy, + template: request, + consumers: new Map([[consumer.requestId, consumer]]), + upstreamId: newUpstreamId(), + passThrough: true, + head: consumer.position, + live: false, + pendingAcks: [], + }; + groups.set(key, group); + groupsByUpstream.set(group.upstreamId, group); + consumerGroups.set(consumer.requestId, group); + sendInner({ ...request, id: group.upstreamId }); + return; + } + const head = existing.head; + existing.consumers.set(consumer.requestId, consumer); + consumerGroups.set(consumer.requestId, existing); + reopen(existing, false); + if (consumer.position !== null && head !== null && head < consumer.position) { + watchAhead(existing, consumer); + } + }; + + const deliverChunks = (group: Group, perConsumer: Map>) => { + const pending: PendingAck = { waiting: new Set(), timer: null }; + for (const [consumer, values] of perConsumer) { + if (values.length === 0) continue; + pending.waiting.add(consumer); + consumer.unacked.push(pending); + deliver(consumer.clientId, { + _tag: "Chunk", + requestId: consumer.requestId, + values: values as never, + }); + } + group.pendingAcks.push(pending); + if (pending.waiting.size > 0) { + pending.timer = runFork( + Effect.sleep(SLOW_SUBSCRIBER_TIMEOUT).pipe( + Effect.andThen( + Effect.sync(() => { + pending.timer = null; + for (const consumer of pending.waiting) { + // Alone, a slow subscriber holds back only itself. + if (group.consumers.size < 2) break; + resync(group, consumer, "This subscriber fell behind the shared stream."); + } + }), + ), + ), + ); + } + ackUpstream(group); + }; + + const onSharedItems = (group: Group, items: ReadonlyArray) => { + const perConsumer = new Map>( + Array.from(group.consumers.values(), (consumer) => [consumer, []]), + ); + const strategy = group.strategy; + if (strategy._tag === "restartable") { + for (const values of perConsumer.values()) values.push(...items); + deliverChunks(group, perConsumer); + return; + } + // A subscriber is caught up once the stream is live and has reached its cursor. + const markCaughtUp = (consumer: Consumer, values: Array) => { + if (!group.live || consumer.position === null) return; + if (consumer.aheadTimer !== null) { + if ((group.head ?? -1) < consumer.position) return; + cancelTimer(consumer.aheadTimer); + consumer.aheadTimer = null; + } + if (consumer.wantsMarker && !consumer.markerSent) { + consumer.markerSent = true; + values.push({ kind: "synchronized" }); + } + }; + for (const item of items) { + if (item.kind === "synchronized") { + group.live = true; + for (const [consumer, values] of perConsumer) markCaughtUp(consumer, values); + continue; + } + const snapshotSequence = strategy.authoritativeSnapshot(item); + if (snapshotSequence !== null) { + group.head = snapshotSequence; + for (const [consumer, values] of perConsumer) { + values.push(item); + consumer.position = snapshotSequence; + } + continue; + } + const sequence = strategy.eventSequence(item); + if (sequence === null) { + // Project enrichment applies to everyone holding a shell; it moves no cursor. + for (const [consumer, values] of perConsumer) { + if (consumer.position !== null) values.push(item); + } + continue; + } + if (group.head === null || sequence > group.head) group.head = sequence; + for (const [consumer, values] of perConsumer) { + if (consumer.position !== null && sequence > consumer.position) { + values.push(item); + consumer.position = sequence; + } + markCaughtUp(consumer, values); + } + } + deliverChunks(group, perConsumer); + }; + + /** The single subscriber's own stream, forwarded as is; only its position is tracked. */ + const onPassThroughItems = ( + group: Group, + response: Extract, + ) => { + const consumer = group.consumers.values().next().value; + if (consumer === undefined) return; + const strategy = group.strategy; + if (strategy._tag === "sequenced") { + for (const item of response.values as ReadonlyArray) { + if (item.kind === "synchronized") { + if (consumer.wantsMarker) consumer.markerSent = true; + continue; + } + const sequence = strategy.authoritativeSnapshot(item) ?? strategy.eventSequence(item); + if (sequence !== null) { + group.head = sequence; + consumer.position = sequence; + } + } + } + deliver(consumer.clientId, { ...response, requestId: consumer.requestId }); + }; + + yield* inner + .run(innerClientId, (response) => + Effect.sync(() => { + const requestId = "requestId" in response ? response.requestId : undefined; + const group = + typeof requestId === "string" ? groupsByUpstream.get(requestId) : undefined; + switch (response._tag) { + case "Chunk": { + if (group === undefined) { + const clientId = routes.get(response.requestId); + if (clientId !== undefined) deliver(clientId, response); + } else if (group.passThrough) { + onPassThroughItems(group, response); + } else { + onSharedItems(group, response.values as ReadonlyArray); + } + return; + } + case "Exit": { + if (group !== undefined) { + for (const consumer of group.consumers.values()) { + deliver(consumer.clientId, { ...response, requestId: consumer.requestId }); + } + closeGroup(group); + return; + } + const clientId = routes.get(response.requestId); + routes.delete(response.requestId); + if (clientId !== undefined) deliver(clientId, response); + return; + } + case "ClientProtocolError": + case "Defect": { + if (response._tag === "ClientProtocolError") failure = response.error; + routes.clear(); + for (const open of groups.values()) closeGroup(open); + for (const clientId of clientIds) deliver(clientId, response); + return; + } + case "Pong": + return; + default: + for (const clientId of clientIds) deliver(clientId, response); + } + }), + ) + .pipe(Effect.forkScoped); + + return { + send: (clientId, request, transferables) => { + if (failure !== undefined) return Effect.fail(failure); + if (request._tag === "Request") { + const strategy = STRATEGIES.get(request.tag); + if (strategy !== undefined) { + return Effect.sync(() => subscribe(clientId, request, strategy)); + } + routes.set(request.id, clientId); + return inner + .send(innerClientId, request, transferables) + .pipe(Effect.onError(() => Effect.sync(() => routes.delete(request.id)))); + } + if (request._tag === "Ack" || request._tag === "Interrupt") { + const group = consumerGroups.get(request.requestId); + const consumer = group?.consumers.get(request.requestId); + if (group !== undefined && consumer !== undefined) { + return Effect.sync(() => { + if (request._tag === "Interrupt") { + leave(group, consumer); + } else if (group.passThrough) { + sendInner({ _tag: "Ack", requestId: group.upstreamId }); + } else { + consumer.unacked.shift()?.waiting.delete(consumer); + ackUpstream(group); + } + }); + } + if (request._tag === "Interrupt") routes.delete(request.requestId); + } + return inner.send(innerClientId, request, transferables); + }, + supportsAck: inner.supportsAck, + supportsTransferables: inner.supportsTransferables, + codecFor: inner.codecFor, + }; + }), + ); diff --git a/packages/contracts/src/desktopWindows.ts b/packages/contracts/src/desktopWindows.ts new file mode 100644 index 0000000000000..55f817e17ee1b --- /dev/null +++ b/packages/contracts/src/desktopWindows.ts @@ -0,0 +1,46 @@ +import * as Schema from "effect/Schema"; + +export const DesktopOpenWindowSchema = Schema.Struct({ + /** Electron's BrowserWindow id. */ + windowId: Schema.Int, + isMain: Schema.Boolean, +}); +export type DesktopOpenWindow = typeof DesktopOpenWindowSchema.Type; + +export const DesktopWindowsStateSchema = Schema.Struct({ + windows: Schema.Array(DesktopOpenWindowSchema), +}); +export type DesktopWindowsState = typeof DesktopWindowsStateSchema.Type; + +/** Read synchronously at preload time; a window keeps its id and role for its lifetime. */ +export const DesktopWindowContextSchema = Schema.Struct({ + windowId: Schema.Int, + isMain: Schema.Boolean, +}); +export type DesktopWindowContext = typeof DesktopWindowContextSchema.Type; + +/** + * `window.postMessage` payload the preload uses to hand a hub link port to the page, + * since a MessagePort cannot cross the context bridge. The port is `event.ports[0]`. + */ +export const DESKTOP_HUB_LINK_MESSAGE_TYPE = "t3code:desktop-hub-link"; +export interface DesktopHubLinkMessage { + readonly type: typeof DESKTOP_HUB_LINK_MESSAGE_TYPE; + /** The BrowserWindow id at the other end of the port. */ + readonly peerWindowId: number; +} + +export interface DesktopWindowsBridge { + getContext: () => DesktopWindowContext; + getState: () => Promise; + onState: (listener: (state: DesktopWindowsState) => void) => () => void; + openNew: () => Promise; + /** Main window only: its renderer serves secondary windows' environment connections. */ + registerHub: () => void; + /** Secondary windows only: asks for a port to the hub, delivered as a `DesktopHubLinkMessage`. */ + requestHubLink: () => void; + /** Hub side: a secondary window's renderer went away, so its links are dead. */ + onHubPeerGone: (listener: (windowId: number) => void) => () => void; + /** Secondary side: the hub's renderer went away; drop links and request a new one. */ + onHubReset: (listener: () => void) => () => void; +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 58863aaebd5e5..cd20a5882baec 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -11,6 +11,7 @@ export * from "./relayClient.ts"; export * from "./desktopBootstrap.ts"; export * from "./desktopBrowser.ts"; export * from "./desktopAppActivation.ts"; +export * from "./desktopWindows.ts"; export * from "./remoteAccess.ts"; export * from "./ipc.ts"; export * from "./terminal.ts"; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 962cfd089dd2b..d8556ea3002f6 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -20,6 +20,7 @@ import type { DesktopAppActivationRequest, DesktopAppActivationResponse, } from "./desktopAppActivation.ts"; +import type { DesktopWindowsBridge } from "./desktopWindows.ts"; export interface ContextMenuItem { id: T; @@ -1139,6 +1140,8 @@ export interface DesktopBridge { getLocalEnvironmentBearerToken: () => Promise; getClientSettings: () => Promise; setClientSettings: (settings: ClientSettings) => Promise; + /** Fires in every other app window after one window saves client settings. */ + onClientSettingsChanged?: (listener: () => void) => () => void; getConnectionCatalog: () => Promise; setConnectionCatalog: (catalog: string) => Promise; discoverSshHosts: () => Promise; @@ -1247,6 +1250,8 @@ export interface DesktopBridge { prepare: (locale: string) => Promise; transcribe: (input: { locale: string; pcm: Uint8Array }) => Promise; }; + /** Multi-window support; absent in shells that predate it. */ + windows?: DesktopWindowsBridge; } /** Renderer callback invoked by Electron with a fresh user gesture before display-media capture. */ diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index eda5138b760b9..4d93f13637f5a 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -85,6 +85,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "filePicker.toggle", "projectSearch.toggle", "usage.open", + "window.new", "theme.select", "appearance.cycle", "themeEditor.toggle", diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 3d9fcc0727d3d..ae055908aee1e 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -114,6 +114,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, { key: "mod+alt+n", command: "chat.newWithoutProject", when: "!terminalFocus" }, + { key: "mod+alt+shift+n", command: "window.new", when: "isDesktop" }, { key: "mod+f", command: "chat.find", when: "!terminalFocus && !previewFocus" }, { key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" }, { key: "mod+shift+h", command: "composer.host", when: "!terminalFocus" }, From cb56d57fe0246df96cbedd5e39ba961013757f71 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 22:37:30 -0500 Subject: [PATCH 02/21] docs: the hidden main window stays open on macOS Co-Authored-By: Claude Opus 5.5 --- docs/user/multiple-windows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user/multiple-windows.md b/docs/user/multiple-windows.md index 7a4934b817309..993aace5fdb9d 100644 --- a/docs/user/multiple-windows.md +++ b/docs/user/multiple-windows.md @@ -11,4 +11,4 @@ macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. Change the shortcut under **Settings → Keybindings** (`window.new`). Closing the main window while others are open hides it instead, since the other windows connect -through it. It closes once the last other window does. +through it. On Windows and Linux it closes once the last other window does. From 6546ea36e70aaece8e4291a610212eca138c8f03 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:18:41 -0500 Subject: [PATCH 03/21] refactor(client-runtime): socket sessions add the relay, and a lease reuses its supervisor Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/connection/hub.ts | 33 +++++++-------- packages/client-runtime/src/rpc/session.ts | 42 +++++++++---------- 2 files changed, 33 insertions(+), 42 deletions(-) diff --git a/packages/client-runtime/src/connection/hub.ts b/packages/client-runtime/src/connection/hub.ts index c6b48ca50dd39..b491a24f5dbe3 100644 --- a/packages/client-runtime/src/connection/hub.ts +++ b/packages/client-runtime/src/connection/hub.ts @@ -97,12 +97,12 @@ const makeHubDriver = Effect.gen(function* () { } satisfies ConnectionDriver.EnvironmentConnectionLease; }), // Route choice belongs to the hub, which owns the socket. - preflight: Effect.fn("HubConnectionDriver.preflight")(function* () { - return yield* Effect.succeed("unchecked" as const); - }), - checkHost: Effect.fn("HubConnectionDriver.checkHost")(function* () { - return yield* Effect.succeed("answered" as const); - }), + preflight: Effect.fn("HubConnectionDriver.preflight")(() => + Effect.succeed("unchecked" as const), + ), + checkHost: Effect.fn("HubConnectionDriver.checkHost")(() => + Effect.succeed("answered" as const), + ), }); }); @@ -113,6 +113,7 @@ type HubSessionState = readonly _tag: "Ready"; readonly prepared: PreparedConnection; readonly session: RpcSession.RpcSession; + readonly supervisor: EnvironmentSupervisor.EnvironmentSupervisor["Service"]; } | { readonly _tag: "Blocked"; readonly error: ConnectionAttemptError }; @@ -132,7 +133,12 @@ const hubSessionStates = Stream.unwrap( ), Stream.map(([session, prepared, state]): Option.Option => { if (Option.isSome(session) && Option.isSome(prepared)) { - return Option.some({ _tag: "Ready", prepared: prepared.value, session: session.value }); + return Option.some({ + _tag: "Ready", + prepared: prepared.value, + session: session.value, + supervisor, + }); } if (state.phase === "blocked" && state.lastFailure !== null) { return Option.some({ _tag: "Blocked", error: state.lastFailure }); @@ -164,7 +170,7 @@ export const serveHubLease = Effect.fn("HubConnection.serveLease")(function* ( } const state = head.value; if (state._tag === "Blocked") return yield* state.error; - const { prepared, session } = state; + const { prepared, session, supervisor } = state; if (session.relay === undefined) { return yield* new ConnectionTransientError({ reason: "transport", @@ -173,17 +179,6 @@ export const serveHubLease = Effect.fn("HubConnection.serveLease")(function* ( } const relay = yield* session.relay(port); // A session that ends or is replaced takes its relays with it, so the window reconnects at once. - const supervisor = yield* registry - .run(environmentId, EnvironmentSupervisor.EnvironmentSupervisor) - .pipe( - Effect.mapError( - () => - new ConnectionTransientError({ - reason: "endpoint-unavailable", - detail: "The main window no longer has this environment.", - }), - ), - ); yield* Effect.raceFirst( session.closed.pipe(Effect.ignore), SubscriptionRef.changes(supervisor.session).pipe( diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index cbfa81ac1204a..56f84272cef28 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -327,14 +327,31 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( Effect.ignore, Effect.forkScoped, ); - return yield* finishSession({ + const session = yield* finishSession({ connection, protocolContext, via, inboundFrames: Effect.sync(() => inboundFrames), mapRpcError, - relayable: true, }); + return { + ...session, + relay: (port: RpcPort) => + serveRelay({ + protocol: Context.get(protocolContext, RpcClient.Protocol), + port, + // Every window subscribes with the same options, so the hub's + // replaying config stream answers them all. + shared: [ + { + tag: WS_METHODS.subscribeServerConfig, + matches: (payload) => canonicalJson(payload) === sharedConfigInputKey, + items: session.subscribeServerConfig().pipe(Stream.orDie), + encode: (events) => encodeServerConfigEvents(events).pipe(Effect.orDie), + }, + ], + }), + } satisfies RpcSession; }); const finishSession = Effect.fnUntraced(function* (input: { @@ -347,7 +364,6 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( readonly mapRpcError: ( error: Parameters[0], ) => ConnectionAttemptError; - readonly relayable: boolean; }) { const { connection, protocolContext, via, mapRpcError } = input; const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); @@ -591,25 +607,6 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( input.relayClosed === undefined ? Deferred.await(configSubscriptionClosed) : Effect.raceFirst(input.relayClosed, Deferred.await(configSubscriptionClosed)), - ...(input.relayable - ? { - relay: (port: RpcPort) => - serveRelay({ - protocol: Context.get(protocolContext, RpcClient.Protocol), - port, - // Every window subscribes with the same options, so the hub's - // replaying config stream answers them all. - shared: [ - { - tag: WS_METHODS.subscribeServerConfig, - matches: (payload) => canonicalJson(payload) === sharedConfigInputKey, - items: subscribeServerConfig().pipe(Stream.orDie), - encode: (events) => encodeServerConfigEvents(events).pipe(Effect.orDie), - }, - ], - }), - } - : {}), } satisfies RpcSession; }); @@ -652,7 +649,6 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ...translatableDetail(msg("{host} disconnected.", { host: connection.label })), }), ), - relayable: false, }); }); From e4f1cd7751e036f933925e5144f6c8c43f95fa68 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:19:16 -0500 Subject: [PATCH 04/21] refactor(desktop): one forwarder routes per-tab preview events to their window Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/ipc/methods/preview.ts | 51 +++++++------------------ 1 file changed, 13 insertions(+), 38 deletions(-) diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 7690cad20f0fd..f937246705f84 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -55,20 +55,11 @@ import * as DesktopIpc from "../DesktopIpc.ts"; * A secondary window's tab ids are scoped to that window, so two windows can each show the * same thread's preview. The main window keeps its ids as they are. */ -function scopePreviewTabId(tabId: string, secondaryWindowId: number | null): string { - return secondaryWindowId === null ? tabId : `w${secondaryWindowId}:${tabId}`; -} - const senderTabId = (tabId: string) => Effect.map(DesktopIpc.DesktopIpcSender, ({ window, isMain }) => - scopePreviewTabId(tabId, isMain ? null : window.id), + isMain ? tabId : `w${window.id}:${tabId}`, ); -const withRendererTabId = (value: A, rendererTabId: string): A => - typeof value === "object" && value !== null && "tabId" in value - ? { ...value, tabId: rendererTabId } - : value; - /** Per-tab events go only to the window that shows the tab, under the id it knows. */ export const installPreviewEventForwarding = Effect.fn( "desktop.ipc.preview.installEventForwarding", @@ -84,38 +75,22 @@ export const installPreviewEventForwarding = Effect.fn( if (Option.isNone(window) || window.value.isDestroyed()) return; send(window.value.webContents, rendererTabId); }); + const forward = + (channel: string) => + (event: E) => + sendToOwner(event.tabId, (contents, tabId) => contents.send(channel, { ...event, tabId })); yield* manager.subscribeStateChanges((tabId, state) => sendToOwner(tabId, (contents, rendererTabId) => - contents.send( - IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, - rendererTabId, - withRendererTabId(state, rendererTabId), - ), - ), - ); - yield* manager.subscribeRecordingInputs((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, { - ...event, + contents.send(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, rendererTabId, { + ...state, tabId: rendererTabId, }), ), ); - yield* manager.subscribePointerEvents((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, { ...event, tabId: rendererTabId }), - ), - ); - yield* manager.subscribeOpenLinks((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, { ...event, tabId: rendererTabId }), - ), - ); - yield* manager.subscribeFindResults((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, { ...event, tabId: rendererTabId }), - ), - ); + yield* manager.subscribeRecordingInputs(forward(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL)); + yield* manager.subscribePointerEvents(forward(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL)); + yield* manager.subscribeOpenLinks(forward(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL)); + yield* manager.subscribeFindResults(forward(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL)); const tunnel = yield* LoopbackTunnel.LoopbackTunnel; yield* tunnel.subscribeForwards((forwards) => electronWindow.sendAll(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, forwards), @@ -560,7 +535,7 @@ export const captureScreenshot = DesktopIpc.makeIpcMethod({ handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; return yield* manager.captureScreenshot(yield* senderTabId(tabId)).pipe( - Effect.map((artifact) => withRendererTabId(artifact, tabId)), + Effect.map((artifact) => ({ ...artifact, tabId })), Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot"))), ); }), @@ -593,7 +568,7 @@ const saveRecording = DesktopIpc.makeIpcMethod({ handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) { const manager = yield* PreviewManager.PreviewManager; const artifact = yield* manager.saveRecording(yield* senderTabId(tabId), mimeType, data); - return withRendererTabId(artifact, tabId); + return { ...artifact, tabId }; }), }); From 6c41553086fdc1130424372e8447dc7b80eaa6cd Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:21:13 -0500 Subject: [PATCH 05/21] refactor(web): read the window context directly instead of through component state Co-Authored-By: Claude Opus 5.5 --- apps/web/src/browser/ElectronBrowserHost.tsx | 2 +- apps/web/src/multiWindow/windowContext.ts | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/apps/web/src/browser/ElectronBrowserHost.tsx b/apps/web/src/browser/ElectronBrowserHost.tsx index ad9f60ff173dd..910334f208ca7 100644 --- a/apps/web/src/browser/ElectronBrowserHost.tsx +++ b/apps/web/src/browser/ElectronBrowserHost.tsx @@ -140,7 +140,7 @@ export function ElectronBrowserHost() { const previewByThreadKey = useActivePreviewSessions(); const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom); // Background previews belong to the main window; a secondary one hosts only what it shows. - const [secondaryWindow] = useState(isSecondaryDesktopWindow); + const secondaryWindow = isSecondaryDesktopWindow(); useDesktopHostedPreviewSessions(secondaryWindow ? null : primaryEnvironmentId); const hostedElsewhere = useThreadsHostedElsewhere(); const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId).filter( diff --git a/apps/web/src/multiWindow/windowContext.ts b/apps/web/src/multiWindow/windowContext.ts index c686fb0203787..0be4435ac6582 100644 --- a/apps/web/src/multiWindow/windowContext.ts +++ b/apps/web/src/multiWindow/windowContext.ts @@ -9,12 +9,7 @@ let cachedContext: DesktopWindowContext | null | undefined; /** Null outside a desktop shell with multi-window support. */ export function readDesktopWindowContext(): DesktopWindowContext | null { - if (cachedContext !== undefined) return cachedContext; - try { - cachedContext = desktopWindowsBridge()?.getContext() ?? null; - } catch { - cachedContext = null; - } + if (cachedContext === undefined) cachedContext = desktopWindowsBridge()?.getContext() ?? null; return cachedContext; } From b1e319da41bb39f408dae5fd2d971f3aec77ad22 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:21:59 -0500 Subject: [PATCH 06/21] test(client-runtime): relay tests share the hub setup Co-Authored-By: Claude Opus 5.5 --- .../client-runtime/src/rpc/session.test.ts | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index d7e0fb326e2c8..be8d02c1d104e 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -1262,8 +1262,9 @@ function makePortPair(): readonly [RpcPort, RpcPort] { const connectHubAndWindows = Effect.fn("TestRpcSessionFactory.connectHubAndWindows")(function* ( count: number, + options: RpcSession.RpcSessionOptions = { shareStreams: true }, ) { - const { factory, sockets } = yield* makeFactory({ shareStreams: true }); + const { factory, sockets } = yield* makeFactory(options); const hub = yield* factory.connect(PREPARED); const hubReady = yield* Effect.forkChild(hub.ready); const socket = yield* awaitSocket(sockets); @@ -1278,7 +1279,7 @@ const connectHubAndWindows = Effect.fn("TestRpcSessionFactory.connectHubAndWindo yield* secondary.ready; windows.push(secondary); } - return { hub, windows, socket, sockets }; + return { factory, hub, windows, socket, sockets }; }); const connectHubAndWindow = Effect.fn("TestRpcSessionFactory.connectHubAndWindow")(function* () { @@ -1375,13 +1376,7 @@ describe("hub relay", () => { it.effect("interrupts a window's open streams on the server when the relay ends", () => Effect.gen(function* () { - const { factory, sockets } = yield* makeFactory(); - const hub = yield* factory.connect(PREPARED); - const hubReady = yield* Effect.forkChild(hub.ready); - const socket = yield* awaitSocket(sockets); - socket.open(); - yield* completeInitialConfig(socket); - yield* Fiber.join(hubReady); + const { factory, hub, socket } = yield* connectHubAndWindows(0, {}); const [hubPort, windowPort] = makePortPair(); const relayScope = yield* Scope.make(); yield* hub.relay!(hubPort).pipe(Scope.provide(relayScope)); @@ -1719,13 +1714,7 @@ describe("shared hub subscriptions", () => { it.effect("ends a window's relay and its config stream when the hub closes it", () => Effect.gen(function* () { - const { factory, sockets } = yield* makeFactory({ shareStreams: true }); - const hub = yield* factory.connect(PREPARED); - const hubReady = yield* Effect.forkChild(hub.ready); - const socket = yield* awaitSocket(sockets); - socket.open(); - yield* completeInitialConfig(socket); - yield* Fiber.join(hubReady); + const { factory, hub } = yield* connectHubAndWindows(0); const [hubPort, windowPort] = makePortPair(); const relay = yield* hub.relay!(hubPort); const secondary = yield* factory.connectOverPort(PREPARED, windowPort); From bfcf1b28ccbededcf5b4bbcdf91d5fbc5c4adc89 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:23:34 -0500 Subject: [PATCH 07/21] refactor(client-runtime): relay ports drain through an Effect queue Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/rpc/relay.ts | 37 ++++++------------------ 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/packages/client-runtime/src/rpc/relay.ts b/packages/client-runtime/src/rpc/relay.ts index cbceb3682a5b8..6d17f44972383 100644 --- a/packages/client-runtime/src/rpc/relay.ts +++ b/packages/client-runtime/src/rpc/relay.ts @@ -1,6 +1,7 @@ import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as RpcClient from "effect/rpc/RpcClient"; @@ -57,31 +58,12 @@ export interface SharedRelayStream { readonly encode: (values: ReadonlyArray) => Effect.Effect; } -/** Runs port messages one at a time and in arrival order, like a socket's frames. */ -const makeSerialRunner = ( - runFork: (effect: Effect.Effect) => unknown, - handle: (message: A) => Effect.Effect, -) => { - const queue: Array = []; - let draining = false; - const drain = Effect.gen(function* () { - while (queue.length > 0) { - yield* handle(queue.shift()!); - } - }).pipe( - Effect.ensuring( - Effect.sync(() => { - draining = false; - }), - ), - ); - return (message: A) => { - queue.push(message); - if (draining) return; - draining = true; - runFork(drain); - }; -}; +/** Handles port messages one at a time and in arrival order, like a socket's frames. */ +const makeInbox = Effect.fnUntraced(function* (handle: (message: A) => Effect.Effect) { + const inbox = yield* Queue.unbounded(); + yield* Queue.take(inbox).pipe(Effect.flatMap(handle), Effect.forever, Effect.forkScoped); + return (message: A) => Queue.offerUnsafe(inbox, message); +}); // RpcClient numbers its clients from 0 within one JavaScript realm, so relay // clients sharing the hub's protocol start far above any realistic count. @@ -225,7 +207,7 @@ export const serveRelay = Effect.fnUntraced(function* (options: { } }; - const enqueue = makeSerialRunner(runFork, handle); + const enqueue = yield* makeInbox(handle); const stopListening = port.onMessage((message) => { if (!closed) enqueue(message as FromClientEncoded); }); @@ -264,7 +246,6 @@ export const makePortProtocol = (options: { RpcClient.Protocol.make( Effect.fnUntraced(function* (writeResponse, clientIds) { const { port } = options; - const runFork = Effect.runForkWith(yield* Effect.context()); const requestClients = new Map(); let closedError: RpcClientError.RpcClientError | undefined; @@ -321,7 +302,7 @@ export const makePortProtocol = (options: { return broadcast(response); }; - const enqueue = makeSerialRunner(runFork, receive); + const enqueue = yield* makeInbox(receive); const stopListening = port.onMessage((message) => { options.onMessage?.(); enqueue(message); From 6ba9daf6d4f67a9c71f63b6c269c66866b0e9fa2 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 23 Nov 2026 10:13:02 -0500 Subject: [PATCH 08/21] feat(desktop): saved windows, Mini Mode and window settings on the shared hub Saved window profiles (project filter, bounds, theme), the close prompt, the Multiple windows switch and Windows settings, project-colour themes, and Mini Mode, built on the shared-connection window hub. Replays the branch's history up to da2ba7c85e as one commit. That history carried its own copy of the window hub and merged the hub branch three times, so its commits no longer apply one by one on the rebased hub. Squashed commits: - 5fa6d22266 feat(desktop): multiple windows that share the main window's connections - cac0fe803f fix(desktop): shared hub subscriptions keep flow control and retain nothing - ddbc66cbc5 fix(desktop): previews, focus and captures stay with their window - 636249f975 fix(desktop): a reloaded secondary window keeps its current filter and profile - 68836c83ba feat(desktop): Mini Mode leads with usage limits in a compact layout - 6b66dace29 feat(desktop): secondary windows take on their projects' icon colours - d0f7871f77 feat(desktop): multi-window toggle and saved windows in Settings - bf9f3164b4 fix(desktop): Mini Mode offers no New Window while multiple windows are off - 6c10b48218 feat(desktop): project colours tint the sidebar banner; window settings round - ac5136e6f1 feat(desktop): Mini Mode becomes a tabbed accessory panel - 7017392122 refactor(client-runtime): keep connect in place and reuse canonicalJson for the shared config match - 8e84740182 refactor(desktop): one way to add a window profile, and no stored window context - edeea989e8 refactor(web): project icon swatches read Tailwind's colour variables - d2a438b0aa refactor(desktop): drop focusedMainOrFirst, which IPC senders replaced - cabc4074a8 refactor(desktop): window context schema lives in contracts - 8150b1d454 refactor(web): hub link messages are schemas - 5168f0e106 docs: multiple windows guide covers tasks, not every control - 6b59152a5f refactor(web): Mini Mode Usage reuses the composer's compact limit rows - 44f9902ea3 refactor(web): register the window commands at startup - acd5babfba docs: multiple windows guide keeps the hidden main window note - 1891a8cf4c docs: the hidden main window stays open on macOS Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app/DesktopLifecycle.test.ts | 8 +- apps/desktop/src/app/DesktopLifecycle.ts | 2 +- .../src/backend/DesktopBackendPool.test.ts | 2 +- apps/desktop/src/ipc/channels.ts | 12 + apps/desktop/src/ipc/methods/window.ts | 8 + apps/desktop/src/ipc/methods/windows.ts | 143 +++- apps/desktop/src/preload.ts | 43 +- .../src/settings/DesktopAppSettings.test.ts | 165 ++++- .../src/settings/DesktopAppSettings.ts | 252 ++++++- .../desktop/src/updates/updatesTestHarness.ts | 4 +- .../src/window/DesktopApplicationMenu.test.ts | 137 +++- .../src/window/DesktopApplicationMenu.ts | 81 ++- apps/desktop/src/window/DesktopWindow.test.ts | 173 ++++- apps/desktop/src/window/DesktopWindow.ts | 687 ++++++++++++++++-- .../src/window/DesktopWindowProfiles.test.ts | 91 ++- .../src/window/DesktopWindowProfiles.ts | 52 ++ .../components/CommandPaletteThemeItems.tsx | 2 +- .../components/CommandPaletteWindowItems.tsx | 57 +- .../components/settings/SettingsPanels.tsx | 3 + .../components/settings/WindowsSettings.tsx | 575 +++++++++++++++ .../src/components/settings/settingsSearch.ts | 7 + .../src/components/sidebar/SidebarChrome.tsx | 15 +- apps/web/src/composerDraftStore.test.ts | 8 +- apps/web/src/hooks/useTheme.ts | 38 +- .../src/multiWindow/ui/DesktopWindowTint.tsx | 36 + .../src/multiWindow/ui/DesktopWindowsHost.tsx | 111 +++ .../ui/MiniMainWindow.browser.test.tsx | 251 +++++++ .../web/src/multiWindow/ui/MiniMainWindow.tsx | 190 +++++ .../src/multiWindow/ui/MiniPullRequests.tsx | 116 +++ apps/web/src/multiWindow/ui/MiniSettings.tsx | 37 + apps/web/src/multiWindow/ui/MiniUpdate.tsx | 43 ++ apps/web/src/multiWindow/ui/MiniUsage.tsx | 96 +++ apps/web/src/multiWindow/ui/MiniWindows.tsx | 114 +++ apps/web/src/multiWindow/ui/mini.fixtures.ts | 210 ++++++ .../multiWindow/ui/useProjectScopeGroups.ts | 34 + .../multiWindow/ui/useProjectTintColors.ts | 37 + apps/web/src/multiWindow/ui/windowActions.ts | 10 +- .../ui/windowProfiles.logic.test.ts | 32 + .../multiWindow/ui/windowProfiles.logic.ts | 34 + apps/web/src/multiWindow/ui/windowTheme.ts | 41 ++ .../multiWindow/ui/windowTint.logic.test.ts | 77 ++ .../src/multiWindow/ui/windowTint.logic.ts | 52 ++ apps/web/src/multiWindow/windowsState.test.ts | 141 ++++ apps/web/src/multiWindow/windowsState.ts | 63 +- apps/web/src/projectIconColors.ts | 5 + apps/web/src/routes/__root.tsx | 13 +- apps/web/src/uiStateStore.ts | 15 +- docs/user/multiple-windows.md | 46 +- packages/contracts/src/desktopWindows.ts | 107 ++- 49 files changed, 4289 insertions(+), 187 deletions(-) create mode 100644 apps/web/src/components/settings/WindowsSettings.tsx create mode 100644 apps/web/src/multiWindow/ui/DesktopWindowTint.tsx create mode 100644 apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx create mode 100644 apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx create mode 100644 apps/web/src/multiWindow/ui/MiniMainWindow.tsx create mode 100644 apps/web/src/multiWindow/ui/MiniPullRequests.tsx create mode 100644 apps/web/src/multiWindow/ui/MiniSettings.tsx create mode 100644 apps/web/src/multiWindow/ui/MiniUpdate.tsx create mode 100644 apps/web/src/multiWindow/ui/MiniUsage.tsx create mode 100644 apps/web/src/multiWindow/ui/MiniWindows.tsx create mode 100644 apps/web/src/multiWindow/ui/mini.fixtures.ts create mode 100644 apps/web/src/multiWindow/ui/useProjectScopeGroups.ts create mode 100644 apps/web/src/multiWindow/ui/useProjectTintColors.ts create mode 100644 apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts create mode 100644 apps/web/src/multiWindow/ui/windowProfiles.logic.ts create mode 100644 apps/web/src/multiWindow/ui/windowTheme.ts create mode 100644 apps/web/src/multiWindow/ui/windowTint.logic.test.ts create mode 100644 apps/web/src/multiWindow/ui/windowTint.logic.ts create mode 100644 apps/web/src/multiWindow/windowsState.test.ts diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index 772379b964374..43952cd6f772d 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -89,7 +89,7 @@ function layerElectronWindow(destroyAll: Effect.Effect = Effect.void) { function layerDesktopWindow( input: { readonly activate?: Effect.Effect; - readonly flushMainWindowBounds?: Effect.Effect; + readonly flushWindowState?: Effect.Effect; } = {}, ) { return Layer.mock(DesktopWindow.DesktopWindow)({ @@ -101,7 +101,7 @@ function layerDesktopWindow( showConnectingSplash: Effect.void, handleBackendReady: () => Effect.void, handleBackendNotReady: Effect.void, - flushMainWindowBounds: input.flushMainWindowBounds ?? Effect.void, + flushWindowState: input.flushWindowState ?? Effect.void, prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.void, dispatchSnapShotEvent: () => Effect.void, @@ -181,7 +181,7 @@ describe("DesktopLifecycle", () => { const destroyAll = Effect.sync(() => { events.push("destroy"); }); - const flushMainWindowBounds = Effect.sync(() => { + const flushWindowState = Effect.sync(() => { events.push("flush"); }); @@ -204,7 +204,7 @@ describe("DesktopLifecycle", () => { Layer.provideMerge(layerElectronApp(appListeners, quit)), Layer.provideMerge(layerElectronTheme), Layer.provideMerge(layerElectronWindow(destroyAll)), - Layer.provideMerge(layerDesktopWindow({ flushMainWindowBounds })), + Layer.provideMerge(layerDesktopWindow({ flushWindowState })), Layer.provideMerge(layerEnvironment), Layer.provideMerge(layerDesktopShutdown), Layer.provideMerge(DesktopState.layer), diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts index 9568e72dde310..7567505bf389d 100644 --- a/apps/desktop/src/app/DesktopLifecycle.ts +++ b/apps/desktop/src/app/DesktopLifecycle.ts @@ -97,7 +97,7 @@ const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdo ): Effect.fn.Return { const shutdown = yield* DesktopShutdown.DesktopShutdown; const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.flushMainWindowBounds; + yield* desktopWindow.flushWindowState; yield* afterBoundsFlush; yield* shutdown.request; yield* shutdown.awaitComplete; diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 1be204cb02354..1656299e8dd52 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -212,7 +212,7 @@ function layerPool( showConnectingSplash: Effect.void, handleBackendReady: () => options.onReady ?? Effect.void, handleBackendNotReady: Effect.void, - flushMainWindowBounds: Effect.void, + flushWindowState: Effect.void, prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.die("unexpected menu action"), dispatchSnapShotEvent: () => Effect.void, diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 072915f952e48..48153f62400a1 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -161,6 +161,18 @@ export const WINDOWS_GET_CONTEXT_CHANNEL = "desktop:windows-get-context"; export const WINDOWS_GET_STATE_CHANNEL = "desktop:windows-get-state"; export const WINDOWS_STATE_CHANNEL = "desktop:windows-state"; export const WINDOWS_OPEN_NEW_CHANNEL = "desktop:windows-open-new"; +export const WINDOWS_OPEN_PROFILE_CHANNEL = "desktop:windows-open-profile"; +export const WINDOWS_FOCUS_CHANNEL = "desktop:windows-focus"; +export const WINDOWS_CREATE_PROFILE_CHANNEL = "desktop:windows-create-profile"; +export const WINDOWS_SAVE_AS_PROFILE_CHANNEL = "desktop:windows-save-as-profile"; +export const WINDOWS_UPDATE_PROFILE_CHANNEL = "desktop:windows-update-profile"; +export const WINDOWS_DELETE_PROFILE_CHANNEL = "desktop:windows-delete-profile"; +export const WINDOWS_SET_PROJECT_SCOPE_KEYS_CHANNEL = "desktop:windows-set-project-scope-keys"; +export const WINDOWS_CLOSE_REQUEST_CHANNEL = "desktop:windows-close-request"; +export const WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL = "desktop:windows-close-request-listening"; +export const WINDOWS_RESOLVE_CLOSE_REQUEST_CHANNEL = "desktop:windows-resolve-close-request"; +export const WINDOWS_SET_MINI_MODE_CHANNEL = "desktop:windows-set-mini-mode"; +export const WINDOWS_SET_MULTI_WINDOW_ENABLED_CHANNEL = "desktop:windows-set-multi-window-enabled"; export const WINDOWS_REGISTER_HUB_CHANNEL = "desktop:windows-register-hub"; export const WINDOWS_REQUEST_HUB_LINK_CHANNEL = "desktop:windows-request-hub-link"; export const WINDOWS_HUB_LINK_CHANNEL = "desktop:windows-hub-link"; diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index d5e491710dd25..eee63f59e392a 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -46,6 +46,7 @@ import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as Electron from "electron"; import { msg } from "gt-i18n"; import * as MacPermissions from "../../permissions/MacPermissions.ts"; +import * as DesktopWindow from "../../window/DesktopWindow.ts"; import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts"; import { m } from "../../i18n/messages.ts"; import * as IpcChannels from "../channels.ts"; @@ -330,6 +331,13 @@ export const setTheme = DesktopIpc.makeIpcMethod({ payload: DesktopThemeSchema, result: Schema.Void, handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) { + const sender = yield* DesktopIpc.DesktopIpcSender; + // A secondary window can use another profile's theme, so it only restyles its own frame. + if (!sender.isMain) { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.setWindowAppearance(sender.window, theme); + return; + } const electronTheme = yield* ElectronTheme.ElectronTheme; yield* electronTheme.setSource(theme); }), diff --git a/apps/desktop/src/ipc/methods/windows.ts b/apps/desktop/src/ipc/methods/windows.ts index a2ce8200510a4..af237b56c85f3 100644 --- a/apps/desktop/src/ipc/methods/windows.ts +++ b/apps/desktop/src/ipc/methods/windows.ts @@ -1,4 +1,15 @@ -import { DesktopWindowContextSchema, DesktopWindowsStateSchema } from "@t3tools/contracts"; +import { + DesktopCreateWindowProfileInputSchema, + DesktopOpenWindowInputSchema, + DesktopResolveWindowCloseInputSchema, + DesktopUpdateWindowProfileInputSchema, + DesktopWindowContextSchema, + DesktopWindowProfileIdSchema, + DesktopWindowProfileNameSchema, + DesktopWindowProfileSchema, + DesktopWindowProjectScopeKeysSchema, + DesktopWindowsStateSchema, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -28,10 +39,116 @@ const getState = DesktopIpc.makeIpcMethod({ const openNew = DesktopIpc.makeIpcMethod({ channel: IpcChannels.WINDOWS_OPEN_NEW_CHANNEL, - payload: Schema.Void, + payload: Schema.UndefinedOr(DesktopOpenWindowInputSchema), + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openNew")(function* (input) { + yield* (yield* DesktopWindow.DesktopWindow).openNewWindow(input ?? {}); + }), +}); + +const openProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_OPEN_PROFILE_CHANNEL, + payload: DesktopWindowProfileIdSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openProfile")(function* (profileId) { + yield* (yield* DesktopWindow.DesktopWindow).openProfile(profileId); + }), +}); + +const focus = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_FOCUS_CHANNEL, + payload: Schema.Int, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.focus")(function* (windowId) { + yield* (yield* DesktopWindow.DesktopWindow).focusWindow(windowId); + }), +}); + +const createProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_CREATE_PROFILE_CHANNEL, + payload: DesktopCreateWindowProfileInputSchema, + result: DesktopWindowProfileSchema, + handler: Effect.fn("desktop.ipc.windows.createProfile")(function* (input) { + return yield* (yield* DesktopWindow.DesktopWindow).createProfile(input); + }), +}); + +const saveAsProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SAVE_AS_PROFILE_CHANNEL, + payload: DesktopWindowProfileNameSchema, + result: DesktopWindowProfileSchema, + handler: Effect.fn("desktop.ipc.windows.saveAsProfile")(function* (name) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + return yield* (yield* DesktopWindow.DesktopWindow).saveWindowAsProfile(window, name); + }), +}); + +const updateProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_UPDATE_PROFILE_CHANNEL, + payload: DesktopUpdateWindowProfileInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.updateProfile")(function* (input) { + yield* (yield* DesktopWindow.DesktopWindow).updateProfile(input); + }), +}); + +const deleteProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_DELETE_PROFILE_CHANNEL, + payload: DesktopWindowProfileIdSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.deleteProfile")(function* (profileId) { + yield* (yield* DesktopWindow.DesktopWindow).deleteProfile(profileId); + }), +}); + +const setProjectScopeKeys = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SET_PROJECT_SCOPE_KEYS_CHANNEL, + payload: DesktopWindowProjectScopeKeysSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setProjectScopeKeys")(function* (projectScopeKeys) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setWindowProjectScopeKeys(window, projectScopeKeys); + }), +}); + +const setCloseRequestListening = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setCloseRequestListening")(function* (listening) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setCloseRequestListening(window, listening); + }), +}); + +const resolveCloseRequest = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_RESOLVE_CLOSE_REQUEST_CHANNEL, + payload: DesktopResolveWindowCloseInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.resolveCloseRequest")(function* ({ + requestId, + decision, + }) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).resolveCloseRequest(window, requestId, decision); + }), +}); + +const setMiniMode = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SET_MINI_MODE_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setMiniMode")(function* (enabled) { + yield* (yield* DesktopWindow.DesktopWindow).setMiniMode(enabled); + }), +}); + +const setMultiWindowEnabled = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SET_MULTI_WINDOW_ENABLED_CHANNEL, + payload: Schema.Boolean, result: Schema.Void, - handler: Effect.fn("desktop.ipc.windows.openNew")(function* () { - yield* (yield* DesktopWindow.DesktopWindow).openNewWindow; + handler: Effect.fn("desktop.ipc.windows.setMultiWindowEnabled")(function* (enabled) { + yield* (yield* DesktopWindow.DesktopWindow).setMultiWindowEnabled(enabled); }), }); @@ -55,4 +172,20 @@ const requestHubLink = DesktopIpc.makeIpcMethod({ }), }); -export const methods = [getState, openNew, registerHub, requestHubLink] as const; +export const methods = [ + getState, + openNew, + openProfile, + focus, + createProfile, + saveAsProfile, + updateProfile, + deleteProfile, + setProjectScopeKeys, + setCloseRequestListening, + resolveCloseRequest, + setMiniMode, + setMultiWindowEnabled, + registerHub, + requestHubLink, +] as const; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 65c714f87dbdb..67929652c8b49 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -9,6 +9,7 @@ import type { DesktopPreviewRecordingInputEvent, DesktopPreviewTabState, DesktopSnapShotEvent, + DesktopWindowCloseRequest, DesktopWindowContext, DesktopWindowsBridge, DesktopWindowsState, @@ -100,7 +101,7 @@ const windowContext = ((): DesktopWindowContext => { const result: unknown = ipcRenderer.sendSync(IpcChannels.WINDOWS_GET_CONTEXT_CHANNEL); if (typeof result === "object" && result !== null) return result as DesktopWindowContext; } catch {} - return { windowId: -1, isMain: true }; + return { windowId: -1, isMain: true, profileId: null, projectScopeKeys: [], theme: null }; })(); // A MessagePort cannot cross the context bridge, so the page receives it as a window message. @@ -130,13 +131,51 @@ const subscribe = }; }; +let closeRequestListeners = 0; const windows: DesktopWindowsBridge = { getContext: () => windowContext, getState: () => ipcRenderer.invoke(IpcChannels.WINDOWS_GET_STATE_CHANNEL), onState: subscribe(IpcChannels.WINDOWS_STATE_CHANNEL, (state) => typeof state === "object" && state !== null ? (state as DesktopWindowsState) : undefined, ), - openNew: () => ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_NEW_CHANNEL), + openNew: (input) => ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_NEW_CHANNEL, input), + openProfile: (profileId) => + ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_PROFILE_CHANNEL, profileId), + focus: (windowId) => ipcRenderer.invoke(IpcChannels.WINDOWS_FOCUS_CHANNEL, windowId), + createProfile: (input) => ipcRenderer.invoke(IpcChannels.WINDOWS_CREATE_PROFILE_CHANNEL, input), + saveAsProfile: (name) => ipcRenderer.invoke(IpcChannels.WINDOWS_SAVE_AS_PROFILE_CHANNEL, name), + updateProfile: (input) => ipcRenderer.invoke(IpcChannels.WINDOWS_UPDATE_PROFILE_CHANNEL, input), + deleteProfile: (profileId) => + ipcRenderer.invoke(IpcChannels.WINDOWS_DELETE_PROFILE_CHANNEL, profileId), + setProjectScopeKeys: (projectScopeKeys) => + ipcRenderer.invoke(IpcChannels.WINDOWS_SET_PROJECT_SCOPE_KEYS_CHANNEL, projectScopeKeys), + // The main process closes without asking while no listener could answer. + onCloseRequest: (listener) => { + const unsubscribe = subscribe(IpcChannels.WINDOWS_CLOSE_REQUEST_CHANNEL, (request) => + typeof request === "object" && request !== null + ? (request as DesktopWindowCloseRequest) + : undefined, + )(listener); + closeRequestListeners += 1; + if (closeRequestListeners === 1) { + void ipcRenderer.invoke(IpcChannels.WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL, true); + } + let subscribed = true; + return () => { + if (!subscribed) return; + subscribed = false; + unsubscribe(); + closeRequestListeners -= 1; + if (closeRequestListeners === 0) { + void ipcRenderer.invoke(IpcChannels.WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL, false); + } + }; + }, + resolveCloseRequest: (requestId, decision) => + ipcRenderer.invoke(IpcChannels.WINDOWS_RESOLVE_CLOSE_REQUEST_CHANNEL, { requestId, decision }), + setMiniMode: (enabled) => ipcRenderer.invoke(IpcChannels.WINDOWS_SET_MINI_MODE_CHANNEL, enabled), + setMultiWindowEnabled: (enabled) => + ipcRenderer.invoke(IpcChannels.WINDOWS_SET_MULTI_WINDOW_ENABLED_CHANNEL, enabled), registerHub: () => { void ipcRenderer.invoke(IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL).catch(() => undefined); }, diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 04406f63c6b3d..692d367b3702c 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -27,6 +27,8 @@ const DesktopSettingsPatch = Schema.Struct({ ), ), mainWindowMaximized: Schema.optionalKey(Schema.Boolean), + windowProfiles: Schema.optionalKey(Schema.Array(Schema.Unknown)), + multiWindowEnabled: Schema.optionalKey(Schema.Boolean), serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])), tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean), tailscaleServePort: Schema.optionalKey(Schema.Number), @@ -110,14 +112,19 @@ describe("DesktopSettings", () => { yield* withSettings( Effect.gen(function* () { const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, true); + yield* settings.setWindowProfilePlacement( + "main", + { x: 10, y: 20, width: 900, height: 600 }, + true, + ); }), ).pipe(Effect.provideService(Tracer.Tracer, tracer)); const operationSpans = spans.filter( - (span) => span.name === "desktop.settings.setMainWindowBounds", + (span) => span.name === "desktop.settings.setWindowProfilePlacement", ); assert.lengthOf(operationSpans, 1); assert.deepEqual(Object.fromEntries(operationSpans[0]!.attributes), { + profileId: "main", x: 10, y: 20, width: 900, @@ -193,7 +200,11 @@ describe("DesktopSettings", () => { yield* Effect.exit(settings.load); yield* Effect.exit( - settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, false), + settings.setWindowProfilePlacement( + "main", + { x: 10, y: 20, width: 900, height: 600 }, + false, + ), ); const persisted = yield* decodeDesktopSettingsPatch( @@ -225,8 +236,13 @@ describe("DesktopSettings", () => { assert.deepEqual(yield* settings.load, { linuxPasswordStore: "auto", localEnvironmentEnabled: true, - mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 }, - mainWindowMaximized: false, + multiWindowEnabled: true, + windowProfiles: [ + { + ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, + bounds: { x: 120, y: 80, width: 1280, height: 900 }, + }, + ], serverExposureMode: "network-accessible", tailscaleServeEnabled: true, tailscaleServePort: 8443, @@ -253,7 +269,11 @@ describe("DesktopSettings", () => { ); assert.isFalse((yield* settings.load).localEnvironmentEnabled); - yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 800, height: 600 }, false); + yield* settings.setWindowProfilePlacement( + "main", + { x: 10, y: 20, width: 800, height: 600 }, + false, + ); assert.include( yield* fileSystem.readFileString(environment.desktopSettingsPath), `"localEnvironmentEnabled":false`, @@ -277,10 +297,10 @@ describe("DesktopSettings", () => { serverExposureMode: "network-accessible", }); - const loaded = yield* settings.load; - assert.isNull(loaded.mainWindowBounds); - assert.isFalse(loaded.mainWindowMaximized); - assert.equal(loaded.serverExposureMode, "network-accessible"); + const loaded = DesktopAppSettings.defaultWindowProfile(yield* settings.load); + assert.isNull(loaded.bounds); + assert.isFalse(loaded.maximized); + assert.equal((yield* settings.get).serverExposureMode, "network-accessible"); } }), ), @@ -293,8 +313,13 @@ describe("DesktopSettings", () => { const fileSystem = yield* FileSystem.FileSystem; const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 400, height: 360 }, true); + yield* settings.setWindowProfilePlacement( + "main", + { x: -1200, y: 40, width: 400, height: 360 }, + true, + ); yield* settings.setServerExposureMode("network-accessible"); + yield* settings.setMultiWindowEnabled(false); const persisted = yield* decodeDesktopSettingsPatch( yield* fileSystem.readFileString(environment.desktopSettingsPath), @@ -302,6 +327,7 @@ describe("DesktopSettings", () => { assert.deepEqual(persisted, { mainWindowBounds: { x: -1200, y: 40, width: 400, height: 360 }, mainWindowMaximized: true, + multiWindowEnabled: false, serverExposureMode: "network-accessible", } satisfies typeof DesktopSettingsPatch.Type); @@ -309,8 +335,17 @@ describe("DesktopSettings", () => { const freshSettings = yield* DesktopAppSettings.DesktopAppSettings; return yield* freshSettings.load; }).pipe(Effect.provide(DesktopAppSettings.layer)); - assert.deepEqual(restored.mainWindowBounds, persisted.mainWindowBounds); - assert.isTrue(restored.mainWindowMaximized); + const restoredMain = DesktopAppSettings.defaultWindowProfile(restored); + assert.deepEqual(restoredMain.bounds, persisted.mainWindowBounds); + assert.isTrue(restoredMain.maximized); + assert.isFalse(restored.multiWindowEnabled); + + // The default leaves the key out, so an older build's file stays as it was. + yield* settings.setMultiWindowEnabled(true); + const reenabled = yield* decodeDesktopSettingsPatch( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + ); + assert.isUndefined(reenabled.multiWindowEnabled); }), ), ); @@ -378,8 +413,8 @@ describe("DesktopSettings", () => { assert.deepEqual(yield* settings.load, { linuxPasswordStore: "auto", localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, + multiWindowEnabled: true, + windowProfiles: [DesktopAppSettings.DEFAULT_WINDOW_PROFILE], serverExposureMode: "local-only", tailscaleServeEnabled: false, tailscaleServePort: 443, @@ -407,8 +442,8 @@ describe("DesktopSettings", () => { assert.deepEqual(yield* settings.load, { linuxPasswordStore: "auto", localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, + multiWindowEnabled: true, + windowProfiles: [DesktopAppSettings.DEFAULT_WINDOW_PROFILE], serverExposureMode: "local-only", tailscaleServeEnabled: false, tailscaleServePort: 443, @@ -483,6 +518,102 @@ describe("DesktopSettings", () => { ), ); + it.effect("moves the legacy main window placement into the default profile and mirrors it", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const settings = yield* DesktopAppSettings.DesktopAppSettings; + const legacyBounds = { x: 40, y: 30, width: 1200, height: 800 }; + yield* writeSettingsPatch({ mainWindowBounds: legacyBounds, mainWindowMaximized: true }); + + assert.deepEqual((yield* settings.load).windowProfiles, [ + { ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, bounds: legacyBounds, maximized: true }, + ]); + + const work = { + id: "work", + name: "Work", + projectScopeKeys: ["env:/repo"], + theme: "dracula", + bounds: { x: 60, y: 50, width: 900, height: 700 }, + maximized: false, + openAtQuit: true, + }; + yield* settings.updateWindowProfiles(([main, ...rest]) => [ + { ...main!, name: "Primary" }, + ...rest, + work, + ]); + yield* settings.setWindowProfilePlacement("main", { ...legacyBounds, x: 80 }, false); + + const persisted = yield* decodeDesktopSettingsPatch( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + ); + // An older build reads only the legacy keys, so they keep the main window's placement. + assert.deepEqual(persisted.mainWindowBounds, { ...legacyBounds, x: 80 }); + assert.isUndefined(persisted.mainWindowMaximized); + assert.deepEqual(persisted.windowProfiles, [{ id: "main", name: "Primary" }, work]); + assert.deepEqual((yield* settings.load).windowProfiles, [ + { + ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, + name: "Primary", + bounds: { ...legacyBounds, x: 80 }, + }, + work, + ]); + }), + ), + ); + + it.effect("keeps only valid, unique window profiles with the default one first", () => + withSettings( + Effect.gen(function* () { + const settings = yield* DesktopAppSettings.DesktopAppSettings; + yield* writeSettingsPatch({ + serverExposureMode: "network-accessible", + windowProfiles: [ + "not a profile", + { name: "No id" }, + { + id: "side", + name: "Side", + projectScopeKeys: ["a", "", "a", 7, "b"], + theme: "", + bounds: { x: 0, y: 0, width: 10, height: 10 }, + maximized: true, + openAtQuit: "yes", + }, + { id: "side", name: "Duplicate" }, + { id: "long", name: "x".repeat(81) }, + { id: "main", name: "Desk", theme: "dark", projectScopeKeys: ["a"], openAtQuit: true }, + ], + }); + + const loaded = yield* settings.load; + assert.equal(loaded.serverExposureMode, "network-accessible"); + assert.deepEqual(loaded.windowProfiles, [ + { ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, name: "Desk" }, + { + id: "side", + name: "Side", + projectScopeKeys: ["a", "b"], + theme: null, + bounds: null, + maximized: false, + openAtQuit: false, + }, + ]); + + // Profile edits normalize the same way, so the default profile cannot be removed. + yield* settings.updateWindowProfiles(() => []); + assert.deepEqual((yield* settings.get).windowProfiles, [ + { ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, name: "Desk" }, + ]); + }), + ), + ); + it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () => withSettings( Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index e81da70660648..ccfd17ab58d47 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -1,6 +1,11 @@ import { + DEFAULT_DESKTOP_WINDOW_PROFILE_ID, DesktopServerExposureModeSchema, DesktopUpdateChannelSchema, + DesktopWindowProfileIdSchema, + DesktopWindowProfileNameSchema, + DesktopWindowProfileThemeSchema, + DesktopWindowProjectScopeKeysSchema, type DesktopServerExposureMode, type DesktopUpdateChannel, } from "@t3tools/contracts"; @@ -30,8 +35,9 @@ import { isValidDistroName } from "../wsl/wslPathParsing.ts"; export interface DesktopSettings { readonly localEnvironmentEnabled: boolean; readonly linuxPasswordStore: LinuxPasswordStorePreference; - readonly mainWindowBounds: DesktopWindowBounds | null; - readonly mainWindowMaximized: boolean; + /** The default (main window) profile is always first. */ + readonly windowProfiles: ReadonlyArray; + readonly multiWindowEnabled: boolean; readonly serverExposureMode: DesktopServerExposureMode; readonly tailscaleServeEnabled: boolean; readonly tailscaleServePort: number; @@ -43,6 +49,17 @@ export interface DesktopSettings { readonly wslOnly: boolean; } +export interface DesktopWindowProfileSettings { + readonly id: string; + readonly name: string; + readonly projectScopeKeys: ReadonlyArray; + readonly theme: string | null; + readonly bounds: DesktopWindowBounds | null; + readonly maximized: boolean; + /** Reopen this profile's window on the next launch; set for windows open when the app quit. */ + readonly openAtQuit: boolean; +} + export interface DesktopSettingsChange { readonly settings: DesktopSettings; readonly changed: boolean; @@ -68,11 +85,23 @@ export const DEFAULT_MAIN_WINDOW_SIZE = { height: 780, } as const; +const DEFAULT_WINDOW_PROFILE_NAME = "Main"; + +export const DEFAULT_WINDOW_PROFILE: DesktopWindowProfileSettings = { + id: DEFAULT_DESKTOP_WINDOW_PROFILE_ID, + name: DEFAULT_WINDOW_PROFILE_NAME, + projectScopeKeys: [], + theme: null, + bounds: null, + maximized: false, + openAtQuit: false, +}; + export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { localEnvironmentEnabled: true, linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE, - mainWindowBounds: null, - mainWindowMaximized: false, + windowProfiles: [DEFAULT_WINDOW_PROFILE], + multiWindowEnabled: true, serverExposureMode: "local-only", tailscaleServeEnabled: false, tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT, @@ -95,11 +124,25 @@ const DesktopWindowBoundsDocument = Schema.Struct({ const optionalReadableKey = (schema: S) => Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone))); +const DesktopWindowProfileDocument = Schema.Struct({ + id: optionalReadableKey(Schema.String), + name: optionalReadableKey(Schema.String), + projectScopeKeys: optionalReadableKey(Schema.Array(Schema.Unknown)), + theme: optionalReadableKey(Schema.NullOr(Schema.String)), + bounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), + maximized: optionalReadableKey(Schema.Boolean), + openAtQuit: optionalReadableKey(Schema.Boolean), +}); +type DesktopWindowProfileDocument = typeof DesktopWindowProfileDocument.Type; + const DesktopSettingsDocument = Schema.Struct({ localEnvironmentEnabled: optionalReadableKey(Schema.Boolean), linuxPasswordStore: optionalReadableKey(Schema.Unknown), + // Mirrors the default profile's placement so an older build keeps the main window where it was. mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), mainWindowMaximized: optionalReadableKey(Schema.Boolean), + windowProfiles: optionalReadableKey(Schema.Array(Schema.Unknown)), + multiWindowEnabled: optionalReadableKey(Schema.Boolean), serverExposureMode: optionalReadableKey(DesktopServerExposureModeSchema), tailscaleServeEnabled: optionalReadableKey(Schema.Boolean), tailscaleServePort: optionalReadableKey(Schema.Number), @@ -119,6 +162,13 @@ const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson); const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson); const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema); const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema); +const decodeWindowProfileDocument = Schema.decodeUnknownOption(DesktopWindowProfileDocument); +const isWindowProfileId = Schema.is(DesktopWindowProfileIdSchema); +const isWindowProfileName = Schema.is(DesktopWindowProfileNameSchema); +const isWindowProfileTheme = Schema.is(DesktopWindowProfileThemeSchema); +const isProjectScopeKeys = Schema.is(DesktopWindowProjectScopeKeysSchema); +const isProjectScopeKey = (key: unknown): key is string => isProjectScopeKeys([key]); +const MAX_PROJECT_SCOPE_KEYS = 1000; const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({ settings, @@ -156,10 +206,20 @@ export class DesktopAppSettings extends Context.Service< readonly setLocalEnvironmentEnabled: ( enabled: boolean, ) => Effect.Effect; - readonly setMainWindowBounds: ( + readonly setMultiWindowEnabled: ( + enabled: boolean, + ) => Effect.Effect; + readonly setWindowProfilePlacement: ( + profileId: string, bounds: DesktopWindowBounds, isMaximized: boolean, ) => Effect.Effect; + /** The result is normalized: invalid and duplicate profiles drop, the default one stays. */ + readonly updateWindowProfiles: ( + update: ( + profiles: ReadonlyArray, + ) => ReadonlyArray, + ) => Effect.Effect; readonly setServerExposureMode: ( mode: DesktopServerExposureMode, ) => Effect.Effect; @@ -208,12 +268,83 @@ export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | return Option.getOrNull(decodeDesktopWindowBounds(value)); } +export function normalizeProjectScopeKeys(value: ReadonlyArray): ReadonlyArray { + const keys = new Set(); + for (const key of value) { + if (keys.size >= MAX_PROJECT_SCOPE_KEYS) break; + if (isProjectScopeKey(key)) keys.add(key); + } + return [...keys]; +} + +function normalizeWindowProfile( + document: DesktopWindowProfileDocument, +): DesktopWindowProfileSettings | null { + const { id, name } = document; + if (!isWindowProfileId(id)) return null; + const isDefault = id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID; + const validName = isWindowProfileName(name) && name.trim() !== "" ? name : null; + if (validName === null && !isDefault) return null; + const bounds = normalizeMainWindowBounds(document.bounds); + return { + id, + name: validName ?? DEFAULT_WINDOW_PROFILE_NAME, + projectScopeKeys: isDefault ? [] : normalizeProjectScopeKeys(document.projectScopeKeys ?? []), + theme: !isDefault && isWindowProfileTheme(document.theme) ? document.theme : null, + bounds, + maximized: bounds !== null && document.maximized === true, + openAtQuit: !isDefault && document.openAtQuit === true, + }; +} + +/** + * Keeps valid profiles in order with unique ids and the default profile first. The default + * profile cannot carry a theme, filter or reopen flag. + */ +export function normalizeWindowProfiles( + profiles: ReadonlyArray, +): ReadonlyArray { + const seen = new Set(); + let defaultProfile: DesktopWindowProfileSettings = DEFAULT_WINDOW_PROFILE; + const others: DesktopWindowProfileSettings[] = []; + for (const candidate of profiles) { + const profile = normalizeWindowProfile(candidate); + if (profile === null || seen.has(profile.id)) continue; + seen.add(profile.id); + if (profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) defaultProfile = profile; + else others.push(profile); + } + return [defaultProfile, ...others]; +} + +function readWindowProfiles(parsed: DesktopSettingsDocument) { + const documents: DesktopWindowProfileDocument[] = []; + for (const entry of parsed.windowProfiles ?? []) { + const decoded = decodeWindowProfileDocument(entry); + if (Option.isSome(decoded)) documents.push(decoded.value); + } + const [defaultProfile = DEFAULT_WINDOW_PROFILE, ...others] = normalizeWindowProfiles(documents); + // The default profile's placement lives in the legacy keys, which older builds also read and write. + const bounds = normalizeMainWindowBounds(parsed.mainWindowBounds); + return [ + { + ...defaultProfile, + bounds, + maximized: bounds !== null && parsed.mainWindowMaximized === true, + }, + ...others, + ]; +} + +export function defaultWindowProfile(settings: DesktopSettings): DesktopWindowProfileSettings { + return settings.windowProfiles[0] ?? DEFAULT_WINDOW_PROFILE; +} + function normalizeDesktopSettingsDocument( parsed: DesktopSettingsDocument, appVersion: string, ): DesktopSettings { const defaultSettings = resolveDefaultDesktopSettings(appVersion); - const mainWindowBounds = normalizeMainWindowBounds(parsed.mainWindowBounds); const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel); const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined; const updateChannelConfiguredByUser = @@ -227,8 +358,8 @@ function normalizeDesktopSettingsDocument( return { localEnvironmentEnabled: parsed.localEnvironmentEnabled !== false, linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore), - mainWindowBounds, - mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true, + windowProfiles: readWindowProfiles(parsed), + multiWindowEnabled: parsed.multiWindowEnabled !== false, serverExposureMode: parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only", tailscaleServeEnabled: parsed.tailscaleServeEnabled === true, @@ -256,12 +387,28 @@ function toDesktopSettingsDocument( if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) { document.linuxPasswordStore = settings.linuxPasswordStore; } - if (settings.mainWindowBounds !== null) { - document.mainWindowBounds = settings.mainWindowBounds; + const [defaultProfile, ...otherProfiles] = settings.windowProfiles; + if (defaultProfile !== undefined && defaultProfile.bounds !== null) { + document.mainWindowBounds = defaultProfile.bounds; } - if (settings.mainWindowMaximized) { + if (defaultProfile?.maximized === true) { document.mainWindowMaximized = true; } + if ( + otherProfiles.length > 0 || + (defaultProfile !== undefined && defaultProfile.name !== DEFAULT_WINDOW_PROFILE_NAME) + ) { + document.windowProfiles = [ + // The legacy keys carry the default profile's placement. + ...(defaultProfile === undefined + ? [] + : [{ id: defaultProfile.id, name: defaultProfile.name }]), + ...otherProfiles, + ]; + } + if (settings.multiWindowEnabled !== defaults.multiWindowEnabled) { + document.multiWindowEnabled = settings.multiWindowEnabled; + } if (settings.serverExposureMode !== defaults.serverExposureMode) { document.serverExposureMode = settings.serverExposureMode; } @@ -302,20 +449,45 @@ function setServerExposureMode( }; } -function setMainWindowBounds( +function setWindowProfilePlacement( settings: DesktopSettings, + profileId: string, bounds: DesktopWindowBounds, isMaximized: boolean, ): DesktopSettings { - return settings.mainWindowBounds !== null && - desktopWindowBoundsEquivalence(settings.mainWindowBounds, bounds) && - settings.mainWindowMaximized === isMaximized + const profile = settings.windowProfiles.find((candidate) => candidate.id === profileId); + if ( + profile === undefined || + (profile.bounds !== null && + desktopWindowBoundsEquivalence(profile.bounds, bounds) && + profile.maximized === isMaximized) + ) { + return settings; + } + return { + ...settings, + windowProfiles: settings.windowProfiles.map((candidate) => + candidate === profile ? { ...candidate, bounds, maximized: isMaximized } : candidate, + ), + }; +} + +function updateWindowProfiles( + settings: DesktopSettings, + update: ( + profiles: ReadonlyArray, + ) => ReadonlyArray, +): DesktopSettings { + const updated = update(settings.windowProfiles); + // Dropping the default profile keeps it as it was; it can only be renamed or moved. + const windowProfiles = normalizeWindowProfiles( + updated.some((profile) => profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) + ? updated + : [defaultWindowProfile(settings), ...updated], + ); + return JSON.stringify(windowProfiles) === JSON.stringify(settings.windowProfiles) ? settings - : { - ...settings, - mainWindowBounds: bounds, - mainWindowMaximized: isMaximized, - }; + : { ...settings, windowProfiles }; } function setTailscaleServe( @@ -376,6 +548,12 @@ function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSetting }; } +function setMultiWindowEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings { + return settings.multiWindowEnabled === enabled + ? settings + : { ...settings, multiWindowEnabled: enabled }; +} + function setLocalEnvironmentEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings { return settings.localEnvironmentEnabled === enabled ? settings @@ -549,9 +727,10 @@ export const make = Effect.gen(function* () { ); return yield* SynchronizedRef.setAndGet(settingsRef, settings); }).pipe(Effect.withSpan("desktop.settings.load")), - setMainWindowBounds: Effect.fn("desktop.settings.setMainWindowBounds")( - function* (bounds, isMaximized) { + setWindowProfilePlacement: Effect.fn("desktop.settings.setWindowProfilePlacement")( + function* (profileId, bounds, isMaximized) { yield* Effect.annotateCurrentSpan({ + profileId, x: bounds.x, y: bounds.y, width: bounds.width, @@ -559,9 +738,14 @@ export const make = Effect.gen(function* () { isMaximized, }); - return yield* persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)); + return yield* persist((settings) => + setWindowProfilePlacement(settings, profileId, bounds, isMaximized), + ); }, ), + updateWindowProfiles: Effect.fn("desktop.settings.updateWindowProfiles")(function* (update) { + return yield* persist((settings) => updateWindowProfiles(settings, update)); + }), setServerExposureMode: Effect.fn("desktop.settings.setServerExposureMode")(function* (mode) { yield* Effect.annotateCurrentSpan({ mode }); @@ -599,6 +783,10 @@ export const make = Effect.gen(function* () { return yield* persist((settings) => setLocalEnvironmentEnabled(settings, enabled)); }, ), + setMultiWindowEnabled: Effect.fn("desktop.settings.setMultiWindowEnabled")(function* (enabled) { + yield* Effect.annotateCurrentSpan({ enabled }); + return yield* persist((settings) => setMultiWindowEnabled(settings, enabled)); + }), applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe( Effect.withSpan("desktop.settings.applyWslWindowsFallback"), ), @@ -630,9 +818,16 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET return DesktopAppSettings.of({ get: SynchronizedRef.get(settingsRef), load: SynchronizedRef.get(settingsRef), - setMainWindowBounds: Effect.fn("DesktopAppSettings.setMainWindowBounds")( - function (bounds, isMaximized) { - return update((settings) => setMainWindowBounds(settings, bounds, isMaximized)); + setWindowProfilePlacement: Effect.fn("DesktopAppSettings.setWindowProfilePlacement")( + function (profileId, bounds, isMaximized) { + return update((settings) => + setWindowProfilePlacement(settings, profileId, bounds, isMaximized), + ); + }, + ), + updateWindowProfiles: Effect.fn("DesktopAppSettings.updateWindowProfiles")( + function (profilesUpdate) { + return update((settings) => updateWindowProfiles(settings, profilesUpdate)); }, ), setServerExposureMode: Effect.fn("DesktopAppSettings.setServerExposureMode")( @@ -662,6 +857,11 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET return update((settings) => setLocalEnvironmentEnabled(settings, enabled)); }, ), + setMultiWindowEnabled: Effect.fn("DesktopAppSettings.setMultiWindowEnabled")( + function (enabled) { + return update((settings) => setMultiWindowEnabled(settings, enabled)); + }, + ), applyWslWindowsFallback: update(applyWslWindowsFallback), applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback), }); diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index 480a4496553b7..acca841f6f945 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -217,7 +217,8 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, { get: Effect.sync(() => testSettings), load: Effect.sync(() => testSettings), - setMainWindowBounds: () => Effect.die("unexpected main window bounds update"), + setWindowProfilePlacement: () => Effect.die("unexpected window bounds update"), + updateWindowProfiles: () => Effect.die("unexpected window profile update"), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: (channel) => @@ -239,6 +240,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"), setWslDistro: () => Effect.die("unexpected WSL distro change"), setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"), + setMultiWindowEnabled: () => Effect.die("unexpected multi-window toggle"), setWslOnly: () => Effect.die("unexpected WSL-only toggle"), applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"), applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"), diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 2166d7c9cb97d..e61220e60b578 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -5,7 +5,11 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import type { DesktopUpdateCheckResult, DesktopUpdateState } from "@t3tools/contracts"; +import type { + DesktopUpdateCheckResult, + DesktopUpdateState, + DesktopWindowsState, +} from "@t3tools/contracts"; import * as Electron from "electron"; import { vi } from "vite-plus/test"; @@ -91,7 +95,17 @@ const layerDesktopUpdates = ({ checkResult }: MenuServices) => installPrepared: () => Effect.die("unexpected installPrepared"), } satisfies DesktopUpdates.DesktopUpdates["Service"]); -const layerDesktopWindow = (selectedAction: Deferred.Deferred) => +const emptyWindowsState: DesktopWindowsState = { + profiles: [], + windows: [], + miniMode: false, + multiWindowEnabled: true, +}; + +const layerDesktopWindow = ( + selectedAction: Deferred.Deferred, + windowsState: DesktopWindowsState = emptyWindowsState, +) => Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected createMain"), ensureMain: Effect.die("unexpected ensureMain"), @@ -101,7 +115,7 @@ const layerDesktopWindow = (selectedAction: Deferred.Deferred) => showConnectingSplash: Effect.void, handleBackendReady: () => Effect.void, handleBackendNotReady: Effect.void, - flushMainWindowBounds: Effect.void, + flushWindowState: Effect.void, prepareCaptureReveal: Effect.void, dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid), dispatchSnapShotEvent: () => Effect.void, @@ -110,6 +124,10 @@ const layerDesktopWindow = (selectedAction: Deferred.Deferred) => runFocusedContentsCommand: (command) => Deferred.succeed(selectedAction, `main-${command}`).pipe(Effect.asVoid), syncAppearance: Effect.void, + windowsState: Effect.succeed(windowsState), + subscribeWindowsState: () => Effect.void, + openProfile: (profileId) => + Deferred.succeed(selectedAction, `open-${profileId}`).pipe(Effect.asVoid), }); const layerElectronMenu = ( @@ -127,6 +145,7 @@ const configureMenu = ( applicationMenuTemplate: Deferred.Deferred, environment: Partial = {}, services: MenuServices = {}, + windowsState?: DesktopWindowsState, ) => Effect.gen(function* () { const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu; @@ -135,7 +154,7 @@ const configureMenu = ( Effect.provide( DesktopApplicationMenu.layer.pipe( Layer.provideMerge(layerElectronMenu(applicationMenuTemplate)), - Layer.provideMerge(layerDesktopWindow(selectedAction)), + Layer.provideMerge(layerDesktopWindow(selectedAction, windowsState)), Layer.provideMerge(layerDesktopUpdates(services)), Layer.provideMerge(layerElectronDialog(services)), Layer.provideMerge(layerElectronApp), @@ -347,12 +366,49 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); - it.effect("leads the Window menu with New Window and leaves its chord to the renderer", () => + it.effect("lists saved windows, marks open ones, and leaves New Window to the renderer", () => Effect.gen(function* () { const selectedAction = yield* Deferred.make(); const applicationMenuTemplate = yield* Deferred.make(); - yield* configureMenu(selectedAction, applicationMenuTemplate); + const profile = (id: string, name: string) => ({ + id, + name, + projectScopeKeys: [], + theme: null, + isDefault: id === "main", + }); + yield* configureMenu( + selectedAction, + applicationMenuTemplate, + {}, + {}, + { + profiles: [profile("main", "Main"), profile("work", "Work"), profile("side", "Side")], + windows: [ + { + windowId: 1, + isMain: true, + profileId: "main", + name: "Main", + title: "", + focused: true, + projectScopeKeys: [], + }, + { + windowId: 2, + isMain: false, + profileId: "work", + name: "Work", + title: "", + focused: false, + projectScopeKeys: [], + }, + ], + miniMode: true, + multiWindowEnabled: true, + }, + ); const windowMenu = (yield* Deferred.await(applicationMenuTemplate)).find( (item) => item.role === "windowMenu", @@ -360,17 +416,76 @@ describe("DesktopApplicationMenu", () => { if (!Array.isArray(windowMenu?.submenu)) { throw new Error("Expected the Window menu submenu to be an array."); } - const [newWindow] = windowMenu.submenu; + const items = windowMenu.submenu.filter((item) => item.label !== undefined); assert.deepEqual( - { label: newWindow?.label, accelerator: newWindow?.accelerator }, - { label: "New Window", accelerator: "CmdOrCtrl+Alt+Shift+N" }, + items.slice(0, 5).map(({ label, checked, accelerator, registerAccelerator }) => ({ + label, + checked, + accelerator, + registerAccelerator, + })), + [ + { + label: "New Window", + checked: undefined, + accelerator: "CmdOrCtrl+Alt+Shift+N", + registerAccelerator: false, + }, + { + label: "Main Window", + checked: undefined, + accelerator: undefined, + registerAccelerator: undefined, + }, + { label: "Work", checked: true, accelerator: undefined, registerAccelerator: undefined }, + { label: "Side", checked: false, accelerator: undefined, registerAccelerator: undefined }, + { + label: "Mini Mode", + checked: true, + accelerator: undefined, + registerAccelerator: undefined, + }, + ], ); - assert.equal(newWindow?.registerAccelerator, false); - newWindow?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + items[0]?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); assert.equal(yield* Deferred.await(selectedAction), "new-window"); }), ); + it.effect( + "drops New Window and saved windows from the Window menu when multi-window is off", + () => + Effect.gen(function* () { + const applicationMenuTemplate = + yield* Deferred.make(); + yield* configureMenu( + yield* Deferred.make(), + applicationMenuTemplate, + {}, + {}, + { + ...emptyWindowsState, + profiles: [ + { id: "main", name: "Main", projectScopeKeys: [], theme: null, isDefault: true }, + { id: "work", name: "Work", projectScopeKeys: [], theme: null, isDefault: false }, + ], + multiWindowEnabled: false, + }, + ); + + const windowMenu = (yield* Deferred.await(applicationMenuTemplate)).find( + (item) => item.role === "windowMenu", + ); + if (!Array.isArray(windowMenu?.submenu)) { + throw new Error("Expected the Window menu submenu to be an array."); + } + assert.deepEqual( + windowMenu.submenu.flatMap((item) => (item.label === undefined ? [] : [item.label])), + ["Mini Mode"], + ); + }), + ); + it.effect("tells the user which update the menu check found", () => Effect.gen(function* () { const dialog = yield* checkForUpdatesFromMacMenu({ diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 524471920374b..34ee8e21690ae 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -4,7 +4,11 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import type { DesktopUpdateChannel } from "@t3tools/contracts"; +import { + DEFAULT_DESKTOP_WINDOW_PROFILE_ID, + type DesktopUpdateChannel, + type DesktopWindowsState, +} from "@t3tools/contracts"; import * as Electron from "electron"; import { msg } from "gt-i18n"; @@ -74,6 +78,15 @@ const trackLabel = (channel: DesktopUpdateChannel) => ? m(msg("Nightly", { $context: "release track" })) : m(msg("Stable", { $context: "release track" })); +// Only what the Window menu shows; focus and title changes do not rebuild the menu. +const windowMenuKey = (state: DesktopWindowsState) => + JSON.stringify({ + profiles: state.profiles.map((profile) => [profile.id, profile.name]), + open: state.windows.flatMap((window) => (window.profileId === null ? [] : [window.profileId])), + miniMode: state.miniMode, + multiWindowEnabled: state.multiWindowEnabled, + }); + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -187,9 +200,11 @@ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const electronApp = yield* ElectronApp.ElectronApp; const clientSettings = yield* Effect.serviceOption(DesktopClientSettings.DesktopClientSettings); + const desktopWindow = yield* DesktopWindow.DesktopWindow; const context = yield* Effect.context(); const runPromise = Effect.runPromiseWith(context); const runFork = Effect.runForkWith(context); + let configuredWindowMenuKey: string | null = null; const runMenuEffect = ( action: string, @@ -207,7 +222,24 @@ export const make = Effect.gen(function* () { ); }; - const configure = Effect.gen(function* () { + const configure: Effect.Effect = Effect.gen(function* () { + const windowsState = yield* desktopWindow.windowsState; + configuredWindowMenuKey = windowMenuKey(windowsState); + // Electron flips a clicked checkbox itself; rebuilding restores the real open state. + const windowMenuClick = + (action: string, effect: Effect.Effect) => () => { + runMenuEffect(action, effect.pipe(Effect.ensuring(configure))); + }; + const openProfileClick = (profileId: string) => + windowMenuClick( + "open-window-profile", + Effect.flatMap(DesktopWindow.DesktopWindow, (windows) => windows.openProfile(profileId)), + ); + const openWindowProfileIds = new Set( + windowsState.windows.flatMap((window) => + window.profileId === null ? [] : [window.profileId], + ), + ); const checkForUpdatesClick = () => { runMenuEffect("check-for-updates", handleCheckForUpdatesMenuClick); }; @@ -396,12 +428,41 @@ export const make = Effect.gen(function* () { role: "windowMenu", label: m(msg("Window", { $context: "menu bar title" })), submenu: [ + ...(windowsState.multiWindowEnabled + ? ([ + { + label: m(msg("New Window", { $context: "Window menu item" })), + // The renderer's window.new keybinding owns the chord and adds its project filter. + accelerator: "CmdOrCtrl+Alt+Shift+N", + registerAccelerator: false, + click: () => runMenuEffect("new-window", dispatchMenuAction("new-window")), + }, + { type: "separator" }, + { + label: m(msg("Main Window", { $context: "Window menu item" })), + click: openProfileClick(DEFAULT_DESKTOP_WINDOW_PROFILE_ID), + }, + ...windowsState.profiles + .filter((profile) => !profile.isDefault) + .map((profile): Electron.MenuItemConstructorOptions => ({ + label: profile.name, + type: "checkbox", + checked: openWindowProfileIds.has(profile.id), + click: openProfileClick(profile.id), + })), + { type: "separator" }, + ] satisfies Electron.MenuItemConstructorOptions[]) + : []), { - label: m(msg("New Window", { $context: "Window menu item" })), - // The renderer's window.new keybinding owns the chord. - accelerator: "CmdOrCtrl+Alt+Shift+N", - registerAccelerator: false, - click: () => runMenuEffect("new-window", dispatchMenuAction("new-window")), + label: m(msg("Mini Mode", { $context: "Window menu item" })), + type: "checkbox", + checked: windowsState.miniMode, + click: windowMenuClick( + "mini-mode", + Effect.flatMap(DesktopWindow.DesktopWindow, (windows) => + windows.setMiniMode(!windowsState.miniMode), + ), + ), }, { type: "separator" }, { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) }, @@ -444,6 +505,12 @@ export const make = Effect.gen(function* () { }); let rebuildsOnLocaleChange = false; + yield* desktopWindow.subscribeWindowsState((state) => { + if (configuredWindowMenuKey === null || windowMenuKey(state) === configuredWindowMenuKey) + return; + void runPromise(configure); + }); + return DesktopApplicationMenu.of({ configure: applySavedLanguage.pipe( Effect.andThen(configure), diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 3d812c82aa5f8..0148ddbdf3a2f 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -11,6 +11,7 @@ import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as TestClock from "effect/testing/TestClock"; import * as Electron from "electron"; @@ -47,7 +48,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; -import { SNAP_SHOT_EVENT_CHANNEL } from "../ipc/channels.ts"; +import { SNAP_SHOT_EVENT_CHANNEL, WINDOWS_CLOSE_REQUEST_CHANNEL } from "../ipc/channels.ts"; import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; import * as DesktopWindow from "./DesktopWindow.ts"; import { @@ -239,6 +240,21 @@ const desktopWindowBoundsEquivalence = Schema.toEquivalence( DesktopAppSettings.DesktopWindowBoundsSchema, ); +function withMainPlacement( + settings: DesktopAppSettings.DesktopSettings, + bounds: DesktopAppSettings.DesktopWindowBounds | null, + maximized: boolean, +): DesktopAppSettings.DesktopSettings { + const [main, ...others] = settings.windowProfiles; + return { ...settings, windowProfiles: [{ ...main!, bounds, maximized }, ...others] }; +} + +let randomByte = 0; +const layerSecureRandom = Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(++randomByte % 256)), +); + function layerTest(input: { readonly window: Electron.BrowserWindow; readonly createCount: Ref.Ref; @@ -274,26 +290,34 @@ function layerTest(input: { const layerDesktopAppSettings = Layer.succeed(DesktopAppSettings.DesktopAppSettings, { get: Effect.sync(() => desktopSettings), load: Effect.sync(() => desktopSettings), - setMainWindowBounds: (bounds, isMaximized) => + setWindowProfilePlacement: (profileId, bounds, isMaximized) => Effect.gen(function* () { if (input.beforeMainWindowBoundsUpdate) { yield* input.beforeMainWindowBoundsUpdate(bounds); } + const main = DesktopAppSettings.defaultWindowProfile(desktopSettings); const changed = - desktopSettings.mainWindowBounds === null || - !desktopWindowBoundsEquivalence(desktopSettings.mainWindowBounds, bounds) || - desktopSettings.mainWindowMaximized !== isMaximized; + profileId === main.id && + (main.bounds === null || + !desktopWindowBoundsEquivalence(main.bounds, bounds) || + main.maximized !== isMaximized); if (changed) { - desktopSettings = { - ...desktopSettings, - mainWindowBounds: bounds, - mainWindowMaximized: isMaximized, - }; + desktopSettings = withMainPlacement(desktopSettings, bounds, isMaximized); input.mainWindowBoundsUpdates?.push(bounds); input.mainWindowMaximizedUpdates?.push(isMaximized); } return { settings: desktopSettings, changed }; }), + updateWindowProfiles: (update) => + Effect.sync(() => { + desktopSettings = { + ...desktopSettings, + windowProfiles: DesktopAppSettings.normalizeWindowProfiles( + update(desktopSettings.windowProfiles), + ), + }; + return { settings: desktopSettings, changed: true }; + }), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: () => Effect.die("unexpected update channel change"), @@ -301,6 +325,12 @@ function layerTest(input: { setWslDistro: () => Effect.die("unexpected WSL distro change"), setWslOnly: () => Effect.die("unexpected WSL-only toggle"), setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"), + setMultiWindowEnabled: (enabled) => + Effect.sync(() => { + const changed = desktopSettings.multiWindowEnabled !== enabled; + desktopSettings = { ...desktopSettings, multiWindowEnabled: enabled }; + return { settings: desktopSettings, changed }; + }), applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"), applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"), } satisfies DesktopAppSettings.DesktopAppSettings["Service"]); @@ -374,6 +404,7 @@ function layerTest(input: { copyText: input.onCopyText ?? (() => Effect.void), } satisfies ElectronShell.ElectronShell["Service"]), layerElectronTheme, + layerSecureRandom, layerElectronWindow, Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: input.primaryPasteEnabled ?? true, @@ -491,6 +522,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n copyText: () => Effect.void, } satisfies ElectronShell.ElectronShell["Service"]), layerElectronTheme, + layerSecureRandom, Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape), Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), Layer.mock(PreviewPasskeys.PreviewPasskeys)({ @@ -1256,10 +1288,11 @@ describe("DesktopWindow", () => { createCount, mainWindow, mainWindowBoundsUpdates, - desktopSettings: { - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 }, - }, + desktopSettings: withMainPlacement( + DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, + { x: 2040, y: 80, width: 1320, height: 880 }, + false, + ), }); yield* Effect.gen(function* () { @@ -1313,7 +1346,7 @@ describe("DesktopWindow", () => { fakeWindow.isMinimized.mockReturnValue(true); fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 }); - yield* desktopWindow.flushMainWindowBounds; + yield* desktopWindow.flushWindowState; resize(); yield* TestClock.adjust(500); yield* Effect.promise(() => Promise.resolve()); @@ -1437,7 +1470,7 @@ describe("DesktopWindow", () => { yield* TestClock.adjust(250); yield* Effect.promise(() => Promise.resolve()); } - yield* desktopWindow.flushMainWindowBounds; + yield* desktopWindow.flushWindowState; assert.deepEqual(mainWindowBoundsUpdates, [ maximized @@ -1485,37 +1518,121 @@ describe("DesktopWindow", () => { }), ); - it.effect("opens a secondary window, keeping the main window hidden while it serves it", () => + it.effect("asks before closing an unsaved window and saves it as a profile", () => Effect.gen(function* () { const main = makeFakeBrowserWindow(); const secondary = makeFakeBrowserWindow(); + secondary.getBounds.mockReturnValue({ x: 60, y: 50, width: 1000, height: 700 }); const createCount = yield* Ref.make(0); const mainWindow = yield* Ref.make>(Option.none()); + const promptRevealed = yield* Deferred.make(); const layer = layerTest({ window: main.window, createdWindows: [main.window, secondary.window], createCount, mainWindow, + onReveal: (window) => { + if (window === secondary.window) Deferred.doneUnsafe(promptRevealed, Exit.void); + }, }); yield* Effect.gen(function* () { const windows = yield* DesktopWindow.DesktopWindow; yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); - yield* windows.openNewWindow; + yield* windows.openNewWindow({ projectScopeKeys: ["env:/repo"] }); assert.equal(yield* Ref.get(createCount), 2); - assert.deepEqual(Option.getOrThrow(yield* windows.windowContext(secondary.window)), { - windowId: secondary.window.id, - isMain: false, - }); - assert.deepEqual((yield* windows.windowsState).windows, [ - { windowId: main.window.id, isMain: true }, - { windowId: secondary.window.id, isMain: false }, - ]); - + secondary.webContentsListeners.get("did-finish-load")?.(); + yield* windows.setCloseRequestListening(secondary.window, true); + yield* windows.setWindowProjectScopeKeys(secondary.window, ["env:/hobby"]); + const reloadedContext = Option.getOrThrow(yield* windows.windowContext(secondary.window)); + assert.deepEqual(reloadedContext.projectScopeKeys, ["env:/hobby"]); + assert.equal(reloadedContext.profileId, null); + + const preventSecondaryClose = vi.fn(); + secondary.windowListeners.get("close")?.({ preventDefault: preventSecondaryClose }); + yield* Deferred.await(promptRevealed); + assert.equal(preventSecondaryClose.mock.calls.length, 1); + const request = secondary.send.mock.calls.find( + ([channel]) => channel === WINDOWS_CLOSE_REQUEST_CHANNEL, + )?.[1] as { readonly requestId: string; readonly suggestedName: string }; + assert.equal(request.suggestedName, "Window 2"); + + // The main window keeps serving the secondary window, so closing it only hides it. const preventMainClose = vi.fn(); main.windowListeners.get("close")?.({ preventDefault: preventMainClose }); assert.equal(preventMainClose.mock.calls.length, 1); assert.equal(main.hide.mock.calls.length, 1); + + yield* windows.resolveCloseRequest(secondary.window, "stale", { action: "discard" }); + assert.equal(secondary.close.mock.calls.length, 0); + yield* windows.resolveCloseRequest(secondary.window, request.requestId, { + action: "save", + name: " Work ", + }); + assert.equal(secondary.close.mock.calls.length, 1); + const state = yield* windows.windowsState; + const saved = state.profiles.find((profile) => profile.name === "Work"); + assert.deepEqual(saved?.projectScopeKeys, ["env:/hobby"]); + const savedContext = Option.getOrThrow(yield* windows.windowContext(secondary.window)); + assert.equal(savedContext.profileId, saved?.id); + assert.deepEqual( + state.windows.map(({ isMain, profileId, name }) => ({ isMain, profileId, name })), + [ + { isMain: true, profileId: "main", name: "Main" }, + { isMain: false, profileId: saved?.id ?? null, name: "Work" }, + ], + ); + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect("opens no secondary window while multi-window is off and saves new profiles", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const secondary = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, secondary.window], + createCount, + mainWindow, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + const saved = yield* windows.createProfile({ + name: " Hobby ", + projectScopeKeys: ["env:/hobby", "env:/hobby"], + theme: null, + }); + assert.deepEqual( + { + name: saved.name, + projectScopeKeys: saved.projectScopeKeys, + isDefault: saved.isDefault, + }, + { name: "Hobby", projectScopeKeys: ["env:/hobby"], isDefault: false }, + ); + + yield* windows.setMultiWindowEnabled(false); + assert.isFalse((yield* windows.windowsState).multiWindowEnabled); + const blocked = [ + yield* Effect.flip(windows.openNewWindow({})), + yield* Effect.flip(windows.openProfile(saved.id)), + ]; + assert.deepEqual( + blocked.map((error) => error._tag === "DesktopWindowProfileError" && error.reason), + ["multi-window-disabled", "multi-window-disabled"], + ); + // The main window still opens from its own profile. + yield* windows.openProfile("main"); + assert.equal(yield* Ref.get(createCount), 1); + + yield* windows.setMultiWindowEnabled(true); + yield* windows.openProfile(saved.id); + assert.equal(yield* Ref.get(createCount), 2); }).pipe(Effect.provide(layer)); }), ); @@ -1554,7 +1671,7 @@ describe("DesktopWindow", () => { yield* Deferred.await(writeStarted); fakeWindow.isDestroyed.mockReturnValue(true); - const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe( + const flushFiber = yield* desktopWindow.flushWindowState.pipe( Effect.andThen(Deferred.succeed(flushCompleted, undefined)), Effect.forkChild({ startImmediately: true }), ); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 6b3aa5b82e655..2ce7439dd4915 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -1,21 +1,30 @@ import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; import { msg } from "gt-i18n"; import { + type DesktopCreateWindowProfileInput, + type DesktopOpenWindowInput, type DesktopSnapShotEvent, + type DesktopTheme, + type DesktopUpdateWindowProfileInput, + type DesktopWindowCloseDecision, type DesktopWindowContext, + type DesktopWindowProfile, type DesktopWindowsState, DEFAULT_CLIENT_SETTINGS, + DEFAULT_DESKTOP_WINDOW_PROFILE_ID, } from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; @@ -36,6 +45,7 @@ import { TRACKPAD_SCROLL_BEGIN_CHANNEL, TRACKPAD_SCROLL_END_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL, + WINDOWS_CLOSE_REQUEST_CHANNEL, WINDOWS_HUB_LINK_CHANNEL, WINDOWS_HUB_PEER_GONE_CHANNEL, WINDOWS_HUB_RESET_CHANNEL, @@ -57,7 +67,12 @@ import { copyContextMenuImage } from "./ContextMenuImage.ts"; import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; import { setUnthrottledHold } from "./BackgroundThrottling.ts"; import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; -import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; +import { + cascadeWindowBounds, + composeWindowTitle, + nextUnsavedWindowName, + resolveWindowCloseAction, +} from "./DesktopWindowProfiles.ts"; const TITLEBAR_HEIGHT = 40; @@ -108,6 +123,8 @@ const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500; const RENDERER_RECOVERY_MAX_ATTEMPTS = 3; const RENDERER_RECOVERY_WINDOW_MS = 60_000; const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]); +const MINI_WINDOW_SIZE = { width: 320, height: 460 } as const; +const MINI_WINDOW_MIN_SIZE = { width: 240, height: 320 } as const; const HUB_UNTHROTTLED_REASON = "hub-serving-windows"; type WindowTitleBarOptions = Pick< @@ -133,6 +150,37 @@ export type DesktopWindowError = | ElectronWindow.ElectronWindowCreateError | PreviewManager.PreviewManagerError; +export class DesktopWindowProfileError extends Schema.TaggedError()( + "DesktopWindowProfileError", + { + reason: Schema.Literals([ + "profile-not-found", + "default-profile", + "not-a-secondary-window", + "multi-window-disabled", + ]), + profileId: Schema.NullOr(Schema.String), + }, +) { + override get message(): string { + switch (this.reason) { + case "profile-not-found": + return `Window profile ${JSON.stringify(this.profileId)} does not exist.`; + case "default-profile": + return "The main window's profile cannot be deleted."; + case "not-a-secondary-window": + return "Only a secondary window can do this."; + case "multi-window-disabled": + return "Multiple windows are turned off in Settings."; + } + } +} + +export type DesktopWindowsOperationError = + | DesktopWindowError + | DesktopAppSettings.DesktopSettingsWriteError + | DesktopWindowProfileError; + export type MainWindowZoomDirection = "in" | "out" | "reset"; export type MainWindowContentsCommand = "reload" | "forceReload" | "toggleDevTools"; @@ -147,7 +195,8 @@ export class DesktopWindow extends Context.Service< readonly showConnectingSplash: Effect.Effect; readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect; readonly handleBackendNotReady: Effect.Effect; - readonly flushMainWindowBounds: Effect.Effect; + /** Before quitting: saves every window's placement and which saved profiles to reopen. */ + readonly flushWindowState: Effect.Effect; readonly prepareCaptureReveal: Effect.Effect; readonly dispatchMenuAction: ( action: string, @@ -161,11 +210,54 @@ export class DesktopWindow extends Context.Service< readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; readonly runFocusedContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; readonly syncAppearance: Effect.Effect; + /** A secondary window's own light/dark frame, which can differ from the main window's. */ + readonly setWindowAppearance: ( + window: Electron.BrowserWindow, + theme: DesktopTheme, + ) => Effect.Effect; readonly windowsState: Effect.Effect; + readonly subscribeWindowsState: ( + listener: (state: DesktopWindowsState) => void, + ) => Effect.Effect; readonly windowContext: ( window: Electron.BrowserWindow, ) => Effect.Effect>; - readonly openNewWindow: Effect.Effect; + readonly openNewWindow: ( + input: DesktopOpenWindowInput, + ) => Effect.Effect; + readonly openProfile: (profileId: string) => Effect.Effect; + readonly focusWindow: (windowId: number) => Effect.Effect; + readonly createProfile: ( + input: DesktopCreateWindowProfileInput, + ) => Effect.Effect; + readonly saveWindowAsProfile: ( + window: Electron.BrowserWindow, + name: string, + ) => Effect.Effect; + readonly updateProfile: ( + input: DesktopUpdateWindowProfileInput, + ) => Effect.Effect; + readonly deleteProfile: ( + profileId: string, + ) => Effect.Effect; + readonly setWindowProjectScopeKeys: ( + window: Electron.BrowserWindow, + projectScopeKeys: ReadonlyArray, + ) => Effect.Effect; + readonly setCloseRequestListening: ( + window: Electron.BrowserWindow, + listening: boolean, + ) => Effect.Effect; + readonly resolveCloseRequest: ( + window: Electron.BrowserWindow, + requestId: string, + decision: DesktopWindowCloseDecision, + ) => Effect.Effect; + readonly setMiniMode: (enabled: boolean) => Effect.Effect; + /** Turning it off blocks new secondary windows and leaves open ones open. */ + readonly setMultiWindowEnabled: ( + enabled: boolean, + ) => Effect.Effect; readonly registerHub: (window: Electron.BrowserWindow) => Effect.Effect; readonly requestHubLink: (window: Electron.BrowserWindow) => Effect.Effect; } @@ -367,7 +459,7 @@ function getWindowTitleBarOptions( } function syncWindowAppearance( - window: Electron.BrowserWindow, + window: Pick, hasTitleBarOverlay: boolean, shouldUseDarkColors: boolean, platform: NodeJS.Platform, @@ -404,18 +496,53 @@ function bindFirstRevealTrigger( type AppWindowSpec = | { readonly role: "main" } - | { readonly role: "secondary"; readonly anchorBounds: DisplayBounds | null }; + | { + readonly role: "secondary"; + readonly profile: DesktopAppSettings.DesktopWindowProfileSettings | null; + readonly projectScopeKeys: ReadonlyArray; + readonly unsavedName: string; + readonly anchorBounds: DisplayBounds | null; + }; interface AppWindowEntry { readonly window: Electron.BrowserWindow; readonly windowId: number; readonly isMain: boolean; + /** Null while a secondary window is unsaved; the main window holds the default profile. */ + profileId: string | null; + unsavedName: string; + /** An unsaved window's filter, kept for saving it as a profile. */ + projectScopeKeys: ReadonlyArray; + name: string; + rendererTitle: string; + appliedTitle: string; + focused: boolean; rendererLive: boolean; + responsive: boolean; + closeRequestListening: boolean; + pendingCloseRequestId: string | null; + closeApproved: boolean; + appearance: DesktopTheme | null; hubUnthrottled: boolean; + readPlacement: () => { + readonly bounds: DesktopAppSettings.DesktopWindowBounds; + readonly isMaximized: boolean; + } | null; + flushPlacement: Effect.Effect; } const serializeWindowsState = (state: DesktopWindowsState) => JSON.stringify(state); +const toWindowProfile = ( + profile: DesktopAppSettings.DesktopWindowProfileSettings, +): DesktopWindowProfile => ({ + id: profile.id, + name: profile.name, + projectScopeKeys: profile.projectScopeKeys, + theme: profile.theme, + isDefault: profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID, +}); + /** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -432,9 +559,11 @@ export const make = Effect.gen(function* () { const clientSettings = yield* DesktopClientSettings.DesktopClientSettings; const electronApp = yield* ElectronApp.ElectronApp; const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory; + const random = yield* SecureRandom.SecureRandom; const backendReadyRef = yield* Ref.make(false); let backendHasStarted = false; let mainClosedDuringStartup = false; + let reopenedProfilesAtLaunch = false; const splashWindowRef = yield* Ref.make>(Option.none()); const context = yield* Effect.context(); const runFork = Effect.runForkWith(context); @@ -445,10 +574,15 @@ export const make = Effect.gen(function* () { const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) => Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), ); - let flushMainWindowBounds: Effect.Effect = Effect.void; let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; const entries = new Map(); + // Placement writes still running for windows that already closed; quitting waits for them. + const closedPlacementWrites = new Set>(); + const stateListeners = new Set<(state: DesktopWindowsState) => void>(); let lastBroadcastState = ""; + // The main window's placement before mini mode, restored when it ends and saved instead of the panel. + let miniPlacement: { readonly bounds: DisplayBounds; readonly isMaximized: boolean } | null = + null; const hubLinks = new HubLinkBroker( () => new Electron.MessageChannelMain(), ); @@ -495,24 +629,59 @@ export const make = Effect.gen(function* () { yield* previewManager.reapplyZoom(); }); - const computeWindowsState = Effect.sync((): DesktopWindowsState => ({ - windows: liveEntries() - .sort((left, right) => Number(right.isMain) - Number(left.isMain)) - .map(({ windowId, isMain }) => ({ windowId, isMain })), - })); + const titleFor = (entry: AppWindowEntry) => + composeWindowTitle({ + rendererTitle: entry.rendererTitle, + fallbackTitle: environment.displayName, + isMain: entry.isMain, + windowName: entry.name, + secondaryWindowCount: secondaryEntries().length, + }); + + const computeWindowsState = Effect.gen(function* () { + const settings = yield* desktopSettings.get; + const live = liveEntries().sort((left, right) => Number(right.isMain) - Number(left.isMain)); + return { + profiles: settings.windowProfiles.map(toWindowProfile), + windows: live.map((entry) => ({ + windowId: entry.windowId, + isMain: entry.isMain, + profileId: entry.profileId, + name: entry.name, + title: entry.appliedTitle, + focused: entry.focused, + projectScopeKeys: entry.projectScopeKeys, + })), + miniMode: miniPlacement !== null, + multiWindowEnabled: settings.multiWindowEnabled, + } satisfies DesktopWindowsState; + }); - // The hub must keep serving secondary windows while it is hidden or minimized. + // The hub must keep serving secondary windows while it is hidden, minimized or a mini panel. const syncHubThrottling = () => { const main = mainEntry(); if (main === undefined) return; - const held = secondaryEntries().length > 0; + const held = secondaryEntries().length > 0 || miniPlacement !== null; if (held === main.hubUnthrottled) return; main.hubUnthrottled = held; setUnthrottledHold(main.window, HUB_UNTHROTTLED_REASON, held); }; - // Throttling and every renderer's list of open windows follow from the open windows. + // Names, titles, renderers and menu listeners all follow from the open windows and profiles. const syncWindows = Effect.fn("desktop.window.syncWindows")(function* () { + const settings = yield* desktopSettings.get; + const defaultProfile = DesktopAppSettings.defaultWindowProfile(settings); + for (const entry of liveEntries()) { + const profile = settings.windowProfiles.find((candidate) => candidate.id === entry.profileId); + entry.name = entry.isMain ? defaultProfile.name : (profile?.name ?? entry.unsavedName); + } + for (const entry of liveEntries()) { + const title = titleFor(entry); + if (title !== entry.appliedTitle) { + entry.appliedTitle = title; + entry.window.setTitle(title); + } + } syncHubThrottling(); const state = yield* computeWindowsState; const serialized = serializeWindowsState(state); @@ -521,6 +690,7 @@ export const make = Effect.gen(function* () { for (const entry of liveEntries()) { if (entry.rendererLive) entry.window.webContents.send(WINDOWS_STATE_CHANNEL, state); } + for (const listener of stateListeners) listener(state); }); const requestSync = () => { runFork(syncWindows()); @@ -548,6 +718,12 @@ export const make = Effect.gen(function* () { }, }); + const updateProfiles = ( + update: ( + profiles: ReadonlyArray, + ) => ReadonlyArray, + ) => desktopSettings.updateWindowProfiles(update).pipe(Effect.andThen(syncWindows())); + const readDisplayBounds = Effect.gen(function* () { const displayBoundsResult = yield* Effect.sync(() => { try { @@ -577,17 +753,23 @@ export const make = Effect.gen(function* () { const iconOption = getIconOption(iconPaths, environment.platform); const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; const persistedSettings = yield* desktopSettings.get; - // Only the main window keeps its placement. - const persistedBounds = isMain ? persistedSettings.mainWindowBounds : null; + const persistedProfile = + spec.role === "main" + ? DesktopAppSettings.defaultWindowProfile(persistedSettings) + : spec.profile; + const persistedBounds = persistedProfile?.bounds ?? null; + const persistedMaximized = persistedProfile?.maximized ?? false; const displayBounds = yield* readDisplayBounds; const restorableBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds); const restoredPersistedBounds = persistedBounds !== null && restorableBounds === persistedBounds; if (persistedBounds !== null && !restoredPersistedBounds) { - yield* logWindowWarning("saved main window bounds could not be restored; using defaults"); + yield* logWindowWarning("saved window bounds could not be restored; using defaults", { + role: spec.role, + }); } const initialBounds = - spec.role === "secondary" + spec.role === "secondary" && !restoredPersistedBounds ? cascadeWindowBounds({ anchor: spec.anchorBounds, size: DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, @@ -634,8 +816,23 @@ export const make = Effect.gen(function* () { window, windowId: window.id, isMain, + profileId: + spec.role === "main" ? DEFAULT_DESKTOP_WINDOW_PROFILE_ID : (spec.profile?.id ?? null), + unsavedName: spec.role === "main" ? "" : spec.unsavedName, + projectScopeKeys: spec.role === "main" ? [] : spec.projectScopeKeys, + name: "", + rendererTitle: environment.displayName, + appliedTitle: environment.displayName, + focused: false, rendererLive: false, + responsive: true, + closeRequestListening: false, + pendingCloseRequestId: null, + closeApproved: false, + appearance: null, hubUnthrottled: false, + readPlacement: () => null, + flushPlacement: Effect.void, }; let boundsPersistFiber: Fiber.Fiber | undefined; let pendingBoundsPersistFiber: Fiber.Fiber | undefined; @@ -648,6 +845,10 @@ export const make = Effect.gen(function* () { if (window.isDestroyed()) { return null; } + if (isMain && miniPlacement !== null) { + const bounds = DesktopAppSettings.normalizeMainWindowBounds(miniPlacement.bounds); + return bounds === null ? null : { bounds, isMaximized: miniPlacement.isMaximized }; + } // Minimized windows report stale state on some platforms (macOS: not maximized, the // pre-move normal frame; Windows: -32000), so they keep the state seen before minimizing. if (window.isMinimized()) { @@ -672,12 +873,15 @@ export const make = Effect.gen(function* () { persistableBounds === null ? null : { bounds: persistableBounds, isMaximized }; return lastPersistableState; }; + entry.readPlacement = readPersistableState; const fallbackWindowBounds = boundsPersistenceEnabled ? null : (readPersistableState()?.bounds ?? null); - const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; + const fallbackWindowMaximized = persistedMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { - if (!isMain || !boundsPersistenceEnabled) { + // Unsaved windows keep no placement until they are saved as a profile. + const profileId = entry.profileId; + if (!boundsPersistenceEnabled || profileId === null) { return pendingBoundsPersistFiber; } const state = readPersistableState(); @@ -685,10 +889,10 @@ export const make = Effect.gen(function* () { return pendingBoundsPersistFiber; } pendingBoundsPersistFiber = runFork( - desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe( + desktopSettings.setWindowProfilePlacement(profileId, state.bounds, state.isMaximized).pipe( Effect.asVoid, Effect.catch((error) => - logWindowWarning("failed to persist main window bounds", { + logWindowWarning("failed to persist window bounds", { message: error.message, }), ), @@ -740,7 +944,7 @@ export const make = Effect.gen(function* () { fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid), ), ); - if (isMain) flushMainWindowBounds = flushBoundsPersist; + entry.flushPlacement = flushBoundsPersist; if (isMain) { yield* previewManager.setMainWindow(window); @@ -923,9 +1127,11 @@ export const make = Effect.gen(function* () { void runPromise(electronShell.openExternal(url)); } }); - // A new document drops the old renderer's hub links. + // A new document drops the old renderer's hub links and close-request listener. const rendererGone = () => { entry.rendererLive = false; + entry.closeRequestListening = false; + entry.pendingCloseRequestId = null; if (isMain) notifyHubReset(); else notifyHubPeerGone(entry.windowId); }; @@ -988,25 +1194,59 @@ export const make = Effect.gen(function* () { runFork(zoomWindow(window, direction)); }); - // The renderer titles the window after the open thread; only a blank title - // falls back to the app name. + // The renderer titles the window after the open thread; a blank title falls back to the + // app name, and the window's name is appended once several windows are open. window.on("page-title-updated", (event, title) => { - if (title.trim() !== "") return; - event.preventDefault(); - window.setTitle(environment.displayName); + entry.rendererTitle = title; + const composed = titleFor(entry); + const changed = composed !== entry.appliedTitle; + entry.appliedTitle = composed; + if (composed !== title) { + event.preventDefault(); + window.setTitle(composed); + } + if (changed && entries.size > 1) requestSync(); }); window.on("resize", scheduleBoundsPersist); window.on("move", scheduleBoundsPersist); window.on("maximize", scheduleBoundsPersist); window.on("unmaximize", scheduleBoundsPersist); + // Focus only matters to the list of other windows. + window.on("focus", () => { + entry.focused = true; + if (entries.size > 1) requestSync(); + }); + window.on("blur", () => { + entry.focused = false; + if (entries.size > 1) requestSync(); + }); + window.on("unresponsive", () => { + entry.responsive = false; + }); + window.on("responsive", () => { + entry.responsive = true; + }); window.on("close", (event) => { - // Hidden, the main window keeps serving the secondary windows' connections. - if (isMain && secondaryEntries().length > 0 && !runSync(Ref.get(desktopState.quitting))) { - event.preventDefault(); - window.hide(); + const action = resolveWindowCloseAction({ + isMain, + quitting: runSync(Ref.get(desktopState.quitting)), + saved: entry.profileId !== null, + secondaryWindowCount: secondaryEntries().length, + closeApproved: entry.closeApproved, + rendererCanPrompt: entry.rendererLive && entry.responsive && entry.closeRequestListening, + promptPending: entry.pendingCloseRequestId !== null, + }); + if (action === "close") { + runFork(flushBoundsPersist); return; } - runFork(flushBoundsPersist); + event.preventDefault(); + if (action === "hide") { + window.hide(); + requestSync(); + } else if (action === "prompt") { + runFork(requestClose(entry)); + } }); if (environment.platform === "darwin") { @@ -1180,7 +1420,7 @@ export const make = Effect.gen(function* () { firstRevealComplete = true; pendingMainReveals.delete(window); setUnthrottledHold(window, "first-reveal", false); - if (isMain && persistedSettings.mainWindowMaximized) window.maximize(); + if (persistedMaximized && (isMain || restoredPersistedBounds)) window.maximize(); yield* electronWindow.reveal(window); if (isMain) yield* dismissConnectingSplash; }); @@ -1226,13 +1466,19 @@ export const make = Effect.gen(function* () { remoteRequestHeaderOwner = null; detachRemoteRequestHeaders(); } + if (pendingBoundsPersistFiber !== undefined) { + const write = pendingBoundsPersistFiber; + closedPlacementWrites.add(write); + write.addObserver(() => closedPlacementWrites.delete(write)); + } if (isMain) { if (!backendHasStarted) mainClosedDuringStartup = true; + miniPlacement = null; notifyHubReset(); void runPromise(electronWindow.clearMain(Option.some(window))); } else { notifyHubPeerGone(entry.windowId); - runFork(handleSecondaryClosed); + runFork(handleSecondaryClosed(entry)); } requestSync(); }); @@ -1240,16 +1486,26 @@ export const make = Effect.gen(function* () { return Option.some(window); }); - const createMain = Effect.gen(function* () { + const createMain: Effect.Effect< + Option.Option, + DesktopWindowError + > = Effect.gen(function* () { const window = yield* buildAppWindow({ role: "main" }); if (Option.isSome(window)) { mainClosedDuringStartup = false; yield* logWindowInfo("main window created"); + if (!reopenedProfilesAtLaunch) { + reopenedProfilesAtLaunch = true; + yield* Effect.forkDetach(reopenProfilesOpenAtQuit); + } } return window; }).pipe(Effect.withSpan("desktop.window.createMain")); - const ensureMain = Effect.gen(function* () { + const ensureMain: Effect.Effect< + Option.Option, + DesktopWindowError + > = Effect.gen(function* () { if (yield* Ref.get(desktopState.quitting)) return Option.none(); const existingWindow = yield* electronWindow.main; if (Option.isSome(existingWindow)) { @@ -1270,25 +1526,161 @@ export const make = Effect.gen(function* () { return window; }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain")); - const openSecondary = Effect.gen(function* () { + const openSecondary = Effect.fn("desktop.window.openSecondary")(function* (input: { + readonly profile: DesktopAppSettings.DesktopWindowProfileSettings | null; + readonly projectScopeKeys: ReadonlyArray; + }): Effect.fn.Return { // Secondary windows reach environments through the main window's renderer. if (Option.isNone(yield* ensureMain)) return; const anchor = yield* electronWindow.focusedApp; yield* buildAppWindow({ role: "secondary", + profile: input.profile, + projectScopeKeys: input.projectScopeKeys, + unsavedName: nextUnsavedWindowName( + liveEntries().flatMap((entry) => (entry.profileId === null ? [entry.unsavedName] : [])), + ), anchorBounds: Option.isSome(anchor) && !anchor.value.isDestroyed() ? anchor.value.getBounds() : null, }); - }).pipe(Effect.withSpan("desktop.window.openSecondary")); + }); - const handleSecondaryClosed = Effect.gen(function* () { + const reopenProfilesOpenAtQuit: Effect.Effect = Effect.gen(function* () { + const settings = yield* desktopSettings.get; + if (!settings.multiWindowEnabled) return; + for (const profile of settings.windowProfiles) { + if (!profile.openAtQuit || profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) continue; + yield* openSecondary({ profile, projectScopeKeys: profile.projectScopeKeys }); + } + }).pipe( + Effect.catchCause((cause) => logWindowWarning("failed to reopen saved windows", { cause })), + Effect.withSpan("desktop.window.reopenProfilesOpenAtQuit"), + ); + + const handleSecondaryClosed = Effect.fn("desktop.window.handleSecondaryClosed")(function* ( + entry: AppWindowEntry, + ) { if (yield* Ref.get(desktopState.quitting)) return; + const profileId = entry.profileId; + if (profileId !== null) { + yield* updateProfiles((profiles) => + profiles.map((profile) => + profile.id === profileId ? { ...profile, openAtQuit: false } : profile, + ), + ).pipe( + Effect.catch((error) => + logWindowWarning("failed to save a closed window's profile", { message: error.message }), + ), + ); + } const main = mainEntry(); if (secondaryEntries().length > 0 || main === undefined || main.window.isVisible()) return; // The hidden main window kept the app alive for its secondary windows; without them, quit // as closing the last window always has. macOS apps outlive their windows. if (environment.platform !== "darwin") main.window.close(); - }).pipe(Effect.withSpan("desktop.window.handleSecondaryClosed")); + }); + + const newId = Effect.map(random.uuidV4(), (uuid) => uuid.replace(/-/g, "")); + + /** Saves a new profile, as normalized; fails if normalizing dropped it. */ + const addProfile = Effect.fn("desktop.window.addProfile")(function* ( + profile: Omit, + ) { + const id = yield* newId; + yield* desktopSettings.updateWindowProfiles((profiles) => [ + ...profiles, + { ...profile, id, name: profile.name.trim(), openAtQuit: false }, + ]); + const saved = (yield* desktopSettings.get).windowProfiles.find( + (candidate) => candidate.id === id, + ); + if (saved === undefined) { + return yield* new DesktopWindowProfileError({ reason: "profile-not-found", profileId: id }); + } + return saved; + }); + + const createProfileFor = Effect.fn("desktop.window.createProfileFor")(function* ( + entry: AppWindowEntry, + name: string, + ) { + const placement = entry.readPlacement(); + const saved = yield* addProfile({ + name, + projectScopeKeys: DesktopAppSettings.normalizeProjectScopeKeys(entry.projectScopeKeys), + theme: null, + bounds: placement?.bounds ?? null, + maximized: placement?.isMaximized ?? false, + }); + entry.profileId = saved.id; + yield* syncWindows(); + return saved; + }); + + const requestClose = Effect.fn("desktop.window.requestClose")(function* (entry: AppWindowEntry) { + const requestId = yield* newId; + entry.pendingCloseRequestId = requestId; + if (entry.window.isDestroyed()) return; + entry.window.webContents.send(WINDOWS_CLOSE_REQUEST_CHANNEL, { + requestId, + suggestedName: entry.unsavedName, + }); + yield* electronWindow.reveal(entry.window); + }); + + const requireMultiWindowEnabled = Effect.gen(function* () { + if ((yield* desktopSettings.get).multiWindowEnabled) return; + return yield* new DesktopWindowProfileError({ + reason: "multi-window-disabled", + profileId: null, + }); + }); + + const requireSecondary = (window: Electron.BrowserWindow) => { + const entry = entryOf(window); + return entry === undefined || entry.isMain + ? Effect.fail( + new DesktopWindowProfileError({ reason: "not-a-secondary-window", profileId: null }), + ) + : Effect.succeed(entry); + }; + + const setMiniMode = Effect.fn("desktop.window.setMiniMode")(function* (enabled: boolean) { + yield* Effect.annotateCurrentSpan({ enabled }); + const main = mainEntry(); + if (main === undefined || enabled === (miniPlacement !== null)) return; + const window = main.window; + if (enabled) { + const isMaximized = window.isMaximized(); + const bounds = + isMaximized || window.isFullScreen() ? window.getNormalBounds() : window.getBounds(); + miniPlacement = { bounds, isMaximized }; + if (window.isFullScreen()) window.setFullScreen(false); + if (isMaximized) window.unmaximize(); + window.setMinimumSize(MINI_WINDOW_MIN_SIZE.width, MINI_WINDOW_MIN_SIZE.height); + window.setBounds({ + x: bounds.x + Math.max(0, bounds.width - MINI_WINDOW_SIZE.width), + y: bounds.y, + ...MINI_WINDOW_SIZE, + }); + } else { + const previous = miniPlacement; + miniPlacement = null; + window.setMinimumSize( + DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width, + DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height, + ); + if (previous !== null) { + window.setBounds(previous.bounds); + if (previous.isMaximized) window.maximize(); + } + } + // The panel's top bar stands in for the traffic lights. Windows and Linux keep their + // controls: Electron cannot take a title bar overlay off a window once it is created. + if (environment.platform === "darwin") window.setWindowButtonVisibility(!enabled); + yield* electronWindow.reveal(window); + yield* syncWindows(); + }); const waitingForBackend = Effect.gen(function* () { if (yield* Ref.get(backendReadyRef)) return false; @@ -1400,6 +1792,9 @@ export const make = Effect.gen(function* () { else webContents.toggleDevTools(); }; + const appearanceDark = (theme: DesktopTheme, systemDark: boolean) => + theme === "system" ? systemDark : theme === "dark"; + return DesktopWindow.of({ createMain: createMain.pipe(Effect.flatMap(requireWindow)), ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)), @@ -1446,9 +1841,22 @@ export const make = Effect.gen(function* () { handleBackendNotReady: Ref.set(backendReadyRef, false).pipe( Effect.withSpan("desktop.window.handleBackendNotReady"), ), - flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe( - Effect.withSpan("desktop.window.flushMainWindowBounds"), - ), + flushWindowState: Effect.gen(function* () { + const openProfileIds = new Set( + secondaryEntries().flatMap((entry) => (entry.profileId === null ? [] : [entry.profileId])), + ); + yield* desktopSettings + .updateWindowProfiles((profiles) => + profiles.map((profile) => ({ ...profile, openAtQuit: openProfileIds.has(profile.id) })), + ) + .pipe( + Effect.catch((error) => + logWindowWarning("failed to save which windows to reopen", { message: error.message }), + ), + ); + yield* Effect.forEach(entries.values(), (entry) => entry.flushPlacement, { discard: true }); + yield* Fiber.joinAll([...closedPlacementWrites]); + }).pipe(Effect.withSpan("desktop.window.flushWindowState")), dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) { yield* Effect.annotateCurrentSpan({ action }); yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options); @@ -1498,20 +1906,189 @@ export const make = Effect.gen(function* () { ), syncAppearance: Effect.gen(function* () { const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; - yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) => - syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform), - ); + yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) => { + const appearance = entries.get(window.id)?.appearance ?? null; + return syncWindowAppearance( + window, + titleBarOverlay, + appearance === null + ? shouldUseDarkColors + : appearanceDark(appearance, shouldUseDarkColors), + environment.platform, + ); + }); }).pipe(Effect.withSpan("desktop.window.syncAppearance")), + setWindowAppearance: Effect.fn("desktop.window.setWindowAppearance")(function* (window, theme) { + const entry = entryOf(window); + if (entry === undefined) return; + entry.appearance = theme; + yield* syncWindowAppearance( + window, + environment.platform !== "darwin", + appearanceDark(theme, yield* electronTheme.shouldUseDarkColors), + environment.platform, + ); + }), windowsState: computeWindowsState, - windowContext: Effect.fn("desktop.window.windowContext")(function (window) { - return Effect.sync(() => { - const entry = entryOf(window); - return entry === undefined - ? Option.none() - : Option.some({ windowId: entry.windowId, isMain: entry.isMain }); + subscribeWindowsState: Effect.fn("desktop.window.subscribeWindowsState")(function* (listener) { + yield* Effect.acquireRelease( + Effect.sync(() => void stateListeners.add(listener)), + () => Effect.sync(() => void stateListeners.delete(listener)), + ); + }), + windowContext: Effect.fn("desktop.window.windowContext")(function* (window) { + const entry = entryOf(window); + if (entry === undefined) return Option.none(); + // A reloaded secondary window resumes its live filter and profile, not its opening ones. + const profile = (yield* desktopSettings.get).windowProfiles.find( + (candidate) => candidate.id === entry.profileId, + ); + return Option.some({ + windowId: entry.windowId, + isMain: entry.isMain, + profileId: entry.profileId, + projectScopeKeys: entry.projectScopeKeys, + theme: profile?.theme ?? null, + }); + }), + openNewWindow: Effect.fn("desktop.window.openNewWindow")(function* (input) { + yield* requireMultiWindowEnabled; + yield* openSecondary({ + profile: null, + projectScopeKeys: DesktopAppSettings.normalizeProjectScopeKeys( + input.projectScopeKeys ?? [], + ), }); }), - openNewWindow: openSecondary, + openProfile: Effect.fn("desktop.window.openProfile")(function* (profileId) { + yield* Effect.annotateCurrentSpan({ profileId }); + if (profileId === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) { + yield* revealOrCreateMain; + return; + } + const open = secondaryEntries().find((entry) => entry.profileId === profileId); + if (open !== undefined) { + yield* electronWindow.reveal(open.window); + return; + } + const profile = (yield* desktopSettings.get).windowProfiles.find( + (candidate) => candidate.id === profileId, + ); + if (profile === undefined) { + return yield* new DesktopWindowProfileError({ reason: "profile-not-found", profileId }); + } + yield* requireMultiWindowEnabled; + yield* openSecondary({ profile, projectScopeKeys: profile.projectScopeKeys }); + }), + focusWindow: Effect.fn("desktop.window.focusWindow")(function* (windowId) { + const entry = liveEntries().find((candidate) => candidate.windowId === windowId); + if (entry !== undefined) yield* electronWindow.reveal(entry.window); + }), + saveWindowAsProfile: Effect.fn("desktop.window.saveWindowAsProfile")(function* (window, name) { + const entry = yield* requireSecondary(window); + if (entry.profileId !== null) { + const current = (yield* desktopSettings.get).windowProfiles.find( + (profile) => profile.id === entry.profileId, + ); + // Saving a saved window as another profile starts from its current filter. + if (current !== undefined) entry.projectScopeKeys = current.projectScopeKeys; + } + return toWindowProfile(yield* createProfileFor(entry, name)); + }), + createProfile: Effect.fn("desktop.window.createProfile")(function* (input) { + const saved = yield* addProfile({ + name: input.name, + projectScopeKeys: DesktopAppSettings.normalizeProjectScopeKeys(input.projectScopeKeys), + theme: input.theme, + bounds: null, + maximized: false, + }); + yield* syncWindows(); + return toWindowProfile(saved); + }), + updateProfile: Effect.fn("desktop.window.updateProfile")(function* (input) { + yield* Effect.annotateCurrentSpan({ profileId: input.profileId }); + const settings = yield* desktopSettings.get; + if (!settings.windowProfiles.some((profile) => profile.id === input.profileId)) { + return yield* new DesktopWindowProfileError({ + reason: "profile-not-found", + profileId: input.profileId, + }); + } + yield* updateProfiles((profiles) => + profiles.map((profile) => + profile.id === input.profileId + ? { + ...profile, + ...(input.name === undefined ? {} : { name: input.name.trim() }), + ...(input.theme === undefined ? {} : { theme: input.theme }), + } + : profile, + ), + ); + }), + deleteProfile: Effect.fn("desktop.window.deleteProfile")(function* (profileId) { + yield* Effect.annotateCurrentSpan({ profileId }); + if (profileId === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) { + return yield* new DesktopWindowProfileError({ reason: "default-profile", profileId }); + } + const profile = (yield* desktopSettings.get).windowProfiles.find( + (candidate) => candidate.id === profileId, + ); + if (profile === undefined) return; + // Its open window stays open as an unsaved window with the same filter. + for (const entry of secondaryEntries()) { + if (entry.profileId !== profileId) continue; + entry.profileId = null; + entry.projectScopeKeys = profile.projectScopeKeys; + entry.unsavedName = nextUnsavedWindowName( + liveEntries().flatMap((other) => (other.profileId === null ? [other.unsavedName] : [])), + ); + } + yield* updateProfiles((profiles) => + profiles.filter((candidate) => candidate.id !== profileId), + ); + }), + setWindowProjectScopeKeys: Effect.fn("desktop.window.setWindowProjectScopeKeys")( + function* (window, projectScopeKeys) { + const entry = entryOf(window); + if (entry === undefined || entry.isMain) return; + const keys = DesktopAppSettings.normalizeProjectScopeKeys(projectScopeKeys); + entry.projectScopeKeys = keys; + const profileId = entry.profileId; + if (profileId === null) return yield* syncWindows(); + yield* updateProfiles((profiles) => + profiles.map((profile) => + profile.id === profileId ? { ...profile, projectScopeKeys: keys } : profile, + ), + ); + }, + ), + setCloseRequestListening: Effect.fn("desktop.window.setCloseRequestListening")( + function (window, listening) { + return Effect.sync(() => { + const entry = entryOf(window); + if (entry !== undefined) entry.closeRequestListening = listening; + }); + }, + ), + resolveCloseRequest: Effect.fn("desktop.window.resolveCloseRequest")( + function* (window, requestId, decision) { + const entry = entryOf(window); + if (entry === undefined || entry.pendingCloseRequestId !== requestId) return; + entry.pendingCloseRequestId = null; + if (decision.action === "cancel") return; + if (decision.action === "save") yield* createProfileFor(entry, decision.name); + entry.closeApproved = true; + window.close(); + }, + ), + setMiniMode, + setMultiWindowEnabled: Effect.fn("desktop.window.setMultiWindowEnabled")(function* (enabled) { + yield* Effect.annotateCurrentSpan({ enabled }); + yield* desktopSettings.setMultiWindowEnabled(enabled); + yield* syncWindows(); + }), registerHub: Effect.fn("desktop.window.registerHub")(function (window) { return Effect.sync(() => { const entry = entryOf(window); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.test.ts b/apps/desktop/src/window/DesktopWindowProfiles.test.ts index f1a8a93b10634..5a2b60ca8e72a 100644 --- a/apps/desktop/src/window/DesktopWindowProfiles.test.ts +++ b/apps/desktop/src/window/DesktopWindowProfiles.test.ts @@ -1,6 +1,95 @@ import { describe, expect, it } from "vite-plus/test"; -import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; +import { + cascadeWindowBounds, + composeWindowTitle, + nextUnsavedWindowName, + resolveWindowCloseAction, + type DesktopWindowCloseInput, +} from "./DesktopWindowProfiles.ts"; + +const unsavedSecondary: DesktopWindowCloseInput = { + isMain: false, + quitting: false, + saved: false, + secondaryWindowCount: 1, + closeApproved: false, + rendererCanPrompt: true, + promptPending: false, +}; + +describe("resolveWindowCloseAction", () => { + it.each([ + ["asks before closing an unsaved window", {}, "prompt"], + ["waits for the answer to an open prompt", { promptPending: true }, "keep-open"], + ["closes a saved window without asking", { saved: true }, "close"], + ["closes without asking while the app quits", { quitting: true }, "close"], + [ + "closes once save or discard approved it", + { closeApproved: true, promptPending: true }, + "close", + ], + ["closes when the renderer cannot answer", { rendererCanPrompt: false }, "close"], + ["hides the main window while it serves others", { isMain: true }, "hide"], + ["closes the main window when it is alone", { isMain: true, secondaryWindowCount: 0 }, "close"], + ["closes the main window on quit", { isMain: true, quitting: true }, "close"], + ] as const)("%s", (_name, overrides, expected) => { + expect(resolveWindowCloseAction({ ...unsavedSecondary, ...overrides })).toBe(expected); + }); + + it("never prompts for the main window, a saved window, or during quit", () => { + const flags = [false, true]; + for (const isMain of flags) + for (const quitting of flags) + for (const saved of flags) + for (const closeApproved of flags) + for (const rendererCanPrompt of flags) + for (const promptPending of flags) { + const action = resolveWindowCloseAction({ + isMain, + quitting, + saved, + secondaryWindowCount: 1, + closeApproved, + rendererCanPrompt, + promptPending, + }); + if (isMain || quitting || saved || closeApproved || !rendererCanPrompt) { + expect(action === "prompt" || action === "keep-open").toBe(false); + } + if (quitting) expect(action).toBe("close"); + } + }); +}); + +describe("nextUnsavedWindowName", () => { + it("takes the lowest free number after the main window", () => { + expect(nextUnsavedWindowName([])).toBe("Window 2"); + expect(nextUnsavedWindowName(["Window 2", "Window 4"])).toBe("Window 3"); + }); +}); + +describe("composeWindowTitle", () => { + const title = (overrides: Partial[0]>) => + composeWindowTitle({ + rendererTitle: "Fix login", + fallbackTitle: "T3 Code", + isMain: true, + windowName: "Main", + secondaryWindowCount: 0, + ...overrides, + }); + + it("names the main window only while other windows are open", () => { + expect(title({})).toBe("Fix login"); + expect(title({ rendererTitle: " " })).toBe("T3 Code"); + expect(title({ secondaryWindowCount: 1 })).toBe("Fix login - Main"); + }); + + it("always names a secondary window", () => { + expect(title({ isMain: false, windowName: "Window 2" })).toBe("Fix login - Window 2"); + }); +}); describe("cascadeWindowBounds", () => { const display = { x: 0, y: 0, width: 1920, height: 1080 }; diff --git a/apps/desktop/src/window/DesktopWindowProfiles.ts b/apps/desktop/src/window/DesktopWindowProfiles.ts index 9e0e07c757bf4..bfbf60f6cf59d 100644 --- a/apps/desktop/src/window/DesktopWindowProfiles.ts +++ b/apps/desktop/src/window/DesktopWindowProfiles.ts @@ -1,3 +1,55 @@ +type DesktopWindowCloseAction = + /** Let the window close. */ + | "close" + /** Keep the main window's renderer running for the secondary windows it serves. */ + | "hide" + /** Ask the renderer whether to save the unsaved window first. */ + | "prompt" + /** A prompt is already open; the renderer's answer decides. */ + | "keep-open"; + +export interface DesktopWindowCloseInput { + readonly isMain: boolean; + readonly quitting: boolean; + readonly saved: boolean; + readonly secondaryWindowCount: number; + /** A save or discard decision already approved this close. */ + readonly closeApproved: boolean; + /** Loaded, not crashed, responsive, and listening for close requests. */ + readonly rendererCanPrompt: boolean; + readonly promptPending: boolean; +} + +export function resolveWindowCloseAction(input: DesktopWindowCloseInput): DesktopWindowCloseAction { + if (input.quitting || input.closeApproved) return "close"; + if (input.isMain) return input.secondaryWindowCount > 0 ? "hide" : "close"; + if (input.saved || !input.rendererCanPrompt) return "close"; + return input.promptPending ? "keep-open" : "prompt"; +} + +const UNSAVED_WINDOW_NAME_PREFIX = "Window "; + +/** The main window is the first window, so unsaved secondary windows count from 2. */ +export function nextUnsavedWindowName(usedNames: Iterable): string { + const used = new Set(usedNames); + for (let index = 2; ; index++) { + const name = `${UNSAVED_WINDOW_NAME_PREFIX}${index}`; + if (!used.has(name)) return name; + } +} + +export function composeWindowTitle(input: { + readonly rendererTitle: string; + readonly fallbackTitle: string; + readonly isMain: boolean; + readonly windowName: string; + readonly secondaryWindowCount: number; +}): string { + const base = input.rendererTitle.trim() === "" ? input.fallbackTitle : input.rendererTitle; + const showName = !input.isMain || input.secondaryWindowCount > 0; + return showName ? `${base} - ${input.windowName}` : base; +} + interface Rectangle { readonly x: number; readonly y: number; diff --git a/apps/web/src/components/CommandPaletteThemeItems.tsx b/apps/web/src/components/CommandPaletteThemeItems.tsx index 4fde126c8c4b9..65a491d8e11be 100644 --- a/apps/web/src/components/CommandPaletteThemeItems.tsx +++ b/apps/web/src/components/CommandPaletteThemeItems.tsx @@ -39,7 +39,7 @@ export function notifyThemeSaveFailure(): void { // Reads its own source hooks so the compiler caches the cards on them. Taking the // sources as arguments would leave it hook-free, and the compiler would cache nothing. -function useThemeCards() { +export function useThemeCards() { const customThemes = useCustomThemes(); const environmentThemes = useEnvironmentThemeDefinitions(); const seen = new Set(); diff --git a/apps/web/src/components/CommandPaletteWindowItems.tsx b/apps/web/src/components/CommandPaletteWindowItems.tsx index f38e3ecb476f9..b83ecc4b2d282 100644 --- a/apps/web/src/components/CommandPaletteWindowItems.tsx +++ b/apps/web/src/components/CommandPaletteWindowItems.tsx @@ -1,18 +1,26 @@ import { useGT } from "gt-react"; -import { AppWindowIcon } from "lucide-react"; +import { AppWindowIcon, Maximize2Icon, PictureInPicture2Icon } from "lucide-react"; import { useState } from "react"; -import { desktopWindowsBridge } from "../multiWindow/windowContext"; -import { openNewDesktopWindow } from "../multiWindow/ui/windowActions"; +import { desktopWindowsBridge, readDesktopWindowContext } from "../multiWindow/windowContext"; +import { selectCurrentWindowProfile, useDesktopWindowsState } from "../multiWindow/windowsState"; +import { notifyWindowActionFailure, openNewDesktopWindow } from "../multiWindow/ui/windowActions"; import { ITEM_ICON_CLASS, type CommandPaletteActionItem } from "./CommandPalette.logic"; /** Desktop multi-window actions; empty on the web and in shells without multi-window support. */ export function useCommandPaletteWindowItems(): ReadonlyArray { const [bridge] = useState(desktopWindowsBridge); const gt = useGT(); + const windowsState = useDesktopWindowsState(); if (bridge === null) return []; - return [ - { + const context = readDesktopWindowContext(); + const currentProfileId = selectCurrentWindowProfile(windowsState, context)?.id ?? null; + + // Off, the saved windows cannot open either. + const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; + const items: CommandPaletteActionItem[] = []; + if (multiWindowEnabled) { + items.push({ kind: "action", value: "action:window-new", title: gt("New Window"), @@ -20,6 +28,41 @@ export function useCommandPaletteWindowItems(): ReadonlyArray, shortcutCommand: "window.new", run: async () => openNewDesktopWindow(bridge), - }, - ]; + }); + } + for (const profile of multiWindowEnabled ? (windowsState?.profiles ?? []) : []) { + if (profile.isDefault || profile.id === currentProfileId) continue; + items.push({ + kind: "action", + value: `action:window-open:${profile.id}`, + title: `Open window: ${profile.name}`, + searchTerms: ["window", "open window", "saved window", profile.name], + icon: , + run: async () => { + await bridge.openProfile(profile.id).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't open the window", cause); + }); + }, + }); + } + if (context?.isMain === true) { + const miniMode = windowsState?.miniMode === true; + items.push({ + kind: "action", + value: "action:window-mini-mode", + title: miniMode ? "Exit Mini Mode" : "Enter Mini Mode", + searchTerms: ["mini mode", "compact", "windows", "usage limits", "collapse", "expand"], + icon: miniMode ? ( + + ) : ( + + ), + run: async () => { + await bridge.setMiniMode(!miniMode).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't change Mini Mode", cause); + }); + }, + }); + } + return items; } diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 97b278a463e9e..dcffeb3211fd2 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -125,6 +125,7 @@ import { AdvancedSettings } from "./AdvancedSettings"; import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings"; import { StorageCleanupSections } from "./StorageSettings"; import { UpdateTrackSwitchDialog } from "./UpdateTrackSwitchDialog"; +import { WindowsSettingsSection } from "./WindowsSettings"; import { environmentIdsKey } from "~/state/environmentAtomList"; import { environmentSessionStatesAtom } from "~/state/session"; import { useCheckProviderUpdates } from "../ProviderUpdatesAction"; @@ -1131,6 +1132,8 @@ export function GeneralSettingsPanel() { ) : null} + + ; + +// The theme's accent, or its projects' colours, washes a window's row this strongly at the right. +const ROW_THEME_WASH_PERCENT = 16; + +/** Saved desktop windows; renders nothing outside a multi-window desktop shell. */ +export function WindowsSettingsSection() { + const [bridge] = useState(desktopWindowsBridge); + return bridge === null ? null : ; +} + +function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const windowsState = useDesktopWindowsState(); + const projectGroups = useProjectScopeGroups(); + const [creating, setCreating] = useState(false); + const context = readDesktopWindowContext(); + const currentWindow = selectCurrentWindow(windowsState, context); + const profiles = windowsState?.profiles ?? []; + const mainProfile = profiles.find((profile) => profile.isDefault); + const savedProfiles = profiles.filter((profile) => !profile.isDefault); + const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; + const isCurrentWindow = (profile: DesktopWindowProfile) => + currentWindow === null + ? context?.profileId === profile.id + : currentWindow.profileId === profile.id; + + return ( + setCreating(true)} + > + + Add saved window + + } + > + { + bridge.setMultiWindowEnabled(checked).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't change multiple windows", cause); + }); + }} + /> + } + /> + {currentWindow !== null && !currentWindow.isMain && currentWindow.profileId === null ? ( + + ) : null} + {mainProfile === undefined ? null : ( + + )} + {savedProfiles.length > 0 || creating ? ( + // Saved windows nest under the main window, whose renderer serves them. +
+
+ {savedProfiles.map((profile) => ( + window.profileId === profile.id)} + isCurrentWindow={isCurrentWindow(profile)} + canOpen={multiWindowEnabled} + /> + ))} + {creating ? ( + setCreating(false)} + /> + ) : null} +
+
+ ) : null} +
+ ); +} + +function SaveCurrentWindowRow({ + bridge, + suggestedName, +}: { + readonly bridge: DesktopWindowsBridge; + readonly suggestedName: string; +}) { + const [name, setName] = useState(suggestedName); + const [saving, setSaving] = useState(false); + const normalized = normalizeWindowProfileName(name); + const save = () => { + if (normalized === null || saving) return; + setSaving(true); + bridge + .saveAsProfile(normalized) + .catch((cause: unknown) => notifyWindowActionFailure("Couldn't save this window", cause)) + .finally(() => setSaving(false)); + }; + return ( + + setName(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + event.preventDefault(); + save(); + }} + /> + + + } + /> + ); +} + +function projectFilterSummary(projectGroups: ProjectScopeGroups, keys: readonly string[]): string { + const names = projectGroups.groupsForKeys(keys).map((group) => group.displayName); + return names.length === 0 ? "All projects" : names.join(", "); +} + +interface WindowThemeOption { + readonly value: string; + readonly label: string; + /** A theme's light and dark previews; the project colour option has none. */ + readonly previews: ThemeCardDefinition["previews"]; + /** What a window with this theme shows of it: the theme's accent, or its projects' colours. */ + readonly colors: readonly string[]; +} + +function useWindowThemeOptions(projects: readonly SidebarProjectSnapshot[]): WindowThemeOption[] { + const themeCards = useThemeCards(); + const appearance = useRenderedAppearance(); + const projectColors = useProjectTintColors(projects); + return [ + // Without a project filter there is no project colour to take on. + { + value: themeSelectValue(null), + label: projects.length > 0 ? "Project colour" : "Follow main window", + previews: [], + colors: projectColors, + }, + ...themeCards.map((card) => { + const preview = + card.previews.find((candidate) => candidate.mode === appearance) ?? card.previews[0]; + return { + value: card.id ?? "system", + label: card.label, + previews: card.previews, + colors: preview === undefined ? [] : [preview.colors.accent], + }; + }), + ]; +} + +/** The row's wash of its theme's colours, from the right edge. */ +function themeWashStyle(options: readonly WindowThemeOption[], theme: string | null) { + const colors = options.find((option) => option.value === themeSelectValue(theme))?.colors ?? []; + return colors.length === 0 + ? undefined + : { backgroundImage: rightFadeBackground(colors, ROW_THEME_WASH_PERCENT) }; +} + +function WindowProfileRow({ + bridge, + profile, + projectGroups, + openWindow, + isCurrentWindow, + canOpen, +}: { + readonly bridge: DesktopWindowsBridge; + readonly profile: DesktopWindowProfile; + readonly projectGroups: ProjectScopeGroups; + readonly openWindow: DesktopOpenWindow | undefined; + readonly isCurrentWindow: boolean; + readonly canOpen: boolean; +}) { + const themeOptions = useWindowThemeOptions(projectGroups.groupsForKeys(profile.projectScopeKeys)); + const deleteProfile = async () => { + const confirmed = await requestConfirmDialog( + `Delete the saved window "${profile.name}"?\nIf it is open, it stays open as an unsaved window.`, + { variant: "destructive" }, + ); + if (confirmed !== true) return; + await bridge.deleteProfile(profile.id).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't delete the saved window", cause); + }); + }; + const isOpen = profile.isDefault || openWindow !== undefined; + + return ( + + + {profile.isDefault ? ( + (main window) + ) : null} + + } + description={ + profile.isDefault + ? "Holds the connections and drafts every window shares." + : projectFilterSummary(projectGroups, profile.projectScopeKeys) + } + style={profile.isDefault ? undefined : themeWashStyle(themeOptions, profile.theme)} + control={ +
+ {profile.isDefault ? null : ( + + )} + {isCurrentWindow || !canOpen ? null : ( + + )} + {profile.isDefault ? null : ( + + void deleteProfile()} + /> + } + > + + + Delete saved window + + )} +
+ } + /> + ); +} + +function NewWindowProfileRow({ + bridge, + projectGroups, + onDone, +}: { + readonly bridge: DesktopWindowsBridge; + readonly projectGroups: ProjectScopeGroups; + readonly onDone: () => void; +}) { + const [name, setName] = useState(""); + const [projectScopeKeys, setProjectScopeKeys] = useState([]); + const [theme, setTheme] = useState(null); + const [saving, setSaving] = useState(false); + const themeOptions = useWindowThemeOptions(projectGroups.groupsForKeys(projectScopeKeys)); + const normalized = normalizeWindowProfileName(name); + const create = () => { + if (normalized === null || saving) return; + setSaving(true); + bridge.createProfile({ name: normalized, projectScopeKeys, theme }).then( + () => onDone(), + (cause: unknown) => { + notifyWindowActionFailure("Couldn't save the window", cause); + setSaving(false); + }, + ); + }; + return ( + setName(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + event.preventDefault(); + create(); + }} + /> + } + description="Open it later from here, the command palette or the Window menu." + style={themeWashStyle(themeOptions, theme)} + control={ +
+ + +
+ } + > +
+
+ + +
+
+ + +
+
+
+ ); +} + +function ProjectFilterSelect({ + projectGroups, + value, + onChange, +}: { + readonly projectGroups: ProjectScopeGroups; + readonly value: readonly string[]; + readonly onChange: (keys: readonly string[]) => void; +}) { + return ( + + ); +} + +/** A theme's name with swatches of its light and dark colours, or of its projects' colours. */ +function ThemeOptionLabel({ option }: { readonly option: WindowThemeOption }) { + return ( + + {option.label} + + {option.previews.length > 0 + ? option.previews.map((preview) => ( + + )) + : option.colors.map((color) => ( + + ))} + + + ); +} + +function WindowThemeSelect({ + options, + value, + ariaLabel, + fullWidth = false, + onChange, +}: { + readonly options: readonly WindowThemeOption[]; + readonly value: string | null; + readonly ariaLabel: string; + readonly fullWidth?: boolean; + readonly onChange: (theme: string | null) => void; +}) { + const selectValue = themeSelectValue(value); + const selected = options.find((option) => option.value === selectValue); + return ( + + ); +} + +/** A window's name, edited in place where it is shown. */ +function WindowNameInput(props: ComponentProps<"input">) { + return ( + + ); +} + +function ProfileNameInput({ + bridge, + profile, +}: { + readonly bridge: DesktopWindowsBridge; + readonly profile: DesktopWindowProfile; +}) { + const [draft, setDraft] = useState({ base: profile.name, value: profile.name }); + if (draft.base !== profile.name) setDraft({ base: profile.name, value: profile.name }); + const commit = () => { + const name = normalizeWindowProfileName(draft.value); + if (name === null || name === profile.name) { + setDraft({ base: profile.name, value: profile.name }); + return; + } + bridge.updateProfile({ profileId: profile.id, name }).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't rename the window", cause); + setDraft({ base: profile.name, value: profile.name }); + }); + }; + return ( + setDraft({ base: profile.name, value: event.target.value })} + onBlur={commit} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing) return; + if (event.key === "Enter") { + event.preventDefault(); + event.currentTarget.blur(); + } else if (event.key === "Escape") { + event.preventDefault(); + setDraft({ base: profile.name, value: profile.name }); + } + }} + /> + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 1f38ed958d368..06ae6cc395f9d 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -933,6 +933,13 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: ["ask before delete stop process shell console history"], }, + { + id: "windows", + title: "Windows", + to: "/settings/general", + searchTerms: ["multiple windows saved window profile theme mini mode new window"], + desktopOnly: true, + }, { id: "quit-confirmation", title: msg("Quit shortcut"), diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index 1dbc9b9fc6366..e59be49e80b6f 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -12,6 +12,7 @@ import { useCanNavigateHistory, type HistoryDirection, } from "../../navigationHistory"; +import { DesktopWindowTint } from "../../multiWindow/ui/DesktopWindowTint"; import { primaryServerKeybindingsAtom } from "../../state/server"; import { cn } from "../../lib/utils"; import { useIssuesSupported, usePullRequestsSupported } from "../../state/environments"; @@ -68,6 +69,7 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({ )} > {backdropVariant ? : null} +
void; }) { return ( @@ -214,7 +219,13 @@ function SidebarUtilityItem({ + {icon} } diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index d9bd98498b1d3..4bfcefe2271b9 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -760,7 +760,13 @@ describe("composerDraftStore context persistence", () => { it("shows a draft another desktop window saved, without reverting it on its next save", async () => { const sharedStorage = createMemoryStorage(); vi.stubGlobal("localStorage", sharedStorage); - const context = { windowId: 2, isMain: false }; + const context = { + windowId: 2, + isMain: false, + profileId: null, + projectScopeKeys: [], + theme: null, + }; vi.stubGlobal( "window", Object.assign(new EventTarget(), { diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts index 2467d89091b24..9f5acecc6f20e 100644 --- a/apps/web/src/hooks/useTheme.ts +++ b/apps/web/src/hooks/useTheme.ts @@ -130,6 +130,27 @@ let lastDesktopTheme: "light" | "dark" | "system" | null = null; let lastAppliedTheme: Omit | null = null; let themeStorageReadFailure: ThemeStorageError | null = null; +interface WindowThemeOverride { + readonly theme: Theme; + readonly save: (theme: Theme) => void; +} + +// A desktop window with its own theme reads and writes it here, never the shared storage. +let windowThemeOverride: WindowThemeOverride | null = null; + +/** Null makes this window follow the shared theme preference again. */ +export function setWindowThemeOverride(next: WindowThemeOverride | null): void { + const previousTheme = windowThemeOverride?.theme ?? null; + windowThemeOverride = next; + if ((next?.theme ?? null) === previousTheme) return; + applyTheme(getStored(), { suppressTransitions: true }); + emitChange(); +} + +function readEffectiveThemeHalves(): ThemeHalves | null { + return windowThemeOverride === null ? readStoredThemeHalves() : null; +} + function emitChange() { snapshotStale = true; for (const listener of listeners) listener(); @@ -218,6 +239,7 @@ function writeThemePreference(theme: Theme): void { } function getStored(): Theme { + if (windowThemeOverride !== null) return canonicalThemePreference(windowThemeOverride.theme); if (themeStorageReadFailure !== null) { return DEFAULT_THEME_SNAPSHOT.theme; } @@ -311,7 +333,7 @@ function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview const appearanceMode = readAppearanceModePreference(theme); const followSystem = appearanceMode === "system"; const systemDark = followSystem ? getSystemDark() : false; - const themeHalves = readStoredThemeHalves(); + const themeHalves = readEffectiveThemeHalves(); if ( lastAppliedTheme?.theme === theme && lastAppliedTheme.systemDark === systemDark && @@ -366,7 +388,8 @@ function syncDesktopTheme( followSystem?: boolean, appearanceMode?: ThemePreferenceMode, ) { - if (typeof window === "undefined") return; + // The native theme is app-wide, so a window with its own theme must not push it. + if (typeof window === "undefined" || windowThemeOverride !== null) return; const bridge = window.desktopBridge; const halves = readStoredThemeHalves(); const desktopTheme = resolveDesktopTheme(theme, followSystem, appearanceMode, halves); @@ -404,7 +427,7 @@ function getSnapshot(): ThemeSnapshot { const appearanceMode = readAppearanceModePreference(theme); const followSystem = appearanceMode === "system"; const systemDark = followSystem ? getSystemDark() : false; - const themeHalves = readStoredThemeHalves(); + const themeHalves = readEffectiveThemeHalves(); const resolvedTheme = resolveThemeAppearance( theme, @@ -517,6 +540,12 @@ export function useRenderedAppearance() { export function setTheme(next: Theme): boolean { if (typeof window === "undefined") return false; + if (windowThemeOverride !== null) { + const { save } = windowThemeOverride; + setWindowThemeOverride({ theme: next, save }); + save(next); + return true; + } try { // Save the current mode first; inferring it from the new theme can switch dark to light. pipe(getStored(), readAppearanceModePreference, writeAppearanceModePreference); @@ -582,6 +611,8 @@ export function setAppearanceMode(nextAppearanceMode: ThemePreferenceMode): bool function setThemeHalf(appearance: ThemeAppearance, themeId: string | null): boolean { if (typeof window === "undefined") return false; + // A window's own theme is one preference id, so a half choice becomes the whole theme. + if (windowThemeOverride !== null) return themeId === null || setTheme(themeId); try { const current = readStoredThemeHalvesRaw(); const next: { light?: string; dark?: string } = { ...current }; @@ -612,6 +643,7 @@ function setThemeHalf(appearance: ThemeAppearance, themeId: string | null): bool function clearThemeHalves(): boolean { if (typeof window === "undefined") return false; + if (windowThemeOverride !== null) return true; try { window.localStorage.removeItem(THEME_HALVES_STORAGE_KEY); } catch (cause) { diff --git a/apps/web/src/multiWindow/ui/DesktopWindowTint.tsx b/apps/web/src/multiWindow/ui/DesktopWindowTint.tsx new file mode 100644 index 0000000000000..ab760cdf6ad03 --- /dev/null +++ b/apps/web/src/multiWindow/ui/DesktopWindowTint.tsx @@ -0,0 +1,36 @@ +import type { DesktopWindowContext } from "@t3tools/contracts"; + +import { useUiStateStore } from "../../uiStateStore"; +import { readDesktopWindowContext } from "../windowContext"; +import { resolveWindowThemeOverride, useDesktopWindowsState } from "../windowsState"; +import { useProjectScopeGroups } from "./useProjectScopeGroups"; +import { useProjectTintColors } from "./useProjectTintColors"; +import { tintBackground } from "./windowTint.logic"; + +/** + * A secondary window's project colours across the sidebar's top banner. The main window, an + * unfiltered window and a window with its own theme show none. + */ +export function DesktopWindowTint() { + const context = readDesktopWindowContext(); + return context === null || context.isMain ? null : ; +} + +function SecondaryWindowTint({ context }: { readonly context: DesktopWindowContext }) { + const windowsState = useDesktopWindowsState(); + const scopeKeys = useUiStateStore((store) => store.sidebarProjectScopeKeys); + const { groupsForKeys } = useProjectScopeGroups(); + const colors = useProjectTintColors(groupsForKeys(scopeKeys)); + if (colors.length === 0 || resolveWindowThemeOverride(windowsState, context) !== null) { + return null; + } + return ( +
+ ); +} diff --git a/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx b/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx new file mode 100644 index 0000000000000..64d9585c43d0e --- /dev/null +++ b/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx @@ -0,0 +1,111 @@ +import type { DesktopWindowCloseRequest, DesktopWindowsBridge } from "@t3tools/contracts"; +import { useEffect, useRef, useState } from "react"; + +import { Button } from "../../components/ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../../components/ui/dialog"; +import { Input } from "../../components/ui/input"; +import { desktopWindowsBridge } from "../windowContext"; +import { notifyWindowActionFailure } from "./windowActions"; +import { + normalizeWindowProfileName, + WINDOW_PROFILE_NAME_MAX_LENGTH, + type WindowCloseChoice, + windowCloseDecision, +} from "./windowProfiles.logic"; + +/** The save-on-close prompt, once per desktop window. */ +export function DesktopWindowsHost() { + const [bridge] = useState(desktopWindowsBridge); + return bridge === null ? null : ; +} + +function DesktopWindowsHostContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const [request, setRequest] = useState(null); + const [name, setName] = useState(""); + const pendingRequestIdRef = useRef(null); + const inputRef = useRef(null); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the desktop shell's close requests + useEffect( + () => + bridge.onCloseRequest((next) => { + const previous = pendingRequestIdRef.current; + // A newer request supersedes one still on screen; the shell waits on every request. + if (previous !== null && previous !== next.requestId) { + void bridge.resolveCloseRequest(previous, { action: "cancel" }).catch(() => {}); + } + pendingRequestIdRef.current = next.requestId; + setRequest(next); + setName(next.suggestedName); + }), + [bridge], + ); + + const resolve = (choice: WindowCloseChoice) => { + if (request === null) return; + const decision = windowCloseDecision(choice, name); + if (decision === null) return; + pendingRequestIdRef.current = null; + setRequest(null); + bridge.resolveCloseRequest(request.requestId, decision).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't close the window", cause); + }); + }; + + return ( + { + if (!open) resolve("cancel"); + }} + > + + + Save this window? + + A saved window keeps its project filter and theme. Reopen it from the command palette or + Settings. + + + + setName(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + event.preventDefault(); + resolve("save"); + }} + /> + + + + + + + + + ); +} diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx new file mode 100644 index 0000000000000..d951944747cca --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx @@ -0,0 +1,251 @@ +import "../../index.css"; + +import type { DesktopOpenWindow, DesktopUpdateState } from "@t3tools/contracts"; +import type { LimitPresentations } from "@t3tools/shared/usageLimits"; +import { useState } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { APP_DISPLAY_NAME } from "../../branding"; +import { + CLAUDE, + CLAUDE_UNREADABLE, + CODEX, + FIXTURE_NOW, + openWindow, + presentations, + projectsFor, + PULL_REQUESTS, + UPDATE_AVAILABLE, +} from "./mini.fixtures"; +import { MiniPanel, type MiniTab } from "./MiniMainWindow"; +import { MiniPullRequestList } from "./MiniPullRequests"; +import { MiniSettings } from "./MiniSettings"; +import { MiniUpdate } from "./MiniUpdate"; +import { MiniUsageSection } from "./MiniUsage"; +import { MiniWindows } from "./MiniWindows"; + +const mocks = vi.hoisted(() => ({ update: null as DesktopUpdateState | null })); +vi.mock("../../state/desktopUpdate", async (importOriginal) => ({ + ...(await importOriginal()), + useDesktopUpdateState: () => mocks.update, +})); + +const WINDOWS = [ + openWindow(2, "Client work", "Rate limit review - Client work", { + projectScopeKeys: ["Northwind"], + }), + openWindow(3, "Window 3", "Filter envelope - Window 3", { profileId: null, focused: true }), + openWindow(4, "Idle", `${APP_DISPLAY_NAME} - Idle`), +]; + +const makeActions = () => ({ + search: vi.fn(), + expand: vi.fn(), + newWindow: vi.fn(), + focusWindow: vi.fn(), + multiWindowEnabledChange: vi.fn(), + openSettings: vi.fn(), + openPullRequest: vi.fn(), +}); + +interface PanelOptions { + readonly usage?: LimitPresentations; + readonly windows?: readonly DesktopOpenWindow[] | null; + readonly multiWindowEnabled?: boolean; + readonly pullRequestsSupported?: boolean; +} + +function Panel({ + usage = presentations([CLAUDE, CODEX]), + windows = WINDOWS, + multiWindowEnabled = true, + pullRequestsSupported = true, + actions, +}: PanelOptions & { readonly actions: ReturnType }) { + const [tab, setTab] = useState("usage"); + return ( + + {tab === "windows" ? ( + + ) : tab === "settings" ? ( + + ) : tab === "pullRequests" ? ( + + ) : tab === "update" ? ( + + ) : ( + + )} + + ); +} + +async function renderPanel(options: PanelOptions = {}) { + await page.viewport(320, 460); + const actions = makeActions(); + const screen = await render(); + const openTab = (name: string) => screen.getByRole("button", { name, exact: true }).click(); + return { screen, actions, openTab }; +} + +const TAB_REGIONS = ["Windows", "Settings", "Pull requests", "Usage", "Update"]; + +describe("MiniPanel", () => { + it("opens on Usage and shows one tab's content at a time", async () => { + mocks.update = UPDATE_AVAILABLE; + const { screen, openTab } = await renderPanel(); + await using _screen = screen; + + await expect.element(screen.getByText("62% left")).toBeVisible(); + expect(document.documentElement.scrollWidth).toBe(320); + for (const tab of ["Windows", "Settings", "Pull requests", "Update", "Usage"]) { + await openTab(tab); + await expect + .element(screen.getByRole("button", { name: tab, exact: true })) + .toHaveAttribute("aria-current", "page"); + await expect.element(screen.getByRole("region", { name: tab })).toBeVisible(); + for (const other of TAB_REGIONS) { + if (other !== tab) expect(screen.getByRole("region", { name: other }).query()).toBeNull(); + } + } + }); + + it("offers Search, New Window and Expand in the top bar, with only Search labelled", async () => { + const { screen, actions } = await renderPanel(); + await using _screen = screen; + + const search = screen.getByRole("button", { name: "Search" }); + await expect.element(search).toHaveTextContent("Search"); + await search.click(); + expect(actions.search).toHaveBeenCalledOnce(); + for (const [name, action] of [ + ["New Window", actions.newWindow], + ["Expand", actions.expand], + ] as const) { + const button = screen.getByRole("button", { name }); + await expect.element(button).toHaveTextContent(""); + await button.click(); + expect(action).toHaveBeenCalledOnce(); + } + }); + + it("hides New Window while multiple windows are off, and PRs where no server supports them", async () => { + const { screen } = await renderPanel({ + multiWindowEnabled: false, + pullRequestsSupported: false, + }); + await using _screen = screen; + await expect.element(screen.getByRole("button", { name: "Expand" })).toBeVisible(); + expect(screen.getByRole("button", { name: "New Window" }).query()).toBeNull(); + expect(screen.getByRole("button", { name: "Pull requests" }).query()).toBeNull(); + }); + + it("lists windows as cards: project filter and state, then name, then what the window shows", async () => { + const { screen, actions, openTab } = await renderPanel(); + await using _screen = screen; + await openTab("Windows"); + + const saved = screen.getByRole("button", { name: /Client work/ }); + await expect.element(saved).toHaveTextContent("NWNorthwindSavedClient workRate limit review"); + const focused = screen.getByRole("button", { name: /Window 3/ }); + await expect.element(focused).toHaveTextContent("All projectsFocusedWindow 3Filter envelope"); + await expect.element(focused).toHaveAttribute("aria-current", "true"); + // A window with no thread open is titled with the app's name, which says nothing. + await expect + .element(screen.getByRole("button", { name: /Idle/ })) + .toHaveTextContent("All projectsSavedIdle"); + await saved.click(); + expect(actions.focusWindow).toHaveBeenCalledWith(2); + }); + + it("keeps both bars on screen and scrolls only the tab when its list is long", async () => { + const { screen, openTab } = await renderPanel({ + windows: Array.from({ length: 14 }, (_, index) => + openWindow( + 10 + index, + `Northwind storefront and checkout redesign ${index + 1} (Q4 holiday freeze)`, + "Investigate why the dungeon lighting pass flickers on integrated GPUs", + { projectScopeKeys: ["Northwind", "Dungeon", "Synth"] }, + ), + ), + }); + await using _screen = screen; + await openTab("Windows"); + + for (const name of ["Search", "Expand", "New Window", "Windows", "Update"]) { + await expect.element(screen.getByRole("button", { name, exact: true })).toBeInViewport(); + } + await expect.element(screen.getByRole("button", { name: /redesign 1 / })).toBeInViewport(); + await expect.element(screen.getByRole("button", { name: /redesign 14 / })).not.toBeInViewport(); + expect(document.documentElement.scrollWidth).toBe(320); + expect(document.documentElement.scrollHeight).toBe(460); + const viewport = screen.container.querySelector("[data-slot=scroll-area-viewport]")!; + expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight); + expect(viewport.scrollWidth).toBe(viewport.clientWidth); + }); + + it("says when Usage has no limits, and why", async () => { + const { screen } = await renderPanel({ usage: presentations([CLAUDE_UNREADABLE]) }); + await using _screen = screen; + await expect.element(screen.getByText("Usage unavailable")).toBeVisible(); + await expect + .element(screen.getByText("Claude: Could not read limits. Sign in again.")) + .toBeVisible(); + }); + + it("Settings toggles multiple windows and leads to the full settings", async () => { + const { screen, actions, openTab } = await renderPanel(); + await using _screen = screen; + await openTab("Settings"); + + await screen.getByRole("switch", { name: "Multiple windows" }).click(); + expect(actions.multiWindowEnabledChange.mock.calls[0]?.[0]).toBe(false); + await screen.getByRole("button", { name: "All settings" }).click(); + expect(actions.openSettings).toHaveBeenCalledOnce(); + }); + + it("PRs opens a pull request on its host", async () => { + const { screen, actions, openTab } = await renderPanel(); + await using _screen = screen; + await openTab("Pull requests"); + + await expect.element(screen.getByLabelText("Some checks were not successful")).toBeVisible(); + await screen.getByRole("button", { name: /Rate limit the checkout webhook/ }).click(); + expect(actions.openPullRequest).toHaveBeenCalledWith(PULL_REQUESTS[0]!.url); + }); + + it("Update names the running version and where its update stands", async () => { + mocks.update = UPDATE_AVAILABLE; + const { screen, openTab } = await renderPanel(); + await using _screen = screen; + await openTab("Update"); + + const update = screen.getByRole("region", { name: "Update" }); + await expect.element(update.getByText(/0\.0\.50$/)).toBeVisible(); + await expect + .element(update.getByRole("status")) + .toHaveTextContent("Update 0.0.51 ready to download"); + }); +}); diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx new file mode 100644 index 0000000000000..735d737fe5352 --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx @@ -0,0 +1,190 @@ +import { useRouter } from "@tanstack/react-router"; +import type { DesktopWindowsBridge } from "@t3tools/contracts"; +import { + AppWindowIcon, + ChartNoAxesColumnIcon, + CircleArrowUpIcon, + Maximize2Icon, + SearchIcon, + SettingsIcon, +} from "lucide-react"; +import { type ReactNode, useEffect, useState } from "react"; + +import { openCommandPalette } from "../../commandPaletteBus"; +import { CommandPalette } from "../../components/CommandPalette"; +import { resolveDesktopUpdateButtonAction } from "../../components/desktopUpdate.logic"; +import { PullRequestGlyph } from "../../components/pullRequest/pullRequestIcons"; +import { SidebarUtilityItem } from "../../components/sidebar/SidebarChrome"; +import { SidebarHeaderIconButton } from "../../components/sidebar/SidebarThreadHeader"; +import { ScrollArea } from "../../components/ui/scroll-area"; +import { + SidebarFooter, + SidebarMenu, + SidebarMenuButton, + SidebarProvider, +} from "../../components/ui/sidebar"; +import { useDesktopUpdateState } from "../../state/desktopUpdate"; +import { usePullRequestsSupported } from "../../state/environments"; +import { desktopWindowsBridge } from "../windowContext"; +import { useDesktopWindowsState } from "../windowsState"; +import { MiniPullRequests } from "./MiniPullRequests"; +import { MiniSettings } from "./MiniSettings"; +import { MiniUpdate } from "./MiniUpdate"; +import { MiniUsage } from "./MiniUsage"; +import { MiniWindows } from "./MiniWindows"; +import { useProjectScopeGroups } from "./useProjectScopeGroups"; +import { notifyWindowActionFailure, openNewDesktopWindow } from "./windowActions"; + +export type MiniTab = "windows" | "settings" | "pullRequests" | "usage" | "update"; + +/** The main window's compact stand-in for the app shell while Mini Mode is on. */ +export function MiniMainWindow() { + const [bridge] = useState(desktopWindowsBridge); + return bridge === null ? null : ; +} + +function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const router = useRouter(); + const windowsState = useDesktopWindowsState(); + const updateState = useDesktopUpdateState(); + const pullRequestsSupported = usePullRequestsSupported(); + const { groupsForKeys } = useProjectScopeGroups(); + const [tab, setTab] = useState("usage"); + const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; + + const expand = () => { + bridge.setMiniMode(false).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't leave Mini Mode", cause); + }); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- follows the router: the panel shows no pages, so going to one (a search result, Settings) needs the full window + useEffect( + () => + router.subscribe("onBeforeNavigate", ({ pathChanged }) => { + if (pathChanged) void bridge.setMiniMode(false); + }), + [bridge, router], + ); + + return ( + + openCommandPalette()} + onExpand={expand} + // Off in Settings, the main process refuses new windows, so don't offer one. + onNewWindow={multiWindowEnabled ? () => openNewDesktopWindow(bridge) : undefined} + > + {tab === "windows" ? ( + !window.isMain) ?? null} + projectsFor={groupsForKeys} + onFocusWindow={(windowId) => { + bridge.focus(windowId).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't focus the window", cause); + }); + }} + /> + ) : tab === "settings" ? ( + { + bridge.setMultiWindowEnabled(enabled).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't change multiple windows", cause); + }); + }} + onOpenSettings={() => void router.navigate({ to: "/settings" })} + /> + ) : tab === "pullRequests" ? ( + + ) : tab === "update" ? ( + + ) : ( + + )} + + + ); +} + +/** The sidebar's top bar and bottom bar around one tab's content; the tabs never share the panel. */ +export function MiniPanel({ + tab, + onTabChange, + pullRequestsSupported, + updateAvailable, + onSearch, + onExpand, + onNewWindow, + children, +}: { + readonly tab: MiniTab; + readonly onTabChange: (tab: MiniTab) => void; + readonly pullRequestsSupported: boolean; + readonly updateAvailable: boolean; + readonly onSearch: () => void; + readonly onExpand: () => void; + /** Omitted while multiple windows are turned off. */ + readonly onNewWindow?: (() => void) | undefined; + readonly children: ReactNode; +}) { + const tabItem = (id: MiniTab, label: string, icon: ReactNode) => ( + onTabChange(id)} + /> + ); + return ( + +
+
+ + + Search + + + {onNewWindow === undefined ? null : ( + + + + )} + + + +
+
+ + {children} + +
+ + + {tabItem("windows", "Windows", )} + {tabItem("settings", "Settings", )} + {pullRequestsSupported + ? tabItem("pullRequests", "Pull requests", ) + : null} + {tabItem("usage", "Usage", )} + + + {tabItem("update", "Update", )} + {updateAvailable ? ( + + ) : null} + + + +
+
+ ); +} diff --git a/apps/web/src/multiWindow/ui/MiniPullRequests.tsx b/apps/web/src/multiWindow/ui/MiniPullRequests.tsx new file mode 100644 index 0000000000000..e7e6ff580287d --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniPullRequests.tsx @@ -0,0 +1,116 @@ +import { useState } from "react"; + +import type { EnvironmentPullRequestEntry } from "../../components/pullRequest/pullRequestList.logic"; +import { readPullRequestListPreferences } from "../../components/pullRequest/pullRequestListPreferences"; +import { + PULL_REQUEST_ROW_CLASS, + PULL_REQUEST_ROW_NUMBER_CLASS, + PullRequestRowGlyph, + PullRequestRowLines, +} from "../../components/pullRequest/PullRequestListRow"; +import { + PullRequestReviewDecisionGlyph, + pullRequestChecksStatePresentation, +} from "../../components/pullRequest/pullRequestPresentation"; +import { Skeleton } from "../../components/ui/skeleton"; +import { cn } from "../../lib/utils"; +import { ensureLocalApi } from "../../localApi"; +import { useEnvironments } from "../../state/environments"; +import { usePullRequestList } from "../../state/pullRequests"; + +const MINI_PULL_REQUEST_LIMIT = 20; + +/** The PRs tab: the list the Pull requests page would open with, read while the tab is showing. */ +export function MiniPullRequests() { + const { environments } = useEnvironments(); + const [{ state, involvement }] = useState(readPullRequestListPreferences); + const list = usePullRequestList( + environments + .filter((environment) => environment.serverConfig !== null) + .map(({ environmentId }) => ({ + environmentId, + input: { state, involvement, limit: MINI_PULL_REQUEST_LIMIT }, + })), + ); + return ( + void ensureLocalApi().shell.openExternal(url)} + /> + ); +} + +export function MiniPullRequestList({ + entries, + error, + onOpen, +}: { + /** Null until a connected environment answers. */ + readonly entries: readonly EnvironmentPullRequestEntry[] | null; + readonly error: string | null; + readonly onOpen: (url: string) => void; +}) { + return ( +
+ {entries === null ? ( +
+ + +
+ ) : entries.length === 0 ? ( +

+ {error ?? "No pull requests match your Pull requests page filter."} +

+ ) : ( +
    + {entries.map((entry) => { + const checks = + entry.checksState === undefined + ? null + : pullRequestChecksStatePresentation(entry.checksState); + return ( +
  • + +
  • + ); + })} +
+ )} +
+ ); +} diff --git a/apps/web/src/multiWindow/ui/MiniSettings.tsx b/apps/web/src/multiWindow/ui/MiniSettings.tsx new file mode 100644 index 0000000000000..b89a9b4664f76 --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniSettings.tsx @@ -0,0 +1,37 @@ +import { ChevronRightIcon } from "lucide-react"; + +import { SidebarMenuButton } from "../../components/ui/sidebar"; +import { Switch } from "../../components/ui/switch"; + +/** The one setting that changes what the panel offers, and the way to the rest. */ +export function MiniSettings({ + multiWindowEnabled, + onMultiWindowEnabledChange, + onOpenSettings, +}: { + readonly multiWindowEnabled: boolean; + readonly onMultiWindowEnabledChange: (enabled: boolean) => void; + readonly onOpenSettings: () => void; +}) { + return ( +
+
+ + Multiple windows + + Turning this off keeps open windows open. + + + +
+ + All settings + + +
+ ); +} diff --git a/apps/web/src/multiWindow/ui/MiniUpdate.tsx b/apps/web/src/multiWindow/ui/MiniUpdate.tsx new file mode 100644 index 0000000000000..93a3a3259e565 --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniUpdate.tsx @@ -0,0 +1,43 @@ +import { managedUpdatesDenial } from "@t3tools/contracts"; + +import { APP_DISPLAY_NAME } from "../../branding"; +import { + getDesktopUpdateButtonTooltip, + getDesktopUpdateDisabledReason, +} from "../../components/desktopUpdate.logic"; +import { SidebarProviderUpdatePill } from "../../components/sidebar/SidebarProviderUpdatePill"; +import { + SidebarUpdateArchitectureWarning, + SidebarUpdatePill, +} from "../../components/sidebar/SidebarUpdatePill"; +import { SidebarMenu } from "../../components/ui/sidebar"; +import { useDesktopUpdateState } from "../../state/desktopUpdate"; +import { usePrimaryManagedPolicy } from "../../state/managedPolicy"; + +/** The Update tab: the running version, where its update stands, and the sidebar's own update controls. */ +export function MiniUpdate() { + const state = useDesktopUpdateState(); + const disabledReason = getDesktopUpdateDisabledReason( + state, + managedUpdatesDenial(usePrimaryManagedPolicy()), + ); + return ( +
+
+
+

+ {APP_DISPLAY_NAME} {state?.currentVersion} +

+

+ {disabledReason ?? (state === null ? null : getDesktopUpdateButtonTooltip(state))} +

+
+ + + +
+ + +
+ ); +} diff --git a/apps/web/src/multiWindow/ui/MiniUsage.tsx b/apps/web/src/multiWindow/ui/MiniUsage.tsx new file mode 100644 index 0000000000000..2b9326aad01a3 --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniUsage.tsx @@ -0,0 +1,96 @@ +import { useAtomValue } from "@effect/atom-react"; +import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage"; +import { + collectExternalUsageLinks, + collectLimitAccounts, + collectLimitNotices, + type LimitPresentations, +} from "@t3tools/shared/usageLimits"; +import { ExternalLinkIcon } from "lucide-react"; +import { useEffect, useEffectEvent, useState } from "react"; + +import { providerClients } from "../../components/settings/providerDriverMeta"; +import { Button } from "../../components/ui/button"; +import { LimitWindows } from "../../components/usage/UsageLimits"; +import { ensureLocalApi } from "../../localApi"; +import { environmentPresentations } from "../../state/presentation"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; + +/** The Usage tab: rereads stale limits when it opens or an environment connects. */ +export function MiniUsage() { + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); + const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { + reportFailure: false, + }); + const [now, setNow] = useState(() => Date.now()); + const connected = [...presentations] + .filter(([, { connection, serverConfig }]) => connection.phase === "connected" && serverConfig) + .map(([environmentId]) => environmentId); + const refreshLimits = useEffectEvent(() => { + void Promise.allSettled( + connected.map((environmentId) => + refreshUsageLimits( + environmentId, + () => refreshProviders({ environmentId, input: {} }), + true, + ), + ), + ).then(() => setNow(Date.now())); + }); + const connectedKey = connected.toSorted().join(","); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rereads provider limits from the server when the tab opens or the connected environment set changes + useEffect(() => { + if (connectedKey) refreshLimits(); + }, [connectedKey]); + + return ; +} + +/** The composer's compact limit rows for every signed-in account. */ +export function MiniUsageSection({ + presentations, + now, +}: { + readonly presentations: LimitPresentations; + readonly now: number; +}) { + const accounts = collectLimitAccounts(presentations); + return ( +
+ {accounts.length === 0 ?

Usage unavailable

: null} + {accounts.map((account) => ( +
+

+ {account.displayName ?? providerClients.get(account.driver)?.label ?? account.driver} + {account.plan ? ` · ${account.plan}` : null} +

+ +
+ ))} + {collectExternalUsageLinks(presentations).map((link) => ( + + ))} + {collectLimitNotices(presentations).map((notice) => ( +

+ {notice} +

+ ))} +
+ ); +} diff --git a/apps/web/src/multiWindow/ui/MiniWindows.tsx b/apps/web/src/multiWindow/ui/MiniWindows.tsx new file mode 100644 index 0000000000000..78afc91c2bf9d --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniWindows.tsx @@ -0,0 +1,114 @@ +import type { DesktopOpenWindow } from "@t3tools/contracts"; +import { ListFilterIcon } from "lucide-react"; + +import { APP_DISPLAY_NAME } from "../../branding"; +import { ProjectFavicon, type ProjectFaviconProject } from "../../components/ProjectFavicon"; +import { Skeleton } from "../../components/ui/skeleton"; +import { cn } from "../../lib/utils"; + +export type MiniWindowProject = ProjectFaviconProject & { + readonly projectKey: string; + readonly displayName: string; +}; + +/** The other open windows as sidebar thread cards: filter, then window name, then what it shows. */ +export function MiniWindows({ + windows, + projectsFor, + onFocusWindow, +}: { + /** Null until the desktop shell reports its windows. */ + readonly windows: readonly DesktopOpenWindow[] | null; + readonly projectsFor: (projectScopeKeys: readonly string[]) => readonly MiniWindowProject[]; + readonly onFocusWindow: (windowId: number) => void; +}) { + return ( +
+ {windows === null ? ( +
+ + +
+ ) : windows.length === 0 ? ( +

+ No other windows are open. +

+ ) : ( +
    + {windows.map((window) => ( + onFocusWindow(window.windowId)} + /> + ))} +
+ )} +
+ ); +} + +function MiniWindowCard({ + window, + projects, + onFocus, +}: { + readonly window: DesktopOpenWindow; + readonly projects: readonly MiniWindowProject[]; + readonly onFocus: () => void; +}) { + // The desktop shell appends the window's name to its title, and the card already leads with it. + // What is left names the open thread, or only the app when the window has none open. + const nameSuffix = ` - ${window.name}`; + const shown = window.title.endsWith(nameSuffix) + ? window.title.slice(0, -nameSuffix.length) + : window.title; + const title = shown === APP_DISPLAY_NAME ? "" : shown; + return ( +
  • + +
  • + ); +} diff --git a/apps/web/src/multiWindow/ui/mini.fixtures.ts b/apps/web/src/multiWindow/ui/mini.fixtures.ts new file mode 100644 index 0000000000000..e596f84dba57c --- /dev/null +++ b/apps/web/src/multiWindow/ui/mini.fixtures.ts @@ -0,0 +1,210 @@ +import { + type DesktopOpenWindow, + type DesktopUpdateState, + EnvironmentId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, + type ServerProviderUsageLimits, + type ServerProviderUsageWindow, + SourceControlProviderKind, +} from "@t3tools/contracts"; +import type { LimitPresentations } from "@t3tools/shared/usageLimits"; + +import type { EnvironmentPullRequestEntry } from "../../components/pullRequest/pullRequestList.logic"; +import type { MiniWindowProject } from "./MiniWindows"; + +export const FIXTURE_NOW = Date.parse("2026-10-25T16:00:00.000Z"); +const HOUR = 3_600_000; + +const iso = (offsetMs: number) => new Date(FIXTURE_NOW + offsetMs).toISOString(); + +function usageWindow( + id: string, + kind: ServerProviderUsageWindow["kind"], + label: string, + usedPercent: number, + resetsInHours: number, + durationHours: number, +): ServerProviderUsageWindow { + return { + id, + kind, + label, + usedPercent, + resetsAt: iso(resetsInHours * HOUR), + windowDurationMins: durationHours * 60, + }; +} + +function provider( + driver: string, + usageLimits: Partial, + options: { readonly plan?: string; readonly name?: string } = {}, +): ServerProvider { + return { + instanceId: ProviderInstanceId.make(options.name ? `${driver}_${options.name}` : driver), + driver: ProviderDriverKind.make(driver), + ...(options.name ? { displayName: options.name } : {}), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated", ...(options.plan ? { label: options.plan } : {}) }, + checkedAt: iso(-4 * 60_000), + models: [], + slashCommands: [], + skills: [], + usageLimits: { checkedAt: iso(-4 * 60_000), windows: [], ...usageLimits }, + }; +} + +export function presentations(providers: readonly ServerProvider[]): LimitPresentations { + return new Map([ + [ + EnvironmentId.make("desk"), + { entry: { target: { label: "Desk" } }, serverConfig: { providers } }, + ], + ]); +} + +export const CLAUDE = provider( + "claudeAgent", + { + windows: [ + usageWindow("five_hour", "session", "Session", 38, 2.25, 5), + usageWindow("seven_day", "weekly", "Weekly", 59, 76, 168), + ], + }, + { plan: "Max" }, +); + +export const CODEX = provider( + "codex", + { + windows: [ + usageWindow("primary", "session", "Session", 94, 0.7, 5), + usageWindow("secondary", "weekly", "Weekly", 22, 120, 168), + ], + }, + { plan: "ChatGPT Pro 100 Subscription" }, +); + +export const CLAUDE_UNREADABLE = provider( + "claudeAgent", + { unavailable: { reason: "probeFailed", message: "Could not read limits. Sign in again." } }, + { name: "Claude" }, +); + +export function openWindow( + windowId: number, + name: string, + title: string, + overrides: Partial = {}, +): DesktopOpenWindow { + return { + windowId, + isMain: false, + profileId: name, + name, + title, + focused: false, + projectScopeKeys: [], + ...overrides, + }; +} + +function windowProject( + displayName: string, + text: string, + color: "orange" | "pink" | "sky", +): MiniWindowProject { + return { + projectKey: displayName, + displayName, + environmentId: EnvironmentId.make("desk"), + workspaceRoot: `/work/${displayName}`, + title: displayName, + faviconPath: null, + projectIcon: { kind: "monogram", text, color }, + }; +} + +const WINDOW_PROJECTS = [ + windowProject("Northwind", "NW", "orange"), + windowProject("Dungeon", "DG", "pink"), + windowProject("Synth", "SY", "sky"), +]; + +export const projectsFor = (keys: readonly string[]) => + WINDOW_PROJECTS.filter((project) => keys.includes(project.projectKey)); + +function pullRequest( + number: number, + title: string, + overrides: Partial = {}, +): EnvironmentPullRequestEntry { + return { + environmentId: EnvironmentId.make("desk"), + provider: SourceControlProviderKind.make("github"), + host: "github.com", + projectId: ProjectId.make("northwind"), + projectTitle: "Northwind", + repository: "acme/northwind", + number, + title, + url: `https://github.com/acme/northwind/pull/${number}`, + author: null, + headBranch: `feature-${number}`, + baseBranch: "main", + state: "open", + isDraft: false, + mergeability: "mergeable", + additions: 0, + deletions: 0, + createdAt: iso(-30 * HOUR), + updatedAt: iso(-2 * HOUR), + viewerReviewRequested: false, + labels: [], + ...overrides, + }; +} + +export const PULL_REQUESTS = [ + pullRequest(482, "Rate limit the checkout webhook", { + checksState: "passing", + reviewDecision: "approved", + }), + pullRequest(479, "Dungeon lighting: fix flicker on integrated GPUs", { + repository: "acme/dungeon", + checksState: "failing", + reviewDecision: "changes-requested", + updatedAt: iso(-5 * HOUR), + }), + pullRequest(31, "Filter envelope presets", { + repository: "acme/synth", + isDraft: true, + checksState: "pending", + updatedAt: iso(-26 * HOUR), + }), +]; + +export const UPDATE_AVAILABLE: DesktopUpdateState = { + enabled: true, + status: "available", + channel: "latest", + currentVersion: "0.0.50", + hostArch: "x64", + appArch: "x64", + runningUnderArm64Translation: false, + availableVersion: "0.0.51", + downloadedVersion: null, + releaseNotes: [], + omittedReleaseCount: 0, + downloadPercent: null, + checkedAt: null, + message: null, + errorContext: null, + canRetry: false, +}; diff --git a/apps/web/src/multiWindow/ui/useProjectScopeGroups.ts b/apps/web/src/multiWindow/ui/useProjectScopeGroups.ts new file mode 100644 index 0000000000000..ac47979e45ca7 --- /dev/null +++ b/apps/web/src/multiWindow/ui/useProjectScopeGroups.ts @@ -0,0 +1,34 @@ +import { + pickableProjectGroups, + selectProjectGroupingSettings, +} from "@t3tools/client-runtime/state/project-grouping"; + +import { useClientSettings } from "../../hooks/useSettings"; +import { + buildSidebarProjectSnapshots, + resolveSidebarProjectScopeKeys, + type SidebarProjectSnapshot, +} from "../../sidebarProjectGrouping"; +import { usePrimaryEnvironmentId } from "../../state/environments"; +import { useProjects } from "../../state/entities"; + +/** The project groups a window's project filter picks from, grouped and ordered as the sidebar's. */ +export function useProjectScopeGroups() { + const projects = useProjects(); + const settings = useClientSettings(selectProjectGroupingSettings); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const groups = pickableProjectGroups( + buildSidebarProjectSnapshots({ + projects, + groupScratchProjects: true, + settings, + primaryEnvironmentId, + resolveEnvironmentLabel: () => null, + }), + ); + const groupsForKeys = (keys: readonly string[]): SidebarProjectSnapshot[] => + resolveSidebarProjectScopeKeys({ groups, keys, settings }).flatMap( + (key) => groups.find((group) => group.projectKey === key) ?? [], + ); + return { groups, groupsForKeys }; +} diff --git a/apps/web/src/multiWindow/ui/useProjectTintColors.ts b/apps/web/src/multiWindow/ui/useProjectTintColors.ts new file mode 100644 index 0000000000000..2ab4cfeddf361 --- /dev/null +++ b/apps/web/src/multiWindow/ui/useProjectTintColors.ts @@ -0,0 +1,37 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { ProjectFaviconTarget } from "@t3tools/client-runtime/project-favicon-cache"; +import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon"; +import { Atom } from "effect/reactivity"; + +import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; +import { projectFaviconUrlAtom } from "../../state/assets"; +import { projectTintColors } from "./windowTint.logic"; + +// Keyed by the JSON of the projects' icon targets, so one atom reads every project's icon. +const projectsShowImageAtom = Atom.family((key: string) => + Atom.make((get) => + (JSON.parse(key) as ProjectFaviconTarget[]).map((target) => { + // As `ProjectFavicon` decides: a fallback URL draws the monogram, not an image. + const src = get(projectFaviconUrlAtom(target)); + return src !== null && !isProjectFaviconFallbackUrl(src); + }), + ), +); + +/** The distinct colours the projects' icons show, in order; emoji and image icons show none. */ +export function useProjectTintColors(projects: readonly SidebarProjectSnapshot[]): string[] { + // Only a project without an icon override can show an image. + const automatic = projects.filter((project) => project.projectIcon == null); + const showsImage = useAtomValue( + projectsShowImageAtom( + JSON.stringify( + automatic.map((project): ProjectFaviconTarget => ({ + environmentId: project.environmentId, + cwd: project.workspaceRoot, + faviconPath: project.faviconPath ?? null, + })), + ), + ), + ); + return projectTintColors(projects, (project) => showsImage[automatic.indexOf(project)] === true); +} diff --git a/apps/web/src/multiWindow/ui/windowActions.ts b/apps/web/src/multiWindow/ui/windowActions.ts index c8d75683481f7..df94d5e21c9e7 100644 --- a/apps/web/src/multiWindow/ui/windowActions.ts +++ b/apps/web/src/multiWindow/ui/windowActions.ts @@ -4,9 +4,11 @@ import { msg } from "gt-react"; import { toastManager } from "../../components/ui/toast"; import { m } from "../../i18n/messages"; import { registerCommands, registerMenuAction } from "../../shortcuts/dispatcher"; +import { useUiStateStore } from "../../uiStateStore"; import { desktopWindowsBridge } from "../windowContext"; +import { readDesktopWindowsState } from "../windowsState"; -function notifyWindowActionFailure(title: string, cause: unknown): void { +export function notifyWindowActionFailure(title: string, cause: unknown): void { console.error(title, cause); toastManager.add({ type: "error", @@ -15,8 +17,10 @@ function notifyWindowActionFailure(title: string, cause: unknown): void { }); } +/** Opens an unsaved window that starts with this window's project filter. */ export function openNewDesktopWindow(bridge: DesktopWindowsBridge): void { - bridge.openNew().catch((cause: unknown) => { + const projectScopeKeys = useUiStateStore.getState().sidebarProjectScopeKeys; + bridge.openNew({ projectScopeKeys }).catch((cause: unknown) => { notifyWindowActionFailure(m(msg("Couldn't open a new window")), cause); }); } @@ -28,6 +32,8 @@ export function registerDesktopWindowCommands(): () => void { const disposers = [ registerCommands({ "window.new": (event) => { + // Off, the chord is free for whatever else is bound to it. + if (readDesktopWindowsState()?.multiWindowEnabled === false) return false; event.preventDefault(); event.stopPropagation(); if (!event.repeat) openNewDesktopWindow(bridge); diff --git a/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts b/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts new file mode 100644 index 0000000000000..024e7e5747543 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + normalizeWindowProfileName, + themeFromSelectValue, + themeSelectValue, + windowCloseDecision, +} from "./windowProfiles.logic"; + +describe("windowCloseDecision", () => { + it.each([ + ["save", " Work ", { action: "save", name: "Work" }], + ["save", " ", null], + ["save", "x".repeat(81), null], + ["discard", "", { action: "discard" }], + ["cancel", "", { action: "cancel" }], + ] as const)("maps %s with %j", (choice, name, expected) => { + expect(windowCloseDecision(choice, name)).toEqual(expected); + }); +}); + +describe("normalizeWindowProfileName", () => { + it("accepts names up to the shell's limit", () => { + expect(normalizeWindowProfileName("x".repeat(80))).toBe("x".repeat(80)); + }); +}); + +describe("theme select values", () => { + it.each([null, "system", "dracula"])("round-trips %j", (theme) => { + expect(themeFromSelectValue(themeSelectValue(theme))).toBe(theme); + }); +}); diff --git a/apps/web/src/multiWindow/ui/windowProfiles.logic.ts b/apps/web/src/multiWindow/ui/windowProfiles.logic.ts new file mode 100644 index 0000000000000..a58438552c04f --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowProfiles.logic.ts @@ -0,0 +1,34 @@ +import type { DesktopWindowCloseDecision } from "@t3tools/contracts"; + +export const WINDOW_PROFILE_NAME_MAX_LENGTH = 80; + +/** The trimmed name, or null when the desktop shell would reject it. */ +export function normalizeWindowProfileName(name: string): string | null { + const trimmed = name.trim(); + if (trimmed.length === 0 || trimmed.length > WINDOW_PROFILE_NAME_MAX_LENGTH) return null; + return trimmed; +} + +export type WindowCloseChoice = DesktopWindowCloseDecision["action"]; + +/** Null when Save has no usable name, so the prompt stays open. */ +export function windowCloseDecision( + choice: WindowCloseChoice, + name: string, +): DesktopWindowCloseDecision | null { + if (choice !== "save") return { action: choice }; + const normalized = normalizeWindowProfileName(name); + return normalized === null ? null : { action: "save", name: normalized }; +} + +// Generated theme ids never contain a colon. +const FOLLOW_MAIN_WINDOW_THEME = ":follow-main-window"; + +/** Select values cannot be null, so "follow the main window" gets a reserved value. */ +export function themeSelectValue(theme: string | null): string { + return theme ?? FOLLOW_MAIN_WINDOW_THEME; +} + +export function themeFromSelectValue(value: string): string | null { + return value === FOLLOW_MAIN_WINDOW_THEME ? null : value; +} diff --git a/apps/web/src/multiWindow/ui/windowTheme.ts b/apps/web/src/multiWindow/ui/windowTheme.ts new file mode 100644 index 0000000000000..e12b59ea3b3b1 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowTheme.ts @@ -0,0 +1,41 @@ +import { setWindowThemeOverride } from "../../hooks/useTheme"; +import { desktopWindowsBridge, readDesktopWindowContext } from "../windowContext"; +import { + readDesktopWindowsState, + resolveWindowThemeOverride, + selectCurrentWindowProfile, + subscribeDesktopWindowsState, +} from "../windowsState"; + +let installed = false; + +/** Applies a secondary window's profile theme in place of the shared one, live. */ +export function installDesktopWindowTheme(): void { + const bridge = desktopWindowsBridge(); + const context = readDesktopWindowContext(); + if (installed || bridge === null || context === null || context.isMain) return; + installed = true; + const sync = () => { + const windowsState = readDesktopWindowsState(); + const theme = resolveWindowThemeOverride(windowsState, context); + const profileId = + windowsState === null + ? context.profileId + : (selectCurrentWindowProfile(windowsState, context)?.id ?? null); + if (theme === null || profileId === null) { + setWindowThemeOverride(null); + return; + } + setWindowThemeOverride({ + theme, + save: (next) => { + bridge.updateProfile({ profileId, theme: next }).catch((cause: unknown) => { + console.error("Failed to save the window theme.", cause); + sync(); + }); + }, + }); + }; + sync(); + subscribeDesktopWindowsState(sync); +} diff --git a/apps/web/src/multiWindow/ui/windowTint.logic.test.ts b/apps/web/src/multiWindow/ui/windowTint.logic.test.ts new file mode 100644 index 0000000000000..724e76d59eba7 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowTint.logic.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { projectIconSwatch } from "../../projectIconColors"; +import { deriveProjectIdentity } from "../../projectIdentity"; +import { + projectIconTintColor, + projectTintColors, + rightFadeBackground, + tintBackground, + type WindowTintProject, +} from "./windowTint.logic"; + +const monogram = (title: string, color: "blue" | "rose" | "green"): WindowTintProject => ({ + title, + projectIcon: { kind: "monogram", text: title.slice(0, 2), color }, +}); +const lucide = (title: string, color: "amber"): WindowTintProject => ({ + title, + projectIcon: { kind: "lucide", name: "folder", color }, +}); +const emoji: WindowTintProject = { title: "party", projectIcon: { kind: "emoji", emoji: "🎉" } }; +const automatic = (title: string): WindowTintProject => ({ title, projectIcon: null }); + +describe("projectIconTintColor", () => { + it("uses the icon's colour, the name's monogram colour without one, and none for an emoji", () => { + expect(projectIconTintColor(monogram("api", "rose"), false)).toBe("rose"); + expect(projectIconTintColor(lucide("api", "amber"), false)).toBe("amber"); + expect(projectIconTintColor(automatic("storefront"), false)).toBe( + deriveProjectIdentity("storefront").color, + ); + expect(projectIconTintColor(emoji, false)).toBeNull(); + }); + + it("has no colour for a project whose icon is an image", () => { + expect(projectIconTintColor(automatic("storefront"), true)).toBeNull(); + // An override replaces the image, so its colour shows. + expect(projectIconTintColor(monogram("api", "rose"), true)).toBe("rose"); + }); +}); + +describe("projectTintColors", () => { + it("lists each colour once, in project order, skipping emoji and image icons", () => { + const image = automatic("brand-site"); + expect( + projectTintColors( + [monogram("api", "rose"), emoji, image, monogram("web", "green"), monogram("docs", "rose")], + (project) => project === image, + ), + ).toEqual([projectIconSwatch("rose"), projectIconSwatch("green")]); + }); + + it("is empty when no project shows a colour", () => { + const image = automatic("brand-site"); + expect(projectTintColors([emoji, image], (project) => project === image)).toEqual([]); + }); +}); + +describe("rightFadeBackground", () => { + it("fades one colour from the right edge to nothing at the left", () => { + expect(rightFadeBackground(["red"], 16)).toBe( + "linear-gradient(to left, color-mix(in oklab, red 16%, transparent) 0%, transparent)", + ); + }); + + it("keeps several colours in order left to right, fainter towards the left", () => { + expect(rightFadeBackground(["red", "blue"], 16)).toBe( + "linear-gradient(to left, color-mix(in oklab, blue 16%, transparent) 0%, color-mix(in oklab, red 8%, transparent) 50%, transparent)", + ); + }); +}); + +describe("tintBackground", () => { + it("fills with one colour and blends several left to right", () => { + expect(tintBackground(["red"])).toBe("red"); + expect(tintBackground(["red", "blue"])).toBe("linear-gradient(to right, red, blue)"); + }); +}); diff --git a/apps/web/src/multiWindow/ui/windowTint.logic.ts b/apps/web/src/multiWindow/ui/windowTint.logic.ts new file mode 100644 index 0000000000000..0399e3c2b2415 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowTint.logic.ts @@ -0,0 +1,52 @@ +import type { ProjectIconColor, ProjectIconOverride } from "@t3tools/contracts"; + +import { projectIconSwatch } from "../../projectIconColors"; +import { deriveProjectIdentity } from "../../projectIdentity"; + +export interface WindowTintProject { + readonly title: string; + readonly projectIcon?: ProjectIconOverride | null | undefined; +} + +/** The colour the project's icon shows; an emoji or an image shows none. */ +export function projectIconTintColor( + project: WindowTintProject, + showsImage: boolean, +): ProjectIconColor | null { + const icon = project.projectIcon; + // Without an override the icon is the project's image, or else the name's monogram in this colour. + if (icon == null) return showsImage ? null : deriveProjectIdentity(project.title).color; + return icon.kind === "emoji" ? null : icon.color; +} + +/** Each distinct colour the projects' icons show, as a CSS colour, in project order. */ +export function projectTintColors( + projects: readonly TProject[], + showsImage: (project: TProject) => boolean, +): string[] { + return [ + ...new Set( + projects.flatMap((project) => projectIconTintColor(project, showsImage(project)) ?? []), + ), + ].map(projectIconSwatch); +} + +/** + * A faint wash strongest at the right edge, fading to nothing at the left. Several colours keep + * their left-to-right order, each fainter than the one to its right. + */ +export function rightFadeBackground(colors: readonly string[], percent: number): string { + const stops = colors.toReversed().map((color, index) => { + const share = index / colors.length; + return `color-mix(in oklab, ${color} ${percent * (1 - share)}%, transparent) ${share * 100}%`; + }); + return `linear-gradient(to left, ${[...stops, "transparent"].join(", ")})`; +} + +/** One colour fills; several blend left to right in order. */ +export function tintBackground(colors: readonly string[]): string { + const [only] = colors; + return colors.length === 1 && only !== undefined + ? only + : `linear-gradient(to right, ${colors.join(", ")})`; +} diff --git a/apps/web/src/multiWindow/windowsState.test.ts b/apps/web/src/multiWindow/windowsState.test.ts new file mode 100644 index 0000000000000..e9f55c786e849 --- /dev/null +++ b/apps/web/src/multiWindow/windowsState.test.ts @@ -0,0 +1,141 @@ +import type { + DesktopWindowContext, + DesktopWindowProfile, + DesktopWindowsState, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + isMiniMainWindow, + resolveWindowThemeOverride, + selectCurrentWindowProfile, +} from "./windowsState"; + +const mainProfile: DesktopWindowProfile = { + id: "main", + name: "Main", + projectScopeKeys: [], + theme: null, + isDefault: true, +}; +const workProfile: DesktopWindowProfile = { + id: "work", + name: "Work", + projectScopeKeys: ["project:a"], + theme: "dracula", + isDefault: false, +}; + +function context(overrides: Partial = {}): DesktopWindowContext { + return { + windowId: 2, + isMain: false, + profileId: null, + projectScopeKeys: [], + theme: null, + ...overrides, + }; +} + +function windowsState(overrides: Partial = {}): DesktopWindowsState { + return { + profiles: [mainProfile, workProfile], + windows: [ + { + windowId: 1, + isMain: true, + profileId: "main", + name: "Main", + title: "", + focused: false, + projectScopeKeys: [], + }, + { + windowId: 2, + isMain: false, + profileId: "work", + name: "Work", + title: "", + focused: true, + projectScopeKeys: [], + }, + ], + miniMode: false, + multiWindowEnabled: true, + ...overrides, + }; +} + +describe("selectCurrentWindowProfile", () => { + it("follows the live window entry, not the profile the window opened with", () => { + // Opened unsaved, then saved as "work". + expect(selectCurrentWindowProfile(windowsState(), context({ profileId: null }))).toBe( + workProfile, + ); + const deleted = windowsState({ + windows: [ + { + windowId: 2, + isMain: false, + profileId: null, + name: "Window 2", + title: "", + focused: true, + projectScopeKeys: [], + }, + ], + }); + expect(selectCurrentWindowProfile(deleted, context({ profileId: "work" }))).toBeNull(); + }); + + it("falls back to the open-time profile until the window appears in state", () => { + expect( + selectCurrentWindowProfile(windowsState({ windows: [] }), context({ profileId: "work" })), + ).toBe(workProfile); + }); +}); + +describe("resolveWindowThemeOverride", () => { + it.each([ + ["no desktop context", null, windowsState(), null], + ["the main window", context({ windowId: 1, isMain: true, theme: "x" }), windowsState(), null], + ["state not loaded yet", context({ theme: "nord" }), null, "nord"], + ["a profile with a theme", context(), windowsState(), "dracula"], + [ + "a profile that follows the main window", + context(), + windowsState({ profiles: [mainProfile, { ...workProfile, theme: null }] }), + null, + ], + [ + "an unsaved window", + context({ theme: "nord" }), + windowsState({ + windows: [ + { + windowId: 2, + isMain: false, + profileId: null, + name: "W", + title: "", + focused: true, + projectScopeKeys: [], + }, + ], + }), + null, + ], + ] as const)("resolves %s", (_label, windowContext, state, expected) => { + expect(resolveWindowThemeOverride(state, windowContext)).toBe(expected); + }); +}); + +describe("isMiniMainWindow", () => { + it("applies Mini Mode to the main window only", () => { + const mini = windowsState({ miniMode: true }); + expect(isMiniMainWindow(mini, context({ windowId: 1, isMain: true }))).toBe(true); + expect(isMiniMainWindow(mini, context())).toBe(false); + expect(isMiniMainWindow(windowsState(), context({ windowId: 1, isMain: true }))).toBe(false); + expect(isMiniMainWindow(null, context({ windowId: 1, isMain: true }))).toBe(false); + }); +}); diff --git a/apps/web/src/multiWindow/windowsState.ts b/apps/web/src/multiWindow/windowsState.ts index dba46d1ddb4e4..a92fdb1cdf786 100644 --- a/apps/web/src/multiWindow/windowsState.ts +++ b/apps/web/src/multiWindow/windowsState.ts @@ -1,6 +1,12 @@ -import type { DesktopWindowsState } from "@t3tools/contracts"; +import type { + DesktopOpenWindow, + DesktopWindowContext, + DesktopWindowProfile, + DesktopWindowsState, +} from "@t3tools/contracts"; +import { useSyncExternalStore } from "react"; -import { desktopWindowsBridge } from "./windowContext"; +import { desktopWindowsBridge, readDesktopWindowContext } from "./windowContext"; let state: DesktopWindowsState | null = null; let started = false; @@ -44,3 +50,56 @@ export function subscribeDesktopWindowsState(listener: () => void): () => void { listeners.delete(listener); }; } + +/** Null outside a desktop shell with multi-window support, and until the first state arrives. */ +export function useDesktopWindowsState(): DesktopWindowsState | null { + return useSyncExternalStore(subscribeDesktopWindowsState, readDesktopWindowsState, () => null); +} + +export function selectCurrentWindow( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): DesktopOpenWindow | null { + if (windowsState === null || context === null) return null; + return windowsState.windows.find((window) => window.windowId === context.windowId) ?? null; +} + +/** The window's live profile: saving or deleting it changes the profile after open. */ +export function selectCurrentWindowProfile( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): DesktopWindowProfile | null { + if (windowsState === null || context === null) return null; + const window = selectCurrentWindow(windowsState, context); + const profileId = window === null ? context.profileId : window.profileId; + if (profileId === null) return null; + return windowsState.profiles.find((profile) => profile.id === profileId) ?? null; +} + +/** + * The theme preference id this window uses instead of the shared one, or null to follow it. + * Before the first state arrives, the preload's open-time theme avoids a flash. + */ +export function resolveWindowThemeOverride( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): string | null { + if (context === null || context.isMain) return null; + if (windowsState === null) return context.theme; + return selectCurrentWindowProfile(windowsState, context)?.theme ?? null; +} + +export function isMiniMainWindow( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): boolean { + return context?.isMain === true && windowsState?.miniMode === true; +} + +const readIsMiniMainWindow = () => + isMiniMainWindow(readDesktopWindowsState(), readDesktopWindowContext()); + +/** Re-renders only when mini mode flips, not for every focus change in the windows state. */ +export function useIsMiniMainWindow(): boolean { + return useSyncExternalStore(subscribeDesktopWindowsState, readIsMiniMainWindow, () => false); +} diff --git a/apps/web/src/projectIconColors.ts b/apps/web/src/projectIconColors.ts index 0f4161a6b86ba..8a4c3a18fbeb5 100644 --- a/apps/web/src/projectIconColors.ts +++ b/apps/web/src/projectIconColors.ts @@ -124,3 +124,8 @@ const PROJECT_ICON_COLOR_CLASSES = Object.fromEntries( export function projectIconColorClassName(color: ProjectIconColor): string { return PROJECT_ICON_COLOR_CLASSES[color]; } + +/** The swatch class's colour as a CSS value, for code that computes with it. */ +export function projectIconSwatch(color: ProjectIconColor): string { + return `var(--color-${color}-500)`; +} diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 17cbcddc4b1d3..61d4ae8f7200f 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -61,8 +61,15 @@ import { readProject } from "../state/entities"; import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; +import { DesktopWindowsHost } from "../multiWindow/ui/DesktopWindowsHost"; +import { MiniMainWindow } from "../multiWindow/ui/MiniMainWindow"; +import { installDesktopWindowTheme } from "../multiWindow/ui/windowTheme"; +import { useIsMiniMainWindow } from "../multiWindow/windowsState"; import { isSecondaryDesktopWindow } from "../multiWindow/windowContext"; +// Before the first render, so a window with its own theme never paints the shared one. +installDesktopWindowTheme(); + export const Route = createRootRoute({ beforeLoad: async ({ location }) => { // Guest links open on the owner's tunnel host in a browser with no T3 session, and must @@ -144,6 +151,7 @@ function RootRouteView() { + ); @@ -161,6 +169,7 @@ function RootRouteBranch() { const hostedPromptLinkLanding = useHostedPromptLinkLanding( authGateState.status === "hosted-static", ); + const miniMainWindow = useIsMiniMainWindow(); const secondaryWindow = isSecondaryDesktopWindow(); if (pathname === GUEST_PAGE_PATH) return ; @@ -211,7 +220,9 @@ function RootRouteBranch() { {import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null} ); - const appShell = ( + const appShell = miniMainWindow ? ( + + ) : ( {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */} diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index c8ce7db1ea1db..c405b17a87779 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -4,7 +4,7 @@ import * as Schema from "effect/Schema"; import { create } from "zustand"; import { normalizeProjectPathForComparison } from "@t3tools/client-runtime/state/projects"; -import { readDesktopWindowContext } from "./multiWindow/windowContext"; +import { desktopWindowsBridge, readDesktopWindowContext } from "./multiWindow/windowContext"; export const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; const THREAD_CHANGED_FILES_EXPANSION_VERSION = 2; @@ -292,7 +292,7 @@ function resolveStateToPersist(state: UiState): UiState { const merged = mergeSharedUiState(stored, state, persistedBaseline ?? stored); return { ...merged, - // A secondary window's filter is its own, never the main window's state. + // A secondary window's filter lives in its window profile, never in the main window's state. sidebarProjectScopeKeys: windowContext.isMain ? state.sidebarProjectScopeKeys : stored.sidebarProjectScopeKeys, @@ -532,7 +532,9 @@ interface UiStateStore extends UiState { function readInitialState(): UiState { const state = readPersistedState(); persistedBaseline = state; - return state; + return windowContext !== null && !windowContext.isMain + ? { ...state, sidebarProjectScopeKeys: [...windowContext.projectScopeKeys] } + : state; } export const useUiStateStore = create((set) => ({ @@ -569,6 +571,13 @@ if (windowContext !== null && typeof window !== "undefined") { persistedBaseline = stored; if (sharedStateChanged(local, merged)) useUiStateStore.setState(merged); }); + if (!windowContext.isMain) { + const bridge = desktopWindowsBridge(); + useUiStateStore.subscribe((state, previous) => { + if (state.sidebarProjectScopeKeys === previous.sidebarProjectScopeKeys) return; + void bridge?.setProjectScopeKeys(state.sidebarProjectScopeKeys).catch(() => undefined); + }); + } } if (typeof window !== "undefined" && typeof window.addEventListener === "function") { diff --git a/docs/user/multiple-windows.md b/docs/user/multiple-windows.md index 993aace5fdb9d..913c29928df81 100644 --- a/docs/user/multiple-windows.md +++ b/docs/user/multiple-windows.md @@ -1,14 +1,50 @@ # Multiple windows -The desktop app can open more than one window, so you can keep different threads side by side. All -windows share the same environments, threads, and settings. The web app and mobile app use a single -window. +The desktop app can open more than one window. Each window has its own sidebar project filter and +can use its own theme, so you can keep one window per project or task side by side. All windows +share the same environments, threads, and settings. The web app and mobile app use a single window. ## Open a window Choose **New Window** in the command palette or the app menu, or press **Cmd+Option+Shift+N** on -macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. Change the shortcut under -**Settings → Keybindings** (`window.new`). +macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. The new window starts with the current window's +project filter. Change the shortcut under **Settings → Keybindings** (`window.new`). Closing the main window while others are open hides it instead, since the other windows connect through it. On Windows and Linux it closes once the last other window does. + +To keep to one window, turn off **Multiple windows** under **Settings → General → Windows**. New +Window, its shortcut, and opening saved windows are then unavailable; windows already open stay open +until you close them. + +## Save a window + +When you close a window you have not saved, T3 Code asks whether to save it. Enter a name and choose +**Save** to keep its project filter and theme, **Don't Save** to close it without keeping anything, +or **Cancel** (or Escape) to keep it open. + +Reopen a saved window with **Open window: _name_** in the command palette, or from +**Settings → General → Windows**. If the window is already open, it comes to the front instead. + +## Manage saved windows + +**Settings → General → Windows** lists the main window with your saved windows below it. Rename a +window by editing its name in place, pick its theme, open or focus it, or delete it. **Add saved +window** creates one without opening it. Deleting a saved window that is open leaves it open as an +unsaved window. A window you have not saved yet can be saved from the same section. + +A window with a project filter uses **Project colour** by default: its projects' icon colours tint +the top of its sidebar, and the rest of the window keeps the main window's theme. Projects whose +icon is an image or an emoji add no colour. Pick a theme for a saved window to use that theme +instead. Changing the theme from inside a window with its own theme changes only that window. +Light, dark, and system appearance stay shared by every window. + +## Mini Mode + +Choose **Enter Mini Mode** in the main window's command palette to turn the main window into a +compact panel. **Expand** returns to the full app, as does opening a search result or the full +settings. On macOS the panel has no close, minimise or zoom buttons. + +The panel's tabs show your other open windows, the multiple windows switch, the list your Pull +requests page opens with, each provider's usage limits, and whether an update is ready. It opens on +**Usage**, which rereads the limits when the tab opens if they are more than five minutes old. diff --git a/packages/contracts/src/desktopWindows.ts b/packages/contracts/src/desktopWindows.ts index 55f817e17ee1b..50185cf74d750 100644 --- a/packages/contracts/src/desktopWindows.ts +++ b/packages/contracts/src/desktopWindows.ts @@ -1,14 +1,58 @@ import * as Schema from "effect/Schema"; +/** The main window's profile. It always exists and cannot be deleted. */ +export const DEFAULT_DESKTOP_WINDOW_PROFILE_ID = "main"; + +export const DesktopWindowProfileIdSchema = Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(64), +); + +export const DesktopWindowProfileNameSchema = Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(80), +); + +export const DesktopWindowProjectScopeKeysSchema = Schema.Array( + Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)), +).check(Schema.isMaxLength(1000)); + +/** A theme preference id, or null for the main window's theme tinted with the filtered projects' icon colours. */ +export const DesktopWindowProfileThemeSchema = Schema.NullOr( + Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)), +); + +export const DesktopWindowProfileSchema = Schema.Struct({ + id: DesktopWindowProfileIdSchema, + name: DesktopWindowProfileNameSchema, + /** Unused for the default profile: the main window keeps its filter in its own UI state. */ + projectScopeKeys: DesktopWindowProjectScopeKeysSchema, + theme: DesktopWindowProfileThemeSchema, + isDefault: Schema.Boolean, +}); +export type DesktopWindowProfile = typeof DesktopWindowProfileSchema.Type; + export const DesktopOpenWindowSchema = Schema.Struct({ /** Electron's BrowserWindow id. */ windowId: Schema.Int, isMain: Schema.Boolean, + /** Null while a secondary window is unsaved. */ + profileId: Schema.NullOr(DesktopWindowProfileIdSchema), + /** The profile name, or a generated "Window N" label for an unsaved window. */ + name: Schema.String, + title: Schema.String, + focused: Schema.Boolean, + /** The window's current project filter; empty shows every project. */ + projectScopeKeys: DesktopWindowProjectScopeKeysSchema, }); export type DesktopOpenWindow = typeof DesktopOpenWindowSchema.Type; export const DesktopWindowsStateSchema = Schema.Struct({ + profiles: Schema.Array(DesktopWindowProfileSchema), windows: Schema.Array(DesktopOpenWindowSchema), + miniMode: Schema.Boolean, + /** Off: no new secondary windows open; windows already open stay open. */ + multiWindowEnabled: Schema.Boolean, }); export type DesktopWindowsState = typeof DesktopWindowsStateSchema.Type; @@ -16,9 +60,53 @@ export type DesktopWindowsState = typeof DesktopWindowsStateSchema.Type; export const DesktopWindowContextSchema = Schema.Struct({ windowId: Schema.Int, isMain: Schema.Boolean, + /** The profile the window opened with; null for an unsaved secondary window. */ + profileId: Schema.NullOr(Schema.String), + /** The profile's project filter at open time (secondary windows only). */ + projectScopeKeys: Schema.Array(Schema.String), + /** The profile's theme override at open time; null follows the default profile. */ + theme: Schema.NullOr(Schema.String), }); export type DesktopWindowContext = typeof DesktopWindowContextSchema.Type; +export const DesktopOpenWindowInputSchema = Schema.Struct({ + /** Seeds an unsaved window's project filter, such as the opener's current filter. */ + projectScopeKeys: Schema.optionalKey(DesktopWindowProjectScopeKeysSchema), +}); +export type DesktopOpenWindowInput = typeof DesktopOpenWindowInputSchema.Type; + +export const DesktopCreateWindowProfileInputSchema = Schema.Struct({ + name: DesktopWindowProfileNameSchema, + projectScopeKeys: DesktopWindowProjectScopeKeysSchema, + theme: DesktopWindowProfileThemeSchema, +}); +export type DesktopCreateWindowProfileInput = typeof DesktopCreateWindowProfileInputSchema.Type; + +export const DesktopUpdateWindowProfileInputSchema = Schema.Struct({ + profileId: DesktopWindowProfileIdSchema, + name: Schema.optionalKey(DesktopWindowProfileNameSchema), + theme: Schema.optionalKey(DesktopWindowProfileThemeSchema), +}); +export type DesktopUpdateWindowProfileInput = typeof DesktopUpdateWindowProfileInputSchema.Type; + +export const DesktopWindowCloseRequestSchema = Schema.Struct({ + requestId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64)), + suggestedName: Schema.String, +}); +export type DesktopWindowCloseRequest = typeof DesktopWindowCloseRequestSchema.Type; + +export const DesktopWindowCloseDecisionSchema = Schema.Union([ + Schema.Struct({ action: Schema.Literal("save"), name: DesktopWindowProfileNameSchema }), + Schema.Struct({ action: Schema.Literal("discard") }), + Schema.Struct({ action: Schema.Literal("cancel") }), +]); +export type DesktopWindowCloseDecision = typeof DesktopWindowCloseDecisionSchema.Type; + +export const DesktopResolveWindowCloseInputSchema = Schema.Struct({ + requestId: DesktopWindowCloseRequestSchema.fields.requestId, + decision: DesktopWindowCloseDecisionSchema, +}); + /** * `window.postMessage` payload the preload uses to hand a hub link port to the page, * since a MessagePort cannot cross the context bridge. The port is `event.ports[0]`. @@ -34,7 +122,24 @@ export interface DesktopWindowsBridge { getContext: () => DesktopWindowContext; getState: () => Promise; onState: (listener: (state: DesktopWindowsState) => void) => () => void; - openNew: () => Promise; + openNew: (input?: DesktopOpenWindowInput) => Promise; + /** Focuses the profile's window when it is open, otherwise opens it. */ + openProfile: (profileId: string) => Promise; + focus: (windowId: number) => Promise; + /** Saves a profile without opening its window. */ + createProfile: (input: DesktopCreateWindowProfileInput) => Promise; + /** Saves the calling window as a new profile. */ + saveAsProfile: (name: string) => Promise; + updateProfile: (input: DesktopUpdateWindowProfileInput) => Promise; + /** An open window of a deleted profile stays open, unsaved. The default profile cannot be deleted. */ + deleteProfile: (profileId: string) => Promise; + /** The calling secondary window's filter; saved to its profile, or held for save-on-close. */ + setProjectScopeKeys: (projectScopeKeys: readonly string[]) => Promise; + /** Asks the calling window whether to save itself before it closes. */ + onCloseRequest: (listener: (request: DesktopWindowCloseRequest) => void) => () => void; + resolveCloseRequest: (requestId: string, decision: DesktopWindowCloseDecision) => Promise; + setMiniMode: (enabled: boolean) => Promise; + setMultiWindowEnabled: (enabled: boolean) => Promise; /** Main window only: its renderer serves secondary windows' environment connections. */ registerHub: () => void; /** Secondary windows only: asks for a port to the hub, delivered as a `DesktopHubLinkMessage`. */ From 729499a1253a1431a96ff825b637b99f5ce23a6b Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:39:01 -0500 Subject: [PATCH 09/21] refactor(web): Mini Mode's panel owns its tab and takes each tab's content The browser test no longer copies the panel's tab switch. Co-Authored-By: Claude Opus 5.5 --- .../ui/MiniMainWindow.browser.test.tsx | 57 +++++++------- .../web/src/multiWindow/ui/MiniMainWindow.tsx | 76 +++++++++---------- 2 files changed, 62 insertions(+), 71 deletions(-) diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx index d951944747cca..7c4dce1b55d52 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx @@ -2,7 +2,6 @@ import "../../index.css"; import type { DesktopOpenWindow, DesktopUpdateState } from "@t3tools/contracts"; import type { LimitPresentations } from "@t3tools/shared/usageLimits"; -import { useState } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; @@ -19,7 +18,7 @@ import { PULL_REQUESTS, UPDATE_AVAILABLE, } from "./mini.fixtures"; -import { MiniPanel, type MiniTab } from "./MiniMainWindow"; +import { MiniPanel } from "./MiniMainWindow"; import { MiniPullRequestList } from "./MiniPullRequests"; import { MiniSettings } from "./MiniSettings"; import { MiniUpdate } from "./MiniUpdate"; @@ -64,41 +63,39 @@ function Panel({ pullRequestsSupported = true, actions, }: PanelOptions & { readonly actions: ReturnType }) { - const [tab, setTab] = useState("usage"); return ( - {tab === "windows" ? ( - - ) : tab === "settings" ? ( - - ) : tab === "pullRequests" ? ( - - ) : tab === "update" ? ( - - ) : ( - - )} - + tabs={{ + windows: ( + + ), + settings: ( + + ), + pullRequests: ( + + ), + usage: , + update: , + }} + /> ); } diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx index 735d737fe5352..447d2d4624a86 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx @@ -35,7 +35,7 @@ import { MiniWindows } from "./MiniWindows"; import { useProjectScopeGroups } from "./useProjectScopeGroups"; import { notifyWindowActionFailure, openNewDesktopWindow } from "./windowActions"; -export type MiniTab = "windows" | "settings" | "pullRequests" | "usage" | "update"; +type MiniTab = "windows" | "settings" | "pullRequests" | "usage" | "update"; /** The main window's compact stand-in for the app shell while Mini Mode is on. */ export function MiniMainWindow() { @@ -49,7 +49,6 @@ function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBrid const updateState = useDesktopUpdateState(); const pullRequestsSupported = usePullRequestsSupported(); const { groupsForKeys } = useProjectScopeGroups(); - const [tab, setTab] = useState("usage"); const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; const expand = () => { @@ -69,8 +68,6 @@ function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBrid return ( openNewDesktopWindow(bridge) : undefined} - > - {tab === "windows" ? ( - !window.isMain) ?? null} - projectsFor={groupsForKeys} - onFocusWindow={(windowId) => { - bridge.focus(windowId).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't focus the window", cause); - }); - }} - /> - ) : tab === "settings" ? ( - { - bridge.setMultiWindowEnabled(enabled).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't change multiple windows", cause); - }); - }} - onOpenSettings={() => void router.navigate({ to: "/settings" })} - /> - ) : tab === "pullRequests" ? ( - - ) : tab === "update" ? ( - - ) : ( - - )} - + tabs={{ + windows: ( + !window.isMain) ?? null} + projectsFor={groupsForKeys} + onFocusWindow={(windowId) => { + bridge.focus(windowId).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't focus the window", cause); + }); + }} + /> + ), + settings: ( + { + bridge.setMultiWindowEnabled(enabled).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't change multiple windows", cause); + }); + }} + onOpenSettings={() => void router.navigate({ to: "/settings" })} + /> + ), + pullRequests: , + usage: , + update: , + }} + /> ); } /** The sidebar's top bar and bottom bar around one tab's content; the tabs never share the panel. */ export function MiniPanel({ - tab, - onTabChange, pullRequestsSupported, updateAvailable, onSearch, onExpand, onNewWindow, - children, + tabs, }: { - readonly tab: MiniTab; - readonly onTabChange: (tab: MiniTab) => void; readonly pullRequestsSupported: boolean; readonly updateAvailable: boolean; readonly onSearch: () => void; readonly onExpand: () => void; /** Omitted while multiple windows are turned off. */ readonly onNewWindow?: (() => void) | undefined; - readonly children: ReactNode; + /** Only the showing tab's content mounts. */ + readonly tabs: Readonly>; }) { + const [tab, setTab] = useState("usage"); const tabItem = (id: MiniTab, label: string, icon: ReactNode) => ( onTabChange(id)} + onClick={() => setTab(id)} /> ); return ( @@ -161,7 +155,7 @@ export function MiniPanel({
    - {children} + {tabs[tab]}
    From 82a444e13bb2e89e6b7d4b98817349ac0b2b20e0 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:39:27 -0500 Subject: [PATCH 10/21] refactor(web): window tint gradients live in the components that draw them Each gradient had one caller, and its tests pinned exact CSS strings. Co-Authored-By: Claude Opus 5.5 --- .../components/settings/WindowsSettings.tsx | 25 ++++++++++++------- .../src/multiWindow/ui/DesktopWindowTint.tsx | 7 ++++-- .../multiWindow/ui/windowTint.logic.test.ts | 23 ----------------- .../src/multiWindow/ui/windowTint.logic.ts | 20 --------------- 4 files changed, 21 insertions(+), 54 deletions(-) diff --git a/apps/web/src/components/settings/WindowsSettings.tsx b/apps/web/src/components/settings/WindowsSettings.tsx index 28c7f0a482399..86d17cc272c9e 100644 --- a/apps/web/src/components/settings/WindowsSettings.tsx +++ b/apps/web/src/components/settings/WindowsSettings.tsx @@ -15,11 +15,8 @@ import { useProjectTintColors } from "../../multiWindow/ui/useProjectTintColors" import { notifyWindowActionFailure } from "../../multiWindow/ui/windowActions"; import { normalizeWindowProfileName, - themeFromSelectValue, - themeSelectValue, WINDOW_PROFILE_NAME_MAX_LENGTH, } from "../../multiWindow/ui/windowProfiles.logic"; -import { rightFadeBackground } from "../../multiWindow/ui/windowTint.logic"; import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; import { useThemeCards } from "../CommandPaletteThemeItems"; import { ProjectFavicon } from "../ProjectFavicon"; @@ -37,6 +34,10 @@ type ProjectScopeGroups = ReturnType; // The theme's accent, or its projects' colours, washes a window's row this strongly at the right. const ROW_THEME_WASH_PERCENT = 16; +// Select values cannot be null, so following the main window gets a value no theme id has. +const FOLLOW_MAIN_WINDOW_THEME = ":follow-main-window"; +const themeSelectValue = (theme: string | null) => theme ?? FOLLOW_MAIN_WINDOW_THEME; + /** Saved desktop windows; renders nothing outside a multi-window desktop shell. */ export function WindowsSettingsSection() { const [bridge] = useState(desktopWindowsBridge); @@ -199,7 +200,7 @@ function useWindowThemeOptions(projects: readonly SidebarProjectSnapshot[]): Win return [ // Without a project filter there is no project colour to take on. { - value: themeSelectValue(null), + value: FOLLOW_MAIN_WINDOW_THEME, label: projects.length > 0 ? "Project colour" : "Follow main window", previews: [], colors: projectColors, @@ -217,12 +218,18 @@ function useWindowThemeOptions(projects: readonly SidebarProjectSnapshot[]): Win ]; } -/** The row's wash of its theme's colours, from the right edge. */ +/** + * The row's wash of its theme's colours, strongest at the right edge and fading to nothing at the + * left. Several colours keep their left-to-right order, each fainter than the one to its right. + */ function themeWashStyle(options: readonly WindowThemeOption[], theme: string | null) { const colors = options.find((option) => option.value === themeSelectValue(theme))?.colors ?? []; - return colors.length === 0 - ? undefined - : { backgroundImage: rightFadeBackground(colors, ROW_THEME_WASH_PERCENT) }; + if (colors.length === 0) return undefined; + const stops = colors.toReversed().map((color, index) => { + const share = index / colors.length; + return `color-mix(in oklab, ${color} ${ROW_THEME_WASH_PERCENT * (1 - share)}%, transparent) ${share * 100}%`; + }); + return { backgroundImage: `linear-gradient(to left, ${[...stops, "transparent"].join(", ")})` }; } function WindowProfileRow({ @@ -502,7 +509,7 @@ function WindowThemeSelect({ value={selectValue} onValueChange={(next) => { if (typeof next !== "string" || next === selectValue) return; - onChange(themeFromSelectValue(next)); + onChange(next === FOLLOW_MAIN_WINDOW_THEME ? null : next); }} > ); } diff --git a/apps/web/src/multiWindow/ui/windowTint.logic.test.ts b/apps/web/src/multiWindow/ui/windowTint.logic.test.ts index 724e76d59eba7..6b32fff31de59 100644 --- a/apps/web/src/multiWindow/ui/windowTint.logic.test.ts +++ b/apps/web/src/multiWindow/ui/windowTint.logic.test.ts @@ -5,8 +5,6 @@ import { deriveProjectIdentity } from "../../projectIdentity"; import { projectIconTintColor, projectTintColors, - rightFadeBackground, - tintBackground, type WindowTintProject, } from "./windowTint.logic"; @@ -54,24 +52,3 @@ describe("projectTintColors", () => { expect(projectTintColors([emoji, image], (project) => project === image)).toEqual([]); }); }); - -describe("rightFadeBackground", () => { - it("fades one colour from the right edge to nothing at the left", () => { - expect(rightFadeBackground(["red"], 16)).toBe( - "linear-gradient(to left, color-mix(in oklab, red 16%, transparent) 0%, transparent)", - ); - }); - - it("keeps several colours in order left to right, fainter towards the left", () => { - expect(rightFadeBackground(["red", "blue"], 16)).toBe( - "linear-gradient(to left, color-mix(in oklab, blue 16%, transparent) 0%, color-mix(in oklab, red 8%, transparent) 50%, transparent)", - ); - }); -}); - -describe("tintBackground", () => { - it("fills with one colour and blends several left to right", () => { - expect(tintBackground(["red"])).toBe("red"); - expect(tintBackground(["red", "blue"])).toBe("linear-gradient(to right, red, blue)"); - }); -}); diff --git a/apps/web/src/multiWindow/ui/windowTint.logic.ts b/apps/web/src/multiWindow/ui/windowTint.logic.ts index 0399e3c2b2415..33c2902dc1c57 100644 --- a/apps/web/src/multiWindow/ui/windowTint.logic.ts +++ b/apps/web/src/multiWindow/ui/windowTint.logic.ts @@ -30,23 +30,3 @@ export function projectTintColors( ), ].map(projectIconSwatch); } - -/** - * A faint wash strongest at the right edge, fading to nothing at the left. Several colours keep - * their left-to-right order, each fainter than the one to its right. - */ -export function rightFadeBackground(colors: readonly string[], percent: number): string { - const stops = colors.toReversed().map((color, index) => { - const share = index / colors.length; - return `color-mix(in oklab, ${color} ${percent * (1 - share)}%, transparent) ${share * 100}%`; - }); - return `linear-gradient(to left, ${[...stops, "transparent"].join(", ")})`; -} - -/** One colour fills; several blend left to right in order. */ -export function tintBackground(colors: readonly string[]): string { - const [only] = colors; - return colors.length === 1 && only !== undefined - ? only - : `linear-gradient(to right, ${colors.join(", ")})`; -} From 5cb154f9d74b4e4336a42fcf87cdbf547f1201a1 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:39:49 -0500 Subject: [PATCH 11/21] refactor(web): the close prompt and theme picker build their own values windowCloseDecision and the theme select-value helpers each had one caller. Co-Authored-By: Claude Opus 5.5 --- .../src/multiWindow/ui/DesktopWindowsHost.tsx | 43 +++++++++++-------- .../ui/windowProfiles.logic.test.ts | 34 ++++----------- .../multiWindow/ui/windowProfiles.logic.ts | 26 ----------- 3 files changed, 33 insertions(+), 70 deletions(-) diff --git a/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx b/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx index 64d9585c43d0e..e3cc7d086deb6 100644 --- a/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx +++ b/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx @@ -1,4 +1,8 @@ -import type { DesktopWindowCloseRequest, DesktopWindowsBridge } from "@t3tools/contracts"; +import type { + DesktopWindowCloseDecision, + DesktopWindowCloseRequest, + DesktopWindowsBridge, +} from "@t3tools/contracts"; import { useEffect, useRef, useState } from "react"; import { Button } from "../../components/ui/button"; @@ -14,12 +18,7 @@ import { import { Input } from "../../components/ui/input"; import { desktopWindowsBridge } from "../windowContext"; import { notifyWindowActionFailure } from "./windowActions"; -import { - normalizeWindowProfileName, - WINDOW_PROFILE_NAME_MAX_LENGTH, - type WindowCloseChoice, - windowCloseDecision, -} from "./windowProfiles.logic"; +import { normalizeWindowProfileName, WINDOW_PROFILE_NAME_MAX_LENGTH } from "./windowProfiles.logic"; /** The save-on-close prompt, once per desktop window. */ export function DesktopWindowsHost() { @@ -49,22 +48,25 @@ function DesktopWindowsHostContent({ bridge }: { readonly bridge: DesktopWindows [bridge], ); - const resolve = (choice: WindowCloseChoice) => { + const resolve = (decision: DesktopWindowCloseDecision) => { if (request === null) return; - const decision = windowCloseDecision(choice, name); - if (decision === null) return; pendingRequestIdRef.current = null; setRequest(null); bridge.resolveCloseRequest(request.requestId, decision).catch((cause: unknown) => { notifyWindowActionFailure("Couldn't close the window", cause); }); }; + const savedName = normalizeWindowProfileName(name); + // Without a usable name, Save leaves the prompt open. + const save = () => { + if (savedName !== null) resolve({ action: "save", name: savedName }); + }; return ( { - if (!open) resolve("cancel"); + if (!open) resolve({ action: "cancel" }); }} > @@ -85,23 +87,28 @@ function DesktopWindowsHostContent({ bridge }: { readonly bridge: DesktopWindows onKeyDown={(event) => { if (event.key !== "Enter" || event.nativeEvent.isComposing) return; event.preventDefault(); - resolve("save"); + save(); }} /> - - + diff --git a/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts b/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts index 024e7e5747543..29bd1252a36db 100644 --- a/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts +++ b/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts @@ -1,32 +1,14 @@ import { describe, expect, it } from "vite-plus/test"; -import { - normalizeWindowProfileName, - themeFromSelectValue, - themeSelectValue, - windowCloseDecision, -} from "./windowProfiles.logic"; - -describe("windowCloseDecision", () => { - it.each([ - ["save", " Work ", { action: "save", name: "Work" }], - ["save", " ", null], - ["save", "x".repeat(81), null], - ["discard", "", { action: "discard" }], - ["cancel", "", { action: "cancel" }], - ] as const)("maps %s with %j", (choice, name, expected) => { - expect(windowCloseDecision(choice, name)).toEqual(expected); - }); -}); +import { normalizeWindowProfileName } from "./windowProfiles.logic"; describe("normalizeWindowProfileName", () => { - it("accepts names up to the shell's limit", () => { - expect(normalizeWindowProfileName("x".repeat(80))).toBe("x".repeat(80)); - }); -}); - -describe("theme select values", () => { - it.each([null, "system", "dracula"])("round-trips %j", (theme) => { - expect(themeFromSelectValue(themeSelectValue(theme))).toBe(theme); + it.each([ + [" Work ", "Work"], + [" ", null], + ["x".repeat(80), "x".repeat(80)], + ["x".repeat(81), null], + ])("normalizes %j", (name, expected) => { + expect(normalizeWindowProfileName(name)).toBe(expected); }); }); diff --git a/apps/web/src/multiWindow/ui/windowProfiles.logic.ts b/apps/web/src/multiWindow/ui/windowProfiles.logic.ts index a58438552c04f..ba24ca2655f91 100644 --- a/apps/web/src/multiWindow/ui/windowProfiles.logic.ts +++ b/apps/web/src/multiWindow/ui/windowProfiles.logic.ts @@ -1,5 +1,3 @@ -import type { DesktopWindowCloseDecision } from "@t3tools/contracts"; - export const WINDOW_PROFILE_NAME_MAX_LENGTH = 80; /** The trimmed name, or null when the desktop shell would reject it. */ @@ -8,27 +6,3 @@ export function normalizeWindowProfileName(name: string): string | null { if (trimmed.length === 0 || trimmed.length > WINDOW_PROFILE_NAME_MAX_LENGTH) return null; return trimmed; } - -export type WindowCloseChoice = DesktopWindowCloseDecision["action"]; - -/** Null when Save has no usable name, so the prompt stays open. */ -export function windowCloseDecision( - choice: WindowCloseChoice, - name: string, -): DesktopWindowCloseDecision | null { - if (choice !== "save") return { action: choice }; - const normalized = normalizeWindowProfileName(name); - return normalized === null ? null : { action: "save", name: normalized }; -} - -// Generated theme ids never contain a colon. -const FOLLOW_MAIN_WINDOW_THEME = ":follow-main-window"; - -/** Select values cannot be null, so "follow the main window" gets a reserved value. */ -export function themeSelectValue(theme: string | null): string { - return theme ?? FOLLOW_MAIN_WINDOW_THEME; -} - -export function themeFromSelectValue(value: string): string | null { - return value === FOLLOW_MAIN_WINDOW_THEME ? null : value; -} From f3b3ef13913f6a07e785eda35800f7a61796a973 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:40:03 -0500 Subject: [PATCH 12/21] refactor(web): Windows settings marks the current window with selectCurrentWindowProfile Co-Authored-By: Claude Opus 5.5 --- .../src/components/settings/WindowsSettings.tsx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/settings/WindowsSettings.tsx b/apps/web/src/components/settings/WindowsSettings.tsx index 86d17cc272c9e..00a23080f95ac 100644 --- a/apps/web/src/components/settings/WindowsSettings.tsx +++ b/apps/web/src/components/settings/WindowsSettings.tsx @@ -9,7 +9,11 @@ import { useState, type ComponentProps } from "react"; import { requestConfirmDialog } from "~/confirmDialog"; import { useRenderedAppearance } from "../../hooks/useTheme"; import { desktopWindowsBridge, readDesktopWindowContext } from "../../multiWindow/windowContext"; -import { selectCurrentWindow, useDesktopWindowsState } from "../../multiWindow/windowsState"; +import { + selectCurrentWindow, + selectCurrentWindowProfile, + useDesktopWindowsState, +} from "../../multiWindow/windowsState"; import { useProjectScopeGroups } from "../../multiWindow/ui/useProjectScopeGroups"; import { useProjectTintColors } from "../../multiWindow/ui/useProjectTintColors"; import { notifyWindowActionFailure } from "../../multiWindow/ui/windowActions"; @@ -54,10 +58,7 @@ function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBri const mainProfile = profiles.find((profile) => profile.isDefault); const savedProfiles = profiles.filter((profile) => !profile.isDefault); const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; - const isCurrentWindow = (profile: DesktopWindowProfile) => - currentWindow === null - ? context?.profileId === profile.id - : currentWindow.profileId === profile.id; + const currentProfileId = selectCurrentWindowProfile(windowsState, context)?.id; return ( )} @@ -115,7 +116,7 @@ function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBri profile={profile} projectGroups={projectGroups} openWindow={windowsState?.windows.find((window) => window.profileId === profile.id)} - isCurrentWindow={isCurrentWindow(profile)} + isCurrentWindow={currentProfileId === profile.id} canOpen={multiWindowEnabled} /> ))} From 179243d555fc1ae8acb3714e69c90d4d6e7b44d0 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:41:21 -0500 Subject: [PATCH 13/21] refactor(desktop): one pass names and titles windows, and saved profiles normalize once Settings already normalizes a new profile's project filter, so the window service no longer does it first. Both unsaved-name lookups share one helper. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/window/DesktopWindow.ts | 29 +++++++++++------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 2ce7439dd4915..04769e85aaf69 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -629,6 +629,11 @@ export const make = Effect.gen(function* () { yield* previewManager.reapplyZoom(); }); + const nextUnsavedName = () => + nextUnsavedWindowName( + liveEntries().flatMap((entry) => (entry.profileId === null ? [entry.unsavedName] : [])), + ); + const titleFor = (entry: AppWindowEntry) => composeWindowTitle({ rendererTitle: entry.rendererTitle, @@ -670,12 +675,10 @@ export const make = Effect.gen(function* () { // Names, titles, renderers and menu listeners all follow from the open windows and profiles. const syncWindows = Effect.fn("desktop.window.syncWindows")(function* () { const settings = yield* desktopSettings.get; - const defaultProfile = DesktopAppSettings.defaultWindowProfile(settings); for (const entry of liveEntries()) { + // The main window always holds the default profile, which cannot be deleted. const profile = settings.windowProfiles.find((candidate) => candidate.id === entry.profileId); - entry.name = entry.isMain ? defaultProfile.name : (profile?.name ?? entry.unsavedName); - } - for (const entry of liveEntries()) { + entry.name = profile?.name ?? entry.unsavedName; const title = titleFor(entry); if (title !== entry.appliedTitle) { entry.appliedTitle = title; @@ -1537,9 +1540,7 @@ export const make = Effect.gen(function* () { role: "secondary", profile: input.profile, projectScopeKeys: input.projectScopeKeys, - unsavedName: nextUnsavedWindowName( - liveEntries().flatMap((entry) => (entry.profileId === null ? [entry.unsavedName] : [])), - ), + unsavedName: nextUnsavedName(), anchorBounds: Option.isSome(anchor) && !anchor.value.isDestroyed() ? anchor.value.getBounds() : null, }); @@ -1587,13 +1588,11 @@ export const make = Effect.gen(function* () { profile: Omit, ) { const id = yield* newId; - yield* desktopSettings.updateWindowProfiles((profiles) => [ + const { settings } = yield* desktopSettings.updateWindowProfiles((profiles) => [ ...profiles, { ...profile, id, name: profile.name.trim(), openAtQuit: false }, ]); - const saved = (yield* desktopSettings.get).windowProfiles.find( - (candidate) => candidate.id === id, - ); + const saved = settings.windowProfiles.find((candidate) => candidate.id === id); if (saved === undefined) { return yield* new DesktopWindowProfileError({ reason: "profile-not-found", profileId: id }); } @@ -1607,7 +1606,7 @@ export const make = Effect.gen(function* () { const placement = entry.readPlacement(); const saved = yield* addProfile({ name, - projectScopeKeys: DesktopAppSettings.normalizeProjectScopeKeys(entry.projectScopeKeys), + projectScopeKeys: entry.projectScopeKeys, theme: null, bounds: placement?.bounds ?? null, maximized: placement?.isMaximized ?? false, @@ -1998,7 +1997,7 @@ export const make = Effect.gen(function* () { createProfile: Effect.fn("desktop.window.createProfile")(function* (input) { const saved = yield* addProfile({ name: input.name, - projectScopeKeys: DesktopAppSettings.normalizeProjectScopeKeys(input.projectScopeKeys), + projectScopeKeys: input.projectScopeKeys, theme: input.theme, bounds: null, maximized: false, @@ -2041,9 +2040,7 @@ export const make = Effect.gen(function* () { if (entry.profileId !== profileId) continue; entry.profileId = null; entry.projectScopeKeys = profile.projectScopeKeys; - entry.unsavedName = nextUnsavedWindowName( - liveEntries().flatMap((other) => (other.profileId === null ? [other.unsavedName] : [])), - ); + entry.unsavedName = nextUnsavedName(); } yield* updateProfiles((profiles) => profiles.filter((candidate) => candidate.id !== profileId), From 51cf6e7161f457a5656900af61b7602251d6912f Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:41:35 -0500 Subject: [PATCH 14/21] refactor(desktop): the settings document always has a default window profile to write Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/settings/DesktopAppSettings.ts | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index ccfd17ab58d47..8807ec5981cfd 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -387,22 +387,17 @@ function toDesktopSettingsDocument( if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) { document.linuxPasswordStore = settings.linuxPasswordStore; } - const [defaultProfile, ...otherProfiles] = settings.windowProfiles; - if (defaultProfile !== undefined && defaultProfile.bounds !== null) { + const [defaultProfile = DEFAULT_WINDOW_PROFILE, ...otherProfiles] = settings.windowProfiles; + if (defaultProfile.bounds !== null) { document.mainWindowBounds = defaultProfile.bounds; } - if (defaultProfile?.maximized === true) { + if (defaultProfile.maximized) { document.mainWindowMaximized = true; } - if ( - otherProfiles.length > 0 || - (defaultProfile !== undefined && defaultProfile.name !== DEFAULT_WINDOW_PROFILE_NAME) - ) { + if (otherProfiles.length > 0 || defaultProfile.name !== DEFAULT_WINDOW_PROFILE_NAME) { document.windowProfiles = [ // The legacy keys carry the default profile's placement. - ...(defaultProfile === undefined - ? [] - : [{ id: defaultProfile.id, name: defaultProfile.name }]), + { id: defaultProfile.id, name: defaultProfile.name }, ...otherProfiles, ]; } From 2dd9fba9cdc535de934e8453fc95d6b03094f815 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:41:49 -0500 Subject: [PATCH 15/21] test: window state and menu tests share small window fixtures Co-Authored-By: Claude Opus 5.5 --- .../src/window/DesktopApplicationMenu.test.ts | 91 +++++++------------ apps/web/src/multiWindow/windowsState.test.ts | 51 ++--------- 2 files changed, 41 insertions(+), 101 deletions(-) diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index e61220e60b578..1f81cb5ffc1f5 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -102,6 +102,24 @@ const emptyWindowsState: DesktopWindowsState = { multiWindowEnabled: true, }; +const windowProfile = (id: string, name: string) => ({ + id, + name, + projectScopeKeys: [], + theme: null, + isDefault: id === "main", +}); + +const openWindow = (windowId: number, profileId: string) => ({ + windowId, + isMain: profileId === "main", + profileId, + name: profileId, + title: "", + focused: false, + projectScopeKeys: [], +}); + const layerDesktopWindow = ( selectedAction: Deferred.Deferred, windowsState: DesktopWindowsState = emptyWindowsState, @@ -371,40 +389,18 @@ describe("DesktopApplicationMenu", () => { const selectedAction = yield* Deferred.make(); const applicationMenuTemplate = yield* Deferred.make(); - const profile = (id: string, name: string) => ({ - id, - name, - projectScopeKeys: [], - theme: null, - isDefault: id === "main", - }); yield* configureMenu( selectedAction, applicationMenuTemplate, {}, {}, { - profiles: [profile("main", "Main"), profile("work", "Work"), profile("side", "Side")], - windows: [ - { - windowId: 1, - isMain: true, - profileId: "main", - name: "Main", - title: "", - focused: true, - projectScopeKeys: [], - }, - { - windowId: 2, - isMain: false, - profileId: "work", - name: "Work", - title: "", - focused: false, - projectScopeKeys: [], - }, + profiles: [ + windowProfile("main", "Main"), + windowProfile("work", "Work"), + windowProfile("side", "Side"), ], + windows: [openWindow(1, "main"), openWindow(2, "work")], miniMode: true, multiWindowEnabled: true, }, @@ -418,35 +414,19 @@ describe("DesktopApplicationMenu", () => { } const items = windowMenu.submenu.filter((item) => item.label !== undefined); assert.deepEqual( - items.slice(0, 5).map(({ label, checked, accelerator, registerAccelerator }) => ({ - label, - checked, - accelerator, - registerAccelerator, - })), + items.slice(0, 5).map(({ label, checked }) => ({ label, checked })), [ - { - label: "New Window", - checked: undefined, - accelerator: "CmdOrCtrl+Alt+Shift+N", - registerAccelerator: false, - }, - { - label: "Main Window", - checked: undefined, - accelerator: undefined, - registerAccelerator: undefined, - }, - { label: "Work", checked: true, accelerator: undefined, registerAccelerator: undefined }, - { label: "Side", checked: false, accelerator: undefined, registerAccelerator: undefined }, - { - label: "Mini Mode", - checked: true, - accelerator: undefined, - registerAccelerator: undefined, - }, + { label: "New Window", checked: undefined }, + { label: "Main Window", checked: undefined }, + { label: "Work", checked: true }, + { label: "Side", checked: false }, + { label: "Mini Mode", checked: true }, ], ); + assert.deepEqual( + { accelerator: items[0]?.accelerator, registerAccelerator: items[0]?.registerAccelerator }, + { accelerator: "CmdOrCtrl+Alt+Shift+N", registerAccelerator: false }, + ); items[0]?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); assert.equal(yield* Deferred.await(selectedAction), "new-window"); }), @@ -465,10 +445,7 @@ describe("DesktopApplicationMenu", () => { {}, { ...emptyWindowsState, - profiles: [ - { id: "main", name: "Main", projectScopeKeys: [], theme: null, isDefault: true }, - { id: "work", name: "Work", projectScopeKeys: [], theme: null, isDefault: false }, - ], + profiles: [windowProfile("main", "Main"), windowProfile("work", "Work")], multiWindowEnabled: false, }, ); diff --git a/apps/web/src/multiWindow/windowsState.test.ts b/apps/web/src/multiWindow/windowsState.test.ts index e9f55c786e849..5c37ecccd81f1 100644 --- a/apps/web/src/multiWindow/windowsState.test.ts +++ b/apps/web/src/multiWindow/windowsState.test.ts @@ -5,6 +5,7 @@ import type { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; +import { openWindow } from "./ui/mini.fixtures"; import { isMiniMainWindow, resolveWindowThemeOverride, @@ -26,6 +27,8 @@ const workProfile: DesktopWindowProfile = { isDefault: false, }; +const unsavedWindow = openWindow(2, "Window 2", "", { profileId: null, focused: true }); + function context(overrides: Partial = {}): DesktopWindowContext { return { windowId: 2, @@ -41,24 +44,8 @@ function windowsState(overrides: Partial = {}): DesktopWind return { profiles: [mainProfile, workProfile], windows: [ - { - windowId: 1, - isMain: true, - profileId: "main", - name: "Main", - title: "", - focused: false, - projectScopeKeys: [], - }, - { - windowId: 2, - isMain: false, - profileId: "work", - name: "Work", - title: "", - focused: true, - projectScopeKeys: [], - }, + openWindow(1, "Main", "", { isMain: true, profileId: "main" }), + openWindow(2, "Work", "", { profileId: "work", focused: true }), ], miniMode: false, multiWindowEnabled: true, @@ -72,19 +59,7 @@ describe("selectCurrentWindowProfile", () => { expect(selectCurrentWindowProfile(windowsState(), context({ profileId: null }))).toBe( workProfile, ); - const deleted = windowsState({ - windows: [ - { - windowId: 2, - isMain: false, - profileId: null, - name: "Window 2", - title: "", - focused: true, - projectScopeKeys: [], - }, - ], - }); + const deleted = windowsState({ windows: [unsavedWindow] }); expect(selectCurrentWindowProfile(deleted, context({ profileId: "work" }))).toBeNull(); }); @@ -110,19 +85,7 @@ describe("resolveWindowThemeOverride", () => { [ "an unsaved window", context({ theme: "nord" }), - windowsState({ - windows: [ - { - windowId: 2, - isMain: false, - profileId: null, - name: "W", - title: "", - focused: true, - projectScopeKeys: [], - }, - ], - }), + windowsState({ windows: [unsavedWindow] }), null, ], ] as const)("resolves %s", (_label, windowContext, state, expected) => { From a15f4beed987b2dc715b551bebfc9b11af217b39 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:42:38 -0500 Subject: [PATCH 16/21] refactor(web): saved windows join New Window under the multiple-windows check Co-Authored-By: Claude Opus 5.5 --- .../components/CommandPaletteWindowItems.tsx | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/CommandPaletteWindowItems.tsx b/apps/web/src/components/CommandPaletteWindowItems.tsx index b83ecc4b2d282..a044eae0022e5 100644 --- a/apps/web/src/components/CommandPaletteWindowItems.tsx +++ b/apps/web/src/components/CommandPaletteWindowItems.tsx @@ -29,21 +29,21 @@ export function useCommandPaletteWindowItems(): ReadonlyArray openNewDesktopWindow(bridge), }); - } - for (const profile of multiWindowEnabled ? (windowsState?.profiles ?? []) : []) { - if (profile.isDefault || profile.id === currentProfileId) continue; - items.push({ - kind: "action", - value: `action:window-open:${profile.id}`, - title: `Open window: ${profile.name}`, - searchTerms: ["window", "open window", "saved window", profile.name], - icon: , - run: async () => { - await bridge.openProfile(profile.id).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't open the window", cause); - }); - }, - }); + for (const profile of windowsState?.profiles ?? []) { + if (profile.isDefault || profile.id === currentProfileId) continue; + items.push({ + kind: "action", + value: `action:window-open:${profile.id}`, + title: `Open window: ${profile.name}`, + searchTerms: ["window", "open window", "saved window", profile.name], + icon: , + run: async () => { + await bridge.openProfile(profile.id).catch((cause: unknown) => { + notifyWindowActionFailure("Couldn't open the window", cause); + }); + }, + }); + } } if (context?.isMain === true) { const miniMode = windowsState?.miniMode === true; From dbcd5fe530f7c21d1737b9521cc17ba7a97b5bb6 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:42:51 -0500 Subject: [PATCH 17/21] refactor(web): a saved window's settings row takes whether it is open Co-Authored-By: Claude Opus 5.5 --- .../src/components/settings/WindowsSettings.tsx | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/settings/WindowsSettings.tsx b/apps/web/src/components/settings/WindowsSettings.tsx index 00a23080f95ac..ed5ffa049a148 100644 --- a/apps/web/src/components/settings/WindowsSettings.tsx +++ b/apps/web/src/components/settings/WindowsSettings.tsx @@ -1,8 +1,4 @@ -import type { - DesktopOpenWindow, - DesktopWindowProfile, - DesktopWindowsBridge, -} from "@t3tools/contracts"; +import type { DesktopWindowProfile, DesktopWindowsBridge } from "@t3tools/contracts"; import { CheckIcon, PlusIcon, Trash2Icon } from "lucide-react"; import { useState, type ComponentProps } from "react"; @@ -100,7 +96,7 @@ function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBri bridge={bridge} profile={mainProfile} projectGroups={projectGroups} - openWindow={undefined} + isOpen isCurrentWindow={currentProfileId === mainProfile.id} canOpen /> @@ -115,7 +111,9 @@ function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBri bridge={bridge} profile={profile} projectGroups={projectGroups} - openWindow={windowsState?.windows.find((window) => window.profileId === profile.id)} + isOpen={ + windowsState?.windows.some((window) => window.profileId === profile.id) ?? false + } isCurrentWindow={currentProfileId === profile.id} canOpen={multiWindowEnabled} /> @@ -237,14 +235,14 @@ function WindowProfileRow({ bridge, profile, projectGroups, - openWindow, + isOpen, isCurrentWindow, canOpen, }: { readonly bridge: DesktopWindowsBridge; readonly profile: DesktopWindowProfile; readonly projectGroups: ProjectScopeGroups; - readonly openWindow: DesktopOpenWindow | undefined; + readonly isOpen: boolean; readonly isCurrentWindow: boolean; readonly canOpen: boolean; }) { @@ -259,7 +257,6 @@ function WindowProfileRow({ notifyWindowActionFailure("Couldn't delete the saved window", cause); }); }; - const isOpen = profile.isDefault || openWindow !== undefined; return ( Date: Sun, 22 Nov 2026 21:15:36 -0500 Subject: [PATCH 18/21] feat(desktop): open Mini Mode short, and drop the sidebar tint of secondary windows The project-colour wash across a secondary window's sidebar banner read as noise. It goes; a saved window's theme options and the colour on its settings entry stay. Mini Mode opened at 320x460, which made a persistent accessory panel feel like a second app window. It now opens at 320x184, like a menu-bar panel, and can be dragged down to 160px or taller for more. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/window/DesktopWindow.ts | 4 +- .../src/components/sidebar/SidebarChrome.tsx | 2 - .../src/multiWindow/ui/DesktopWindowTint.tsx | 39 ------------------- .../ui/MiniMainWindow.browser.test.tsx | 4 +- docs/user/multiple-windows.md | 6 +-- 5 files changed, 7 insertions(+), 48 deletions(-) delete mode 100644 apps/web/src/multiWindow/ui/DesktopWindowTint.tsx diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 04769e85aaf69..0d20bc8892f6b 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -123,8 +123,8 @@ const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500; const RENDERER_RECOVERY_MAX_ATTEMPTS = 3; const RENDERER_RECOVERY_WINDOW_MS = 60_000; const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]); -const MINI_WINDOW_SIZE = { width: 320, height: 460 } as const; -const MINI_WINDOW_MIN_SIZE = { width: 240, height: 320 } as const; +const MINI_WINDOW_SIZE = { width: 320, height: 184 } as const; +const MINI_WINDOW_MIN_SIZE = { width: 240, height: 160 } as const; const HUB_UNTHROTTLED_REASON = "hub-serving-windows"; type WindowTitleBarOptions = Pick< diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index e59be49e80b6f..7d442f96f8b15 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -12,7 +12,6 @@ import { useCanNavigateHistory, type HistoryDirection, } from "../../navigationHistory"; -import { DesktopWindowTint } from "../../multiWindow/ui/DesktopWindowTint"; import { primaryServerKeybindingsAtom } from "../../state/server"; import { cn } from "../../lib/utils"; import { useIssuesSupported, usePullRequestsSupported } from "../../state/environments"; @@ -69,7 +68,6 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({ )} > {backdropVariant ? : null} -
    ; -} - -function SecondaryWindowTint({ context }: { readonly context: DesktopWindowContext }) { - const windowsState = useDesktopWindowsState(); - const scopeKeys = useUiStateStore((store) => store.sidebarProjectScopeKeys); - const { groupsForKeys } = useProjectScopeGroups(); - const colors = useProjectTintColors(groupsForKeys(scopeKeys)); - if (colors.length === 0 || resolveWindowThemeOverride(windowsState, context) !== null) { - return null; - } - return ( -
    - ); -} diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx index 7c4dce1b55d52..2cc6ba29c71e9 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx @@ -100,7 +100,7 @@ function Panel({ } async function renderPanel(options: PanelOptions = {}) { - await page.viewport(320, 460); + await page.viewport(320, 184); const actions = makeActions(); const screen = await render(); const openTab = (name: string) => screen.getByRole("button", { name, exact: true }).click(); @@ -197,7 +197,7 @@ describe("MiniPanel", () => { await expect.element(screen.getByRole("button", { name: /redesign 1 / })).toBeInViewport(); await expect.element(screen.getByRole("button", { name: /redesign 14 / })).not.toBeInViewport(); expect(document.documentElement.scrollWidth).toBe(320); - expect(document.documentElement.scrollHeight).toBe(460); + expect(document.documentElement.scrollHeight).toBe(184); const viewport = screen.container.querySelector("[data-slot=scroll-area-viewport]")!; expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight); expect(viewport.scrollWidth).toBe(viewport.clientWidth); diff --git a/docs/user/multiple-windows.md b/docs/user/multiple-windows.md index 913c29928df81..905817fb9b86a 100644 --- a/docs/user/multiple-windows.md +++ b/docs/user/multiple-windows.md @@ -33,9 +33,9 @@ window by editing its name in place, pick its theme, open or focus it, or delete window** creates one without opening it. Deleting a saved window that is open leaves it open as an unsaved window. A window you have not saved yet can be saved from the same section. -A window with a project filter uses **Project colour** by default: its projects' icon colours tint -the top of its sidebar, and the rest of the window keeps the main window's theme. Projects whose -icon is an image or an emoji add no colour. Pick a theme for a saved window to use that theme +A window with a project filter uses **Project colour** by default: it keeps the main window's +theme, and its projects' icon colours mark its entry in the list. Projects whose icon is an image or +an emoji add no colour. Pick a theme for a saved window to use that theme instead. Changing the theme from inside a window with its own theme changes only that window. Light, dark, and system appearance stay shared by every window. From e2d756ae44a4ca491e7815ebaac13e3830006e45 Mon Sep 17 00:00:00 2001 From: Na0s Date: Sun, 22 Nov 2026 21:27:25 -0500 Subject: [PATCH 19/21] feat(web): Mini Mode tabs move to the top bar, Settings goes, Usage fits two accounts At 184px tall the panel had room for one tab's content between two bars, and the Settings tab's switch was hard to use there. Settings goes; the full settings are a search away. The tabs (Windows, Pull requests, Usage, Update) move into the top bar on the left; Search becomes an icon beside New Window and Expand on the right. Windows takes a layers icon so it doesn't repeat New Window's. Usage showed one account's rows per screen. It now draws each limit as a small bar with its percent left, two to a line, so Claude and OpenAI show together. The bar keeps its tooltip with the reset time. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/usage/UsageLimits.tsx | 37 +++++++++- .../ui/MiniMainWindow.browser.test.tsx | 55 +++++++-------- .../web/src/multiWindow/ui/MiniMainWindow.tsx | 70 +++++++------------ apps/web/src/multiWindow/ui/MiniSettings.tsx | 37 ---------- apps/web/src/multiWindow/ui/MiniUsage.tsx | 13 ++-- docs/user/multiple-windows.md | 11 +-- 6 files changed, 98 insertions(+), 125 deletions(-) delete mode 100644 apps/web/src/multiWindow/ui/MiniSettings.tsx diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsx index a36b220ee3efa..7cf25ddd295d3 100644 --- a/apps/web/src/components/usage/UsageLimits.tsx +++ b/apps/web/src/components/usage/UsageLimits.tsx @@ -23,6 +23,7 @@ import { Fragment, useLayoutEffect, useState } from "react"; import { usePrimarySettings } from "../../hooks/useSettings"; import { observeResize } from "../../lib/observeResize"; +import { cn } from "../../lib/utils"; import { environmentPresentations } from "../../state/presentation"; import { useEnvironmentScope, readEnvironmentScope } from "../../state/session"; import { serverEnvironment } from "../../state/server"; @@ -125,10 +126,12 @@ function WindowBar({ color, window, now, + className, }: { readonly color: string; readonly window: ServerProviderUsageWindow; readonly now: number; + readonly className?: string; }) { const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); const gt = useGT(); @@ -168,7 +171,10 @@ function WindowBar({ role="img" aria-label={summary} tabIndex={0} - className="relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background" + className={cn( + "relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background", + className, + )} /> } > @@ -262,6 +268,35 @@ export function LimitWindows({ ); } +/** Two limits to a line, each a label, a bar and the percent left; the bar's tooltip says the rest. */ +export function LimitMeters({ + driver, + accentColor, + windows, + now, +}: { + readonly driver: ServerProvider["driver"]; + readonly accentColor?: string | undefined; + readonly windows: ReadonlyArray; + readonly now: number; +}) { + const color = normalizeProviderAccentColor(accentColor) ?? barColor(driver); + return ( +
      + {windows.map((window) => ( +
    • + {window.label} + + {remainingPercent(window)}% +
    • + ))} +
    + ); +} + const OUTCOME_TEXT: Record = { reset: msg("Reset applied. Your windows have cleared."), nothingToReset: msg("Nothing to reset right now."), diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx index 2cc6ba29c71e9..853aa4e3019ef 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx @@ -20,7 +20,6 @@ import { } from "./mini.fixtures"; import { MiniPanel } from "./MiniMainWindow"; import { MiniPullRequestList } from "./MiniPullRequests"; -import { MiniSettings } from "./MiniSettings"; import { MiniUpdate } from "./MiniUpdate"; import { MiniUsageSection } from "./MiniUsage"; import { MiniWindows } from "./MiniWindows"; @@ -44,8 +43,6 @@ const makeActions = () => ({ expand: vi.fn(), newWindow: vi.fn(), focusWindow: vi.fn(), - multiWindowEnabledChange: vi.fn(), - openSettings: vi.fn(), openPullRequest: vi.fn(), }); @@ -78,13 +75,6 @@ function Panel({ onFocusWindow={actions.focusWindow} /> ), - settings: ( - - ), pullRequests: ( { it("opens on Usage and shows one tab's content at a time", async () => { @@ -115,9 +105,9 @@ describe("MiniPanel", () => { const { screen, openTab } = await renderPanel(); await using _screen = screen; - await expect.element(screen.getByText("62% left")).toBeVisible(); + await expect.element(screen.getByText("62%")).toBeVisible(); expect(document.documentElement.scrollWidth).toBe(320); - for (const tab of ["Windows", "Settings", "Pull requests", "Update", "Usage"]) { + for (const tab of ["Windows", "Pull requests", "Update", "Usage"]) { await openTab(tab); await expect .element(screen.getByRole("button", { name: tab, exact: true })) @@ -129,15 +119,20 @@ describe("MiniPanel", () => { } }); - it("offers Search, New Window and Expand in the top bar, with only Search labelled", async () => { + it("puts the tabs at the left of the top bar and Search, New Window and Expand at its right", async () => { const { screen, actions } = await renderPanel(); await using _screen = screen; - const search = screen.getByRole("button", { name: "Search" }); - await expect.element(search).toHaveTextContent("Search"); - await search.click(); - expect(actions.search).toHaveBeenCalledOnce(); + const left = (name: string) => + screen.getByRole("button", { name, exact: true }).element().getBoundingClientRect(); + expect(left("Windows").left).toBeLessThan(left("Update").left); + expect(left("Update").right).toBeLessThan(left("Search").left); + expect(left("Search").right).toBeLessThan(left("New Window").left); + expect(left("New Window").right).toBeLessThan(left("Expand").left); + // Flush with the panel's right edge, inside its content inset. + expect(320 - left("Expand").right).toBeLessThanOrEqual(12); for (const [name, action] of [ + ["Search", actions.search], ["New Window", actions.newWindow], ["Expand", actions.expand], ] as const) { @@ -148,6 +143,19 @@ describe("MiniPanel", () => { } }); + it("shows Claude's and OpenAI's limits together at the panel's default size", async () => { + const { screen } = await renderPanel(); + await using _screen = screen; + + await expect.element(screen.getByText("Claude · Max")).toBeInViewport(); + await expect.element(screen.getByText("Codex · ChatGPT Pro 100 Subscription")).toBeInViewport(); + for (const percent of ["62%", "41%", "6%", "78%"]) { + await expect.element(screen.getByText(percent, { exact: true })).toBeInViewport(); + } + const viewport = screen.container.querySelector("[data-slot=scroll-area-viewport]")!; + expect(viewport.scrollHeight).toBe(viewport.clientHeight); + }); + it("hides New Window while multiple windows are off, and PRs where no server supports them", async () => { const { screen } = await renderPanel({ multiWindowEnabled: false, @@ -212,17 +220,6 @@ describe("MiniPanel", () => { .toBeVisible(); }); - it("Settings toggles multiple windows and leads to the full settings", async () => { - const { screen, actions, openTab } = await renderPanel(); - await using _screen = screen; - await openTab("Settings"); - - await screen.getByRole("switch", { name: "Multiple windows" }).click(); - expect(actions.multiWindowEnabledChange.mock.calls[0]?.[0]).toBe(false); - await screen.getByRole("button", { name: "All settings" }).click(); - expect(actions.openSettings).toHaveBeenCalledOnce(); - }); - it("PRs opens a pull request on its host", async () => { const { screen, actions, openTab } = await renderPanel(); await using _screen = screen; diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx index 447d2d4624a86..b6959e9552c06 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx @@ -4,9 +4,9 @@ import { AppWindowIcon, ChartNoAxesColumnIcon, CircleArrowUpIcon, + LayersIcon, Maximize2Icon, SearchIcon, - SettingsIcon, } from "lucide-react"; import { type ReactNode, useEffect, useState } from "react"; @@ -17,25 +17,19 @@ import { PullRequestGlyph } from "../../components/pullRequest/pullRequestIcons" import { SidebarUtilityItem } from "../../components/sidebar/SidebarChrome"; import { SidebarHeaderIconButton } from "../../components/sidebar/SidebarThreadHeader"; import { ScrollArea } from "../../components/ui/scroll-area"; -import { - SidebarFooter, - SidebarMenu, - SidebarMenuButton, - SidebarProvider, -} from "../../components/ui/sidebar"; +import { SidebarMenu, SidebarProvider } from "../../components/ui/sidebar"; import { useDesktopUpdateState } from "../../state/desktopUpdate"; import { usePullRequestsSupported } from "../../state/environments"; import { desktopWindowsBridge } from "../windowContext"; import { useDesktopWindowsState } from "../windowsState"; import { MiniPullRequests } from "./MiniPullRequests"; -import { MiniSettings } from "./MiniSettings"; import { MiniUpdate } from "./MiniUpdate"; import { MiniUsage } from "./MiniUsage"; import { MiniWindows } from "./MiniWindows"; import { useProjectScopeGroups } from "./useProjectScopeGroups"; import { notifyWindowActionFailure, openNewDesktopWindow } from "./windowActions"; -type MiniTab = "windows" | "settings" | "pullRequests" | "usage" | "update"; +type MiniTab = "windows" | "pullRequests" | "usage" | "update"; /** The main window's compact stand-in for the app shell while Mini Mode is on. */ export function MiniMainWindow() { @@ -88,17 +82,6 @@ function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBrid }} /> ), - settings: ( - { - bridge.setMultiWindowEnabled(enabled).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't change multiple windows", cause); - }); - }} - onOpenSettings={() => void router.navigate({ to: "/settings" })} - /> - ), pullRequests: , usage: , update: , @@ -108,7 +91,7 @@ function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBrid ); } -/** The sidebar's top bar and bottom bar around one tab's content; the tabs never share the panel. */ +/** One top bar, tabs on the left and actions on the right, over one tab's content. */ export function MiniPanel({ pullRequestsSupported, updateAvailable, @@ -138,12 +121,27 @@ export function MiniPanel({ return (
    -
    - - - Search - +
    + + {tabItem("windows", "Windows", )} + {pullRequestsSupported + ? tabItem("pullRequests", "Pull requests", ) + : null} + {tabItem("usage", "Usage", )} + + {tabItem("update", "Update", )} + {updateAvailable ? ( + + ) : null} + + + + + {onNewWindow === undefined ? null : ( @@ -158,26 +156,6 @@ export function MiniPanel({ {tabs[tab]} - - - {tabItem("windows", "Windows", )} - {tabItem("settings", "Settings", )} - {pullRequestsSupported - ? tabItem("pullRequests", "Pull requests", ) - : null} - {tabItem("usage", "Usage", )} - - - {tabItem("update", "Update", )} - {updateAvailable ? ( - - ) : null} - - -
    ); diff --git a/apps/web/src/multiWindow/ui/MiniSettings.tsx b/apps/web/src/multiWindow/ui/MiniSettings.tsx deleted file mode 100644 index b89a9b4664f76..0000000000000 --- a/apps/web/src/multiWindow/ui/MiniSettings.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { ChevronRightIcon } from "lucide-react"; - -import { SidebarMenuButton } from "../../components/ui/sidebar"; -import { Switch } from "../../components/ui/switch"; - -/** The one setting that changes what the panel offers, and the way to the rest. */ -export function MiniSettings({ - multiWindowEnabled, - onMultiWindowEnabledChange, - onOpenSettings, -}: { - readonly multiWindowEnabled: boolean; - readonly onMultiWindowEnabledChange: (enabled: boolean) => void; - readonly onOpenSettings: () => void; -}) { - return ( -
    -
    - - Multiple windows - - Turning this off keeps open windows open. - - - -
    - - All settings - - -
    - ); -} diff --git a/apps/web/src/multiWindow/ui/MiniUsage.tsx b/apps/web/src/multiWindow/ui/MiniUsage.tsx index 2b9326aad01a3..204c8622661cc 100644 --- a/apps/web/src/multiWindow/ui/MiniUsage.tsx +++ b/apps/web/src/multiWindow/ui/MiniUsage.tsx @@ -11,7 +11,7 @@ import { useEffect, useEffectEvent, useState } from "react"; import { providerClients } from "../../components/settings/providerDriverMeta"; import { Button } from "../../components/ui/button"; -import { LimitWindows } from "../../components/usage/UsageLimits"; +import { LimitMeters } from "../../components/usage/UsageLimits"; import { ensureLocalApi } from "../../localApi"; import { environmentPresentations } from "../../state/presentation"; import { serverEnvironment } from "../../state/server"; @@ -47,7 +47,7 @@ export function MiniUsage() { return ; } -/** The composer's compact limit rows for every signed-in account. */ +/** Every signed-in account's limits as small meters, so Claude and OpenAI fit the panel together. */ export function MiniUsageSection({ presentations, now, @@ -57,16 +57,15 @@ export function MiniUsageSection({ }) { const accounts = collectLimitAccounts(presentations); return ( -
    +
    {accounts.length === 0 ?

    Usage unavailable

    : null} {accounts.map((account) => ( -
    -

    +
    +

    {account.displayName ?? providerClients.get(account.driver)?.label ?? account.driver} {account.plan ? ` · ${account.plan}` : null}

    - Date: Sun, 22 Nov 2026 21:32:00 -0500 Subject: [PATCH 20/21] fix(desktop,web): fit Mini Mode's top bar beside the Windows and Linux window controls On Windows and Linux the title bar overlay keeps its buttons in the panel's top right, and at 320px the tabs ran under Search. In Mini Mode the window is no longer maximizable or minimizable, which drops Maximize on Linux; the tabs take the top bar's 28px buttons instead of the sidebar footer's 32px ones. The bar now fits with Minimize and Close beside it, and the sidebar footer item goes back to how it was. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/window/DesktopWindow.ts | 8 ++++++-- .../src/components/sidebar/SidebarChrome.tsx | 13 ++----------- .../components/sidebar/SidebarThreadHeader.tsx | 2 +- apps/web/src/multiWindow/ui/MiniMainWindow.tsx | 17 +++++++++-------- 4 files changed, 18 insertions(+), 22 deletions(-) diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 0d20bc8892f6b..c43b0bd808bf5 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -1674,9 +1674,13 @@ export const make = Effect.gen(function* () { if (previous.isMaximized) window.maximize(); } } - // The panel's top bar stands in for the traffic lights. Windows and Linux keep their - // controls: Electron cannot take a title bar overlay off a window once it is created. + // The panel's top bar stands in for the traffic lights. Windows and Linux keep the title bar + // overlay, which Electron cannot take off a created window, so the panel keeps only Close. if (environment.platform === "darwin") window.setWindowButtonVisibility(!enabled); + else { + window.setMinimizable(!enabled); + window.setMaximizable(!enabled); + } yield* electronWindow.reveal(window); yield* syncWindows(); }); diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index 7d442f96f8b15..1dbc9b9fc6366 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -200,16 +200,13 @@ function SidebarBrandMark({ onBackdrop }: { onBackdrop: boolean }) { ); } -export function SidebarUtilityItem({ +function SidebarUtilityItem({ icon, label, - isActive = false, onClick, }: { icon: ReactNode; label: string; - /** Mini Mode's tabs mark the one that is showing. */ - isActive?: boolean; onClick: () => void; }) { return ( @@ -217,13 +214,7 @@ export function SidebarUtilityItem({ + {icon} } diff --git a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx index 185f8fc8487a5..d7d7a6679ca97 100644 --- a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx @@ -139,7 +139,7 @@ export function SidebarHeaderIconButton({ children?: ReactNode; } & Omit< ComponentProps, - "children" | "className" | "tooltip" | "isActive" | "aria-label" + "children" | "className" | "tooltip" | "aria-label" >) { return ( diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx index b6959e9552c06..9aee7430d593e 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx @@ -14,10 +14,9 @@ import { openCommandPalette } from "../../commandPaletteBus"; import { CommandPalette } from "../../components/CommandPalette"; import { resolveDesktopUpdateButtonAction } from "../../components/desktopUpdate.logic"; import { PullRequestGlyph } from "../../components/pullRequest/pullRequestIcons"; -import { SidebarUtilityItem } from "../../components/sidebar/SidebarChrome"; import { SidebarHeaderIconButton } from "../../components/sidebar/SidebarThreadHeader"; import { ScrollArea } from "../../components/ui/scroll-area"; -import { SidebarMenu, SidebarProvider } from "../../components/ui/sidebar"; +import { SidebarProvider } from "../../components/ui/sidebar"; import { useDesktopUpdateState } from "../../state/desktopUpdate"; import { usePullRequestsSupported } from "../../state/environments"; import { desktopWindowsBridge } from "../windowContext"; @@ -111,18 +110,20 @@ export function MiniPanel({ }) { const [tab, setTab] = useState("usage"); const tabItem = (id: MiniTab, label: string, icon: ReactNode) => ( - setTab(id)} - /> + > + {icon} + ); return (
    -
    - +
    + From 76a95e98bc9e59b3bbff9f01a243de864775f710 Mon Sep 17 00:00:00 2001 From: Na0s Date: Mon, 23 Nov 2026 10:19:24 -0500 Subject: [PATCH 21/21] fix(desktop,web): translate the multi-window UI and read usage notices from the copy module The app's UI is now translated. Saved windows, Windows settings, the close prompt, Mini Mode, the Window menu entries and unsaved window names use gt(), and msg(), with keys in en and every locale catalog for web and desktop. Mini Mode's Usage tab takes collectLimitNotices and collectExternalUsageLinks from usageLimitsCopy, which moved there to translate, and its update and pull request rows pass the active resolver. The Mini Mode test fixtures are renamed to mini.test-fixtures.ts so the untranslated-copy rule skips them. The Window menu test expects Minimize and Zoom too, which now carry translated labels. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/i18n/translations/de.json | 3 + apps/desktop/src/i18n/translations/en.json | 3 + apps/desktop/src/i18n/translations/es.json | 3 + apps/desktop/src/i18n/translations/fr.json | 3 + apps/desktop/src/i18n/translations/ja.json | 3 + apps/desktop/src/i18n/translations/ko.json | 3 + apps/desktop/src/i18n/translations/pt-BR.json | 3 + apps/desktop/src/i18n/translations/ru.json | 3 + apps/desktop/src/i18n/translations/sv.json | 3 + apps/desktop/src/i18n/translations/zh.json | 3 + .../src/window/DesktopApplicationMenu.test.ts | 3 +- .../src/window/DesktopWindowProfiles.ts | 13 +- .../components/CommandPaletteWindowItems.tsx | 8 +- .../components/settings/WindowsSettings.tsx | 115 ++++++++++++------ .../src/components/settings/settingsSearch.ts | 4 +- apps/web/src/i18n/translations/de.json | 54 ++++++++ apps/web/src/i18n/translations/en.json | 54 ++++++++ apps/web/src/i18n/translations/es.json | 54 ++++++++ apps/web/src/i18n/translations/fr.json | 54 ++++++++ apps/web/src/i18n/translations/ja.json | 54 ++++++++ apps/web/src/i18n/translations/ko.json | 54 ++++++++ apps/web/src/i18n/translations/pt-BR.json | 54 ++++++++ apps/web/src/i18n/translations/ru.json | 54 ++++++++ apps/web/src/i18n/translations/sv.json | 54 ++++++++ apps/web/src/i18n/translations/zh.json | 54 ++++++++ .../src/multiWindow/ui/DesktopWindowsHost.tsx | 22 ++-- .../ui/MiniMainWindow.browser.test.tsx | 2 +- .../web/src/multiWindow/ui/MiniMainWindow.tsx | 38 ++++-- .../src/multiWindow/ui/MiniPullRequests.tsx | 15 ++- apps/web/src/multiWindow/ui/MiniUpdate.tsx | 16 ++- apps/web/src/multiWindow/ui/MiniUsage.tsx | 26 ++-- apps/web/src/multiWindow/ui/MiniWindows.tsx | 24 +++- ...mini.fixtures.ts => mini.test-fixtures.ts} | 0 apps/web/src/multiWindow/windowsState.test.ts | 2 +- 34 files changed, 764 insertions(+), 94 deletions(-) rename apps/web/src/multiWindow/ui/{mini.fixtures.ts => mini.test-fixtures.ts} (100%) diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json index 55145c7cda1eb..e5ba2df4f420b 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "Vollbildmodus ein/aus", "d8c6d6d9845353da": "Fenster", "c015841b7b2523c6": "Neues Fenster", + "d5203c78d46e1282": "Hauptfenster", + "f8e9094362fa962a": "Mini-Modus", "f184aa190588625e": "Minimieren", "c20a9deaed71bd1c": "Zoomen", "d207ba3a23f94223": "Alle nach vorne bringen", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "Link kopieren", "8af79268f2349f4c": "E-Mail-Adresse kopieren", "a9f9254d458e49fe": "Bild kopieren", + "0ec1ce287d61c59a": "Fenster {number}", "9c1b20fbc881de5d": "Desktop-Konfiguration", "1b14230874f19eb9": "Bilder" } diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 578c3a86c961e..003abd97c04d3 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "Toggle Full Screen", "d8c6d6d9845353da": "Window", "c015841b7b2523c6": "New Window", + "d5203c78d46e1282": "Main Window", + "f8e9094362fa962a": "Mini Mode", "f184aa190588625e": "Minimize", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Bring All to Front", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "Copy Link", "8af79268f2349f4c": "Copy Email Address", "a9f9254d458e49fe": "Copy Image", + "0ec1ce287d61c59a": "Window {number}", "9c1b20fbc881de5d": "Desktop config", "1b14230874f19eb9": "Images" } diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index 155d2d7e22e48..c379187e60c87 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "Activar/desactivar pantalla completa", "d8c6d6d9845353da": "Ventana", "c015841b7b2523c6": "Nueva ventana", + "d5203c78d46e1282": "Ventana principal", + "f8e9094362fa962a": "Modo mini", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Traer todo al frente", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "Copiar enlace", "8af79268f2349f4c": "Copiar dirección de correo", "a9f9254d458e49fe": "Copiar imagen", + "0ec1ce287d61c59a": "Ventana {number}", "9c1b20fbc881de5d": "Configuración de escritorio", "1b14230874f19eb9": "Imágenes" } diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 9312fb6c77f57..dbc94b18801f4 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "Activer/désactiver le plein écran", "d8c6d6d9845353da": "Fenêtre", "c015841b7b2523c6": "Nouvelle fenêtre", + "d5203c78d46e1282": "Fenêtre principale", + "f8e9094362fa962a": "Mode mini", "f184aa190588625e": "Réduire", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Tout ramener au premier plan", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "Copier le lien", "8af79268f2349f4c": "Copier l’adresse e-mail", "a9f9254d458e49fe": "Copier l’image", + "0ec1ce287d61c59a": "Fenêtre {number}", "9c1b20fbc881de5d": "Configuration du bureau", "1b14230874f19eb9": "Images" } diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index 46759a18b9b1c..75b8922c407c3 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "フルスクリーンに切り替え", "d8c6d6d9845353da": "ウインドウ", "c015841b7b2523c6": "新規ウインドウ", + "d5203c78d46e1282": "メインウインドウ", + "f8e9094362fa962a": "ミニモード", "f184aa190588625e": "しまう", "c20a9deaed71bd1c": "拡大/縮小", "d207ba3a23f94223": "すべてを手前に移動", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "リンクをコピー", "8af79268f2349f4c": "メールアドレスをコピー", "a9f9254d458e49fe": "画像をコピー", + "0ec1ce287d61c59a": "ウインドウ {number}", "9c1b20fbc881de5d": "デスクトップの構成", "1b14230874f19eb9": "画像" } diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index eac165f0b91ce..d8c0629d18668 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "전체 화면 전환", "d8c6d6d9845353da": "윈도우", "c015841b7b2523c6": "새 윈도우", + "d5203c78d46e1282": "메인 윈도우", + "f8e9094362fa962a": "미니 모드", "f184aa190588625e": "최소화", "c20a9deaed71bd1c": "확대/축소", "d207ba3a23f94223": "모두 앞으로 가져오기", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "링크 복사", "8af79268f2349f4c": "이메일 주소 복사", "a9f9254d458e49fe": "이미지 복사", + "0ec1ce287d61c59a": "윈도우 {number}", "9c1b20fbc881de5d": "데스크톱 구성", "1b14230874f19eb9": "이미지" } diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 7d39c2e2bb2ee..7e15d42fd9231 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "Alternar tela cheia", "d8c6d6d9845353da": "Janela", "c015841b7b2523c6": "Nova janela", + "d5203c78d46e1282": "Janela principal", + "f8e9094362fa962a": "Modo mini", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Trazer tudo para a frente", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "Copiar link", "8af79268f2349f4c": "Copiar endereço de e-mail", "a9f9254d458e49fe": "Copiar imagem", + "0ec1ce287d61c59a": "Janela {number}", "9c1b20fbc881de5d": "Configuração do desktop", "1b14230874f19eb9": "Imagens" } diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index 2f56fc560ab1b..d7ee16c6c6216 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "Полноэкранный режим", "d8c6d6d9845353da": "Окно", "c015841b7b2523c6": "Новое окно", + "d5203c78d46e1282": "Главное окно", + "f8e9094362fa962a": "Мини-режим", "f184aa190588625e": "Свернуть", "c20a9deaed71bd1c": "Масштаб", "d207ba3a23f94223": "Все окна на передний план", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "Копировать ссылку", "8af79268f2349f4c": "Копировать адрес электронной почты", "a9f9254d458e49fe": "Копировать изображение", + "0ec1ce287d61c59a": "Окно {number}", "9c1b20fbc881de5d": "Конфигурация десктопа", "1b14230874f19eb9": "Изображения" } diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index e161a7f984dfc..089ce99563dcd 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "Växla helskärm", "d8c6d6d9845353da": "Fönster", "c015841b7b2523c6": "Nytt fönster", + "d5203c78d46e1282": "Huvudfönster", + "f8e9094362fa962a": "Miniläge", "f184aa190588625e": "Minimera", "c20a9deaed71bd1c": "Zooma", "d207ba3a23f94223": "Lägg alla överst", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "Kopiera länk", "8af79268f2349f4c": "Kopiera e-postadress", "a9f9254d458e49fe": "Kopiera bild", + "0ec1ce287d61c59a": "Fönster {number}", "9c1b20fbc881de5d": "Skrivbordskonfiguration", "1b14230874f19eb9": "Bilder" } diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index b414c5fd1f0df..66c42efdc40ef 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -115,6 +115,8 @@ "50fe114d093a5bc7": "切换全屏", "d8c6d6d9845353da": "窗口", "c015841b7b2523c6": "新建窗口", + "d5203c78d46e1282": "主窗口", + "f8e9094362fa962a": "迷你模式", "f184aa190588625e": "最小化", "c20a9deaed71bd1c": "缩放", "d207ba3a23f94223": "前置全部窗口", @@ -123,6 +125,7 @@ "202e13f15a3dcd30": "复制链接", "8af79268f2349f4c": "复制邮箱地址", "a9f9254d458e49fe": "复制图片", + "0ec1ce287d61c59a": "窗口 {number}", "9c1b20fbc881de5d": "桌面配置", "1b14230874f19eb9": "图片" } diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 1f81cb5ffc1f5..d1ba722a7f229 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -458,7 +458,8 @@ describe("DesktopApplicationMenu", () => { } assert.deepEqual( windowMenu.submenu.flatMap((item) => (item.label === undefined ? [] : [item.label])), - ["Mini Mode"], + // The role items carry translated labels too. + ["Mini Mode", "Minimize", "Zoom"], ); }), ); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.ts b/apps/desktop/src/window/DesktopWindowProfiles.ts index bfbf60f6cf59d..f7a334a84c2e4 100644 --- a/apps/desktop/src/window/DesktopWindowProfiles.ts +++ b/apps/desktop/src/window/DesktopWindowProfiles.ts @@ -1,3 +1,7 @@ +import { msg } from "gt-i18n"; + +import { m } from "../i18n/messages.ts"; + type DesktopWindowCloseAction = /** Let the window close. */ | "close" @@ -27,13 +31,16 @@ export function resolveWindowCloseAction(input: DesktopWindowCloseInput): Deskto return input.promptPending ? "keep-open" : "prompt"; } -const UNSAVED_WINDOW_NAME_PREFIX = "Window "; - /** The main window is the first window, so unsaved secondary windows count from 2. */ export function nextUnsavedWindowName(usedNames: Iterable): string { const used = new Set(usedNames); for (let index = 2; ; index++) { - const name = `${UNSAVED_WINDOW_NAME_PREFIX}${index}`; + const name = m( + msg("Window {number}", { + $context: "name of an unsaved app window", + number: String(index), + }), + ); if (!used.has(name)) return name; } } diff --git a/apps/web/src/components/CommandPaletteWindowItems.tsx b/apps/web/src/components/CommandPaletteWindowItems.tsx index a044eae0022e5..a551cb35fd3b9 100644 --- a/apps/web/src/components/CommandPaletteWindowItems.tsx +++ b/apps/web/src/components/CommandPaletteWindowItems.tsx @@ -34,12 +34,12 @@ export function useCommandPaletteWindowItems(): ReadonlyArray, run: async () => { await bridge.openProfile(profile.id).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't open the window", cause); + notifyWindowActionFailure(gt("Couldn't open the window"), cause); }); }, }); @@ -50,7 +50,7 @@ export function useCommandPaletteWindowItems(): ReadonlyArray @@ -59,7 +59,7 @@ export function useCommandPaletteWindowItems(): ReadonlyArray { await bridge.setMiniMode(!miniMode).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't change Mini Mode", cause); + notifyWindowActionFailure(gt("Couldn't change Mini Mode"), cause); }); }, }); diff --git a/apps/web/src/components/settings/WindowsSettings.tsx b/apps/web/src/components/settings/WindowsSettings.tsx index ed5ffa049a148..698ed0b6ac5ce 100644 --- a/apps/web/src/components/settings/WindowsSettings.tsx +++ b/apps/web/src/components/settings/WindowsSettings.tsx @@ -1,9 +1,11 @@ import type { DesktopWindowProfile, DesktopWindowsBridge } from "@t3tools/contracts"; +import { msg, T, useGT, useMessages } from "gt-react"; import { CheckIcon, PlusIcon, Trash2Icon } from "lucide-react"; import { useState, type ComponentProps } from "react"; import { requestConfirmDialog } from "~/confirmDialog"; import { useRenderedAppearance } from "../../hooks/useTheme"; +import { m as resolveMessage, type MessageResolver } from "../../i18n/messages"; import { desktopWindowsBridge, readDesktopWindowContext } from "../../multiWindow/windowContext"; import { selectCurrentWindow, @@ -45,6 +47,7 @@ export function WindowsSettingsSection() { } function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const gt = useGT(); const windowsState = useDesktopWindowsState(); const projectGroups = useProjectScopeGroups(); const [creating, setCreating] = useState(false); @@ -59,7 +62,7 @@ function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBri return ( setCreating(true)} > - Add saved window + Add saved window } > + Open more windows that share this app's connections. Turning this off keeps open windows + open. + + } control={ { bridge.setMultiWindowEnabled(checked).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't change multiple windows", cause); + notifyWindowActionFailure(gt("Couldn't change multiple windows"), cause); }); }} /> @@ -139,6 +147,7 @@ function SaveCurrentWindowRow({ readonly bridge: DesktopWindowsBridge; readonly suggestedName: string; }) { + const gt = useGT(); const [name, setName] = useState(suggestedName); const [saving, setSaving] = useState(false); const normalized = normalizeWindowProfileName(name); @@ -147,19 +156,19 @@ function SaveCurrentWindowRow({ setSaving(true); bridge .saveAsProfile(normalized) - .catch((cause: unknown) => notifyWindowActionFailure("Couldn't save this window", cause)) + .catch((cause: unknown) => notifyWindowActionFailure(gt("Couldn't save this window"), cause)) .finally(() => setSaving(false)); }; return ( Keep this window's project filter and theme so you can reopen it later.} control={
    setName(event.target.value)} @@ -170,7 +179,7 @@ function SaveCurrentWindowRow({ }} />
    } @@ -178,9 +187,13 @@ function SaveCurrentWindowRow({ ); } -function projectFilterSummary(projectGroups: ProjectScopeGroups, keys: readonly string[]): string { +function projectFilterSummary( + projectGroups: ProjectScopeGroups, + keys: readonly string[], + resolve: MessageResolver = resolveMessage, +): string { const names = projectGroups.groupsForKeys(keys).map((group) => group.displayName); - return names.length === 0 ? "All projects" : names.join(", "); + return names.length === 0 ? resolve(msg("All projects")) : names.join(", "); } interface WindowThemeOption { @@ -193,6 +206,7 @@ interface WindowThemeOption { } function useWindowThemeOptions(projects: readonly SidebarProjectSnapshot[]): WindowThemeOption[] { + const gt = useGT(); const themeCards = useThemeCards(); const appearance = useRenderedAppearance(); const projectColors = useProjectTintColors(projects); @@ -200,7 +214,7 @@ function useWindowThemeOptions(projects: readonly SidebarProjectSnapshot[]): Win // Without a project filter there is no project colour to take on. { value: FOLLOW_MAIN_WINDOW_THEME, - label: projects.length > 0 ? "Project colour" : "Follow main window", + label: projects.length > 0 ? gt("Project colour") : gt("Follow main window"), previews: [], colors: projectColors, }, @@ -246,15 +260,19 @@ function WindowProfileRow({ readonly isCurrentWindow: boolean; readonly canOpen: boolean; }) { + const gt = useGT(); + const m = useMessages(); const themeOptions = useWindowThemeOptions(projectGroups.groupsForKeys(profile.projectScopeKeys)); const deleteProfile = async () => { const confirmed = await requestConfirmDialog( - `Delete the saved window "${profile.name}"?\nIf it is open, it stays open as an unsaved window.`, + gt('Delete the saved window "{name}"?\nIf it is open, it stays open as an unsaved window.', { + name: profile.name, + }), { variant: "destructive" }, ); if (confirmed !== true) return; await bridge.deleteProfile(profile.id).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't delete the saved window", cause); + notifyWindowActionFailure(gt("Couldn't delete the saved window"), cause); }); }; @@ -264,28 +282,33 @@ function WindowProfileRow({ <> {profile.isDefault ? ( - (main window) + + {" "} + (main window) + ) : null} } description={ - profile.isDefault - ? "Holds the connections and drafts every window shares." - : projectFilterSummary(projectGroups, profile.projectScopeKeys) + profile.isDefault ? ( + Holds the connections and drafts every window shares. + ) : ( + projectFilterSummary(projectGroups, profile.projectScopeKeys, m) + ) } style={profile.isDefault ? undefined : themeWashStyle(themeOptions, profile.theme)} control={
    {profile.isDefault ? null : (
    @@ -336,6 +363,7 @@ function NewWindowProfileRow({ readonly projectGroups: ProjectScopeGroups; readonly onDone: () => void; }) { + const gt = useGT(); const [name, setName] = useState(""); const [projectScopeKeys, setProjectScopeKeys] = useState([]); const [theme, setTheme] = useState(null); @@ -348,7 +376,7 @@ function NewWindowProfileRow({ bridge.createProfile({ name: normalized, projectScopeKeys, theme }).then( () => onDone(), (cause: unknown) => { - notifyWindowActionFailure("Couldn't save the window", cause); + notifyWindowActionFailure(gt("Couldn't save the window"), cause); setSaving(false); }, ); @@ -357,8 +385,8 @@ function NewWindowProfileRow({ setName(event.target.value)} @@ -369,22 +397,24 @@ function NewWindowProfileRow({ }} /> } - description="Open it later from here, the command palette or the Window menu." + description={Open it later from here, the command palette or the Window menu.} style={themeWashStyle(themeOptions, theme)} control={
    } >
    - +
    - + @@ -415,6 +447,8 @@ function ProjectFilterSelect({ readonly value: readonly string[]; readonly onChange: (keys: readonly string[]) => void; }) { + const gt = useGT(); + const m = useMessages(); return ( setName(event.target.value)} @@ -98,7 +104,7 @@ function DesktopWindowsHostContent({ bridge }: { readonly bridge: DesktopWindows size="sm" onClick={() => resolve({ action: "cancel" })} > - Cancel + Cancel diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx index 853aa4e3019ef..96186000d0fda 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx @@ -17,7 +17,7 @@ import { projectsFor, PULL_REQUESTS, UPDATE_AVAILABLE, -} from "./mini.fixtures"; +} from "./mini.test-fixtures"; import { MiniPanel } from "./MiniMainWindow"; import { MiniPullRequestList } from "./MiniPullRequests"; import { MiniUpdate } from "./MiniUpdate"; diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx index 9aee7430d593e..860e723e2abca 100644 --- a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx @@ -1,5 +1,6 @@ import { useRouter } from "@tanstack/react-router"; import type { DesktopWindowsBridge } from "@t3tools/contracts"; +import { useGT } from "gt-react"; import { AppWindowIcon, ChartNoAxesColumnIcon, @@ -37,6 +38,7 @@ export function MiniMainWindow() { } function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const gt = useGT(); const router = useRouter(); const windowsState = useDesktopWindowsState(); const updateState = useDesktopUpdateState(); @@ -46,7 +48,7 @@ function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBrid const expand = () => { bridge.setMiniMode(false).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't leave Mini Mode", cause); + notifyWindowActionFailure(gt("Couldn't leave Mini Mode"), cause); }); }; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- follows the router: the panel shows no pages, so going to one (a search result, Settings) needs the full window @@ -76,7 +78,7 @@ function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBrid projectsFor={groupsForKeys} onFocusWindow={(windowId) => { bridge.focus(windowId).catch((cause: unknown) => { - notifyWindowActionFailure("Couldn't focus the window", cause); + notifyWindowActionFailure(gt("Couldn't focus the window"), cause); }); }} /> @@ -108,6 +110,7 @@ export function MiniPanel({ /** Only the showing tab's content mounts. */ readonly tabs: Readonly>; }) { + const gt = useGT(); const [tab, setTab] = useState("usage"); const tabItem = (id: MiniTab, label: string, icon: ReactNode) => (
    -
    diff --git a/apps/web/src/multiWindow/ui/MiniPullRequests.tsx b/apps/web/src/multiWindow/ui/MiniPullRequests.tsx index e7e6ff580287d..f320ebc49304b 100644 --- a/apps/web/src/multiWindow/ui/MiniPullRequests.tsx +++ b/apps/web/src/multiWindow/ui/MiniPullRequests.tsx @@ -1,3 +1,4 @@ +import { T, useGT, useMessages } from "gt-react"; import { useState } from "react"; import type { EnvironmentPullRequestEntry } from "../../components/pullRequest/pullRequestList.logic"; @@ -51,16 +52,22 @@ export function MiniPullRequestList({ readonly error: string | null; readonly onOpen: (url: string) => void; }) { + const gt = useGT(); + const messages = useMessages(); return ( -
    +
    {entries === null ? ( -
    +
    ) : entries.length === 0 ? (

    - {error ?? "No pull requests match your Pull requests page filter."} + {error ?? No pull requests match your Pull requests page filter.}

    ) : (
      @@ -68,7 +75,7 @@ export function MiniPullRequestList({ const checks = entry.checksState === undefined ? null - : pullRequestChecksStatePresentation(entry.checksState); + : pullRequestChecksStatePresentation(entry.checksState, messages); return (
    • ))} - {collectLimitNotices(presentations).map((notice) => ( + {collectLimitNotices(presentations, m).map((notice) => (

      {notice}

      diff --git a/apps/web/src/multiWindow/ui/MiniWindows.tsx b/apps/web/src/multiWindow/ui/MiniWindows.tsx index 78afc91c2bf9d..b76246586ed47 100644 --- a/apps/web/src/multiWindow/ui/MiniWindows.tsx +++ b/apps/web/src/multiWindow/ui/MiniWindows.tsx @@ -1,4 +1,5 @@ import type { DesktopOpenWindow } from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; import { ListFilterIcon } from "lucide-react"; import { APP_DISPLAY_NAME } from "../../branding"; @@ -22,16 +23,20 @@ export function MiniWindows({ readonly projectsFor: (projectScopeKeys: readonly string[]) => readonly MiniWindowProject[]; readonly onFocusWindow: (windowId: number) => void; }) { + const gt = useGT(); return ( -
      +
      {windows === null ? ( -
      +
      ) : windows.length === 0 ? (

      - No other windows are open. + No other windows are open.

      ) : (
        @@ -58,6 +63,7 @@ function MiniWindowCard({ readonly projects: readonly MiniWindowProject[]; readonly onFocus: () => void; }) { + const gt = useGT(); // The desktop shell appends the window's name to its title, and the card already leads with it. // What is left names the open thread, or only the app when the window has none open. const nameSuffix = ` - ${window.name}`; @@ -95,13 +101,19 @@ function MiniWindowCard({ )} {projects.length === 0 - ? "All projects" + ? gt("All projects") : projects.map((project) => project.displayName).join(", ")} {window.focused ? ( - Focused + + {gt("Focused", { $context: "state of a window that has focus" })} + ) : ( - {window.profileId === null ? "Unsaved" : "Saved"} + + {window.profileId === null + ? gt("Unsaved", { $context: "state of a window without a saved profile" }) + : gt("Saved", { $context: "state of a window with a saved profile" })} + )} {window.name} diff --git a/apps/web/src/multiWindow/ui/mini.fixtures.ts b/apps/web/src/multiWindow/ui/mini.test-fixtures.ts similarity index 100% rename from apps/web/src/multiWindow/ui/mini.fixtures.ts rename to apps/web/src/multiWindow/ui/mini.test-fixtures.ts diff --git a/apps/web/src/multiWindow/windowsState.test.ts b/apps/web/src/multiWindow/windowsState.test.ts index 5c37ecccd81f1..9e139bf53676d 100644 --- a/apps/web/src/multiWindow/windowsState.test.ts +++ b/apps/web/src/multiWindow/windowsState.test.ts @@ -5,7 +5,7 @@ import type { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { openWindow } from "./ui/mini.fixtures"; +import { openWindow } from "./ui/mini.test-fixtures"; import { isMiniMainWindow, resolveWindowThemeOverride,