From 98acf8f5e14b0892b3cfd9c5088a7fadca1be4fe Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 22:32:08 -0500 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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);