From 98acf8f5e14b0892b3cfd9c5088a7fadca1be4fe Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 22:32:08 -0500 Subject: [PATCH 01/20] feat(desktop): open more windows that share the main window's connection Secondary windows are thin clients: the main window's renderer is a hub that relays each environment's RPC over a MessagePort and shares its subscription streams, so a new window opens without its own sockets or auth. The desktop shell opens them from New Window (command palette, Window menu, and mod+alt+shift+n), trusts IPC from every app window, scopes preview tabs to the window that shows them, and keeps the main window hidden rather than closed while it serves other windows. Windows merge their shared UI state and composer drafts instead of overwriting each other's saves. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app/DesktopLifecycle.test.ts | 7 +- .../src/backend/DesktopBackendPool.test.ts | 5 +- apps/desktop/src/electron/ElectronWindow.ts | 41 +- apps/desktop/src/i18n/translations/de.json | 1 + apps/desktop/src/i18n/translations/en.json | 1 + apps/desktop/src/i18n/translations/es.json | 1 + apps/desktop/src/i18n/translations/fr.json | 1 + apps/desktop/src/i18n/translations/ja.json | 1 + apps/desktop/src/i18n/translations/ko.json | 1 + apps/desktop/src/i18n/translations/pt-BR.json | 1 + apps/desktop/src/i18n/translations/ru.json | 1 + apps/desktop/src/i18n/translations/sv.json | 1 + apps/desktop/src/i18n/translations/zh.json | 1 + apps/desktop/src/ipc/DesktopIpc.test.ts | 28 +- apps/desktop/src/ipc/DesktopIpc.ts | 63 ++- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 8 + apps/desktop/src/ipc/channels.ts | 12 + .../desktop/src/ipc/methods/clientSettings.ts | 7 + apps/desktop/src/ipc/methods/fileDrag.test.ts | 2 +- apps/desktop/src/ipc/methods/fileDrag.ts | 10 +- apps/desktop/src/ipc/methods/preview.test.ts | 85 ++- apps/desktop/src/ipc/methods/preview.ts | 104 +++- apps/desktop/src/ipc/methods/snapShot.test.ts | 10 +- apps/desktop/src/ipc/methods/snapShot.ts | 12 +- apps/desktop/src/ipc/methods/window.test.ts | 32 +- apps/desktop/src/ipc/methods/window.ts | 79 +-- apps/desktop/src/ipc/methods/windows.ts | 58 ++ apps/desktop/src/preload.ts | 66 +++ apps/desktop/src/preview/Manager.test.ts | 80 +++ apps/desktop/src/preview/Manager.ts | 152 +++-- .../src/ssh/DesktopSshPasswordPrompts.test.ts | 4 +- .../desktop/src/updates/updatesTestHarness.ts | 4 +- .../src/window/BackgroundThrottling.ts | 21 + .../src/window/DesktopApplicationMenu.test.ts | 32 +- .../src/window/DesktopApplicationMenu.ts | 20 +- .../src/window/DesktopHubLinks.test.ts | 66 +++ apps/desktop/src/window/DesktopHubLinks.ts | 55 ++ apps/desktop/src/window/DesktopWindow.test.ts | 70 ++- apps/desktop/src/window/DesktopWindow.ts | 397 ++++++++++--- .../src/window/DesktopWindowProfiles.test.ts | 26 + .../src/window/DesktopWindowProfiles.ts | 41 ++ apps/web/src/appInit.tsx | 23 +- apps/web/src/browser/ElectronBrowserHost.tsx | 28 +- apps/web/src/components/CommandPalette.tsx | 3 + .../components/CommandPaletteWindowItems.tsx | 25 + .../settings/KeybindingsSettings.logic.ts | 1 + apps/web/src/composerDraftStore.test.ts | 51 ++ apps/web/src/composerDraftStore.ts | 140 +++++ apps/web/src/connection/runtime.ts | 18 +- apps/web/src/hooks/useSettings.ts | 17 +- apps/web/src/i18n/translations/de.json | 2 + apps/web/src/i18n/translations/en.json | 2 + apps/web/src/i18n/translations/es.json | 2 + apps/web/src/i18n/translations/fr.json | 2 + apps/web/src/i18n/translations/ja.json | 2 + apps/web/src/i18n/translations/ko.json | 2 + apps/web/src/i18n/translations/pt-BR.json | 2 + apps/web/src/i18n/translations/ru.json | 2 + apps/web/src/i18n/translations/sv.json | 2 + apps/web/src/i18n/translations/zh.json | 2 + apps/web/src/keybindings.test.ts | 27 + apps/web/src/multiWindow/hub.ts | 126 +++++ apps/web/src/multiWindow/hubLink.ts | 66 +++ .../src/multiWindow/previewHosting.test.ts | 21 + apps/web/src/multiWindow/previewHosting.ts | 104 ++++ apps/web/src/multiWindow/secondary.ts | 170 ++++++ apps/web/src/multiWindow/ui/windowActions.ts | 41 ++ apps/web/src/multiWindow/windowContext.ts | 24 + apps/web/src/multiWindow/windowsState.ts | 46 ++ apps/web/src/routes/__root.tsx | 7 +- apps/web/src/uiStateStore.test.ts | 30 + apps/web/src/uiStateStore.ts | 115 +++- docs/README.md | 1 + docs/user/keybindings.md | 3 + docs/user/multiple-windows.md | 14 + .../client-runtime/src/connection/hub.test.ts | 37 ++ packages/client-runtime/src/connection/hub.ts | 195 +++++++ .../client-runtime/src/connection/index.ts | 1 + .../client-runtime/src/connection/layer.ts | 19 +- packages/client-runtime/src/rpc/index.ts | 1 + packages/client-runtime/src/rpc/relay.ts | 357 ++++++++++++ .../client-runtime/src/rpc/session.test.ts | 512 +++++++++++++++++ packages/client-runtime/src/rpc/session.ts | 122 +++- .../client-runtime/src/rpc/sharedStreams.ts | 529 ++++++++++++++++++ packages/contracts/src/desktopWindows.ts | 46 ++ packages/contracts/src/index.ts | 1 + packages/contracts/src/ipc.ts | 5 + packages/contracts/src/keybindings.ts | 1 + packages/shared/src/keybindings.ts | 1 + 89 files changed, 4238 insertions(+), 317 deletions(-) create mode 100644 apps/desktop/src/ipc/methods/windows.ts create mode 100644 apps/desktop/src/window/BackgroundThrottling.ts create mode 100644 apps/desktop/src/window/DesktopHubLinks.test.ts create mode 100644 apps/desktop/src/window/DesktopHubLinks.ts create mode 100644 apps/desktop/src/window/DesktopWindowProfiles.test.ts create mode 100644 apps/desktop/src/window/DesktopWindowProfiles.ts create mode 100644 apps/web/src/components/CommandPaletteWindowItems.tsx create mode 100644 apps/web/src/multiWindow/hub.ts create mode 100644 apps/web/src/multiWindow/hubLink.ts create mode 100644 apps/web/src/multiWindow/previewHosting.test.ts create mode 100644 apps/web/src/multiWindow/previewHosting.ts create mode 100644 apps/web/src/multiWindow/secondary.ts create mode 100644 apps/web/src/multiWindow/ui/windowActions.ts create mode 100644 apps/web/src/multiWindow/windowContext.ts create mode 100644 apps/web/src/multiWindow/windowsState.ts create mode 100644 docs/user/multiple-windows.md create mode 100644 packages/client-runtime/src/connection/hub.test.ts create mode 100644 packages/client-runtime/src/connection/hub.ts create mode 100644 packages/client-runtime/src/rpc/relay.ts create mode 100644 packages/client-runtime/src/rpc/sharedStreams.ts create mode 100644 packages/contracts/src/desktopWindows.ts diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index e11e946dd41ba..772379b964374 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -73,7 +73,9 @@ function layerElectronWindow(destroyAll: Effect.Effect = Effect.void) { create: () => Effect.die("unexpected window creation"), main: Effect.die("unexpected main window read"), currentMainOrFirst: Effect.die("unexpected current window read"), - focusedMainOrFirst: Effect.die("unexpected focused window read"), + apps: Effect.succeed([]), + focusedApp: Effect.succeedNone, + registerApp: () => Effect.void, setMain: () => Effect.void, clearMain: () => Effect.void, prepareReveal: () => Effect.succeed(false), @@ -90,7 +92,7 @@ function layerDesktopWindow( readonly flushMainWindowBounds?: Effect.Effect; } = {}, ) { - return Layer.succeed(DesktopWindow.DesktopWindow, { + return Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected window creation"), ensureMain: Effect.die("unexpected window creation"), revealOrCreateMain: Effect.die("unexpected window creation"), @@ -103,7 +105,6 @@ function layerDesktopWindow( prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.void, dispatchSnapShotEvent: () => Effect.void, - zoomMain: () => Effect.void, runMainContentsCommand: () => Effect.void, syncAppearance: Effect.void, }); diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 005a1cde1224a..1be204cb02354 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -203,7 +203,7 @@ function layerPool( showErrorBox: () => Effect.void, } satisfies ElectronDialog.ElectronDialog["Service"]), ElectronApp.layer, - Layer.succeed(DesktopWindow.DesktopWindow, { + Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected window create"), ensureMain: Effect.die("unexpected window ensure"), revealOrCreateMain: Effect.die("unexpected window reveal"), @@ -216,11 +216,10 @@ function layerPool( prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.die("unexpected menu action"), dispatchSnapShotEvent: () => Effect.void, - zoomMain: () => Effect.die("unexpected zoom"), runMainContentsCommand: options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")), syncAppearance: Effect.void, - } satisfies DesktopWindow.DesktopWindow["Service"]), + }), ), ), ); diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts index b5f89969e66c7..098e9191328f2 100644 --- a/apps/desktop/src/electron/ElectronWindow.ts +++ b/apps/desktop/src/electron/ElectronWindow.ts @@ -117,7 +117,11 @@ export class ElectronWindow extends Context.Service< ) => Effect.Effect; readonly main: Effect.Effect>; readonly currentMainOrFirst: Effect.Effect>; - readonly focusedMainOrFirst: Effect.Effect>; + /** Windows that load the app renderer: the main window first, then secondary windows. */ + readonly apps: Effect.Effect>; + /** The focused app window, else the main window; never a popup or auxiliary window. */ + readonly focusedApp: Effect.Effect>; + readonly registerApp: (window: Electron.BrowserWindow) => Effect.Effect; readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect; readonly clearMain: (window: Option.Option) => Effect.Effect; readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect; @@ -148,6 +152,7 @@ export const make = Effect.gen(function* () { yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close())); const mainWindowRef = yield* Ref.make>(Option.none()); const auxiliaryWindows = new WeakSet(); + const appWindows = new Set(); const titleBarOverlayWindows = new WeakSet(); const listWindows = Effect.try({ @@ -198,9 +203,22 @@ export const make = Effect.gen(function* () { return first; }); - const focusedMainOrFirst = Effect.gen(function* () { + const liveApps = Effect.gen(function* () { + const main = yield* liveMain; + const apps: Electron.BrowserWindow[] = Option.isSome(main) ? [main.value] : []; + for (const window of appWindows) { + if (yield* isWindowDestroyed(window)) { + appWindows.delete(window); + } else if (!apps.includes(window)) { + apps.push(window); + } + } + return apps; + }); + + const focusedApp = Effect.gen(function* () { const focused = yield* Effect.try({ - try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null), + try: () => Electron.BrowserWindow.getFocusedWindow(), catch: (cause) => new ElectronWindowOperationError({ operation: "get-focused-window", @@ -210,10 +228,9 @@ export const make = Effect.gen(function* () { cause, }), }).pipe(Effect.orDie); - if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) { - return focused; - } - return yield* currentMainOrFirst; + const apps = yield* liveApps; + if (focused !== null && apps.includes(focused)) return Option.some(focused); + return yield* liveMain; }); return ElectronWindow.of({ @@ -255,9 +272,15 @@ export const make = Effect.gen(function* () { }), main: liveMain, currentMainOrFirst, - focusedMainOrFirst, + apps: liveApps, + focusedApp, + registerApp: Effect.fn("ElectronWindow.registerApp")(function (window) { + return Effect.sync(() => void appWindows.add(window)); + }), setMain: Effect.fn("ElectronWindow.setMain")(function (window) { - return Ref.set(mainWindowRef, Option.some(window)); + return Ref.set(mainWindowRef, Option.some(window)).pipe( + Effect.andThen(Effect.sync(() => void appWindows.add(window))), + ); }), clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) { return Ref.update(mainWindowRef, (current) => { diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json index 8e39e7585f60d..55145c7cda1eb 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Verkleinern", "50fe114d093a5bc7": "Vollbildmodus ein/aus", "d8c6d6d9845353da": "Fenster", + "c015841b7b2523c6": "Neues Fenster", "f184aa190588625e": "Minimieren", "c20a9deaed71bd1c": "Zoomen", "d207ba3a23f94223": "Alle nach vorne bringen", diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 9a07ef060cbc9..578c3a86c961e 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Zoom Out", "50fe114d093a5bc7": "Toggle Full Screen", "d8c6d6d9845353da": "Window", + "c015841b7b2523c6": "New Window", "f184aa190588625e": "Minimize", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Bring All to Front", diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index f891e9eaf850b..155d2d7e22e48 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Alejar", "50fe114d093a5bc7": "Activar/desactivar pantalla completa", "d8c6d6d9845353da": "Ventana", + "c015841b7b2523c6": "Nueva ventana", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Traer todo al frente", diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 0bb5a47518581..9312fb6c77f57 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Zoom arrière", "50fe114d093a5bc7": "Activer/désactiver le plein écran", "d8c6d6d9845353da": "Fenêtre", + "c015841b7b2523c6": "Nouvelle fenêtre", "f184aa190588625e": "Réduire", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Tout ramener au premier plan", diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index df89efe466261..46759a18b9b1c 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "縮小", "50fe114d093a5bc7": "フルスクリーンに切り替え", "d8c6d6d9845353da": "ウインドウ", + "c015841b7b2523c6": "新規ウインドウ", "f184aa190588625e": "しまう", "c20a9deaed71bd1c": "拡大/縮小", "d207ba3a23f94223": "すべてを手前に移動", diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index 566724b9b91c1..eac165f0b91ce 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "축소", "50fe114d093a5bc7": "전체 화면 전환", "d8c6d6d9845353da": "윈도우", + "c015841b7b2523c6": "새 윈도우", "f184aa190588625e": "최소화", "c20a9deaed71bd1c": "확대/축소", "d207ba3a23f94223": "모두 앞으로 가져오기", diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 67f4eefd1c9ec..7d39c2e2bb2ee 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Diminuir zoom", "50fe114d093a5bc7": "Alternar tela cheia", "d8c6d6d9845353da": "Janela", + "c015841b7b2523c6": "Nova janela", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Trazer tudo para a frente", diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index 46364dfabe488..2f56fc560ab1b 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Уменьшить", "50fe114d093a5bc7": "Полноэкранный режим", "d8c6d6d9845353da": "Окно", + "c015841b7b2523c6": "Новое окно", "f184aa190588625e": "Свернуть", "c20a9deaed71bd1c": "Масштаб", "d207ba3a23f94223": "Все окна на передний план", diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index 67bcaf6a380aa..e161a7f984dfc 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "Zooma ut", "50fe114d093a5bc7": "Växla helskärm", "d8c6d6d9845353da": "Fönster", + "c015841b7b2523c6": "Nytt fönster", "f184aa190588625e": "Minimera", "c20a9deaed71bd1c": "Zooma", "d207ba3a23f94223": "Lägg alla överst", diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index 72122de01df62..b414c5fd1f0df 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -114,6 +114,7 @@ "df6ed2014f1737a8": "缩小", "50fe114d093a5bc7": "切换全屏", "d8c6d6d9845353da": "窗口", + "c015841b7b2523c6": "新建窗口", "f184aa190588625e": "最小化", "c20a9deaed71bd1c": "缩放", "d207ba3a23f94223": "前置全部窗口", diff --git a/apps/desktop/src/ipc/DesktopIpc.test.ts b/apps/desktop/src/ipc/DesktopIpc.test.ts index 1973ab49cefeb..36defff9eb9ea 100644 --- a/apps/desktop/src/ipc/DesktopIpc.test.ts +++ b/apps/desktop/src/ipc/DesktopIpc.test.ts @@ -9,9 +9,12 @@ vi.mock("electron", () => ({})); import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as DesktopIpc from "./DesktopIpc.ts"; -it.effect("answers only the main window's top frame", () => +it.effect("answers only app windows' top frames and tells handlers which window sent", () => Effect.gen(function* () { const mainFrame = {}; + const secondaryFrame = {}; + const mainWindow = { id: 10, webContents: { id: 1, mainFrame } }; + const secondaryWindow = { id: 11, webContents: { id: 3, mainFrame: secondaryFrame } }; const invoke = new Map(); const sync = new Map(); const ipc = yield* DesktopIpc.DesktopIpc.pipe( @@ -24,9 +27,11 @@ it.effect("answers only the main window's top frame", () => }).pipe( Layer.provide( Layer.mock(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ - webContents: { id: 1, mainFrame }, - } as unknown as Electron.BrowserWindow), + main: Effect.succeedSome(mainWindow as unknown as Electron.BrowserWindow), + apps: Effect.succeed([ + mainWindow, + secondaryWindow, + ] as unknown as ReadonlyArray), }), ), ), @@ -37,13 +42,21 @@ it.effect("answers only the main window's top frame", () => channel: "token", payload: Schema.Void, result: Schema.String, - handler: () => Effect.succeed("secret"), + handler: () => + Effect.map( + DesktopIpc.DesktopIpcSender, + ({ window, isMain }) => `secret-${window.id}${isMain ? "-main" : ""}`, + ), }), ); - yield* ipc.handleSync({ channel: "token-sync", handler: () => Effect.succeed("secret") }); + yield* ipc.handleSync({ + channel: "token-sync", + handler: () => Effect.map(DesktopIpc.DesktopIpcSender, ({ window }) => `secret-${window.id}`), + }); const senders = { app: { sender: { id: 1 }, senderFrame: mainFrame }, + secondary: { sender: { id: 3 }, senderFrame: secondaryFrame }, appSubframe: { sender: { id: 1 }, senderFrame: {} }, previewGuest: { sender: { id: 2 }, senderFrame: {} }, }; @@ -59,7 +72,8 @@ it.effect("answers only the main window's top frame", () => ]; } assert.deepEqual(results, { - app: ["secret", "secret"], + app: ["secret-10-main", "secret-10"], + secondary: ["secret-11", "secret-11"], appSubframe: ["rejected", undefined], previewGuest: ["rejected", undefined], }); diff --git a/apps/desktop/src/ipc/DesktopIpc.ts b/apps/desktop/src/ipc/DesktopIpc.ts index 69d4f70c15a0e..16a5e01bae121 100644 --- a/apps/desktop/src/ipc/DesktopIpc.ts +++ b/apps/desktop/src/ipc/DesktopIpc.ts @@ -5,6 +5,8 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import type * as Electron from "electron"; + import * as ElectronWindow from "../electron/ElectronWindow.ts"; export interface DesktopIpcInvokeEvent { @@ -16,7 +18,16 @@ export interface DesktopIpcSyncEvent extends DesktopIpcInvokeEvent { returnValue: unknown; } -export type DesktopIpcSenderGuard = (event: DesktopIpcInvokeEvent) => Effect.Effect; +/** The app window that sent the IPC call being handled. */ +export class DesktopIpcSender extends Context.Service< + DesktopIpcSender, + { readonly window: Electron.BrowserWindow; readonly isMain: boolean } +>()("@t3tools/desktop/ipc/DesktopIpc/DesktopIpcSender") {} + +/** Resolves the app window whose top frame sent the event; none rejects the call. */ +export type DesktopIpcSenderGuard = ( + event: DesktopIpcInvokeEvent, +) => Effect.Effect>; export type DesktopIpcHandleListener = ( event: DesktopIpcInvokeEvent, @@ -83,15 +94,17 @@ export interface DesktopSyncIpcMethod { readonly handler: () => Effect.Effect; } +type HandlerServices = Exclude; + export class DesktopIpc extends Context.Service< DesktopIpc, { readonly handle: ( input: DesktopIpcMethod, - ) => Effect.Effect; + ) => Effect.Effect | Scope.Scope>; readonly handleSync: ( input: DesktopSyncIpcMethod, - ) => Effect.Effect; + ) => Effect.Effect | Scope.Scope>; } >()("@t3tools/desktop/ipc/DesktopIpc") {} @@ -106,7 +119,7 @@ export const make = ( handler, }: DesktopIpcMethod) { yield* Effect.annotateCurrentSpan({ channel }); - const context = yield* Effect.context(); + const context = yield* Effect.context>(); const runPromise = Effect.runPromiseWith(context); yield* Effect.acquireRelease( @@ -117,10 +130,13 @@ export const make = ( runPromise( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); - if (!(yield* isTrustedSender(event))) { + const sender = yield* isTrustedSender(event); + if (Option.isNone(sender)) { return yield* new DesktopIpcUntrustedSenderError({ channel }); } - return yield* handler(raw, event); + return yield* handler(raw, event).pipe( + Effect.provideService(DesktopIpcSender, sender.value), + ); }).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")), ), ); @@ -142,7 +158,7 @@ export const make = ( handler, }: DesktopSyncIpcMethod) { yield* Effect.annotateCurrentSpan({ channel }); - const context = yield* Effect.context(); + const context = yield* Effect.context>(); const runSync = Effect.runSyncWith(context); yield* Effect.acquireRelease( @@ -154,11 +170,14 @@ export const make = ( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); // Throwing here would surface as an uncaught main-process exception. - if (!(yield* isTrustedSender(event))) { + const sender = yield* isTrustedSender(event); + if (Option.isNone(sender)) { yield* Effect.logWarning("Rejected sync IPC from an untrusted sender."); return undefined; } - return yield* handler(); + return yield* handler().pipe( + Effect.provideService(DesktopIpcSender, sender.value), + ); }).pipe( Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync"), @@ -184,22 +203,30 @@ export const layer = (ipcMain: DesktopIpcMain) => DesktopIpc, Effect.gen(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; + // Only an app window's top frame is trusted, never a preview guest or subframe. return make(ipcMain, (event) => - Effect.map( - electronWindow.main, - (main) => - Option.isSome(main) && - main.value.webContents.id === event.sender.id && - main.value.webContents.mainFrame === event.senderFrame, - ), + Effect.gen(function* () { + const main = yield* electronWindow.main; + const window = (yield* electronWindow.apps).find( + (candidate) => + candidate.webContents.id === event.sender.id && + candidate.webContents.mainFrame === event.senderFrame, + ); + return window === undefined + ? Option.none() + : Option.some({ window, isMain: Option.contains(main, window) }); + }), ); }), ); -export const layerTest = (ipcMain: DesktopIpcMain) => +export const layerTest = ( + ipcMain: DesktopIpcMain, + sender: DesktopIpcSender["Service"] = { window: {} as Electron.BrowserWindow, isMain: true }, +) => Layer.succeed( DesktopIpc, - make(ipcMain, () => Effect.succeed(true)), + make(ipcMain, () => Effect.succeedSome(sender)), ); export interface DesktopIpcMethodRegistration< diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index c88ddd0827df0..099ae312c7c12 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -79,6 +79,7 @@ import { setSnapShotShortcutSuppressed, } from "./methods/snapShot.ts"; import * as PreviewIpc from "./methods/preview.ts"; +import * as WindowsIpc from "./methods/windows.ts"; import * as AppActivationIpc from "./methods/appActivation.ts"; import * as WebLinksIpc from "./methods/webLinks.ts"; import { @@ -189,6 +190,13 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" Effect.Services> >(previewMethod); } + yield* ipc.handleSync(WindowsIpc.getContext); + for (const windowsMethod of WindowsIpc.methods) { + yield* ipc.handle< + Effect.Error>, + Effect.Services> + >(windowsMethod); + } yield* ipc.handle(PreviewIpc.listBrowserImportSources); yield* ipc.handle(PreviewIpc.importBrowserCookies); }); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 71d272333fdc7..072915f952e48 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -154,3 +154,15 @@ export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-lo export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; export const START_FILE_DRAG_CHANNEL = "desktop:start-file-drag"; + +export const CLIENT_SETTINGS_CHANGED_CHANNEL = "desktop:client-settings-changed"; + +export const WINDOWS_GET_CONTEXT_CHANNEL = "desktop:windows-get-context"; +export const WINDOWS_GET_STATE_CHANNEL = "desktop:windows-get-state"; +export const WINDOWS_STATE_CHANNEL = "desktop:windows-state"; +export const WINDOWS_OPEN_NEW_CHANNEL = "desktop:windows-open-new"; +export const WINDOWS_REGISTER_HUB_CHANNEL = "desktop:windows-register-hub"; +export const WINDOWS_REQUEST_HUB_LINK_CHANNEL = "desktop:windows-request-hub-link"; +export const WINDOWS_HUB_LINK_CHANNEL = "desktop:windows-hub-link"; +export const WINDOWS_HUB_PEER_GONE_CHANNEL = "desktop:windows-hub-peer-gone"; +export const WINDOWS_HUB_RESET_CHANNEL = "desktop:windows-hub-reset"; diff --git a/apps/desktop/src/ipc/methods/clientSettings.ts b/apps/desktop/src/ipc/methods/clientSettings.ts index 56e861944871d..cf8da650564fa 100644 --- a/apps/desktop/src/ipc/methods/clientSettings.ts +++ b/apps/desktop/src/ipc/methods/clientSettings.ts @@ -4,6 +4,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { applyLanguage } from "../../i18n/messages.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts"; import * as IpcChannels from "../channels.ts"; @@ -29,5 +30,11 @@ export const setClientSettings = DesktopIpc.makeIpcMethod({ yield* clientSettings.set(settings); yield* snapShot.configure(settings); yield* applyLanguage(settings.language); + const sender = yield* DesktopIpc.DesktopIpcSender; + for (const window of yield* (yield* ElectronWindow.ElectronWindow).apps) { + if (window !== sender.window && !window.isDestroyed()) { + window.webContents.send(IpcChannels.CLIENT_SETTINGS_CHANGED_CHANNEL); + } + } }), }); diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts index 7e140f9db5445..b10d8f58beab6 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.test.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -33,7 +33,7 @@ it.effect("only drags existing absolute paths from the host environment and app platform, } as DesktopEnvironment.DesktopEnvironment["Service"]), Effect.provideService(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 1, startDrag } }), + apps: Effect.succeed([{ webContents: { id: 1, startDrag } }]), } as unknown as ElectronWindow.ElectronWindow["Service"]), ); assert.isFalse(yield* run("remote", filePath)); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts index 227849c5935be..f3a3f3ab1a25b 100644 --- a/apps/desktop/src/ipc/methods/fileDrag.ts +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -1,6 +1,5 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Electron from "electron"; @@ -20,14 +19,17 @@ export const startFileDrag = makeIpcMethod({ if (!environment.path.isAbsolute(input.path)) return false; const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; - const window = yield* (yield* ElectronWindow.ElectronWindow).main; - if (Option.isNone(window) || event?.sender.id !== window.value.webContents.id) return false; + // Drags start from whichever app window asked. + const window = (yield* (yield* ElectronWindow.ElectronWindow).apps).find( + (candidate) => event !== undefined && candidate.webContents.id === event.sender.id, + ); + if (window === undefined) return false; const fs = yield* FileSystem.FileSystem; if (!(yield* fs.exists(input.path))) return false; return yield* Effect.promise(async () => { try { const icon = await Electron.app.getFileIcon(input.path, { size: "normal" }); - window.value.webContents.startDrag({ file: input.path, icon }); + window.webContents.startDrag({ file: input.path, icon }); return true; } catch { return false; diff --git a/apps/desktop/src/ipc/methods/preview.test.ts b/apps/desktop/src/ipc/methods/preview.test.ts index bd7e44bec8307..a971eedc45c88 100644 --- a/apps/desktop/src/ipc/methods/preview.test.ts +++ b/apps/desktop/src/ipc/methods/preview.test.ts @@ -6,13 +6,17 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as LoopbackTunnel from "../../preview/LoopbackTunnel.ts"; import * as PreviewManager from "../../preview/Manager.ts"; import * as PreviewIpc from "./preview.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; +import * as IpcChannels from "../channels.ts"; const { fromPartition } = vi.hoisted(() => ({ fromPartition: vi.fn(() => { @@ -51,7 +55,7 @@ describe("preview IPC methods", () => { removeAllListeners: vi.fn(), on: vi.fn(), }, - () => Effect.succeed(true), + () => Effect.succeedSome({ window: {} as Electron.BrowserWindow, isMain: true }), ); yield* ipc.handle(method); return yield* Effect.promise(async () => @@ -110,6 +114,85 @@ describe("preview IPC methods", () => { }), ); + effectIt.effect( + "scopes a secondary window's tabs and sends their events only to it, unscoped", + () => + Effect.scoped( + Effect.gen(function* () { + const appWindow = (id: number) => + ({ + id, + isDestroyed: () => false, + webContents: { send: vi.fn() }, + }) as unknown as Electron.BrowserWindow; + const main = appWindow(1); + const secondary = appWindow(3); + const created: unknown[] = []; + let emitState: + | Parameters[0] + | undefined; + const manager = { + createTab: (tabId, _defaults, owner) => + Effect.sync(() => { + created.push({ tabId, owner }); + return {} as never; + }), + tabRoute: (tabId) => + Effect.succeed( + tabId === "w3:tab" + ? { window: Option.some(secondary), rendererTabId: "tab" } + : { window: Option.some(main), rendererTabId: tabId }, + ), + subscribeStateChanges: (listener) => + Effect.sync(() => { + emitState = listener; + }), + subscribeRecordingInputs: () => Effect.void, + subscribePointerEvents: () => Effect.void, + subscribeOpenLinks: () => Effect.void, + subscribeFindResults: () => Effect.void, + } satisfies Partial; + let listener: DesktopIpc.DesktopIpcHandleListener | undefined; + const ipc = DesktopIpc.make( + { + removeHandler: vi.fn(), + handle: (_channel, registered) => { + listener = registered; + }, + removeAllListeners: vi.fn(), + on: vi.fn(), + }, + () => Effect.succeedSome({ window: secondary, isMain: false }), + ); + yield* Effect.gen(function* () { + yield* ipc.handle(PreviewIpc.createTab); + yield* PreviewIpc.installPreviewEventForwarding(); + yield* Effect.promise(async () => listener!({ sender: { id: 3 } }, { tabId: "tab" })); + yield* emitState!("w3:tab", { tabId: "w3:tab" } as never); + }).pipe( + Effect.provideService( + PreviewManager.PreviewManager, + manager as unknown as PreviewManager.PreviewManager["Service"], + ), + Effect.provideService(ElectronWindow.ElectronWindow, { + sendAll: () => Effect.void, + } as unknown as ElectronWindow.ElectronWindow["Service"]), + Effect.provideService(LoopbackTunnel.LoopbackTunnel, { + subscribeForwards: () => Effect.void, + } as unknown as LoopbackTunnel.LoopbackTunnel["Service"]), + ); + + expect(created).toEqual([ + { tabId: "w3:tab", owner: { window: secondary, rendererTabId: "tab" } }, + ]); + expect(vi.mocked(secondary.webContents.send).mock.calls).toEqual([ + [IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, "tab", { tabId: "tab" }], + ]); + expect(vi.mocked(main.webContents.send)).not.toHaveBeenCalled(); + }), + ), + ); + beforeEach(() => { fromPartition.mockClear(); }); diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 9dc0465c1e55a..7690cad20f0fd 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -39,6 +39,8 @@ import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; import * as NodeURL from "node:url"; +import type * as Electron from "electron"; + import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts"; import * as LoopbackTunnel from "../../preview/LoopbackTunnel.ts"; @@ -49,25 +51,70 @@ import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts import * as IpcChannels from "../channels.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; +/** + * A secondary window's tab ids are scoped to that window, so two windows can each show the + * same thread's preview. The main window keeps its ids as they are. + */ +function scopePreviewTabId(tabId: string, secondaryWindowId: number | null): string { + return secondaryWindowId === null ? tabId : `w${secondaryWindowId}:${tabId}`; +} + +const senderTabId = (tabId: string) => + Effect.map(DesktopIpc.DesktopIpcSender, ({ window, isMain }) => + scopePreviewTabId(tabId, isMain ? null : window.id), + ); + +const withRendererTabId = (value: A, rendererTabId: string): A => + typeof value === "object" && value !== null && "tabId" in value + ? { ...value, tabId: rendererTabId } + : value; + +/** Per-tab events go only to the window that shows the tab, under the id it knows. */ export const installPreviewEventForwarding = Effect.fn( "desktop.ipc.preview.installEventForwarding", )(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; const manager = yield* PreviewManager.PreviewManager; + // Pointer and recording-input events stream per frame, so routing them adds no span. + const sendToOwner = Effect.fnUntraced(function* ( + tabId: string, + send: (contents: Electron.WebContents, rendererTabId: string) => void, + ) { + const { window, rendererTabId } = yield* manager.tabRoute(tabId); + if (Option.isNone(window) || window.value.isDestroyed()) return; + send(window.value.webContents, rendererTabId); + }); yield* manager.subscribeStateChanges((tabId, state) => - electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state), + sendToOwner(tabId, (contents, rendererTabId) => + contents.send( + IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, + rendererTabId, + withRendererTabId(state, rendererTabId), + ), + ), ); yield* manager.subscribeRecordingInputs((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, { + ...event, + tabId: rendererTabId, + }), + ), ); yield* manager.subscribePointerEvents((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, { ...event, tabId: rendererTabId }), + ), ); yield* manager.subscribeOpenLinks((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, { ...event, tabId: rendererTabId }), + ), ); yield* manager.subscribeFindResults((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, event), + sendToOwner(event.tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, { ...event, tabId: rendererTabId }), + ), ); const tunnel = yield* LoopbackTunnel.LoopbackTunnel; yield* tunnel.subscribeForwards((forwards) => @@ -85,7 +132,7 @@ const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ }), }); -const createTab = DesktopIpc.makeIpcMethod({ +export const createTab = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, payload: DesktopPreviewCreateTabInputSchema, result: Schema.Void, @@ -96,7 +143,12 @@ const createTab = DesktopIpc.makeIpcMethod({ serverTab, }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.createTab(tabId, { zoomFactor, colorScheme, serverTab }); + const sender = yield* DesktopIpc.DesktopIpcSender; + yield* manager.createTab( + yield* senderTabId(tabId), + { zoomFactor, colorScheme, serverTab }, + sender.isMain ? undefined : { window: sender.window, rendererTabId: tabId }, + ); }), }); @@ -106,7 +158,7 @@ const closeTab = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.closeTab(tabId); + yield* manager.closeTab(yield* senderTabId(tabId)); }), }); @@ -116,7 +168,7 @@ const registerWebview = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.registerWebview(tabId, webContentsId); + yield* manager.registerWebview(yield* senderTabId(tabId), webContentsId); }), }); @@ -126,7 +178,7 @@ const navigate = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.navigate(tabId, url); + yield* manager.navigate(yield* senderTabId(tabId), url); }), }); @@ -141,7 +193,7 @@ const findInPage = DesktopIpc.makeIpcMethod({ newSession, }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.findInPage(tabId, text, { forward, newSession }); + yield* manager.findInPage(yield* senderTabId(tabId), text, { forward, newSession }); }), }); @@ -159,7 +211,7 @@ const tabMethod = ( result: Schema.Void, handler: Effect.fn(name)(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; - yield* invoke(manager, tabId); + yield* invoke(manager, yield* senderTabId(tabId)); }), }); @@ -214,7 +266,7 @@ const setZoomFactor = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setZoomFactor")(function* ({ tabId, zoomFactor }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setZoomFactor(tabId, zoomFactor); + yield* manager.setZoomFactor(yield* senderTabId(tabId), zoomFactor); }), }); const setColorScheme = DesktopIpc.makeIpcMethod({ @@ -223,7 +275,7 @@ const setColorScheme = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setColorScheme")(function* ({ tabId, colorScheme }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setColorScheme(tabId, colorScheme); + yield* manager.setColorScheme(yield* senderTabId(tabId), colorScheme); }), }); const setAudioMuted = DesktopIpc.makeIpcMethod({ @@ -232,7 +284,7 @@ const setAudioMuted = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setAudioMuted")(function* ({ tabId, audioMuted }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setAudioMuted(tabId, audioMuted); + yield* manager.setAudioMuted(yield* senderTabId(tabId), audioMuted); }), }); const setShown = DesktopIpc.makeIpcMethod({ @@ -241,7 +293,7 @@ const setShown = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setShown")(function* ({ tabId, shown }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setShown(tabId, shown); + yield* manager.setShown(yield* senderTabId(tabId), shown); }), }); const setCaptureDrawn = DesktopIpc.makeIpcMethod({ @@ -250,7 +302,7 @@ const setCaptureDrawn = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.setCaptureDrawn")(function* ({ tabId, drawn }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setCaptureDrawn(tabId, drawn); + yield* manager.setCaptureDrawn(yield* senderTabId(tabId), drawn); }), }); const openDevTools = tabMethod( @@ -277,7 +329,7 @@ export const startRecording = DesktopIpc.makeIpcMethod({ showMousePresses: value.browserRecordingShowMousePresses, })); return yield* manager - .startRecording(tabId, Option.getOrUndefined(options)) + .startRecording(yield* senderTabId(tabId), Option.getOrUndefined(options)) .pipe( Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "recording-start"))), ); @@ -474,7 +526,7 @@ const pickElement = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema), handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId, voice }) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager.pickElement(tabId, voice); + return yield* manager.pickElement(yield* senderTabId(tabId), voice); }), }); @@ -484,7 +536,7 @@ const updateAnnotationVoice = DesktopIpc.makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.preview.updateAnnotationVoice")(function* (state) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.updateAnnotationVoice(state); + yield* manager.updateAnnotationVoice({ ...state, tabId: yield* senderTabId(state.tabId) }); }), }); @@ -497,7 +549,7 @@ const setAnnotationSendEnabled = DesktopIpc.makeIpcMethod({ enabled, }) { const manager = yield* PreviewManager.PreviewManager; - yield* manager.setAnnotationSendEnabled(tabId, enabled); + yield* manager.setAnnotationSendEnabled(yield* senderTabId(tabId), enabled); }), }); @@ -507,9 +559,10 @@ export const captureScreenshot = DesktopIpc.makeIpcMethod({ result: Schema.Union([DesktopPreviewScreenshotArtifactSchema, PreviewCaptureFailure]), handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager - .captureScreenshot(tabId) - .pipe(Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot")))); + return yield* manager.captureScreenshot(yield* senderTabId(tabId)).pipe( + Effect.map((artifact) => withRendererTabId(artifact, tabId)), + Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot"))), + ); }), }); @@ -539,7 +592,8 @@ const saveRecording = DesktopIpc.makeIpcMethod({ result: DesktopPreviewRecordingArtifactSchema, handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager.saveRecording(tabId, mimeType, data); + const artifact = yield* manager.saveRecording(yield* senderTabId(tabId), mimeType, data); + return withRendererTabId(artifact, tabId); }), }); diff --git a/apps/desktop/src/ipc/methods/snapShot.test.ts b/apps/desktop/src/ipc/methods/snapShot.test.ts index 7e1ae602f979d..04cfc193b6d14 100644 --- a/apps/desktop/src/ipc/methods/snapShot.test.ts +++ b/apps/desktop/src/ipc/methods/snapShot.test.ts @@ -44,8 +44,8 @@ describe("window capture IPC", () => { Effect.provide( Layer.mergeAll( Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), + apps: Effect.succeed([{ webContents: { id: 7 } }]), + } as unknown as ElectronWindow.ElectronWindow["Service"]), Layer.succeed(DesktopSnapShot.DesktopSnapShot, { previewConfig: () => Effect.sync(() => { @@ -67,7 +67,7 @@ describe("window capture IPC", () => { ); }); - it.effect("allows capture setup only from the trusted main renderer", () => { + it.effect("allows capture setup only from a trusted app renderer", () => { const actions: string[] = []; return Effect.gen(function* () { yield* setupSnapShot.handler("install-extension", { sender: { id: 7 } }); @@ -81,8 +81,8 @@ describe("window capture IPC", () => { Effect.provide( Layer.mergeAll( Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), + apps: Effect.succeed([{ webContents: { id: 7 } }]), + } as unknown as ElectronWindow.ElectronWindow["Service"]), Layer.succeed(DesktopSnapShot.DesktopSnapShot, { setup: (action: string) => Effect.sync(() => { diff --git a/apps/desktop/src/ipc/methods/snapShot.ts b/apps/desktop/src/ipc/methods/snapShot.ts index 1a37882f4871e..1cb62a28fd132 100644 --- a/apps/desktop/src/ipc/methods/snapShot.ts +++ b/apps/desktop/src/ipc/methods/snapShot.ts @@ -35,15 +35,13 @@ class SnapShotIpcUnauthorizedSenderError extends Schema.TaggedError event !== undefined && candidate.webContents.id === event.sender.id, + ); + if (window === undefined) { return yield* new SnapShotIpcUnauthorizedSenderError(); } - return main.value; + return window; }, ); diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index 9c50501a1bdfd..56aa3bb14a4ac 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -33,7 +33,6 @@ import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; -import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as IpcChannels from "../channels.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; import { @@ -314,7 +313,7 @@ describe("installRelayTelemetryEnabled", () => { }); describe("readMedia", () => { - it.effect("reads http(s) media only for the main window", () => + it.effect("reads only http(s) media, through the sending window's session", () => Effect.gen(function* () { const mib = new Uint8Array(1024 * 1024); const fetch = vi.fn(async (url: string) => { @@ -327,32 +326,30 @@ describe("readMedia", () => { }); return new Response(huge); }); - const main = { + const sender = { + isDestroyed: () => false, webContents: { id: 1, session: { fetch } }, } as unknown as Electron.BrowserWindow; - const read = (url: string, senderId: number) => + const read = (url: string) => readMedia - .handler(url, { sender: { id: senderId } }) + .handler(url) .pipe( - Effect.provide( - Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(main) }), - ), + Effect.provideService(DesktopIpc.DesktopIpcSender, { window: sender, isMain: false }), ); - assert.strictEqual(yield* read("https://example.com/a.png", 2), null); - assert.strictEqual(yield* read("file:///etc/passwd", 1), null); + assert.strictEqual(yield* read("file:///etc/passwd"), null); assert.strictEqual(fetch.mock.calls.length, 0); - assert.deepEqual(yield* read("https://example.com/small.png", 1), { + assert.deepEqual(yield* read("https://example.com/small.png"), { status: 200, mimeType: "", data: Buffer.from([1, 2]), }); - assert.deepEqual(yield* read("https://example.com/missing.png", 1), { + assert.deepEqual(yield* read("https://example.com/missing.png"), { status: 404, mimeType: "text/plain;charset=UTF-8", data: new Uint8Array(), }); - assert.deepEqual(yield* read("https://example.com/huge.mp4", 1), { + assert.deepEqual(yield* read("https://example.com/huge.mp4"), { status: 413, mimeType: "", data: new Uint8Array(), @@ -362,15 +359,14 @@ describe("readMedia", () => { }); describe("pickProjectFavicon", () => { + const pickerOwner = { id: 3 } as Electron.BrowserWindow; const pickerLayer = ( pickFiles: () => Effect.Effect>, settings?: DesktopAppSettings.DesktopSettings, ) => Layer.mergeAll( Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }), - Layer.mock(ElectronWindow.ElectronWindow)({ - focusedMainOrFirst: Effect.succeedNone, - }), + Layer.succeed(DesktopIpc.DesktopIpcSender, { window: pickerOwner, isMain: true }), DesktopAppSettings.layerTest(settings), ); @@ -385,7 +381,7 @@ describe("pickProjectFavicon", () => { assert.deepEqual(pickFiles.mock.calls, [ [ { - owner: Option.none(), + owner: Option.some(pickerOwner), defaultPath: Option.some("/project"), multiple: false, filters: [ @@ -465,7 +461,7 @@ describe("syncHtmlFullscreen", () => { if (event === "leave-full-screen") leaveListeners.push(listener); }, } as unknown as Electron.BrowserWindow; - const layer = Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(window) }); + const layer = Layer.succeed(DesktopIpc.DesktopIpcSender, { window, isMain: true }); return { window, setFullScreen, finishExit, layer }; }; const fromMainRenderer = { sender: { id: 1 } }; diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index c6ad0bef18c81..d5e491710dd25 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -142,9 +142,8 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL, result: Schema.Boolean, handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.currentMainOrFirst; - return Option.isSome(window) && window.value.isFullScreen(); + const { window } = yield* DesktopIpc.DesktopIpcSender; + return !window.isDestroyed() && window.isFullScreen(); }), }); @@ -237,7 +236,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const environment = yield* DesktopEnvironment.DesktopEnvironment; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; @@ -268,7 +267,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ ) : environment.resolvePickFolderDefaultPath(options); const selectedPath = yield* dialog.pickFolder({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath, }); if (Option.isNone(selectedPath)) { @@ -306,13 +305,13 @@ export const pickProjectFavicon = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; if (!(yield* appSettings.get).localEnvironmentEnabled) { return null; } const paths = yield* dialog.pickFiles({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath: Option.fromNullishOr(initialPath), multiple: false, filters: [ @@ -342,14 +341,13 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) { const electronMenu = yield* ElectronMenu.ElectronMenu; - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.focusedMainOrFirst; - if (Option.isNone(window)) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return null; } const selectedItemId = yield* electronMenu.showContextMenu({ - window: window.value, + window, items: input.items, position: Option.fromNullishOr(input.position), source: Option.fromNullishOr(input.source), @@ -381,17 +379,12 @@ export const readMedia = DesktopIpc.makeIpcMethod({ channel: IpcChannels.READ_MEDIA_CHANNEL, payload: Schema.String, result: Schema.NullOr(DesktopMediaReadSchema), - handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) { - const window = yield* (yield* ElectronWindow.ElectronWindow).main; - if ( - event === undefined || - Option.isNone(window) || - window.value.webContents.id !== event.sender.id || - !/^https?:$/.test(URL.parse(url)?.protocol ?? "") - ) { + handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed() || !/^https?:$/.test(URL.parse(url)?.protocol ?? "")) { return null; } - const session = window.value.webContents.session; + const session = window.webContents.session; return yield* Effect.tryPromise({ try: async () => { // Like an , send the session's cookies. @@ -463,22 +456,16 @@ export const pasteAsText = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PASTE_AS_TEXT_CHANNEL, payload: Schema.Undefined, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(window) || - window.value.isDestroyed() || - window.value.webContents.id !== event.sender.id - ) { + handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return; } const focused = Electron.webContents.getFocusedWebContents(); if ( focused && !focused.isDestroyed() && - Electron.BrowserWindow.fromWebContents(focused) === window.value + Electron.BrowserWindow.fromWebContents(focused) === window ) { focused.paste(); } @@ -489,17 +476,10 @@ export const revealWindow = DesktopIpc.makeIpcMethod({ channel: IpcChannels.REVEAL_WINDOW_CHANNEL, payload: Schema.Undefined, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) { + handler: Effect.fn("desktop.ipc.window.revealWindow")(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(window) || - window.value.webContents.id !== event.sender.id - ) { - return; - } - yield* electronWindow.reveal(window.value); + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* electronWindow.reveal(window); }), }); @@ -521,24 +501,17 @@ const htmlFullscreenState = (window: Electron.BrowserWindow) => { return state; }; -// The main window keeps HTML fullscreen inside itself so preview guests stay in their webview, +// App windows keep HTML fullscreen inside themselves so preview guests stay in their webview, // so the app's own fullscreen elements, such as chat videos, take the screen here. export const syncHtmlFullscreen = DesktopIpc.makeIpcMethod({ channel: IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL, payload: Schema.Boolean, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen, event) { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const main = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(main) || - main.value.isDestroyed() || - main.value.webContents.id !== event.sender.id - ) { + handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return; } - const window = main.value; const state = htmlFullscreenState(window); if (fullscreen) { // macOS reports fullscreen until its exit animation ends, and Electron queues the re-entry. @@ -561,7 +534,7 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)), handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions"); @@ -569,7 +542,7 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({ .exists(extensionsDir) .pipe(Effect.orElseSucceed(() => false)); const paths = yield* dialog.pickFiles({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(), filters: [{ name: "JSON", extensions: ["json"] }], multiple: true, diff --git a/apps/desktop/src/ipc/methods/windows.ts b/apps/desktop/src/ipc/methods/windows.ts new file mode 100644 index 0000000000000..a2ce8200510a4 --- /dev/null +++ b/apps/desktop/src/ipc/methods/windows.ts @@ -0,0 +1,58 @@ +import { DesktopWindowContextSchema, DesktopWindowsStateSchema } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as DesktopWindow from "../../window/DesktopWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; + +export const getContext = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.WINDOWS_GET_CONTEXT_CHANNEL, + result: Schema.NullOr(DesktopWindowContextSchema), + handler: Effect.fn("desktop.ipc.windows.getContext")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + const desktopWindow = yield* DesktopWindow.DesktopWindow; + return Option.getOrNull(yield* desktopWindow.windowContext(window)); + }), +}); + +const getState = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_GET_STATE_CHANNEL, + payload: Schema.Void, + result: DesktopWindowsStateSchema, + handler: Effect.fn("desktop.ipc.windows.getState")(function* () { + return yield* (yield* DesktopWindow.DesktopWindow).windowsState; + }), +}); + +const openNew = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_OPEN_NEW_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openNew")(function* () { + yield* (yield* DesktopWindow.DesktopWindow).openNewWindow; + }), +}); + +const registerHub = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.registerHub")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).registerHub(window); + }), +}); + +const requestHubLink = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_REQUEST_HUB_LINK_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.requestHubLink")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).requestHubLink(window); + }), +}); + +export const methods = [getState, openNew, registerHub, requestHubLink] as const; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ac52fbc73d868..65c714f87dbdb 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -1,5 +1,7 @@ import type { + DESKTOP_HUB_LINK_MESSAGE_TYPE, DesktopBridge, + DesktopHubLinkMessage, DesktopPreviewAnnotationVoiceEvent, DesktopPreviewFindResultEvent, DesktopPreviewOpenLinkEvent, @@ -7,6 +9,9 @@ import type { DesktopPreviewRecordingInputEvent, DesktopPreviewTabState, DesktopSnapShotEvent, + DesktopWindowContext, + DesktopWindowsBridge, + DesktopWindowsState, } from "@t3tools/contracts"; import { exposeClerkBridge } from "@clerk/electron/preload"; import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron"; @@ -87,6 +92,64 @@ if (!primaryPasteEnabled) { ); } +// Typed against the contract's constant so they cannot drift; importing it would bundle contracts. +const HUB_LINK_MESSAGE_TYPE: typeof DESKTOP_HUB_LINK_MESSAGE_TYPE = "t3code:desktop-hub-link"; + +const windowContext = ((): DesktopWindowContext => { + try { + const result: unknown = ipcRenderer.sendSync(IpcChannels.WINDOWS_GET_CONTEXT_CHANNEL); + if (typeof result === "object" && result !== null) return result as DesktopWindowContext; + } catch {} + return { windowId: -1, isMain: true }; +})(); + +// A MessagePort cannot cross the context bridge, so the page receives it as a window message. +ipcRenderer.on(IpcChannels.WINDOWS_HUB_LINK_CHANNEL, (event, message: unknown) => { + const peerWindowId = + typeof message === "object" && message !== null && "peerWindowId" in message + ? message.peerWindowId + : undefined; + if (typeof peerWindowId !== "number" || event.ports.length === 0) return; + window.postMessage( + { type: HUB_LINK_MESSAGE_TYPE, peerWindowId } satisfies DesktopHubLinkMessage, + "*", + event.ports, + ); +}); + +const subscribe = + (channel: string, decode: (value: unknown) => A | undefined) => + (listener: (value: A) => void) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, value: unknown) => { + const decoded = decode(value); + if (decoded !== undefined) listener(decoded); + }; + ipcRenderer.on(channel, wrappedListener); + return () => { + ipcRenderer.removeListener(channel, wrappedListener); + }; + }; + +const windows: DesktopWindowsBridge = { + getContext: () => windowContext, + getState: () => ipcRenderer.invoke(IpcChannels.WINDOWS_GET_STATE_CHANNEL), + onState: subscribe(IpcChannels.WINDOWS_STATE_CHANNEL, (state) => + typeof state === "object" && state !== null ? (state as DesktopWindowsState) : undefined, + ), + openNew: () => ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_NEW_CHANNEL), + registerHub: () => { + void ipcRenderer.invoke(IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL).catch(() => undefined); + }, + requestHubLink: () => { + void ipcRenderer.invoke(IpcChannels.WINDOWS_REQUEST_HUB_LINK_CHANNEL).catch(() => undefined); + }, + onHubPeerGone: subscribe(IpcChannels.WINDOWS_HUB_PEER_GONE_CHANNEL, (windowId) => + typeof windowId === "number" ? windowId : undefined, + ), + onHubReset: (listener) => + subscribe(IpcChannels.WINDOWS_HUB_RESET_CHANNEL, () => true)(() => listener()), +}; + function unwrapEnsureSshEnvironmentResult(result: unknown) { if ( typeof result === "object" && @@ -164,6 +227,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL), setClientSettings: (settings) => ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings), + onClientSettingsChanged: (listener) => + subscribe(IpcChannels.CLIENT_SETTINGS_CHANGED_CHANNEL, () => true)(() => listener()), requestSnapShotPermissions: (includeAccessibility) => ipcRenderer.invoke(IpcChannels.REQUEST_SNAP_SHOT_PERMISSIONS_CHANNEL, includeAccessibility), getSnapShotState: () => ipcRenderer.invoke(IpcChannels.GET_SNAP_SHOT_STATE_CHANNEL), @@ -570,4 +635,5 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.removeListener(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, wrappedListener); }, }, + windows, } satisfies DesktopBridge); diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 9c15a0e0a4a95..4abd3e61487de 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -2289,6 +2289,86 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("keeps a secondary window's preview tab to that window until it closes", () => + withManager((manager) => + Effect.gen(function* () { + let closeSecondaryWindow: (() => void) | undefined; + let secondaryDestroyed = false; + const mainThrottling = vi.fn(); + const secondaryHost = Object.assign(makeTestHostWebContents(), { + id: 9, + setBackgroundThrottling: vi.fn(), + }); + const secondaryWindow = { + id: 3, + isDestroyed: () => secondaryDestroyed, + once: vi.fn((event: string, listener: () => void) => { + if (event === "closed") closeSecondaryWindow = listener; + }), + webContents: secondaryHost, + } as unknown as Electron.BrowserWindow; + const capturePage = vi.fn(async () => ({ + toJPEG: () => Buffer.from("recording-frame"), + getSize: () => ({ width: 1280, height: 720 }), + })); + const mainHost = makeTestHostWebContents(); + const webContentsById = new Map([ + [42, makeTestPreviewWebContents(capturePage, 42, mainHost)], + [43, makeTestPreviewWebContents(capturePage, 43, secondaryHost)], + ]); + fromId.mockImplementation((id) => + id === undefined ? null : (webContentsById.get(id) ?? null), + ); + yield* manager.setMainWindow({ + isDestroyed: () => false, + once: vi.fn(), + webContents: Object.assign(mainHost, { setBackgroundThrottling: mainThrottling }), + } as never); + yield* manager.registerSecondaryWindow(secondaryWindow); + const tabClosed = yield* Deferred.make(); + yield* manager.subscribeStateChanges((tabId, state) => + secondaryDestroyed && tabId === "w3:tab" && state.webContentsId === null + ? Deferred.succeed(tabClosed, undefined).pipe(Effect.asVoid) + : Effect.void, + ); + + yield* manager.createTab("w3:tab", undefined, { + window: secondaryWindow, + rendererTabId: "tab", + }); + const route = yield* manager.tabRoute("w3:tab"); + expect(Option.getOrNull(route.window)).toBe(secondaryWindow); + expect(route.rendererTabId).toBe("tab"); + + // A guest that the main window hosts cannot take over the secondary window's tab. + const hijack = yield* Effect.exit(manager.registerWebview("w3:tab", 42)); + expect(Exit.isFailure(hijack)).toBe(true); + if (Exit.isFailure(hijack)) { + expect(Option.getOrThrow(Cause.findErrorOption(hijack.cause))).toMatchObject({ + _tag: "PreviewWebContentsNotFoundError", + }); + } + yield* manager.registerWebview("w3:tab", 43); + + yield* manager.startRecording("w3:tab"); + expect(secondaryHost.setBackgroundThrottling.mock.calls).toEqual([[false]]); + expect(mainThrottling).not.toHaveBeenCalled(); + + secondaryDestroyed = true; + closeSecondaryWindow?.(); + yield* Deferred.await(tabClosed); + const afterClose = yield* Effect.exit(manager.startRecording("w3:tab")); + expect(Exit.isFailure(afterClose)).toBe(true); + if (Exit.isFailure(afterClose)) { + expect(Option.getOrThrow(Cause.findErrorOption(afterClose.cause))).toMatchObject({ + _tag: "PreviewTabNotFoundError", + }); + } + expect(mainThrottling).not.toHaveBeenCalled(); + }), + ), + ); + effectIt.effect("releases frame capture when the main window closes", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 531e269a07f11..e420093e8765a 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -94,6 +94,7 @@ import { import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS, type RecordingInputOptions } from "./RecordingInput.ts"; +import { setUnthrottledHold } from "../window/BackgroundThrottling.ts"; export type PreviewNavStatus = | { kind: "Idle" } @@ -407,6 +408,16 @@ interface PictureInPictureSession { readonly initializationScope: Scope.Closeable; } +export interface PreviewTabOwner { + readonly window: BrowserWindow; + readonly rendererTabId: string; +} + +export interface PreviewTabRoute { + readonly window: Option.Option; + readonly rendererTabId: string; +} + interface PendingRecording { readonly tabId: string; readonly webContents: Electron.WebContents; @@ -581,6 +592,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const annotationThemeRef = yield* Ref.make(DEFAULT_ANNOTATION_THEME); const annotationSendEnabled = new Map(); const mainWindowRef = yield* Ref.make>(Option.none()); + // Tabs created by a secondary app window; every other tab belongs to the main window. + const secondaryTabOwners = new Map(); const tabsRef = yield* SynchronizedRef.make>(new Map()); const attachedRef = yield* Ref.make>(new Map()); const listenersRef = yield* Ref.make>(new Set()); @@ -702,13 +715,29 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { if (window.isDestroyed()) return; yield* attempt({ operation: "frameCapture.setBackgroundThrottling" }, () => - window.webContents.setBackgroundThrottling(enabled), + setUnthrottledHold(window, "preview-frame-capture", !enabled), ); }); - const setFrameCaptureBackgroundThrottling = Effect.fnUntraced(function* (enabled: boolean) { - const mainWindow = yield* Ref.get(mainWindowRef); - if (Option.isNone(mainWindow)) return; - yield* setWindowBackgroundThrottling(mainWindow.value, enabled); + const ownerWindowOf = (tabId: string) => + Effect.map(Ref.get(mainWindowRef), (mainWindow) => { + const owner = secondaryTabOwners.get(tabId); + return owner === undefined ? mainWindow : Option.some(owner.window); + }); + const sameOwner = (left: string, right: string) => + secondaryTabOwners.get(left)?.window === secondaryTabOwners.get(right)?.window; + const ownerHasFrameCapture = (sessions: ReadonlyMap, tabId: string) => + [...sessions.keys()].some((sessionTabId) => sameOwner(sessionTabId, tabId)); + const ownerWindowOpen = (tabId: string) => { + const owner = secondaryTabOwners.get(tabId); + return owner === undefined ? frameCaptureWindowOpen : !owner.window.isDestroyed(); + }; + const setFrameCaptureBackgroundThrottling = Effect.fnUntraced(function* ( + tabId: string, + enabled: boolean, + ) { + const window = yield* ownerWindowOf(tabId); + if (Option.isNone(window)) return; + yield* setWindowBackgroundThrottling(window.value, enabled); }); const setFrameCaptureWebContentsBackgroundThrottling = Effect.fnUntraced(function* ( wc: Electron.WebContents, @@ -826,8 +855,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* restoreFrameCaptureWebContentsBackgroundThrottling( current.unthrottledWebContentsIds, ); - if (remainingSessions.size === 0) { - yield* setFrameCaptureBackgroundThrottling(true).pipe( + if (!ownerHasFrameCapture(remainingSessions, tabId)) { + yield* setFrameCaptureBackgroundThrottling(tabId, true).pipe( Effect.retry({ times: 2 }), Effect.catch((error) => Effect.logWarning("Failed to restore preview frame capture throttling.", { error }), @@ -844,14 +873,19 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); - const stopAllRecordings = Effect.fn("PreviewManager.stopAllRecordings")(function* () { - pendingRecording = null; - const sessions = yield* SynchronizedRef.get(frameCaptureSessionsRef); - yield* Effect.forEach(sessions.keys(), (tabId) => stopFrameCapture(tabId, "recording"), { - concurrency: "unbounded", - discard: true, - }); - }); + const stopMainWindowRecordings = Effect.fn("PreviewManager.stopMainWindowRecordings")( + function* () { + if (pendingRecording !== null && !secondaryTabOwners.has(pendingRecording.tabId)) { + pendingRecording = null; + } + const sessions = yield* SynchronizedRef.get(frameCaptureSessionsRef); + yield* Effect.forEach( + [...sessions.keys()].filter((tabId) => !secondaryTabOwners.has(tabId)), + (tabId) => stopFrameCapture(tabId, "recording"), + { concurrency: "unbounded", discard: true }, + ); + }, + ); const deliverEvent = ( eventKind: "state-change" | "recording-input" | "pointer-event" | "open-link" | "find-result", @@ -1727,7 +1761,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function Effect.gen(function* () { // Cleanup or lock acquisition can outlive the replacement window. if (window.isDestroyed()) return [undefined, sessions] as const; - if (sessions.size > 0) { + if ([...sessions.keys()].some((tabId) => !secondaryTabOwners.has(tabId))) { yield* setWindowBackgroundThrottling(window, false); } yield* Ref.set(mainWindowRef, Option.some(window)); @@ -1738,7 +1772,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function currentMainWindow = undefined; frameCaptureWindowOpen = false; mainWindowCleanupFiber = runFork( - Effect.all([closeAllPictureInPicture(), stopAllRecordings()], { + Effect.all([closeMainWindowPictureInPicture(), stopMainWindowRecordings()], { concurrency: "unbounded", discard: true, }).pipe(Effect.ignore), @@ -1749,9 +1783,35 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ).pipe(Effect.uninterruptible); }); + // Closing the window closes its tabs, which also ends their picture-in-picture and recordings. + const registerSecondaryWindow = Effect.fn("PreviewManager.registerSecondaryWindow")(function* ( + window: BrowserWindow, + ) { + yield* Effect.sync(() => + window.once("closed", () => { + const owned = [...secondaryTabOwners] + .filter(([, owner]) => owner.window === window) + .map(([tabId]) => tabId); + runFork( + Effect.forEach(owned, (tabId) => closeTab(tabId).pipe(Effect.ignore), { + concurrency: "unbounded", + discard: true, + }), + ); + }), + ); + }); + + const tabRoute = (tabId: string): Effect.Effect => + Effect.map(ownerWindowOf(tabId), (window) => ({ + window, + rendererTabId: secondaryTabOwners.get(tabId)?.rendererTabId ?? tabId, + })); + const createTabUnlocked = Effect.fn("PreviewManager.createTabUnlocked")(function* ( tabId: string, defaults?: DesktopPreviewTabDefaults, + owner?: PreviewTabOwner, ) { const updatedAt = yield* currentIso; const result = yield* SynchronizedRef.modify( @@ -1790,6 +1850,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); if (result.created) { tabLifecycleGenerations.set(tabId, (tabLifecycleGenerations.get(tabId) ?? 0) + 1); + if (owner !== undefined) secondaryTabOwners.set(tabId, owner); } yield* emit(tabId, result.state); return result.state; @@ -1798,8 +1859,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const createTab = Effect.fn("PreviewManager.createTab")(function* ( tabId: string, defaults?: DesktopPreviewTabDefaults, + owner?: PreviewTabOwner, ) { - return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId, defaults)); + return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId, defaults, owner)); }); const closeTabUnlocked = Effect.fn("PreviewManager.closeTabUnlocked")(function* (tabId: string) { @@ -1859,6 +1921,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function updatedAt, }; yield* emit(tabId, closed); + secondaryTabOwners.delete(tabId); }); const closeTab = Effect.fn("PreviewManager.closeTab")(function* (tabId: string) { @@ -1893,12 +1956,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function return yield* new PreviewTabNotFoundError({ tabId }); } const wc = webContents.fromId(webContentsId); - const mainWindow = yield* Ref.get(mainWindowRef); + // A guest must be hosted by the window that owns its tab, not by another app window. + const ownerWindow = yield* ownerWindowOf(tabId); if ( !wc || wc.isDestroyed() || wc.getType() !== "webview" || - (Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents) + (Option.isSome(ownerWindow) && wc.hostWebContents !== ownerWindow.value.webContents) ) { return yield* new PreviewWebContentsNotFoundError({ tabId, webContentsId }); } @@ -2461,12 +2525,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (decoded.value.sessionId !== voice.sessionId) return; runFork( Effect.gen(function* () { - const window = yield* Ref.get(mainWindowRef); + const { window, rendererTabId } = yield* tabRoute(tabId); if (Option.isNone(window) || window.value.isDestroyed()) return; yield* attempt({ operation: "annotationVoice.forward", tabId }, () => window.value.webContents.send( PREVIEW_ANNOTATION_VOICE_EVENT_CHANNEL, - tabId, + rendererTabId, decoded.value, ), ).pipe(Effect.ignore); @@ -2997,7 +3061,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function frameCaptureSessionsRef, (sessions) => { return Effect.gen(function* () { - if (!frameCaptureWindowOpen) { + if (!ownerWindowOpen(tabId)) { return yield* new PreviewMainWindowClosedError({ tabId }); } const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); @@ -3030,14 +3094,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), ] as const; } - if (sessions.size === 0) { - yield* setFrameCaptureBackgroundThrottling(false); + const ownerAlreadyUnthrottled = ownerHasFrameCapture(sessions, tabId); + if (!ownerAlreadyUnthrottled) { + yield* setFrameCaptureBackgroundThrottling(tabId, false); } yield* setFrameCaptureWebContentsBackgroundThrottling(wc, false).pipe( Effect.onError(() => - sessions.size === 0 - ? setFrameCaptureBackgroundThrottling(true).pipe(Effect.ignore) - : Effect.void, + ownerAlreadyUnthrottled + ? Effect.void + : setFrameCaptureBackgroundThrottling(tabId, true).pipe(Effect.ignore), ), ); const scope = @@ -3130,15 +3195,16 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* pictureInPictureMutationSemaphore.withPermit(closePictureInPictureUnlocked(tabId)); }); - const closeAllPictureInPicture = Effect.fn("PreviewManager.closeAllPictureInPicture")( - function* () { - const sessions = yield* SynchronizedRef.get(pictureInPictureSessionsRef); - yield* Effect.forEach(sessions.keys(), closePictureInPicture, { - concurrency: "unbounded", - discard: true, - }); - }, - ); + const closeMainWindowPictureInPicture = Effect.fn( + "PreviewManager.closeMainWindowPictureInPicture", + )(function* () { + const sessions = yield* SynchronizedRef.get(pictureInPictureSessionsRef); + yield* Effect.forEach( + [...sessions.keys()].filter((tabId) => !secondaryTabOwners.has(tabId)), + closePictureInPicture, + { concurrency: "unbounded", discard: true }, + ); + }); const openPictureInPicture = Effect.fn("PreviewManager.openPictureInPicture")(function* ( tabId: string, @@ -3488,7 +3554,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function webContentsId: wc.id, }); } - if (!frameCaptureWindowOpen || requestWebContents.isDestroyed()) { + if (!ownerWindowOpen(tabId) || requestWebContents.isDestroyed()) { return yield* new PreviewMainWindowClosedError({ tabId }); } installDisplayMediaRequestHandler(requestWebContents.session); @@ -3771,6 +3837,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function setCaptureDrawn, setColorScheme, setMainWindow, + registerSecondaryWindow, + tabRoute, setForwardedShortcuts: (shortcuts: ReadonlyArray) => Effect.sync(() => { forwardedShortcuts = shortcuts; @@ -3937,6 +4005,10 @@ export class PreviewManager extends Context.Service< PreviewManager, { readonly setMainWindow: (window: BrowserWindow) => Effect.Effect; + /** Closes the tabs a secondary app window created once that window closes. */ + readonly registerSecondaryWindow: (window: BrowserWindow) => Effect.Effect; + /** The app window that shows a tab and the id its renderer knows the tab by. */ + readonly tabRoute: (tabId: string) => Effect.Effect; readonly setForwardedShortcuts: ( shortcuts: ReadonlyArray, ) => Effect.Effect; @@ -3946,9 +4018,11 @@ export class PreviewManager extends Context.Service< namespace?: BrowserSession.BrowserSessionPartitionNamespace, ) => Effect.Effect; readonly isBrowserPartition: (partition: string) => boolean; + /** Without an owner the tab belongs to the main window. */ readonly createTab: ( tabId: string, defaults?: DesktopPreviewTabDefaults, + owner?: PreviewTabOwner, ) => Effect.Effect; readonly closeTab: (tabId: string) => Effect.Effect; readonly registerWebview: ( @@ -4112,6 +4186,8 @@ export const make = Effect.gen(function* PreviewManagerMake() { return PreviewManager.of({ setMainWindow: operations.setMainWindow, + registerSecondaryWindow: operations.registerSecondaryWindow, + tabRoute: operations.tabRoute, setForwardedShortcuts: operations.setForwardedShortcuts, getBrowserSession: Effect.fn("PreviewManager.getBrowserSession")( function* (scope, persistent, namespace) { diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts index 15977b34f398b..792d23697fad5 100644 --- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts +++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts @@ -96,7 +96,9 @@ function layerElectronWindow(window: ReturnType["window"] create: () => Effect.die("unexpected BrowserWindow creation"), main: Effect.succeedSome(window as Electron.BrowserWindow), currentMainOrFirst: Effect.succeedSome(window as Electron.BrowserWindow), - focusedMainOrFirst: Effect.succeedSome(window as Electron.BrowserWindow), + apps: Effect.succeed([]), + focusedApp: Effect.succeedNone, + registerApp: () => Effect.void, setMain: () => Effect.void, clearMain: () => Effect.void, prepareReveal: () => Effect.succeed(false), diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index b118d15ced674..480a4496553b7 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -122,7 +122,9 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { create: () => Effect.die("unexpected BrowserWindow creation"), main: Effect.succeedNone, currentMainOrFirst: Effect.succeedNone, - focusedMainOrFirst: Effect.succeedNone, + apps: Effect.succeed([]), + focusedApp: Effect.succeedNone, + registerApp: () => Effect.void, setMain: () => Effect.void, clearMain: () => Effect.void, prepareReveal: () => Effect.succeed(false), diff --git a/apps/desktop/src/window/BackgroundThrottling.ts b/apps/desktop/src/window/BackgroundThrottling.ts new file mode 100644 index 0000000000000..41f4200d691b5 --- /dev/null +++ b/apps/desktop/src/window/BackgroundThrottling.ts @@ -0,0 +1,21 @@ +import type * as Electron from "electron"; + +const holds = new WeakMap>(); + +/** + * Preview frame capture and the hub's secondary windows can each need a renderer unthrottled; + * it throttles again only once every holder releases. + */ +export function setUnthrottledHold( + window: Pick, + reason: string, + held: boolean, +): void { + if (window.isDestroyed()) return; + const contents = window.webContents; + const reasons = holds.get(contents) ?? new Set(); + if (held) reasons.add(reason); + else reasons.delete(reason); + holds.set(contents, reasons); + contents.setBackgroundThrottling(reasons.size === 0); +} diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 8b2c4317bd20f..2166d7c9cb97d 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -92,7 +92,7 @@ const layerDesktopUpdates = ({ checkResult }: MenuServices) => } satisfies DesktopUpdates.DesktopUpdates["Service"]); const layerDesktopWindow = (selectedAction: Deferred.Deferred) => - Layer.succeed(DesktopWindow.DesktopWindow, { + Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected createMain"), ensureMain: Effect.die("unexpected ensureMain"), revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"), @@ -105,12 +105,12 @@ const layerDesktopWindow = (selectedAction: Deferred.Deferred) => prepareCaptureReveal: Effect.void, dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid), dispatchSnapShotEvent: () => Effect.void, - zoomMain: (direction) => + zoomFocused: (direction) => Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid), - runMainContentsCommand: (command) => + runFocusedContentsCommand: (command) => Deferred.succeed(selectedAction, `main-${command}`).pipe(Effect.asVoid), syncAppearance: Effect.void, - } satisfies DesktopWindow.DesktopWindow["Service"]); + }); const layerElectronMenu = ( applicationMenuTemplate: Deferred.Deferred, @@ -347,6 +347,30 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); + it.effect("leads the Window menu with New Window and leaves its chord to the renderer", () => + Effect.gen(function* () { + const selectedAction = yield* Deferred.make(); + const applicationMenuTemplate = + yield* Deferred.make(); + yield* configureMenu(selectedAction, applicationMenuTemplate); + + const windowMenu = (yield* Deferred.await(applicationMenuTemplate)).find( + (item) => item.role === "windowMenu", + ); + if (!Array.isArray(windowMenu?.submenu)) { + throw new Error("Expected the Window menu submenu to be an array."); + } + const [newWindow] = windowMenu.submenu; + assert.deepEqual( + { label: newWindow?.label, accelerator: newWindow?.accelerator }, + { label: "New Window", accelerator: "CmdOrCtrl+Alt+Shift+N" }, + ); + assert.equal(newWindow?.registerAccelerator, false); + newWindow?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + assert.equal(yield* Deferred.await(selectedAction), "new-window"); + }), + ); + it.effect("tells the user which update the menu check found", () => Effect.gen(function* () { const dialog = yield* checkForUpdatesFromMacMenu({ diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 543d8d245731b..524471920374b 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -55,18 +55,18 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function }); }); -const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* ( +const zoomFocusedWindow = Effect.fn("desktop.menu.zoomFocusedWindow")(function* ( direction: DesktopWindow.MainWindowZoomDirection, ): Effect.fn.Return { const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.zoomMain(direction); + yield* desktopWindow.zoomFocused(direction); }); -const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(function* ( +const runFocusedContentsCommand = Effect.fn("desktop.menu.runFocusedContentsCommand")(function* ( command: DesktopWindow.MainWindowContentsCommand, ): Effect.fn.Return { const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.runMainContentsCommand(command); + yield* desktopWindow.runFocusedContentsCommand(command); }); const trackLabel = (channel: DesktopUpdateChannel) => @@ -224,10 +224,10 @@ export const make = Effect.gen(function* () { runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text")); }; const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => { - runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction)); + runMenuEffect(`zoom-${direction}`, zoomFocusedWindow(direction)); }; const mainContentsClick = (command: DesktopWindow.MainWindowContentsCommand) => () => { - runMenuEffect(command, runMainContentsCommand(command)); + runMenuEffect(command, runFocusedContentsCommand(command)); }; const template: Electron.MenuItemConstructorOptions[] = []; @@ -396,6 +396,14 @@ export const make = Effect.gen(function* () { role: "windowMenu", label: m(msg("Window", { $context: "menu bar title" })), submenu: [ + { + label: m(msg("New Window", { $context: "Window menu item" })), + // The renderer's window.new keybinding owns the chord. + accelerator: "CmdOrCtrl+Alt+Shift+N", + registerAccelerator: false, + click: () => runMenuEffect("new-window", dispatchMenuAction("new-window")), + }, + { type: "separator" }, { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) }, { role: "zoom", diff --git a/apps/desktop/src/window/DesktopHubLinks.test.ts b/apps/desktop/src/window/DesktopHubLinks.test.ts new file mode 100644 index 0000000000000..af4d8ce49dd3f --- /dev/null +++ b/apps/desktop/src/window/DesktopHubLinks.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; + +const setup = () => { + let channels = 0; + const deliveries: Array<{ to: number; port: string; peerWindowId: number }> = []; + const broker = new HubLinkBroker(() => { + channels += 1; + return { port1: `hub-end-${channels}`, port2: `window-end-${channels}` }; + }); + const peer = (windowId: number): HubLinkPeer => ({ + windowId, + deliver: (port, peerWindowId) => deliveries.push({ to: windowId, port, peerWindowId }), + }); + return { broker, deliveries, peer }; +}; + +describe("HubLinkBroker", () => { + it("holds requests until the hub registers, once per window", () => { + const { broker, deliveries, peer } = setup(); + broker.request(peer(2)); + broker.request(peer(2)); + broker.request(peer(3)); + expect(deliveries).toEqual([]); + + broker.registerHub(peer(1)); + expect(deliveries).toEqual([ + { to: 1, port: "hub-end-1", peerWindowId: 2 }, + { to: 2, port: "window-end-1", peerWindowId: 1 }, + { to: 1, port: "hub-end-2", peerWindowId: 3 }, + { to: 3, port: "window-end-2", peerWindowId: 1 }, + ]); + }); + + it("links at once while the hub is ready and makes windows relink after it resets", () => { + const { broker, deliveries, peer } = setup(); + broker.registerHub(peer(1)); + broker.request(peer(2)); + expect(deliveries).toHaveLength(2); + + expect(broker.resetHub()).toBe(true); + expect(broker.resetHub()).toBe(false); + expect(broker.peerGone(2)).toBe(false); + broker.request(peer(2)); + expect(deliveries).toHaveLength(2); + + broker.registerHub(peer(1)); + expect(deliveries.slice(2)).toEqual([ + { to: 1, port: "hub-end-2", peerWindowId: 2 }, + { to: 2, port: "window-end-2", peerWindowId: 1 }, + ]); + }); + + it("tells the hub about a gone window only when it held links to it", () => { + const { broker, deliveries, peer } = setup(); + broker.request(peer(4)); + expect(broker.peerGone(4)).toBe(false); + broker.registerHub(peer(1)); + expect(deliveries).toEqual([]); + + broker.request(peer(2)); + expect(broker.peerGone(2)).toBe(true); + expect(broker.peerGone(2)).toBe(false); + }); +}); diff --git a/apps/desktop/src/window/DesktopHubLinks.ts b/apps/desktop/src/window/DesktopHubLinks.ts new file mode 100644 index 0000000000000..e0e91197c0411 --- /dev/null +++ b/apps/desktop/src/window/DesktopHubLinks.ts @@ -0,0 +1,55 @@ +export interface HubLinkPeer { + readonly windowId: number; + readonly deliver: (port: Port, peerWindowId: number) => void; +} + +/** + * Pairs secondary windows with the main window's renderer, which owns every environment + * connection. Requests made before the hub registers wait for it. + */ +export class HubLinkBroker { + private hub: HubLinkPeer | null = null; + private readonly pending = new Map>(); + private readonly linked = new Set(); + private readonly createChannel: () => { port1: Port; port2: Port }; + + constructor(createChannel: () => { port1: Port; port2: Port }) { + this.createChannel = createChannel; + } + + registerHub(hub: HubLinkPeer): void { + this.hub = hub; + const waiting = [...this.pending.values()]; + this.pending.clear(); + for (const peer of waiting) this.link(hub, peer); + } + + /** Returns whether the hub had been serving; its secondary windows must then relink. */ + resetHub(): boolean { + if (this.hub === null) return false; + this.hub = null; + this.linked.clear(); + return true; + } + + request(peer: HubLinkPeer): void { + if (this.hub === null) { + this.pending.set(peer.windowId, peer); + return; + } + this.link(this.hub, peer); + } + + /** Returns whether the hub held links to the peer and must drop them. */ + peerGone(windowId: number): boolean { + this.pending.delete(windowId); + return this.linked.delete(windowId) && this.hub !== null; + } + + private link(hub: HubLinkPeer, peer: HubLinkPeer): void { + const { port1, port2 } = this.createChannel(); + hub.deliver(port1, peer.windowId); + peer.deliver(port2, hub.windowId); + this.linked.add(peer.windowId); + } +} diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index e4e426b1975ae..3d812c82aa5f8 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -69,6 +69,8 @@ const environmentInput = { runningUnderArm64Translation: false, } satisfies DesktopEnvironment.MakeDesktopEnvironmentInput; +let nextFakeWindowId = 1; + function makeFakeBrowserWindow() { const windowListeners = new Map void>(); const webContentsListeners = new Map void>(); @@ -112,7 +114,9 @@ function makeFakeBrowserWindow() { }; const window = { + id: nextFakeWindowId++, close: vi.fn(), + hide: vi.fn(), focus: vi.fn(), getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })), getNormalBounds: vi.fn(() => ({ x: 0, y: 0, width: 1100, height: 780 })), @@ -167,6 +171,8 @@ function makeFakeBrowserWindow() { webContentsListeners, webContentsOnce: webContents.once, windowListeners, + close: window.close, + hide: window.hide, }; } @@ -252,6 +258,8 @@ function layerTest(input: { readonly onPopupTemplate?: (input: ElectronMenu.ElectronMenuTemplateInput) => Effect.Effect; readonly previewZoomReapplies?: number[]; readonly onReveal?: (window: Electron.BrowserWindow) => void; + /** Windows to hand out in creation order; `window` once these run out. */ + readonly createdWindows?: Electron.BrowserWindow[]; readonly focusedWindow?: Electron.BrowserWindow; readonly fallbackWindow?: Electron.BrowserWindow; readonly platform?: NodeJS.Platform; @@ -304,16 +312,20 @@ function layerTest(input: { }).pipe( Effect.andThen(Ref.update(input.createCount, (count) => count + 1)), Effect.andThen(input.onWindowCreate ?? Effect.void), - Effect.as(input.window), + Effect.map(() => input.createdWindows?.shift() ?? input.window), ), main: Ref.get(input.mainWindow), currentMainOrFirst: Ref.get(input.mainWindow).pipe( Effect.map(Option.orElse(() => Option.fromNullishOr(input.fallbackWindow ?? null))), ), - focusedMainOrFirst: - input.focusedWindow === undefined - ? Ref.get(input.mainWindow) - : Effect.succeedSome(input.focusedWindow), + apps: Effect.map(Ref.get(input.mainWindow), Option.toArray), + // Popups and auxiliary windows are never app windows, so focus falls back to main. + focusedApp: Effect.map(Ref.get(input.mainWindow), (main) => + input.focusedWindow !== undefined && Option.contains(main, input.focusedWindow) + ? Option.some(input.focusedWindow) + : main, + ), + registerApp: () => Effect.void, setMain: (window) => Ref.set(input.mainWindow, Option.some(window)), clearMain: () => Ref.set(input.mainWindow, Option.none()), prepareReveal: () => Effect.succeed(false), @@ -374,6 +386,7 @@ function layerTest(input: { Layer.mock(PreviewManager.PreviewManager)({ getBrowserSession: () => Effect.succeed({} as Electron.Session), setMainWindow: input.setPreviewMainWindow ?? (() => Effect.void), + registerSecondaryWindow: () => Effect.void, prepareWebview: () => Effect.void, isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"), getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"), @@ -443,7 +456,9 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n }), main: Ref.get(mainWindow), currentMainOrFirst, - focusedMainOrFirst: currentMainOrFirst, + apps: Effect.map(Ref.get(mainWindow), Option.toArray), + focusedApp: Ref.get(mainWindow), + registerApp: () => Effect.void, setMain: (window) => Ref.set(mainWindow, Option.some(window)), clearMain: () => Ref.set(mainWindow, Option.none()), prepareReveal: () => Effect.succeed(false), @@ -807,10 +822,10 @@ describe("DesktopWindow", () => { const desktopWindow = yield* DesktopWindow.DesktopWindow; yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - yield* desktopWindow.zoomMain("out"); - yield* desktopWindow.zoomMain("out"); - yield* desktopWindow.zoomMain("in"); - yield* desktopWindow.zoomMain("reset"); + yield* desktopWindow.zoomFocused("out"); + yield* desktopWindow.zoomFocused("out"); + yield* desktopWindow.zoomFocused("in"); + yield* desktopWindow.zoomFocused("reset"); assert.deepEqual( fakeWindow.setZoomLevel.mock.calls.map(([level]) => level), @@ -1470,6 +1485,41 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens a secondary window, keeping the main window hidden while it serves it", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const secondary = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, secondary.window], + createCount, + mainWindow, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* windows.openNewWindow; + assert.equal(yield* Ref.get(createCount), 2); + assert.deepEqual(Option.getOrThrow(yield* windows.windowContext(secondary.window)), { + windowId: secondary.window.id, + isMain: false, + }); + assert.deepEqual((yield* windows.windowsState).windows, [ + { windowId: main.window.id, isMain: true }, + { windowId: secondary.window.id, isMain: false }, + ]); + + const preventMainClose = vi.fn(); + main.windowListeners.get("close")?.({ preventDefault: preventMainClose }); + assert.equal(preventMainClose.mock.calls.length, 1); + assert.equal(main.hide.mock.calls.length, 1); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("persists the current main window bounds before the window closes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index c99fbb52c49e2..6b3aa5b82e655 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -11,7 +11,12 @@ import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; import { msg } from "gt-i18n"; -import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; +import { + type DesktopSnapShotEvent, + type DesktopWindowContext, + type DesktopWindowsState, + DEFAULT_CLIENT_SETTINGS, +} from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; import * as DesktopClerk from "../app/DesktopClerk.ts"; @@ -31,6 +36,10 @@ import { TRACKPAD_SCROLL_BEGIN_CHANNEL, TRACKPAD_SCROLL_END_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL, + WINDOWS_HUB_LINK_CHANNEL, + WINDOWS_HUB_PEER_GONE_CHANNEL, + WINDOWS_HUB_RESET_CHANNEL, + WINDOWS_STATE_CHANNEL, } from "../ipc/channels.ts"; import { PASSKEY_BRIDGE_ARGUMENT, @@ -46,6 +55,9 @@ import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts" import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; +import { setUnthrottledHold } from "./BackgroundThrottling.ts"; +import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; +import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; const TITLEBAR_HEIGHT = 40; @@ -96,6 +108,7 @@ const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500; const RENDERER_RECOVERY_MAX_ATTEMPTS = 3; const RENDERER_RECOVERY_WINDOW_MS = 60_000; const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]); +const HUB_UNTHROTTLED_REASON = "hub-serving-windows"; type WindowTitleBarOptions = Pick< Electron.BrowserWindowConstructorOptions, @@ -143,10 +156,18 @@ export class DesktopWindow extends Context.Service< readonly dispatchSnapShotEvent: ( event: DesktopSnapShotEvent, ) => Effect.Effect; - // Electron zoom roles target focused guests; zoomMain must always target the app. - readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect; + // Electron zoom roles target focused guests; this must always target an app window. + readonly zoomFocused: (direction: MainWindowZoomDirection) => Effect.Effect; readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; + readonly runFocusedContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; readonly syncAppearance: Effect.Effect; + readonly windowsState: Effect.Effect; + readonly windowContext: ( + window: Electron.BrowserWindow, + ) => Effect.Effect>; + readonly openNewWindow: Effect.Effect; + readonly registerHub: (window: Electron.BrowserWindow) => Effect.Effect; + readonly requestHubLink: (window: Electron.BrowserWindow) => Effect.Effect; } >()("@t3tools/desktop/window/DesktopWindow") {} @@ -381,6 +402,20 @@ function bindFirstRevealTrigger( } } +type AppWindowSpec = + | { readonly role: "main" } + | { readonly role: "secondary"; readonly anchorBounds: DisplayBounds | null }; + +interface AppWindowEntry { + readonly window: Electron.BrowserWindow; + readonly windowId: number; + readonly isMain: boolean; + rendererLive: boolean; + hubUnthrottled: boolean; +} + +const serializeWindowsState = (state: DesktopWindowsState) => JSON.stringify(state); + /** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -404,6 +439,7 @@ export const make = Effect.gen(function* () { const context = yield* Effect.context(); const runFork = Effect.runForkWith(context); const runPromise = Effect.runPromiseWith(context); + const runSync = Effect.runSyncWith(context); const mainWindowMutex = yield* Semaphore.make(1); const pendingMainReveals = new WeakMap>(); const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) => @@ -411,6 +447,21 @@ export const make = Effect.gen(function* () { ); let flushMainWindowBounds: Effect.Effect = Effect.void; let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; + const entries = new Map(); + let lastBroadcastState = ""; + const hubLinks = new HubLinkBroker( + () => new Electron.MessageChannelMain(), + ); + + const liveEntries = () => [...entries.values()].filter((entry) => !entry.window.isDestroyed()); + const mainEntry = () => liveEntries().find((entry) => entry.isMain); + const secondaryEntries = () => liveEntries().filter((entry) => !entry.isMain); + const entryOf = (window: Electron.BrowserWindow) => { + const entry = entries.get(window.id); + return entry !== undefined && entry.window === window && !window.isDestroyed() + ? entry + : undefined; + }; const dismissConnectingSplash = Effect.gen(function* () { const splash = yield* Ref.getAndSet(splashWindowRef, Option.none()); @@ -444,18 +495,60 @@ export const make = Effect.gen(function* () { yield* previewManager.reapplyZoom(); }); - const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return< - Option.Option, - DesktopWindowError - > { - if (yield* Ref.get(desktopState.quitting)) return Option.none(); - yield* previewManager.getBrowserSession(); - const applicationUrl = getDesktopUrl(environment.isDevelopment); - const iconPaths = yield* assets.iconPaths; - const iconOption = getIconOption(iconPaths, environment.platform); - const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; - const persistedSettings = yield* desktopSettings.get; - const persistedBounds = persistedSettings.mainWindowBounds; + const computeWindowsState = Effect.sync((): DesktopWindowsState => ({ + windows: liveEntries() + .sort((left, right) => Number(right.isMain) - Number(left.isMain)) + .map(({ windowId, isMain }) => ({ windowId, isMain })), + })); + + // The hub must keep serving secondary windows while it is hidden or minimized. + const syncHubThrottling = () => { + const main = mainEntry(); + if (main === undefined) return; + const held = secondaryEntries().length > 0; + if (held === main.hubUnthrottled) return; + main.hubUnthrottled = held; + setUnthrottledHold(main.window, HUB_UNTHROTTLED_REASON, held); + }; + + // Throttling and every renderer's list of open windows follow from the open windows. + const syncWindows = Effect.fn("desktop.window.syncWindows")(function* () { + syncHubThrottling(); + const state = yield* computeWindowsState; + const serialized = serializeWindowsState(state); + if (serialized === lastBroadcastState) return; + lastBroadcastState = serialized; + for (const entry of liveEntries()) { + if (entry.rendererLive) entry.window.webContents.send(WINDOWS_STATE_CHANNEL, state); + } + }); + const requestSync = () => { + runFork(syncWindows()); + }; + + const notifyHubReset = () => { + if (!hubLinks.resetHub()) return; + for (const entry of secondaryEntries()) { + if (entry.rendererLive) entry.window.webContents.send(WINDOWS_HUB_RESET_CHANNEL); + } + }; + const notifyHubPeerGone = (windowId: number) => { + if (!hubLinks.peerGone(windowId)) return; + const main = mainEntry(); + if (main !== undefined) main.window.webContents.send(WINDOWS_HUB_PEER_GONE_CHANNEL, windowId); + }; + const hubPeer = (entry: AppWindowEntry): HubLinkPeer => ({ + windowId: entry.windowId, + deliver: (port, peerWindowId) => { + if (entry.window.isDestroyed()) { + port.close(); + return; + } + entry.window.webContents.postMessage(WINDOWS_HUB_LINK_CHANNEL, { peerWindowId }, [port]); + }, + }); + + const readDisplayBounds = Effect.gen(function* () { const displayBoundsResult = yield* Effect.sync(() => { try { return { @@ -466,17 +559,41 @@ export const make = Effect.gen(function* () { return { _tag: "Failure" as const, cause }; } }); - const displayBounds = - displayBoundsResult._tag === "Success" - ? displayBoundsResult.bounds - : yield* logWindowWarning("failed to read connected displays; using defaults", { - cause: displayBoundsResult.cause, - }).pipe(Effect.as([])); - const initialBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds); - const restoredPersistedBounds = persistedBounds !== null && initialBounds === persistedBounds; - if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) { + return displayBoundsResult._tag === "Success" + ? displayBoundsResult.bounds + : yield* logWindowWarning("failed to read connected displays; using defaults", { + cause: displayBoundsResult.cause, + }).pipe(Effect.as([])); + }); + + const buildAppWindow = Effect.fn("desktop.window.createWindow")(function* ( + spec: AppWindowSpec, + ): Effect.fn.Return, DesktopWindowError> { + if (yield* Ref.get(desktopState.quitting)) return Option.none(); + const isMain = spec.role === "main"; + yield* previewManager.getBrowserSession(); + const applicationUrl = getDesktopUrl(environment.isDevelopment); + const iconPaths = yield* assets.iconPaths; + const iconOption = getIconOption(iconPaths, environment.platform); + const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; + const persistedSettings = yield* desktopSettings.get; + // Only the main window keeps its placement. + const persistedBounds = isMain ? persistedSettings.mainWindowBounds : null; + const displayBounds = yield* readDisplayBounds; + const restorableBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds); + const restoredPersistedBounds = + persistedBounds !== null && restorableBounds === persistedBounds; + if (persistedBounds !== null && !restoredPersistedBounds) { yield* logWindowWarning("saved main window bounds could not be restored; using defaults"); } + const initialBounds = + spec.role === "secondary" + ? cascadeWindowBounds({ + anchor: spec.anchorBounds, + size: DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, + displays: displayBounds, + }) + : restorableBounds; if (yield* Ref.get(desktopState.quitting)) return Option.none(); const window = yield* electronWindow.create({ ...initialBounds, @@ -507,11 +624,19 @@ export const make = Effect.gen(function* () { return Option.none(); } - pendingMainReveals.set(window, Effect.void); + if (isMain) pendingMainReveals.set(window, Effect.void); + setUnthrottledHold(window, "first-reveal", true); yield* rendererHistory.register(window.webContents, { surface: "main" }); if (environment.platform === "darwin") { window.setAutoHideCursor(false); } + const entry: AppWindowEntry = { + window, + windowId: window.id, + isMain, + rendererLive: false, + hubUnthrottled: false, + }; let boundsPersistFiber: Fiber.Fiber | undefined; let pendingBoundsPersistFiber: Fiber.Fiber | undefined; let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds; @@ -552,7 +677,7 @@ export const make = Effect.gen(function* () { : (readPersistableState()?.bounds ?? null); const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { - if (!boundsPersistenceEnabled) { + if (!isMain || !boundsPersistenceEnabled) { return pendingBoundsPersistFiber; } const state = readPersistableState(); @@ -615,9 +740,13 @@ export const make = Effect.gen(function* () { fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid), ), ); - flushMainWindowBounds = flushBoundsPersist; + if (isMain) flushMainWindowBounds = flushBoundsPersist; - yield* previewManager.setMainWindow(window); + if (isMain) { + yield* previewManager.setMainWindow(window); + } else { + yield* previewManager.registerSecondaryWindow(window); + } if (yield* Ref.get(desktopState.quitting)) { yield* electronWindow.destroyAll; return Option.none(); @@ -794,6 +923,16 @@ export const make = Effect.gen(function* () { void runPromise(electronShell.openExternal(url)); } }); + // A new document drops the old renderer's hub links. + const rendererGone = () => { + entry.rendererLive = false; + if (isMain) notifyHubReset(); + else notifyHubPeerGone(entry.windowId); + }; + window.webContents.on("did-start-navigation", (event) => { + if (event.isMainFrame && !event.isSameDocument) rendererGone(); + }); + window.webContents.on("destroyed", rendererGone); const quitShortcutHandler = makeQuitShortcutHandler({ platform: environment.platform, @@ -860,7 +999,13 @@ export const make = Effect.gen(function* () { window.on("move", scheduleBoundsPersist); window.on("maximize", scheduleBoundsPersist); window.on("unmaximize", scheduleBoundsPersist); - window.on("close", () => { + window.on("close", (event) => { + // Hidden, the main window keeps serving the secondary windows' connections. + if (isMain && secondaryEntries().length > 0 && !runSync(Ref.get(desktopState.quitting))) { + event.preventDefault(); + window.hide(); + return; + } runFork(flushBoundsPersist); }); @@ -936,6 +1081,11 @@ export const make = Effect.gen(function* () { clearDevelopmentLoadRetry(); developmentLoadRetryIndex = 0; if (environment.platform === "darwin") syncMacosWindowButtons(window); + entry.rendererLive = true; + if (entries.size > 1 || !isMain) { + lastBroadcastState = ""; + requestSync(); + } }); window.webContents.on( "did-fail-load", @@ -954,7 +1104,8 @@ export const make = Effect.gen(function* () { ? scheduleDevelopmentLoadRetry() : undefined; void runPromise( - logWindowWarning("main window failed to load", { + logWindowWarning("app window failed to load", { + role: spec.role, errorCode, errorDescription, url: validatedURL, @@ -964,6 +1115,7 @@ export const make = Effect.gen(function* () { }, ); window.webContents.on("render-process-gone", (_event, details) => { + rendererGone(); const recoverable = details.reason === "crashed" || details.reason === "oom" || @@ -992,7 +1144,8 @@ export const make = Effect.gen(function* () { RENDERER_RECOVERY_RELOAD_DELAY_MS, oldestAttempt + RENDERER_RECOVERY_WINDOW_MS - now, ); - yield* logWindowWarning("main window render process gone", { + yield* logWindowWarning("app window render process gone", { + role: spec.role, reason: details.reason, exitCode: details.exitCode, recovering: shouldRecover, @@ -1026,53 +1179,69 @@ export const make = Effect.gen(function* () { return; firstRevealComplete = true; pendingMainReveals.delete(window); - window.webContents.setBackgroundThrottling(true); - if (persistedSettings.mainWindowMaximized) window.maximize(); + setUnthrottledHold(window, "first-reveal", false); + if (isMain && persistedSettings.mainWindowMaximized) window.maximize(); yield* electronWindow.reveal(window); - yield* dismissConnectingSplash; + if (isMain) yield* dismissConnectingSplash; }); - pendingMainReveals.set(window, revealWhenReady); + if (isMain) pendingMainReveals.set(window, revealWhenReady); bindFirstRevealTrigger(revealSubscribers, () => { rendererReady = true; void runPromise(revealWhenReady); }); - // Desktop IPC only answers the main window, so register it before its renderer can call in. - yield* electronWindow.setMain(window); - remoteRequestHeaderOwner = window; - const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( - window.webContents.session, - { - desktopOrigin: getDesktopOrigin(environment.isDevelopment), - mainWebContentsId: window.webContents.id, - clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, - devServerOrigin: Option.getOrUndefined( - Option.map(environment.devServerUrl, (url) => url.origin), - ), - isDevelopment: environment.isDevelopment, - }, - ); + entries.set(window.id, entry); + // Desktop IPC only answers app windows, so register this one before its renderer can call in. + let detachRemoteRequestHeaders = () => {}; + if (isMain) { + yield* electronWindow.setMain(window); + // App windows share one session, whose single header listener follows the main window. + remoteRequestHeaderOwner = window; + detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( + window.webContents.session, + { + desktopOrigin: getDesktopOrigin(environment.isDevelopment), + mainWebContentsId: window.webContents.id, + clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, + devServerOrigin: Option.getOrUndefined( + Option.map(environment.devServerUrl, (url) => url.origin), + ), + isDevelopment: environment.isDevelopment, + }, + ); + } else { + yield* electronWindow.registerApp(window); + } + yield* syncWindows(); loadApplication(); - if (environment.isDevelopment) { + if (isMain && environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); } window.on("closed", () => { - if (!backendHasStarted) mainClosedDuringStartup = true; + if (entries.get(window.id) === entry) entries.delete(window.id); clearDevelopmentLoadRetry(); clearBoundsPersist(); if (remoteRequestHeaderOwner === window) { remoteRequestHeaderOwner = null; detachRemoteRequestHeaders(); } - void runPromise(electronWindow.clearMain(Option.some(window))); + if (isMain) { + if (!backendHasStarted) mainClosedDuringStartup = true; + notifyHubReset(); + void runPromise(electronWindow.clearMain(Option.some(window))); + } else { + notifyHubPeerGone(entry.windowId); + runFork(handleSecondaryClosed); + } + requestSync(); }); return Option.some(window); }); const createMain = Effect.gen(function* () { - const window = yield* createWindow(); + const window = yield* buildAppWindow({ role: "main" }); if (Option.isSome(window)) { mainClosedDuringStartup = false; yield* logWindowInfo("main window created"); @@ -1101,6 +1270,26 @@ export const make = Effect.gen(function* () { return window; }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain")); + const openSecondary = Effect.gen(function* () { + // Secondary windows reach environments through the main window's renderer. + if (Option.isNone(yield* ensureMain)) return; + const anchor = yield* electronWindow.focusedApp; + yield* buildAppWindow({ + role: "secondary", + anchorBounds: + Option.isSome(anchor) && !anchor.value.isDestroyed() ? anchor.value.getBounds() : null, + }); + }).pipe(Effect.withSpan("desktop.window.openSecondary")); + + const handleSecondaryClosed = Effect.gen(function* () { + if (yield* Ref.get(desktopState.quitting)) return; + const main = mainEntry(); + if (secondaryEntries().length > 0 || main === undefined || main.window.isVisible()) return; + // The hidden main window kept the app alive for its secondary windows; without them, quit + // as closing the last window always has. macOS apps outlive their windows. + if (environment.platform !== "darwin") main.window.close(); + }).pipe(Effect.withSpan("desktop.window.handleSecondaryClosed")); + const waitingForBackend = Effect.gen(function* () { if (yield* Ref.get(backendReadyRef)) return false; return (yield* desktopSettings.get).localEnvironmentEnabled; @@ -1166,14 +1355,22 @@ export const make = Effect.gen(function* () { const dispatchRendererEvent = Effect.fn("desktop.window.dispatchRendererEvent")(function* ( channel: string, payload: unknown, - { reveal = true }: { readonly reveal?: boolean } = {}, - ) { - if (yield* Ref.get(desktopState.quitting)) return; - // Only the main renderer loads the app preload that listens on these channels. - const existingWindow = yield* electronWindow.main; - if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return; + { + reveal = true, + target, + }: { readonly reveal?: boolean; readonly target?: Electron.BrowserWindow } = {}, + ): Effect.fn.Return, DesktopWindowError> { + if (yield* Ref.get(desktopState.quitting)) return Option.none(); + // Only app renderers load the preload that listens on these channels; the focused one acts. + const existingWindow = + target !== undefined && !target.isDestroyed() + ? Option.some(target) + : yield* electronWindow.focusedApp; + if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) { + return Option.none(); + } const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain; - if (Option.isNone(window) || window.value.isDestroyed()) return; + if (Option.isNone(window) || window.value.isDestroyed()) return Option.none(); const targetWindow = window.value; const send = Effect.sync(() => { if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload); @@ -1184,17 +1381,35 @@ export const make = Effect.gen(function* () { : send; if (targetWindow.webContents.isLoadingMainFrame()) { targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch)); - return; + return window; } yield* dispatch; + return window; }); + // A capture finishes in the window it started in, even if focus moved meanwhile. + const captureWindows = new Map(); + + const runContentsCommand = ( + window: Electron.BrowserWindow, + command: MainWindowContentsCommand, + ) => { + if (window.isDestroyed()) return; + const webContents = window.webContents; + if (command === "reload") webContents.reload(); + else if (command === "forceReload") webContents.reloadIgnoringCache(); + else webContents.toggleDevTools(); + }; return DesktopWindow.of({ createMain: createMain.pipe(Effect.flatMap(requireWindow)), ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)), revealOrCreateMain, prepareCaptureReveal: Effect.gen(function* () { - const existingWindow = yield* currentMainWindow; + // The capture lands in the focused app window, so that is the one to bring forward. + const focusedWindow = yield* electronWindow.focusedApp; + const existingWindow = Option.isSome(focusedWindow) + ? focusedWindow + : yield* currentMainWindow; if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) { yield* electronWindow.prepareReveal(existingWindow.value); } @@ -1243,13 +1458,26 @@ export const make = Effect.gen(function* () { event: event.type, captureId: "id" in event ? (event.id ?? null) : null, }); - yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, { + if (event.type === "shortcut-changed") { + for (const entry of entries.values()) { + if (!entry.window.isDestroyed()) + entry.window.webContents.send(SNAP_SHOT_EVENT_CHANNEL, event); + } + return; + } + const id = event.id; + const started = id === undefined ? undefined : captureWindows.get(id); + const delivered = yield* dispatchRendererEvent(SNAP_SHOT_EVENT_CHANNEL, event, { reveal: event.type === "started", + ...(started === undefined ? {} : { target: started }), }); + if (id === undefined) return; + if (event.type === "ready" || event.type === "failed") captureWindows.delete(id); + else if (Option.isSome(delivered)) captureWindows.set(id, delivered.value); }), - zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) { + zoomFocused: Effect.fn("desktop.window.zoomFocused")(function* (direction) { yield* Effect.annotateCurrentSpan({ direction }); - const window = yield* electronWindow.main; + const window = yield* electronWindow.focusedApp; if (Option.isNone(window) || window.value.isDestroyed()) { return; } @@ -1257,20 +1485,45 @@ export const make = Effect.gen(function* () { }), runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) { yield* Effect.annotateCurrentSpan({ command }); - // A focused OAuth popup must not receive the app's Reload command. const window = yield* electronWindow.main; - if (Option.isNone(window) || window.value.isDestroyed()) return; - const webContents = window.value.webContents; - if (command === "reload") webContents.reload(); - else if (command === "forceReload") webContents.reloadIgnoringCache(); - else webContents.toggleDevTools(); + if (Option.isSome(window)) runContentsCommand(window.value, command); }), + runFocusedContentsCommand: Effect.fn("desktop.window.runFocusedContentsCommand")( + function* (command) { + yield* Effect.annotateCurrentSpan({ command }); + // A focused OAuth popup must not receive the app's Reload command. + const window = yield* electronWindow.focusedApp; + if (Option.isSome(window)) runContentsCommand(window.value, command); + }, + ), syncAppearance: Effect.gen(function* () { const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) => syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform), ); }).pipe(Effect.withSpan("desktop.window.syncAppearance")), + windowsState: computeWindowsState, + windowContext: Effect.fn("desktop.window.windowContext")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + return entry === undefined + ? Option.none() + : Option.some({ windowId: entry.windowId, isMain: entry.isMain }); + }); + }), + openNewWindow: openSecondary, + registerHub: Effect.fn("desktop.window.registerHub")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + if (entry !== undefined && entry.isMain) hubLinks.registerHub(hubPeer(entry)); + }); + }), + requestHubLink: Effect.fn("desktop.window.requestHubLink")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + if (entry !== undefined && !entry.isMain) hubLinks.request(hubPeer(entry)); + }); + }), }); }); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.test.ts b/apps/desktop/src/window/DesktopWindowProfiles.test.ts new file mode 100644 index 0000000000000..f1a8a93b10634 --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; + +describe("cascadeWindowBounds", () => { + const display = { x: 0, y: 0, width: 1920, height: 1080 }; + + it("offsets from the opener and wraps back inside its display", () => { + const size = { width: 1100, height: 780 }; + expect( + cascadeWindowBounds({ + anchor: { x: 100, y: 100, width: 1100, height: 780 }, + size, + displays: [display], + }), + ).toEqual({ x: 128, y: 128, width: 1100, height: 780 }); + expect( + cascadeWindowBounds({ + anchor: { x: 900, y: 290, width: 1100, height: 780 }, + size, + displays: [display], + }), + ).toEqual({ x: 28, y: 28, width: 1100, height: 780 }); + expect(cascadeWindowBounds({ anchor: null, size, displays: [display] })).toEqual(size); + }); +}); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.ts b/apps/desktop/src/window/DesktopWindowProfiles.ts new file mode 100644 index 0000000000000..9e0e07c757bf4 --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.ts @@ -0,0 +1,41 @@ +interface Rectangle { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +const CASCADE_OFFSET_PX = 28; + +/** Places a new window down and right of the window it opened from, wrapping inside that display. */ +export function cascadeWindowBounds(input: { + readonly anchor: Rectangle | null; + readonly size: { readonly width: number; readonly height: number }; + readonly displays: readonly Rectangle[]; +}): Rectangle | { readonly width: number; readonly height: number } { + const { anchor } = input; + if (anchor === null) return input.size; + const display = + input.displays.find( + (candidate) => + anchor.x >= candidate.x && + anchor.y >= candidate.y && + anchor.x < candidate.x + candidate.width && + anchor.y < candidate.y + candidate.height, + ) ?? input.displays[0]; + if (display === undefined) return input.size; + const width = Math.min(input.size.width, display.width); + const height = Math.min(input.size.height, display.height); + let x = anchor.x + CASCADE_OFFSET_PX; + let y = anchor.y + CASCADE_OFFSET_PX; + if (x + width > display.x + display.width || y + height > display.y + display.height) { + x = display.x + CASCADE_OFFSET_PX; + y = display.y + CASCADE_OFFSET_PX; + } + return { + x: Math.round(Math.min(x, display.x + display.width - width)), + y: Math.round(Math.min(y, display.y + display.height - height)), + width, + height, + }; +} diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index cce59f08f6d12..f63de9c4818b0 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -48,6 +48,9 @@ import { import { syncBrowserChromeTheme } from "./hooks/useTheme"; import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration"; import { installDesktopPasteAsText } from "./lib/desktopPasteAsText"; +import { startDesktopWindowHub } from "./multiWindow/hub"; +import { registerDesktopWindowCommands } from "./multiWindow/ui/windowActions"; +import { isSecondaryDesktopWindow } from "./multiWindow/windowContext"; import { syncDocumentElectronPlatformClasses, syncDocumentWindowControlsOverlayClass, @@ -259,6 +262,8 @@ export function startAppServices(): AppRouter { // Ahead of the history: the provider auth code must leave the address before anything reads it. startProviderAuthDelivery(); + // App-wide duties run once, in the main window: secondary desktop windows only host UI. + const appWideWindow = !isSecondaryDesktopWindow(); // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues. const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory()); @@ -278,14 +283,15 @@ export function startAppServices(): AppRouter { startThemeBackground(); startBrowserChromeThemeSync(router); startDefaultThemeAdoption(); - startModelPreferencesMigration(); - startAgentOpenedPreviews(); + if (appWideWindow) startModelPreferencesMigration(); + if (appWideWindow) startAgentOpenedPreviews(); if (isElectron) startElectronBrowserHost(); startPreviewTitleRecording(); - startBrowserProfileReporting(); + if (appWideWindow) startBrowserProfileReporting(); installChatRouteCommands(router); installCommandPaletteCommands(router); registerOpenFavoriteEditorCommand(); + registerDesktopWindowCommands(); startThreadOverlayRetention(router); // Drafts promote as their server threads arrive, wherever the user is. subscribeDraftThreadPromotion({ @@ -303,7 +309,7 @@ export function startAppServices(): AppRouter { startMainAppLocationTracking(router); startWorkspaceFocus(router); startBackgroundThreadAnnouncements(appAtomRegistry, router); - startThreadVisitedMigration(appAtomRegistry); + if (appWideWindow) startThreadVisitedMigration(appAtomRegistry); startSshPasswordPromptQueue(); startKeybindingsUpdateToasts(); @@ -311,9 +317,12 @@ export function startAppServices(): AppRouter { startHostFreezeToasts(); startLegacyThreadMigrationToast(); startPermissionUpdateNotices(router); - startThreadNotifications(appAtomRegistry, router); - startGuideRunNotifications(appAtomRegistry, router); - if (isElectron) startDesktopUpdateLaunchNotice(); + if (appWideWindow) { + startThreadNotifications(appAtomRegistry, router); + startGuideRunNotifications(appAtomRegistry, router); + if (isElectron) startDesktopUpdateLaunchNotice(); + } + startDesktopWindowHub(); return router; } diff --git a/apps/web/src/browser/ElectronBrowserHost.tsx b/apps/web/src/browser/ElectronBrowserHost.tsx index e818b4b400dc1..ad9f60ff173dd 100644 --- a/apps/web/src/browser/ElectronBrowserHost.tsx +++ b/apps/web/src/browser/ElectronBrowserHost.tsx @@ -1,4 +1,4 @@ -import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; +import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { AuthPreviewOperateScope, type DesktopPreviewBridge, @@ -8,9 +8,14 @@ import { } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; -import { type ComponentProps, useState } from "react"; +import { type ComponentProps, useEffect, useState } from "react"; import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment"; +import { + publishHostedPreviewThreads, + useThreadsHostedElsewhere, +} from "~/multiWindow/previewHosting"; +import { isSecondaryDesktopWindow } from "~/multiWindow/windowContext"; import { isElectron } from "~/env"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; @@ -134,8 +139,23 @@ export function startElectronBrowserHost(): () => void { export function ElectronBrowserHost() { const previewByThreadKey = useActivePreviewSessions(); const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom); - useDesktopHostedPreviewSessions(primaryEnvironmentId); - const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId); + // Background previews belong to the main window; a secondary one hosts only what it shows. + const [secondaryWindow] = useState(isSecondaryDesktopWindow); + useDesktopHostedPreviewSessions(secondaryWindow ? null : primaryEnvironmentId); + const hostedElsewhere = useThreadsHostedElsewhere(); + const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId).filter( + (session) => !hostedElsewhere.has(scopedThreadKey(session.threadRef)), + ); + const hostedThreadKeys = secondaryWindow + ? [...new Set(sessions.map((session) => scopedThreadKey(session.threadRef)))] + .toSorted() + .join("\n") + : ""; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this window's hosted previews to the main window through shared storage + useEffect(() => { + if (!secondaryWindow) return; + return publishHostedPreviewThreads(hostedThreadKeys === "" ? [] : hostedThreadKeys.split("\n")); + }, [secondaryWindow, hostedThreadKeys]); if (!isElectron) return null; return ( diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 4610ef7542890..3745ed9b83d50 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -257,6 +257,7 @@ import { } from "./CommandPaletteAddProject"; import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems"; import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems"; +import { useCommandPaletteWindowItems } from "./CommandPaletteWindowItems"; import { PORT_FORWARD_GROUP_PREFIX, useCommandPalettePortForwardItem, @@ -558,6 +559,7 @@ function OpenCommandPaletteDialog(props: { activeThread: activeThread ?? null, query: deferredQuery, }); + const windowItems = useCommandPaletteWindowItems(); const currentView = viewStack.at(-1)?.view ?? null; const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : ""; const [browseGeneration, setBrowseGeneration] = useState(0); @@ -1678,6 +1680,7 @@ function OpenCommandPaletteDialog(props: { actionItems.push(changeAppearanceItem); actionItems.push(themeEditorItem); + actionItems.push(...windowItems); if (environments.some((environment) => environment.serverConfig !== null)) { actionItems.push({ diff --git a/apps/web/src/components/CommandPaletteWindowItems.tsx b/apps/web/src/components/CommandPaletteWindowItems.tsx new file mode 100644 index 0000000000000..f38e3ecb476f9 --- /dev/null +++ b/apps/web/src/components/CommandPaletteWindowItems.tsx @@ -0,0 +1,25 @@ +import { useGT } from "gt-react"; +import { AppWindowIcon } from "lucide-react"; +import { useState } from "react"; + +import { desktopWindowsBridge } from "../multiWindow/windowContext"; +import { openNewDesktopWindow } from "../multiWindow/ui/windowActions"; +import { ITEM_ICON_CLASS, type CommandPaletteActionItem } from "./CommandPalette.logic"; + +/** Desktop multi-window actions; empty on the web and in shells without multi-window support. */ +export function useCommandPaletteWindowItems(): ReadonlyArray { + const [bridge] = useState(desktopWindowsBridge); + const gt = useGT(); + if (bridge === null) return []; + return [ + { + kind: "action", + value: "action:window-new", + title: gt("New Window"), + searchTerms: ["new window", "window", "open window", "multiple windows"], + icon: , + shortcutCommand: "window.new", + run: async () => openNewDesktopWindow(bridge), + }, + ]; +} diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 9d03b7ab72e48..9907448c60914 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -517,6 +517,7 @@ const USAGE_COMMAND_LABELS: Record< const LATE_COMMAND_LABELS: Partial> = { "view.reopenClosed": msg("Reopen Closed Tab"), + "window.new": msg("New Window"), "preview.focusUrl": msg("Preview: Focus URL"), "preview.find": msg("Preview: Find on Page"), }; diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index c6942b7e01c88..d9bd98498b1d3 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -756,6 +756,57 @@ describe("composerDraftStore context persistence", () => { vi.resetModules(); } }); + + it("shows a draft another desktop window saved, without reverting it on its next save", async () => { + const sharedStorage = createMemoryStorage(); + vi.stubGlobal("localStorage", sharedStorage); + const context = { windowId: 2, isMain: false }; + vi.stubGlobal( + "window", + Object.assign(new EventTarget(), { + desktopBridge: { windows: { getContext: () => context } }, + }), + ); + vi.useFakeTimers(); + vi.resetModules(); + try { + const thisWindow = await import("./composerDraftStore"); + vi.resetModules(); + const otherWindow = await import("./composerDraftStore"); + const alphaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("alpha-window-thread")); + const betaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("beta-window-thread")); + const announceSave = () => + window.dispatchEvent( + Object.assign(new Event("storage"), { + key: COMPOSER_DRAFT_STORAGE_KEY, + newValue: sharedStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY), + }), + ); + + thisWindow.useComposerDraftStore.getState().setPrompt(alphaRef, "alpha draft"); + await vi.advanceTimersByTimeAsync(300); + otherWindow.useComposerDraftStore.getState().setPrompt(betaRef, "beta draft"); + await vi.advanceTimersByTimeAsync(300); + announceSave(); + + const drafts = thisWindow.useComposerDraftStore.getState().draftsByThreadKey; + expect(drafts[scopedThreadKey(betaRef)]?.prompt).toBe("beta draft"); + expect(drafts[scopedThreadKey(alphaRef)]?.prompt).toBe("alpha draft"); + + otherWindow.useComposerDraftStore.getState().setPrompt(betaRef, "beta edited"); + await vi.advanceTimersByTimeAsync(300); + thisWindow.useComposerDraftStore.getState().setPrompt(alphaRef, "alpha edited"); + await vi.advanceTimersByTimeAsync(300); + + const saved = JSON.parse(sharedStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) as string); + expect(saved.state.draftsByThreadKey[scopedThreadKey(betaRef)]?.prompt).toBe("beta edited"); + expect(saved.state.draftsByThreadKey[scopedThreadKey(alphaRef)]?.prompt).toBe("alpha edited"); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); }); describe("composerDraftStore thread contexts", () => { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 07eca76db05f3..629638b690c5e 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -97,6 +97,7 @@ import { persist, type PersistStorage, type StorageValue } from "zustand/middlew import { useShallow } from "zustand/react/shallow"; import { draftModelSelectionApplies } from "./lib/chatThreadActions"; import { createDeferredStorage, createMemoryStorage } from "./lib/storage"; +import { readDesktopWindowContext } from "./multiWindow/windowContext"; import { getDefaultServerModel } from "./providerModels"; import { replaceComposerContextReferences, @@ -4580,6 +4581,145 @@ composerDraftLoadedState = partializeComposerDraftStoreState(composerDraftStore. export const useComposerDraftStore = composerDraftStore; +type DraftRecordKey = + | "draftsByThreadKey" + | "draftThreadsByThreadKey" + | "logicalProjectDraftThreadKeyByLogicalProjectKey"; +const DRAFT_RECORD_KEYS: ReadonlyArray = [ + "draftsByThreadKey", + "draftThreadsByThreadKey", + "logicalProjectDraftThreadKeyByLogicalProjectKey", +]; +const DRAFT_STICKY_KEYS = [ + "stickyModelSelectionByProvider", + "stickyOptionsByModelByProvider", + "stickyActiveProvider", +] as const; + +interface AdoptedComposerDrafts { + /** Entries another window saved that this window had not changed; undefined removes one. */ + readonly records: { readonly [K in DraftRecordKey]: Record }; + readonly sticky: Partial< + Pick + >; + /** The baseline the next write merges against, now including the adopted entries. */ + readonly baseline: PersistedComposerDraftStoreState; + readonly changed: boolean; +} + +/** + * The read side of `mergeComposerDraftStates`: what another window saved since `baseline` + * replaces this window's entry only where this window has not changed it since. + */ +function adoptStoredComposerDrafts( + stored: PersistedComposerDraftStoreState, + local: PersistedComposerDraftStoreState, + baseline: PersistedComposerDraftStoreState, +): AdoptedComposerDrafts { + let changed = false; + const nextBaseline: Record = { ...baseline }; + const records = {} as Record>; + for (const field of DRAFT_RECORD_KEYS) { + const storedRecord: Readonly> = stored[field]; + const localRecord: Readonly> = local[field]; + const baselineRecord: Readonly> = baseline[field]; + const adopted: Record = {}; + const nextBaselineRecord: Record = { ...baselineRecord }; + for (const key of new Set([...Object.keys(storedRecord), ...Object.keys(baselineRecord)])) { + if (Equal.equals(storedRecord[key], baselineRecord[key])) continue; + if (!Equal.equals(localRecord[key], baselineRecord[key])) continue; + adopted[key] = storedRecord[key]; + if (storedRecord[key] === undefined) delete nextBaselineRecord[key]; + else nextBaselineRecord[key] = storedRecord[key]; + changed = true; + } + records[field] = adopted; + nextBaseline[field] = nextBaselineRecord; + } + const sticky: Record = {}; + for (const field of DRAFT_STICKY_KEYS) { + if (Equal.equals(stored[field], baseline[field])) continue; + if (!Equal.equals(local[field], baseline[field])) continue; + sticky[field] = stored[field]; + nextBaseline[field] = stored[field]; + changed = true; + } + return { + records, + sticky, + baseline: nextBaseline as PersistedComposerDraftStoreState, + changed, + }; +} + +function applyRecordChanges( + current: Readonly>, + adopted: Readonly>, + hydrate: (value: never) => V, +): Record { + const next = { ...current }; + for (const [key, value] of Object.entries(adopted)) { + if (value === undefined) delete next[key]; + else next[key] = hydrate(value as never); + } + return next; +} + +function adoptOtherWindowDrafts(text: string): void { + let parsed: StorageValue; + try { + parsed = JSON.parse(text) as StorageValue; + } catch { + return; + } + if (parsed.version !== COMPOSER_DRAFT_STORAGE_VERSION) return; + const baseline = composerDraftLastWrite?.local ?? composerDraftLoadedState; + if (baseline === null) return; + const stored = normalizeCurrentPersistedComposerDraftStoreState(parsed.state); + const adopted = adoptStoredComposerDrafts( + stored, + partializeComposerDraftStoreState(composerDraftStore.getState()), + baseline, + ); + composerDraftLastWrite = { text, local: adopted.baseline, merged: stored }; + if (!adopted.changed) return; + composerDraftStore.setState((state) => ({ + draftsByThreadKey: applyRecordChanges( + state.draftsByThreadKey, + adopted.records.draftsByThreadKey, + toHydratedThreadDraft, + ), + draftThreadsByThreadKey: applyRecordChanges( + state.draftThreadsByThreadKey, + adopted.records.draftThreadsByThreadKey, + toHydratedDraftThreadState, + ) as Record, + logicalProjectDraftThreadKeyByLogicalProjectKey: applyRecordChanges( + state.logicalProjectDraftThreadKeyByLogicalProjectKey, + adopted.records.logicalProjectDraftThreadKeyByLogicalProjectKey, + (value: string) => value, + ), + ...("stickyModelSelectionByProvider" in adopted.sticky + ? { stickyModelSelectionByProvider: adopted.sticky.stickyModelSelectionByProvider ?? {} } + : {}), + ...("stickyOptionsByModelByProvider" in adopted.sticky + ? { stickyOptionsByModelByProvider: adopted.sticky.stickyOptionsByModelByProvider ?? {} } + : {}), + ...("stickyActiveProvider" in adopted.sticky + ? { stickyActiveProvider: adopted.sticky.stickyActiveProvider ?? null } + : {}), + })); +} + +// Desktop windows share drafts through storage; each picks up what the others save. +if (readDesktopWindowContext() !== null && typeof window !== "undefined") { + window.addEventListener("storage", (event) => { + if (event.key === COMPOSER_DRAFT_STORAGE_KEY && event.newValue !== null) { + adoptOtherWindowDrafts(event.newValue); + } + }); +} + export function subscribeComposerDraftModelReconciliation(input: { readonly registry: AtomRegistry.AtomRegistry; readonly threadRefsAtom: Atom.Atom>; diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.ts index 6a3cc4acb43f3..2490d2d397940 100644 --- a/apps/web/src/connection/runtime.ts +++ b/apps/web/src/connection/runtime.ts @@ -10,6 +10,8 @@ import * as Layer from "effect/Layer"; import { Atom } from "effect/reactivity"; import { isGuestPage } from "../guestPage"; +import { isSecondaryDesktopWindow, readDesktopWindowContext } from "../multiWindow/windowContext"; +import { layerHubLeaseSource } from "../multiWindow/secondary"; import * as Runtime from "../lib/runtime"; import * as BackgroundActivityReporter from "../lib/backgroundActivityReporter"; @@ -34,11 +36,17 @@ type ConnectionLayerSource = const layerProvidedClientConnection = layerSnapshotLoader.pipe( Layer.provideMerge( - Connection.layerWithOptions({ - environmentThemes: true, - usageLimitSources: true, - usageLimitsCommand: true, - }), + Connection.layerWithOptions( + { + environmentThemes: true, + usageLimitSources: true, + usageLimitsCommand: true, + // The main desktop window serves other windows, which share its subscriptions. + shareStreams: readDesktopWindowContext()?.isMain === true, + }, + // A secondary desktop window shares the main window's sockets. + isSecondaryDesktopWindow() ? layerHubLeaseSource : undefined, + ), ), Layer.provideMerge( Layer.mergeAll( diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 9cb27b4cc2611..14a14d7129c4f 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -157,9 +157,7 @@ async function hydrateClientSettings(): Promise { if (persistedSettings) { replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings }); } - unsubscribeOtherTabClientSettings ??= subscribeBrowserClientSettingsWrites( - refreshClientSettingsFromOtherTab, - ); + unsubscribeOtherTabClientSettings ??= subscribeOtherWindowClientSettingsWrites(); setClientSettingsHydrationStatus("ready"); } catch (error) { if (hydrationGeneration === clientSettingsHydrationGeneration) { @@ -183,6 +181,19 @@ async function hydrateClientSettings(): Promise { return clientSettingsHydrationPromise; } +/** Browser tabs share storage events; desktop windows hear of the desktop's settings file writes. */ +function subscribeOtherWindowClientSettingsWrites(): () => void { + const unsubscribeTabs = subscribeBrowserClientSettingsWrites(refreshClientSettingsFromOtherTab); + const unsubscribeWindows = + typeof window === "undefined" + ? undefined + : window.desktopBridge?.onClientSettingsChanged?.(refreshClientSettingsFromOtherTab); + return () => { + unsubscribeTabs(); + unsubscribeWindows?.(); + }; +} + function refreshClientSettingsFromOtherTab(): void { void enqueueClientSettingsPersistence(async () => { const persistedSettings = await ensureLocalApi().persistence.getClientSettings(); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7900e73186091..6604147270dd5 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1969,6 +1969,7 @@ "9c6962c66efa5668": "Darstellung ändern", "074c1660aac1c7cf": "Design-Editor umschalten", "02c340f8d0bb7649": "Aktuell", + "9268423936e5989f": "Neues Fenster", "b8ec049821ce511c": "Berechtigungen: {label}", "f0d4573b2e03e2a7": "Berechtigungen", "38695f22426981d6": "Vorschau von {path}", @@ -12669,6 +12670,7 @@ "0e4b49c8203aae81": "Zeitüberschreitung beim Warten auf eine authentifizierte Sitzung nach dem Bootstrap.", "d7ffde2874d60d4f": "Gib ein Kopplungstoken ein, um fortzufahren.", "5d18537f82794deb": "Die lokale Umgebung ist deaktiviert.", + "67b874ad1deb2ab5": "Neues Fenster konnte nicht geöffnet werden", "d5ef094f40aedece": "Terminal-Eingabe", "f7046b10d49caab6": "Terminal-Verlauf", "24de858bbcf05f40": "Folie {number}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 5bdd7c383d319..c9cc4bbd6d72b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Change appearance", "074c1660aac1c7cf": "Toggle theme editor", "02c340f8d0bb7649": "Current", + "9268423936e5989f": "New Window", "b8ec049821ce511c": "Permissions: {label}", "f0d4573b2e03e2a7": "Permissions", "38695f22426981d6": "Preview {path}", @@ -12677,6 +12678,7 @@ "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", "d7ffde2874d60d4f": "Enter a pairing token to continue.", "5d18537f82794deb": "The local environment is disabled.", + "67b874ad1deb2ab5": "Couldn't open a new window", "d5ef094f40aedece": "Terminal input", "f7046b10d49caab6": "Terminal scrollback", "24de858bbcf05f40": "Slide {number}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 91dbb2b07f50f..a48a6e84a0947 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Cambiar apariencia", "074c1660aac1c7cf": "Mostrar u ocultar el editor de temas", "02c340f8d0bb7649": "Actual", + "9268423936e5989f": "Nueva ventana", "b8ec049821ce511c": "Permisos: {label}", "f0d4573b2e03e2a7": "Permisos", "38695f22426981d6": "Vista previa de {path}", @@ -12662,6 +12663,7 @@ "0e4b49c8203aae81": "Se agotó el tiempo de espera de la sesión autenticada tras el arranque.", "d7ffde2874d60d4f": "Introduce un token de emparejamiento para continuar.", "5d18537f82794deb": "El entorno local está desactivado.", + "67b874ad1deb2ab5": "No se pudo abrir una ventana nueva", "d5ef094f40aedece": "Entrada de la terminal", "f7046b10d49caab6": "Historial de desplazamiento de la terminal", "24de858bbcf05f40": "Diapositiva {number}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f5cf7e62a4744..ac59673409150 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Changer l’apparence", "074c1660aac1c7cf": "Afficher/masquer l’éditeur de thème", "02c340f8d0bb7649": "Actuel", + "9268423936e5989f": "Nouvelle fenêtre", "b8ec049821ce511c": "Autorisations : {label}", "f0d4573b2e03e2a7": "Autorisations", "38695f22426981d6": "Aperçu de {path}", @@ -12667,6 +12668,7 @@ "0e4b49c8203aae81": "Délai dépassé en attendant la session authentifiée après l’amorçage.", "d7ffde2874d60d4f": "Saisissez un jeton d’appairage pour continuer.", "5d18537f82794deb": "L’environnement local est désactivé.", + "67b874ad1deb2ab5": "Impossible d’ouvrir une nouvelle fenêtre", "d5ef094f40aedece": "Saisie du terminal", "f7046b10d49caab6": "Historique du terminal", "24de858bbcf05f40": "Diapositive {number}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 7e3be343b068b..baf98a6bfc3da 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1968,6 +1968,7 @@ "9c6962c66efa5668": "外観を変更", "074c1660aac1c7cf": "テーマエディターの切り替え", "02c340f8d0bb7649": "使用中", + "9268423936e5989f": "新しいウィンドウ", "b8ec049821ce511c": "権限: {label}", "f0d4573b2e03e2a7": "権限", "38695f22426981d6": "{path} をプレビュー", @@ -12610,6 +12611,7 @@ "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", "d7ffde2874d60d4f": "続行するにはペアリングトークンを入力してください。", "5d18537f82794deb": "ローカル環境は無効になっています。", + "67b874ad1deb2ab5": "新しいウィンドウを開けませんでした", "d5ef094f40aedece": "ターミナルの入力", "f7046b10d49caab6": "ターミナルのスクロールバック", "24de858bbcf05f40": "スライド {number}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index ef69858aead11..0976d4d356dd2 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "모양 변경", "074c1660aac1c7cf": "테마 편집기 전환", "02c340f8d0bb7649": "현재", + "9268423936e5989f": "새 창", "b8ec049821ce511c": "권한: {label}", "f0d4573b2e03e2a7": "권한", "38695f22426981d6": "{path} 미리 보기", @@ -12607,6 +12608,7 @@ "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", "d7ffde2874d60d4f": "계속하려면 페어링 토큰을 입력하세요.", "5d18537f82794deb": "로컬 환경이 꺼져 있습니다.", + "67b874ad1deb2ab5": "새 창을 열 수 없습니다", "d5ef094f40aedece": "터미널 입력", "f7046b10d49caab6": "터미널 스크롤백", "24de858bbcf05f40": "슬라이드 {number}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2f82a27a416..17e5bfff912da 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Mudar aparência", "074c1660aac1c7cf": "Alternar editor de temas", "02c340f8d0bb7649": "Atual", + "9268423936e5989f": "Nova janela", "b8ec049821ce511c": "Permissões: {label}", "f0d4573b2e03e2a7": "Permissões", "38695f22426981d6": "Pré-visualizar {path}", @@ -12667,6 +12668,7 @@ "0e4b49c8203aae81": "Tempo esgotado aguardando a sessão autenticada após a inicialização.", "d7ffde2874d60d4f": "Informe um token de pareamento para continuar.", "5d18537f82794deb": "O ambiente local está desativado.", + "67b874ad1deb2ab5": "Não foi possível abrir uma nova janela", "d5ef094f40aedece": "Entrada do terminal", "f7046b10d49caab6": "Histórico de rolagem do terminal", "24de858bbcf05f40": "Slide {number}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 2891cb8165d7c..b331b4d57cd8f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Изменить оформление", "074c1660aac1c7cf": "Показать/скрыть редактор темы", "02c340f8d0bb7649": "Текущая", + "9268423936e5989f": "Новое окно", "b8ec049821ce511c": "Разрешения: {label}", "f0d4573b2e03e2a7": "Разрешения", "38695f22426981d6": "Предпросмотр {path}", @@ -12668,6 +12669,7 @@ "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", "d7ffde2874d60d4f": "Введите токен сопряжения, чтобы продолжить.", "5d18537f82794deb": "Локальное окружение отключено.", + "67b874ad1deb2ab5": "Не удалось открыть новое окно", "d5ef094f40aedece": "Ввод терминала", "f7046b10d49caab6": "Прокрутка терминала", "24de858bbcf05f40": "Слайд {number}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c792d6fb4a981..f641de70d4dc3 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1970,6 +1970,7 @@ "9c6962c66efa5668": "Ändra utseende", "074c1660aac1c7cf": "Växla temaredigerare", "02c340f8d0bb7649": "Aktuellt", + "9268423936e5989f": "Nytt fönster", "b8ec049821ce511c": "Behörigheter: {label}", "f0d4573b2e03e2a7": "Behörigheter", "38695f22426981d6": "Förhandsvisa {path}", @@ -12675,6 +12676,7 @@ "0e4b49c8203aae81": "Tidsgränsen överskreds i väntan på en autentiserad session efter uppstart.", "d7ffde2874d60d4f": "Ange en parkopplingstoken för att fortsätta.", "5d18537f82794deb": "Den lokala miljön är inaktiverad.", + "67b874ad1deb2ab5": "Kunde inte öppna ett nytt fönster", "d5ef094f40aedece": "Terminalinmatning", "f7046b10d49caab6": "Terminalens rullningshistorik", "24de858bbcf05f40": "Bild {number}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cd80e9a35102a..c3490a202ed1c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1971,6 +1971,7 @@ "9c6962c66efa5668": "切换外观", "074c1660aac1c7cf": "开关主题编辑器", "02c340f8d0bb7649": "当前", + "9268423936e5989f": "新建窗口", "b8ec049821ce511c": "权限:{label}", "f0d4573b2e03e2a7": "权限", "38695f22426981d6": "预览 {path}", @@ -12686,6 +12687,7 @@ "0e4b49c8203aae81": "引导完成后等待登录状态超时。", "d7ffde2874d60d4f": "请输入配对 token 以继续。", "5d18537f82794deb": "本地环境已停用。", + "67b874ad1deb2ab5": "无法打开新窗口", "d5ef094f40aedece": "终端输入", "f7046b10d49caab6": "终端回滚缓冲", "24de858bbcf05f40": "幻灯片 {number}", diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 84463efc3abfd..2ce2fe870540c 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -400,6 +400,33 @@ describe("thread navigation helpers", () => { }); }); +describe("new window shortcut", () => { + it("opens a window only in the desktop app, apart from the no-project thread shortcut", () => { + const newWindow = event({ key: "n", ctrlKey: true, altKey: true, shiftKey: true }); + assert.strictEqual( + resolveShortcutCommand(newWindow, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context: { isDesktop: true }, + }), + "window.new", + ); + assert.isNull( + resolveShortcutCommand(newWindow, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context: { isDesktop: false }, + }), + ); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "n", ctrlKey: true, altKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { platform: "Linux", context: { isDesktop: true } }, + ), + "chat.newWithoutProject", + ); + }); +}); + describe("model picker navigation helpers", () => { it("keeps default model jumps off the web even while the picker is open", () => { const input = event({ key: "3", metaKey: true }); diff --git a/apps/web/src/multiWindow/hub.ts b/apps/web/src/multiWindow/hub.ts new file mode 100644 index 0000000000000..bcd356bc7b6a7 --- /dev/null +++ b/apps/web/src/multiWindow/hub.ts @@ -0,0 +1,126 @@ +import { EnvironmentRegistry, HubConnection } from "@t3tools/client-runtime/connection"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import { Atom } from "effect/reactivity"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { + type HubLinkRequest, + type HubLinkResponse, + isHubLinkRequest, + onHubLinkPort, + toRpcPort, +} from "./hubLink"; +import { desktopWindowsBridge, readDesktopWindowContext } from "./windowContext"; + +/** + * Serves secondary windows' environment connections from this window's own + * sessions. Each link is one secondary window; each lease relays one + * environment's RPC traffic over a dedicated port until that window releases it. + */ +const hubAtom = connectionAtomRuntime + .atom( + Effect.gen(function* () { + const bridge = desktopWindowsBridge(); + if (bridge === null) return; + const hubScope = yield* Effect.scope; + const runFork = Effect.runForkWith( + yield* Effect.context(), + ); + const links = new Map(); + + const serveLease = Effect.fn("DesktopWindowHub.serveLease")(function* ( + link: MessagePort, + linkScope: Scope.Scope, + leases: Map, + request: Extract, + ) { + const leaseScope = yield* Scope.fork(linkScope); + leases.set(request.leaseId, leaseScope); + const channel = new MessageChannel(); + const respond = (response: HubLinkResponse, transfer: Transferable[] = []) => + Effect.sync(() => link.postMessage(response, transfer)); + yield* HubConnection.serveHubLease( + EnvironmentId.make(request.environmentId), + toRpcPort(channel.port1), + ).pipe( + Scope.provide(leaseScope), + Effect.matchEffect({ + onSuccess: (prepared) => + respond( + { + type: "leased", + leaseId: request.leaseId, + prepared: HubConnection.encodePreparedConnection(prepared), + }, + [channel.port2], + ), + onFailure: (error) => + respond({ + type: "leaseFailed", + leaseId: request.leaseId, + error: HubConnection.encodeConnectionAttemptError(error), + }).pipe(Effect.andThen(Scope.close(leaseScope, Exit.void))), + }), + Effect.forkIn(leaseScope), + ); + }); + + const openLink = (port: MessagePort, peerWindowId: number) => { + const previous = links.get(peerWindowId); + if (previous !== undefined) runFork(Scope.close(previous, Exit.void)); + const linkScope = Scope.forkUnsafe(hubScope); + links.set(peerWindowId, linkScope); + const leases = new Map(); + const handle = (event: MessageEvent) => { + const request: unknown = event.data; + if (!isHubLinkRequest(request)) return; + if (request.type === "release") { + const lease = leases.get(request.leaseId); + leases.delete(request.leaseId); + if (lease !== undefined) runFork(Scope.close(lease, Exit.void)); + return; + } + runFork(serveLease(port, linkScope, leases, request)); + }; + port.addEventListener("message", handle); + port.start(); + runFork( + Scope.addFinalizer( + linkScope, + Effect.sync(() => { + port.removeEventListener("message", handle); + port.close(); + if (links.get(peerWindowId) === linkScope) links.delete(peerWindowId); + }), + ), + ); + }; + + const closeLink = (peerWindowId: number) => { + const link = links.get(peerWindowId); + if (link !== undefined) runFork(Scope.close(link, Exit.void)); + }; + + const stopListening = onHubLinkPort(openLink); + const stopPeerGone = bridge.onHubPeerGone(closeLink); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + stopListening(); + stopPeerGone(); + }), + ); + bridge.registerHub(); + return yield* Effect.never; + }), + ) + .pipe(Atom.keepAlive, Atom.withLabel("desktop-window-hub")); + +/** The main window serves every other window's connections for the life of the page. */ +export function startDesktopWindowHub(): void { + if (readDesktopWindowContext()?.isMain !== true) return; + appAtomRegistry.mount(hubAtom); +} diff --git a/apps/web/src/multiWindow/hubLink.ts b/apps/web/src/multiWindow/hubLink.ts new file mode 100644 index 0000000000000..d359fd22baeec --- /dev/null +++ b/apps/web/src/multiWindow/hubLink.ts @@ -0,0 +1,66 @@ +import { DESKTOP_HUB_LINK_MESSAGE_TYPE, type DesktopHubLinkMessage } from "@t3tools/contracts"; +import type { RpcPort } from "@t3tools/client-runtime/rpc"; +import * as Schema from "effect/Schema"; + +/** Messages a secondary window sends the hub over its link port. */ +const HubLinkRequest = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("lease"), + leaseId: Schema.Number, + environmentId: Schema.String, + }), + Schema.Struct({ type: Schema.Literal("release"), leaseId: Schema.Number }), +]); +export type HubLinkRequest = typeof HubLinkRequest.Type; +export const isHubLinkRequest = Schema.is(HubLinkRequest); + +/** The hub's answers. A `leased` message transfers the lease's session port. */ +const HubLinkResponse = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("leased"), + leaseId: Schema.Number, + prepared: Schema.Unknown, + }), + Schema.Struct({ + type: Schema.Literal("leaseFailed"), + leaseId: Schema.Number, + error: Schema.Unknown, + }), +]); +export type HubLinkResponse = typeof HubLinkResponse.Type; +export const isHubLinkResponse = Schema.is(HubLinkResponse); + +export function toRpcPort(port: MessagePort): RpcPort { + return { + postMessage: (message) => port.postMessage(message), + onMessage: (listener) => { + const handle = (event: MessageEvent) => listener(event.data); + port.addEventListener("message", handle); + port.start(); + return () => port.removeEventListener("message", handle); + }, + close: () => port.close(), + }; +} + +function isHubLinkMessage(data: unknown): data is DesktopHubLinkMessage { + return ( + typeof data === "object" && + data !== null && + (data as { readonly type?: unknown }).type === DESKTOP_HUB_LINK_MESSAGE_TYPE && + typeof (data as { readonly peerWindowId?: unknown }).peerWindowId === "number" + ); +} + +/** The preload hands link ports to the page with `window.postMessage`, as ports cannot cross the bridge. */ +export function onHubLinkPort( + listener: (port: MessagePort, peerWindowId: number) => void, +): () => void { + const handle = (event: MessageEvent) => { + const port = event.ports[0]; + if (event.source !== window || port === undefined || !isHubLinkMessage(event.data)) return; + listener(port, event.data.peerWindowId); + }; + window.addEventListener("message", handle); + return () => window.removeEventListener("message", handle); +} diff --git a/apps/web/src/multiWindow/previewHosting.test.ts b/apps/web/src/multiWindow/previewHosting.test.ts new file mode 100644 index 0000000000000..69882a0ea1f2d --- /dev/null +++ b/apps/web/src/multiWindow/previewHosting.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { threadsHostedByOtherWindows } from "./previewHosting"; + +describe("threadsHostedByOtherWindows", () => { + it("collects open secondary windows' threads and ignores its own, closed and broken lists", () => { + const hosted = threadsHostedByOtherWindows( + [ + ["t3code:desktop-window-previews:2", JSON.stringify(["env:a", "env:b"])], + ["t3code:desktop-window-previews:3", JSON.stringify(["env:c"])], + ["t3code:desktop-window-previews:1", JSON.stringify(["env:own"])], + ["t3code:desktop-window-previews:4", "not json"], + ["t3code:other", JSON.stringify(["env:x"])], + ], + new Set([1, 2, 4]), + 1, + ); + + expect([...hosted].toSorted()).toEqual(["env:a", "env:b"]); + }); +}); diff --git a/apps/web/src/multiWindow/previewHosting.ts b/apps/web/src/multiWindow/previewHosting.ts new file mode 100644 index 0000000000000..5ade60d32e6f5 --- /dev/null +++ b/apps/web/src/multiWindow/previewHosting.ts @@ -0,0 +1,104 @@ +import { useSyncExternalStore } from "react"; + +import { readDesktopWindowContext } from "./windowContext"; +import { readDesktopWindowsState, subscribeDesktopWindowsState } from "./windowsState"; + +const KEY_PREFIX = "t3code:desktop-window-previews:"; + +/** + * Threads whose previews another open window hosts, from each window's published list. + * Lists from windows that are no longer open are ignored, since a crash leaves them behind. + */ +export function threadsHostedByOtherWindows( + entries: ReadonlyArray, + openWindowIds: ReadonlySet, + ownWindowId: number, +): ReadonlySet { + const hosted = new Set(); + for (const [key, value] of entries) { + if (!key.startsWith(KEY_PREFIX) || value === null) continue; + const windowId = Number(key.slice(KEY_PREFIX.length)); + if (windowId === ownWindowId || !openWindowIds.has(windowId)) continue; + try { + const threadKeys: unknown = JSON.parse(value); + if (!Array.isArray(threadKeys)) continue; + for (const threadKey of threadKeys) if (typeof threadKey === "string") hosted.add(threadKey); + } catch {} + } + return hosted; +} + +/** A secondary window announces the threads whose previews it shows, so the main window skips them. */ +export function publishHostedPreviewThreads(threadKeys: ReadonlyArray): () => void { + const context = readDesktopWindowContext(); + if (context === null || context.isMain) return () => {}; + const key = `${KEY_PREFIX}${context.windowId}`; + try { + if (threadKeys.length === 0) window.localStorage.removeItem(key); + else window.localStorage.setItem(key, JSON.stringify(threadKeys)); + } catch {} + return () => { + try { + window.localStorage.removeItem(key); + } catch {} + }; +} + +const EMPTY: ReadonlySet = new Set(); +let cachedSignature = ""; +let cachedHosted: ReadonlySet = EMPTY; +// React reads the snapshot every render; storage is scanned only after a change. +let stale = true; + +function readHostedElsewhere(): ReadonlySet { + if (!stale) return cachedHosted; + stale = false; + const context = readDesktopWindowContext(); + const state = readDesktopWindowsState(); + if (context === null || !context.isMain || state === null || state.windows.length < 2) { + cachedSignature = ""; + cachedHosted = EMPTY; + return EMPTY; + } + const entries: Array = []; + try { + for (let index = 0; index < window.localStorage.length; index++) { + const key = window.localStorage.key(index); + if (key?.startsWith(KEY_PREFIX)) entries.push([key, window.localStorage.getItem(key)]); + } + } catch { + return EMPTY; + } + const hosted = threadsHostedByOtherWindows( + entries, + new Set(state.windows.map((open) => open.windowId)), + context.windowId, + ); + const signature = [...hosted].toSorted().join("\n"); + if (signature !== cachedSignature) { + cachedSignature = signature; + cachedHosted = hosted; + } + return cachedHosted; +} + +function subscribeHostedElsewhere(listener: () => void): () => void { + const changed = () => { + stale = true; + listener(); + }; + const onStorage = (event: StorageEvent) => { + if (event.key === null || event.key.startsWith(KEY_PREFIX)) changed(); + }; + window.addEventListener("storage", onStorage); + const unsubscribeWindows = subscribeDesktopWindowsState(changed); + return () => { + window.removeEventListener("storage", onStorage); + unsubscribeWindows(); + }; +} + +/** In the main window: threads a secondary window shows, whose previews it hosts instead. */ +export function useThreadsHostedElsewhere(): ReadonlySet { + return useSyncExternalStore(subscribeHostedElsewhere, readHostedElsewhere, () => EMPTY); +} diff --git a/apps/web/src/multiWindow/secondary.ts b/apps/web/src/multiWindow/secondary.ts new file mode 100644 index 0000000000000..9feb25fe05c8a --- /dev/null +++ b/apps/web/src/multiWindow/secondary.ts @@ -0,0 +1,170 @@ +import { + type ConnectionAttemptError, + ConnectionTransientError, + HubConnection, +} from "@t3tools/client-runtime/connection"; +import type { RpcPort } from "@t3tools/client-runtime/rpc"; +import type { DesktopWindowsBridge, EnvironmentId } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { type HubLinkRequest, isHubLinkResponse, onHubLinkPort, toRpcPort } from "./hubLink"; +import { desktopWindowsBridge } from "./windowContext"; + +const hubGone = (detail: string) => + new ConnectionTransientError({ reason: "transport", detail, hop: "device" }); + +const sendToHub = (port: MessagePort, request: HubLinkRequest) => port.postMessage(request); + +interface ActiveLease { + readonly result: Deferred.Deferred; + /** Ends the lease's session as if the relay had closed it. */ + end: (detail: string) => void; +} + +interface Link { + readonly port: MessagePort; + readonly leases: Map; +} + +/** A session port that can also be ended locally when the hub disappears without a word. */ +function endableRpcPort(port: MessagePort): { + readonly port: RpcPort; + readonly end: (detail: string) => void; +} { + const base = toRpcPort(port); + const listeners = new Set<(message: unknown) => void>(); + return { + port: { + ...base, + onMessage: (listener) => { + listeners.add(listener); + const stop = base.onMessage(listener); + return () => { + listeners.delete(listener); + stop(); + }; + }, + }, + end: (detail) => { + for (const listener of listeners) listener({ _tag: "RelayClosed", detail }); + }, + }; +} + +function makeLeaseSource(bridge: DesktopWindowsBridge) { + let link: Link | null = null; + let linkWaiters: Array<(link: Link) => void> = []; + let linkRequested = false; + let nextLeaseId = 1; + + const onResponse = (current: Link) => (event: MessageEvent) => { + const response: unknown = event.data; + if (!isHubLinkResponse(response)) return; + const lease = current.leases.get(response.leaseId); + if (lease === undefined) return; + if (response.type === "leaseFailed") { + current.leases.delete(response.leaseId); + Deferred.doneUnsafe( + lease.result, + Effect.fail(HubConnection.decodeConnectionAttemptError(response.error)), + ); + return; + } + const sessionPort = event.ports[0]; + if (sessionPort === undefined) return; + const endable = endableRpcPort(sessionPort); + lease.end = endable.end; + Deferred.doneUnsafe( + lease.result, + Effect.succeed({ + prepared: HubConnection.decodePreparedConnection(response.prepared), + port: endable.port, + }), + ); + }; + + onHubLinkPort((port) => { + dropLink("The main window replaced this window's link."); + const next: Link = { port, leases: new Map() }; + link = next; + linkRequested = false; + port.addEventListener("message", onResponse(next)); + port.start(); + const waiters = linkWaiters; + linkWaiters = []; + for (const waiter of waiters) waiter(next); + }); + + const dropLink = (detail: string) => { + const current = link; + link = null; + if (current === null) return; + for (const lease of current.leases.values()) { + Deferred.doneUnsafe(lease.result, Effect.fail(hubGone(detail))); + lease.end(detail); + } + current.leases.clear(); + current.port.close(); + }; + + bridge.onHubReset(() => { + linkRequested = false; + dropLink("The main window reloaded."); + // Sessions waiting on the old link reconnect through a fresh one. + if (linkWaiters.length > 0) { + linkRequested = true; + bridge.requestHubLink(); + } + }); + + const awaitLink = Effect.callback((resume) => { + if (link !== null) { + resume(Effect.succeed(link)); + return; + } + const waiter = (ready: Link) => resume(Effect.succeed(ready)); + linkWaiters.push(waiter); + if (!linkRequested) { + linkRequested = true; + bridge.requestHubLink(); + } + return Effect.sync(() => { + linkWaiters = linkWaiters.filter((candidate) => candidate !== waiter); + }); + }); + + return HubConnection.HubLeaseSource.of({ + lease: Effect.fn("DesktopHubLeaseSource.lease")(function* (environmentId: EnvironmentId) { + const current = yield* awaitLink; + const leaseId = nextLeaseId++; + const lease: ActiveLease = { + result: yield* Deferred.make(), + end: () => undefined, + }; + current.leases.set(leaseId, lease); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + current.leases.delete(leaseId); + if (link === current) { + sendToHub(current.port, { type: "release", leaseId }); + } + }), + ); + sendToHub(current.port, { type: "lease", leaseId, environmentId }); + return yield* Deferred.await(lease.result); + }), + }); +} + +/** Secondary windows connect every environment through the main window's sessions. */ +export const layerHubLeaseSource = Layer.effect( + HubConnection.HubLeaseSource, + Effect.suspend(() => { + const bridge = desktopWindowsBridge(); + return bridge === null + ? Effect.die(new Error("Secondary windows need the desktop windows bridge.")) + : Effect.succeed(makeLeaseSource(bridge)); + }), +); diff --git a/apps/web/src/multiWindow/ui/windowActions.ts b/apps/web/src/multiWindow/ui/windowActions.ts new file mode 100644 index 0000000000000..c8d75683481f7 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowActions.ts @@ -0,0 +1,41 @@ +import type { DesktopWindowsBridge } from "@t3tools/contracts"; +import { msg } from "gt-react"; + +import { toastManager } from "../../components/ui/toast"; +import { m } from "../../i18n/messages"; +import { registerCommands, registerMenuAction } from "../../shortcuts/dispatcher"; +import { desktopWindowsBridge } from "../windowContext"; + +function notifyWindowActionFailure(title: string, cause: unknown): void { + console.error(title, cause); + toastManager.add({ + type: "error", + title, + description: cause instanceof Error ? cause.message : undefined, + }); +} + +export function openNewDesktopWindow(bridge: DesktopWindowsBridge): void { + bridge.openNew().catch((cause: unknown) => { + notifyWindowActionFailure(m(msg("Couldn't open a new window")), cause); + }); +} + +/** The New Window shortcut and menu item; a no-op outside a multi-window desktop shell. */ +export function registerDesktopWindowCommands(): () => void { + const bridge = desktopWindowsBridge(); + if (bridge === null) return () => {}; + const disposers = [ + registerCommands({ + "window.new": (event) => { + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) openNewDesktopWindow(bridge); + }, + }), + registerMenuAction("new-window", () => openNewDesktopWindow(bridge)), + ]; + return () => { + for (const dispose of disposers) dispose(); + }; +} diff --git a/apps/web/src/multiWindow/windowContext.ts b/apps/web/src/multiWindow/windowContext.ts new file mode 100644 index 0000000000000..c686fb0203787 --- /dev/null +++ b/apps/web/src/multiWindow/windowContext.ts @@ -0,0 +1,24 @@ +import type { DesktopWindowContext, DesktopWindowsBridge } from "@t3tools/contracts"; + +export function desktopWindowsBridge(): DesktopWindowsBridge | null { + if (typeof window === "undefined") return null; + return window.desktopBridge?.windows ?? null; +} + +let cachedContext: DesktopWindowContext | null | undefined; + +/** Null outside a desktop shell with multi-window support. */ +export function readDesktopWindowContext(): DesktopWindowContext | null { + if (cachedContext !== undefined) return cachedContext; + try { + cachedContext = desktopWindowsBridge()?.getContext() ?? null; + } catch { + cachedContext = null; + } + return cachedContext; +} + +/** A secondary window hosts UI only; the main window's renderer owns its connections. */ +export function isSecondaryDesktopWindow(): boolean { + return readDesktopWindowContext()?.isMain === false; +} diff --git a/apps/web/src/multiWindow/windowsState.ts b/apps/web/src/multiWindow/windowsState.ts new file mode 100644 index 0000000000000..dba46d1ddb4e4 --- /dev/null +++ b/apps/web/src/multiWindow/windowsState.ts @@ -0,0 +1,46 @@ +import type { DesktopWindowsState } from "@t3tools/contracts"; + +import { desktopWindowsBridge } from "./windowContext"; + +let state: DesktopWindowsState | null = null; +let started = false; +const listeners = new Set<() => void>(); + +function publish(next: DesktopWindowsState): void { + state = next; + for (const listener of listeners) listener(); +} + +function ensureStarted(): void { + if (started) return; + const bridge = desktopWindowsBridge(); + if (bridge === null) return; + started = true; + let pushed = false; + bridge.onState((next) => { + pushed = true; + publish(next); + }); + // A push that lands first is newer than this snapshot. + void bridge.getState().then( + (next) => { + if (!pushed) publish(next); + }, + (cause: unknown) => { + console.error("Failed to read desktop windows state.", cause); + }, + ); +} + +export function readDesktopWindowsState(): DesktopWindowsState | null { + ensureStarted(); + return state; +} + +export function subscribeDesktopWindowsState(listener: () => void): () => void { + ensureStarted(); + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 3cbef77306c8e..17cbcddc4b1d3 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -61,6 +61,7 @@ import { readProject } from "../state/entities"; import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; +import { isSecondaryDesktopWindow } from "../multiWindow/windowContext"; export const Route = createRootRoute({ beforeLoad: async ({ location }) => { @@ -160,6 +161,7 @@ function RootRouteBranch() { const hostedPromptLinkLanding = useHostedPromptLinkLanding( authGateState.status === "hosted-static", ); + const secondaryWindow = isSecondaryDesktopWindow(); if (pathname === GUEST_PAGE_PATH) return ; @@ -186,13 +188,14 @@ function RootRouteBranch() { // first-run gate and the event router, whose first navigation would leave the page. const appHosts = ( <> - {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? ( + {/* The desktop routes activations and web links to the main window, which also keeps the app awake. */} + {(primaryEnvironmentAuthenticated || localEnvironmentDisabled) && !secondaryWindow ? ( <> ) : null} - {isElectron ? : null} + {isElectron && !secondaryWindow ? : null} diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 804757e78307a..a4a80a7d58e58 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -5,6 +5,7 @@ import { legacyProjectCwdPreferenceKey, markThreadUnread, markThreadVisited, + mergeSharedUiState, parsePersistedState, PERSISTED_STATE_KEY, type PersistedUiState, @@ -94,6 +95,35 @@ describe("uiStateStore pure functions", () => { }); }); +describe("mergeSharedUiState", () => { + it("keeps this window's changes over another window's save and takes the rest", () => { + const { sidebarProjectScopeKeys: _baselineScope, ...baseline } = makeUiState({ + projectExpandedById: { a: true, b: true }, + projectOrder: ["a", "b"], + threadLastVisitedAtById: { t1: "2026-01-01T00:00:00.000Z" }, + }); + const { sidebarProjectScopeKeys: _localScope, ...local } = makeUiState({ + projectExpandedById: { a: false, b: true }, + projectOrder: ["a", "b"], + threadLastVisitedAtById: { t1: "2026-01-01T00:00:00.000Z" }, + }); + const { sidebarProjectScopeKeys: _storedScope, ...stored } = makeUiState({ + projectExpandedById: { a: true, b: false }, + projectOrder: ["b", "a"], + threadLastVisitedAtById: { + t1: "2026-01-01T00:00:00.000Z", + t2: "2026-01-02T00:00:00.000Z", + }, + pullRequestMergeMethod: "squash", + }); + + expect(mergeSharedUiState(stored, local, baseline)).toEqual({ + ...stored, + projectExpandedById: { a: false, b: false }, + }); + }); +}); + describe("parsePersistedState", () => { it("hydrates raw UI-owned state without server entities", () => { const parsed = parsePersistedState({ diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index b2ac1a508c7a6..c8ce7db1ea1db 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -4,6 +4,8 @@ import * as Schema from "effect/Schema"; import { create } from "zustand"; import { normalizeProjectPathForComparison } from "@t3tools/client-runtime/state/projects"; +import { readDesktopWindowContext } from "./multiWindow/windowContext"; + export const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; const THREAD_CHANGED_FILES_EXPANSION_VERSION = 2; const LEGACY_PERSISTED_STATE_KEYS = [ @@ -209,11 +211,101 @@ function sanitizePersistedThreadChangedFilesExpanded( return nextState; } -export function persistState(state: UiState): void { +type SharedUiState = Omit; + +function sameValue(left: unknown, right: unknown): boolean { + return left === right || JSON.stringify(left) === JSON.stringify(right); +} + +function mergeRecord( + stored: Readonly>, + local: Readonly>, + baseline: Readonly>, +): Record { + const merged = { ...stored }; + for (const key of new Set([...Object.keys(local), ...Object.keys(baseline)])) { + if (sameValue(local[key], baseline[key])) continue; + const value = local[key]; + if (value === undefined) delete merged[key]; + else merged[key] = value; + } + return merged; +} + +/** + * Keeps what this window changed since `baseline` (the state it last read or wrote) over + * what other windows saved since. The project filter belongs to each window, so it is left out. + */ +export function mergeSharedUiState( + stored: SharedUiState, + local: SharedUiState, + baseline: SharedUiState, +): SharedUiState { + const pick = (key: K): SharedUiState[K] => + sameValue(local[key], baseline[key]) ? stored[key] : local[key]; + return { + projectExpandedById: mergeRecord( + stored.projectExpandedById, + local.projectExpandedById, + baseline.projectExpandedById, + ), + projectOrder: pick("projectOrder"), + threadLastVisitedAtById: mergeRecord( + stored.threadLastVisitedAtById, + local.threadLastVisitedAtById, + baseline.threadLastVisitedAtById, + ), + threadChangedFilesExpandedById: mergeRecord( + stored.threadChangedFilesExpandedById, + local.threadChangedFilesExpandedById, + baseline.threadChangedFilesExpandedById, + ), + defaultAdvertisedEndpointKey: pick("defaultAdvertisedEndpointKey"), + pullRequestMergeMethod: pick("pullRequestMergeMethod"), + }; +} + +function sharedStateChanged(left: SharedUiState, right: SharedUiState): boolean { + return (Object.keys(right) as Array).some( + (key) => !sameValue(left[key], right[key]), + ); +} + +// Desktop windows share this storage; null outside a multi-window desktop shell. +const windowContext = readDesktopWindowContext(); +let persistedBaseline: UiState | null = null; + +function readStoredState(): UiState | null { + try { + const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); + return raw ? parsePersistedState(JSON.parse(raw) as PersistedUiState) : null; + } catch { + return null; + } +} + +/** What this window writes: its own changes over other windows' saves, and only its own filter. */ +function resolveStateToPersist(state: UiState): UiState { + if (windowContext === null) return state; + const stored = readStoredState(); + if (stored === null) return state; + const merged = mergeSharedUiState(stored, state, persistedBaseline ?? stored); + return { + ...merged, + // A secondary window's filter is its own, never the main window's state. + sidebarProjectScopeKeys: windowContext.isMain + ? state.sidebarProjectScopeKeys + : stored.sidebarProjectScopeKeys, + }; +} + +export function persistState(current: UiState): void { if (typeof window === "undefined") { return; } try { + const state = resolveStateToPersist(current); + persistedBaseline = state; window.localStorage.setItem( PERSISTED_STATE_KEY, JSON.stringify({ @@ -437,8 +529,14 @@ interface UiStateStore extends UiState { ) => void; } +function readInitialState(): UiState { + const state = readPersistedState(); + persistedBaseline = state; + return state; +} + export const useUiStateStore = create((set) => ({ - ...readPersistedState(), + ...readInitialState(), markThreadVisited: (threadId, visitedAt) => set((state) => markThreadVisited(state, threadId, visitedAt)), markThreadUnread: (threadId, latestTurnCompletedAt) => @@ -460,6 +558,19 @@ export const useUiStateStore = create((set) => ({ useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state)); +if (windowContext !== null && typeof window !== "undefined") { + // Another window saved: take its changes to state this window has not changed since. + window.addEventListener("storage", (event) => { + if (event.key !== PERSISTED_STATE_KEY || event.newValue === null) return; + const stored = readStoredState(); + if (stored === null) return; + const local = useUiStateStore.getState(); + const merged = mergeSharedUiState(stored, local, persistedBaseline ?? stored); + persistedBaseline = stored; + if (sharedStateChanged(local, merged)) useUiStateStore.setState(merged); + }); +} + if (typeof window !== "undefined" && typeof window.addEventListener === "function") { window.addEventListener("beforeunload", () => { debouncedPersistState.flush(); diff --git a/docs/README.md b/docs/README.md index 622d31096da05..e1cb610ab8982 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,6 +5,7 @@ - [Install T3 Code](./user/install.md) - [Messages and context](./user/composer.md) - [Working with threads](./user/thread-sidebar.md) +- [Multiple windows](./user/multiple-windows.md) - [Permission modes](./user/permission-modes.md) - [Terminal history](./user/terminal.md) - [Source control](./user/source-control.md) diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index eab9e88ec98f0..b77939bbb6c3b 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -195,6 +195,9 @@ through the pages you have visited, like a browser's back and forward buttons. [new-thread defaults](./thread-sidebar.md#start-a-thread). `chat.newWithoutProject` (`mod+alt+n`) starts a thread [without a project](./thread-sidebar.md#start-without-a-project). +`window.new` (`mod+alt+shift+n`) opens another window in the desktop app. See +[Multiple windows](./multiple-windows.md). + ## Reserved shortcuts In the desktop app, `mod+w` closes the focused terminal or the active right-panel diff --git a/docs/user/multiple-windows.md b/docs/user/multiple-windows.md new file mode 100644 index 0000000000000..7a4934b817309 --- /dev/null +++ b/docs/user/multiple-windows.md @@ -0,0 +1,14 @@ +# Multiple windows + +The desktop app can open more than one window, so you can keep different threads side by side. All +windows share the same environments, threads, and settings. The web app and mobile app use a single +window. + +## Open a window + +Choose **New Window** in the command palette or the app menu, or press **Cmd+Option+Shift+N** on +macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. Change the shortcut under +**Settings → Keybindings** (`window.new`). + +Closing the main window while others are open hides it instead, since the other windows connect +through it. It closes once the last other window does. diff --git a/packages/client-runtime/src/connection/hub.test.ts b/packages/client-runtime/src/connection/hub.test.ts new file mode 100644 index 0000000000000..1b40ab6b9177d --- /dev/null +++ b/packages/client-runtime/src/connection/hub.test.ts @@ -0,0 +1,37 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; + +import { + decodeConnectionAttemptError, + decodePreparedConnection, + encodeConnectionAttemptError, + encodePreparedConnection, +} from "./hub.ts"; +import { ConnectionBlockedError, RelayConnectionTarget, type PreparedConnection } from "./model.ts"; + +describe("HubConnection window boundary", () => { + it("rebuilds a lease's connection and failures after a structured clone", () => { + const prepared: PreparedConnection = { + environmentId: EnvironmentId.make("environment-1"), + label: "Remote", + httpBaseUrl: "https://remote.example.test", + socketUrl: "wss://remote.example.test/ws", + httpAuthorization: { _tag: "Dpop", accessToken: "token", expiresAtEpochMs: 1 }, + target: new RelayConnectionTarget({ + environmentId: EnvironmentId.make("environment-1"), + label: "Remote", + }), + }; + const error = new ConnectionBlockedError({ reason: "permission", detail: "No access." }); + + const received = decodePreparedConnection(structuredClone(encodePreparedConnection(prepared))); + const failure = decodeConnectionAttemptError( + structuredClone(encodeConnectionAttemptError(error)), + ); + + expect(received).toEqual(prepared); + expect(received.target).toBeInstanceOf(RelayConnectionTarget); + expect(failure).toBeInstanceOf(ConnectionBlockedError); + expect(failure.message).toBe("No access."); + }); +}); diff --git a/packages/client-runtime/src/connection/hub.ts b/packages/client-runtime/src/connection/hub.ts new file mode 100644 index 0000000000000..c6b48ca50dd39 --- /dev/null +++ b/packages/client-runtime/src/connection/hub.ts @@ -0,0 +1,195 @@ +import { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import * as ConnectionDriver from "./driver.ts"; +import { + type ConnectionAttemptError, + ConnectionBlockedError, + ConnectionTarget, + ConnectionTransientError, + type PreparedConnection, +} from "./model.ts"; +import * as EnvironmentRegistry from "./registry.ts"; +import * as EnvironmentSupervisor from "./supervisor.ts"; +import type { RpcPort } from "../rpc/relay.ts"; +import * as RpcSession from "../rpc/session.ts"; + +const PreparedHttpAuthorization = Schema.Union([ + Schema.TaggedStruct("Bearer", { token: Schema.String }), + Schema.TaggedStruct("Dpop", { accessToken: Schema.String, expiresAtEpochMs: Schema.Number }), +]); + +const PreparedConnectionSchema = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + httpBaseUrl: Schema.String, + socketUrl: Schema.String, + httpAuthorization: Schema.NullOr(PreparedHttpAuthorization), + target: ConnectionTarget, + descriptor: Schema.optionalKey(ExecutionEnvironmentDescriptor), +}); + +const ConnectionAttemptErrorSchema = Schema.Union([ + ConnectionTransientError, + ConnectionBlockedError, +]); + +/** Plain values for crossing a window boundary, where class instances lose their prototype. */ +export const encodePreparedConnection = Schema.encodeSync( + Schema.toCodecJson(PreparedConnectionSchema), +); +export const decodePreparedConnection = Schema.decodeUnknownSync( + Schema.toCodecJson(PreparedConnectionSchema), +); +export const encodeConnectionAttemptError = Schema.encodeSync( + Schema.toCodecJson(ConnectionAttemptErrorSchema), +); +export const decodeConnectionAttemptError = Schema.decodeUnknownSync( + Schema.toCodecJson(ConnectionAttemptErrorSchema), +); + +export interface HubLease { + readonly prepared: PreparedConnection; + readonly port: RpcPort; +} + +/** How a secondary window asks the hub window for one environment's connection. */ +export class HubLeaseSource extends Context.Service< + HubLeaseSource, + { + /** The lease ends, and the hub stops relaying, when the scope closes. */ + readonly lease: ( + environmentId: EnvironmentId, + ) => Effect.Effect; + } +>()("@t3tools/client-runtime/connection/hub/HubLeaseSource") {} + +/** + * The connection driver of a secondary window: every environment connects + * through the hub window's existing session instead of a socket of its own. + */ +const makeHubDriver = Effect.gen(function* () { + const hub = yield* HubLeaseSource; + const sessions = yield* RpcSession.RpcSessionFactory; + return ConnectionDriver.ConnectionDriver.of({ + connect: Effect.fn("HubConnectionDriver.connect")(function* (entry, reportProgress) { + yield* Effect.annotateCurrentSpan({ + "connection.environment.id": entry.target.environmentId, + }); + yield* reportProgress({ stage: "preparing" }); + const { prepared, port } = yield* hub.lease(entry.target.environmentId); + yield* reportProgress({ stage: "opening", prepared }); + const session = yield* sessions.connectOverPort(prepared, port); + yield* reportProgress({ stage: "synchronizing", prepared }); + yield* session.ready; + // The hub owns route choice, so it alone reports refused routes. + return { + prepared, + session, + refusedRouteIds: [], + } satisfies ConnectionDriver.EnvironmentConnectionLease; + }), + // Route choice belongs to the hub, which owns the socket. + preflight: Effect.fn("HubConnectionDriver.preflight")(function* () { + return yield* Effect.succeed("unchecked" as const); + }), + checkHost: Effect.fn("HubConnectionDriver.checkHost")(function* () { + return yield* Effect.succeed("answered" as const); + }), + }); +}); + +export const layerHubDriver = Layer.effect(ConnectionDriver.ConnectionDriver, makeHubDriver); + +type HubSessionState = + | { + readonly _tag: "Ready"; + readonly prepared: PreparedConnection; + readonly session: RpcSession.RpcSession; + } + | { readonly _tag: "Blocked"; readonly error: ConnectionAttemptError }; + +const hubSessionStates = Stream.unwrap( + Effect.gen(function* () { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + return Stream.merge( + SubscriptionRef.changes(supervisor.session), + SubscriptionRef.changes(supervisor.state), + ).pipe( + Stream.mapEffect(() => + Effect.all([ + SubscriptionRef.get(supervisor.session), + SubscriptionRef.get(supervisor.prepared), + SubscriptionRef.get(supervisor.state), + ]), + ), + Stream.map(([session, prepared, state]): Option.Option => { + if (Option.isSome(session) && Option.isSome(prepared)) { + return Option.some({ _tag: "Ready", prepared: prepared.value, session: session.value }); + } + if (state.phase === "blocked" && state.lastFailure !== null) { + return Option.some({ _tag: "Blocked", error: state.lastFailure }); + } + return Option.none(); + }), + Stream.filter(Option.isSome), + Stream.map((state) => state.value), + ); + }), +); + +/** + * The hub's side of a lease: waits for this window's own session to the + * environment, then relays `port` through it until the scope closes or the + * session ends. A blocked environment fails the lease with its own error. + */ +export const serveHubLease = Effect.fn("HubConnection.serveLease")(function* ( + environmentId: EnvironmentId, + port: RpcPort, +) { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + const head = yield* registry.followStream(environmentId, hubSessionStates).pipe(Stream.runHead); + if (Option.isNone(head)) { + return yield* new ConnectionTransientError({ + reason: "endpoint-unavailable", + detail: "The main window no longer has this environment.", + }); + } + const state = head.value; + if (state._tag === "Blocked") return yield* state.error; + const { prepared, session } = state; + if (session.relay === undefined) { + return yield* new ConnectionTransientError({ + reason: "transport", + detail: `${prepared.label} cannot be shared with another window.`, + }); + } + const relay = yield* session.relay(port); + // A session that ends or is replaced takes its relays with it, so the window reconnects at once. + const supervisor = yield* registry + .run(environmentId, EnvironmentSupervisor.EnvironmentSupervisor) + .pipe( + Effect.mapError( + () => + new ConnectionTransientError({ + reason: "endpoint-unavailable", + detail: "The main window no longer has this environment.", + }), + ), + ); + yield* Effect.raceFirst( + session.closed.pipe(Effect.ignore), + SubscriptionRef.changes(supervisor.session).pipe( + Stream.filter((current) => Option.getOrNull(current) !== session), + Stream.runHead, + ), + ).pipe(Effect.andThen(relay.close("The main window's connection ended.")), Effect.forkScoped); + return prepared; +}); diff --git a/packages/client-runtime/src/connection/index.ts b/packages/client-runtime/src/connection/index.ts index 02a30adb57fae..7c7c6d8fe9388 100644 --- a/packages/client-runtime/src/connection/index.ts +++ b/packages/client-runtime/src/connection/index.ts @@ -17,6 +17,7 @@ export * as EnvironmentRegistry from "./registry.ts"; // Flat so consumers' inferred types can name them. export { EnvironmentNotRegisteredError, PlatformEnvironmentRemovalError } from "./registry.ts"; export * as EnvironmentSupervisor from "./supervisor.ts"; +export * as HubConnection from "./hub.ts"; export * as Wakeups from "./wakeups.ts"; export { orchestrationProtocolCompatibilityError } from "./compatibility.ts"; diff --git a/packages/client-runtime/src/connection/layer.ts b/packages/client-runtime/src/connection/layer.ts index 0ab9e0d2f96b1..dd6ada5dddef0 100644 --- a/packages/client-runtime/src/connection/layer.ts +++ b/packages/client-runtime/src/connection/layer.ts @@ -8,6 +8,7 @@ import { orchestrationProtocolCompatibilityError } from "./compatibility.ts"; import * as ConnectionResolver from "./resolver.ts"; import * as ConnectionDriver from "./driver.ts"; +import * as HubConnection from "./hub.ts"; import * as EnvironmentRegistry from "./registry.ts"; import * as ConnectionOnboarding from "./onboarding.ts"; import { connectionRoutes, hasRelayRoute } from "./routes.ts"; @@ -71,10 +72,22 @@ export const watchDiscoveredCompatibility = Effect.fn("connection.watchDiscovere }, ); -export function layerWithOptions(options: RpcSession.RpcSessionOptions) { - const layerDriver = ConnectionDriver.layer.pipe( - Layer.provide(Layer.mergeAll(ConnectionResolver.layer, RpcSession.layer(options))), +/** + * With `hubLeases`, environments connect through another window's sessions + * (see `HubConnection`) instead of opening sockets of their own. + */ +export function layerWithOptions( + options: RpcSession.RpcSessionOptions, + hubLeases?: Layer.Layer, +) { + const layerSessions = RpcSession.layer(options); + const layerSocketDriver = ConnectionDriver.layer.pipe( + Layer.provide(Layer.mergeAll(ConnectionResolver.layer, layerSessions)), ); + const layerDriver: typeof layerSocketDriver = + hubLeases === undefined + ? layerSocketDriver + : HubConnection.layerHubDriver.pipe(Layer.provide(Layer.mergeAll(layerSessions, hubLeases))); const layerRegistry = EnvironmentRegistry.layer.pipe(Layer.provide(layerDriver)); const layerOnboarding = ConnectionOnboarding.layer.pipe(Layer.provide(layerRegistry)); const layerConnectionServices = Layer.mergeAll( diff --git a/packages/client-runtime/src/rpc/index.ts b/packages/client-runtime/src/rpc/index.ts index e0e269bdfa8ad..1e970329e9116 100644 --- a/packages/client-runtime/src/rpc/index.ts +++ b/packages/client-runtime/src/rpc/index.ts @@ -2,3 +2,4 @@ export * from "./client.ts"; export * from "./http.ts"; export type { WsRpcProtocolClient } from "./protocol.ts"; export { type RpcSession } from "./session.ts"; +export { type RpcPort } from "./relay.ts"; diff --git a/packages/client-runtime/src/rpc/relay.ts b/packages/client-runtime/src/rpc/relay.ts new file mode 100644 index 0000000000000..cbceb3682a5b8 --- /dev/null +++ b/packages/client-runtime/src/rpc/relay.ts @@ -0,0 +1,357 @@ +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import * as RpcClient from "effect/rpc/RpcClient"; +import * as RpcClientError from "effect/rpc/RpcClientError"; +import type { FromClientEncoded, FromServerEncoded, RequestEncoded } from "effect/rpc/RpcMessage"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; + +/** + * One end of a message channel carrying encoded RPC messages, such as a DOM + * `MessagePort` between two windows. Messages are plain JSON-compatible values. + */ +export interface RpcPort { + readonly postMessage: (message: unknown) => void; + readonly onMessage: (listener: (message: unknown) => void) => () => void; + readonly close: () => void; +} + +/** Sent by the relay instead of forwarding a transport failure, then the port closes. */ +export interface RelayClosedMessage { + readonly _tag: "RelayClosed"; + readonly detail: string; +} + +/** Fails only these requests, which then resubscribe; the relay stays open. */ +interface RelayRequestsFailedMessage { + readonly _tag: "RelayRequestsFailed"; + readonly requestIds: ReadonlyArray; + readonly detail: string; +} + +const relayTag = (message: unknown): unknown => + typeof message === "object" && message !== null + ? (message as { readonly _tag?: unknown })._tag + : undefined; +const isRelayClosedMessage = (message: unknown): message is RelayClosedMessage => + relayTag(message) === "RelayClosed"; +const isRelayRequestsFailedMessage = (message: unknown): message is RelayRequestsFailedMessage => + relayTag(message) === "RelayRequestsFailed"; + +export interface RelayHandle { + /** Ends the relay now; the secondary's session closes and reconnects. */ + readonly close: (detail: string) => Effect.Effect; +} + +/** + * A stream the relay serves from state the hub already holds instead of + * opening another subscription on the server. `encode` turns a chunk of + * `items` into the RPC's encoded chunk values. + */ +export interface SharedRelayStream { + readonly tag: string; + readonly matches: (payload: unknown) => boolean; + readonly items: Stream.Stream; + readonly encode: (values: ReadonlyArray) => Effect.Effect; +} + +/** Runs port messages one at a time and in arrival order, like a socket's frames. */ +const makeSerialRunner = ( + runFork: (effect: Effect.Effect) => unknown, + handle: (message: A) => Effect.Effect, +) => { + const queue: Array = []; + let draining = false; + const drain = Effect.gen(function* () { + while (queue.length > 0) { + yield* handle(queue.shift()!); + } + }).pipe( + Effect.ensuring( + Effect.sync(() => { + draining = false; + }), + ), + ); + return (message: A) => { + queue.push(message); + if (draining) return; + draining = true; + runFork(drain); + }; +}; + +// RpcClient numbers its clients from 0 within one JavaScript realm, so relay +// clients sharing the hub's protocol start far above any realistic count. +let nextRelayClientId = 1_000_000_000; + +/** + * Serves a secondary window's RpcClient over `port` through the hub's socket. + * Request ids are renamed on the way in and restored on the way out: each + * window numbers requests from its own counter, and the server keys them per socket. + */ +export const serveRelay = Effect.fnUntraced(function* (options: { + readonly protocol: RpcClient.Protocol["Service"]; + readonly port: RpcPort; + readonly shared?: ReadonlyArray; +}): Effect.fn.Return { + const { protocol, port } = options; + const runFork = Effect.runForkWith(yield* Effect.context()); + const clientId = nextRelayClientId++; + const prefix = `relay${clientId}:`; + // Hub id -> the secondary's original id, whose type the secondary's client keys on. + const forwarded = new Map(); + const sharedFibers = new Map>(); + let closed = false; + + const toHubId = (id: string | number) => `${prefix}${String(id)}`; + + // The port itself closes with the scope: closing right after the last post could drop it. + const close = (detail: string) => + Effect.sync(() => { + if (closed) return; + closed = true; + try { + port.postMessage({ _tag: "RelayClosed", detail } satisfies RelayClosedMessage); + } catch {} + }); + + const post = (message: FromServerEncoded) => + Effect.sync(() => { + if (!closed) port.postMessage(message); + }); + + const restore = (requestId: string | number) => + typeof requestId === "string" ? forwarded.get(requestId) : undefined; + + yield* protocol + .run(clientId, (response) => { + switch (response._tag) { + case "Chunk": + case "Exit": { + const original = restore(response.requestId); + if (original === undefined) return Effect.void; + if (response._tag === "Exit") forwarded.delete(String(response.requestId)); + return post({ ...response, requestId: original }); + } + case "ClientProtocolError": { + if (response.requestIds === undefined) return close(response.error.message); + const requestIds = response.requestIds.flatMap((requestId) => { + const original = restore(requestId); + if (original === undefined) return []; + forwarded.delete(String(requestId)); + return [original]; + }); + if (requestIds.length === 0) return Effect.void; + return Effect.sync(() => { + if (closed) return; + port.postMessage({ + _tag: "RelayRequestsFailed", + requestIds, + detail: response.error.message, + } satisfies RelayRequestsFailedMessage); + }); + } + case "Pong": + return Effect.void; + default: + return post(response); + } + }) + .pipe(Effect.forkScoped); + + const serveShared = (shared: SharedRelayStream, request: RequestEncoded) => { + const fiber = shared.items.pipe( + Stream.runForEachArray((values) => + values.length === 0 + ? Effect.void + : shared + .encode(values) + .pipe( + Effect.flatMap((encoded) => + post({ _tag: "Chunk", requestId: request.id, values: encoded as never }), + ), + ), + ), + // Shared streams outlive any one subscriber, so their end means the hub's session ended. + Effect.matchCauseEffect({ + onSuccess: () => close("The main window's shared subscription ended."), + onFailure: (cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : close("The main window's shared subscription failed."), + }), + Effect.ensuring(Effect.sync(() => sharedFibers.delete(request.id))), + ); + sharedFibers.set(request.id, runFork(fiber)); + }; + + const handle = (message: FromClientEncoded): Effect.Effect => { + switch (message._tag) { + case "Request": { + const shared = options.shared?.find( + (candidate) => candidate.tag === message.tag && candidate.matches(message.payload), + ); + if (shared !== undefined) { + serveShared(shared, message); + return Effect.void; + } + const hubId = toHubId(message.id); + forwarded.set(hubId, message.id); + return protocol.send(clientId, { ...message, id: hubId }).pipe( + Effect.catch((error: RpcClientError.RpcClientError) => { + forwarded.delete(hubId); + return close(error.message); + }), + ); + } + case "Ack": + case "Interrupt": { + const fiber = sharedFibers.get(message.requestId); + if (fiber !== undefined) { + return message._tag === "Interrupt" ? Fiber.interrupt(fiber) : Effect.void; + } + const hubId = toHubId(message.requestId); + if (!forwarded.has(hubId)) return Effect.void; + if (message._tag === "Interrupt") forwarded.delete(hubId); + return protocol + .send(clientId, { ...message, requestId: hubId }) + .pipe(Effect.catch((error) => close(error.message))); + } + default: + return Effect.void; + } + }; + + const enqueue = makeSerialRunner(runFork, handle); + const stopListening = port.onMessage((message) => { + if (!closed) enqueue(message as FromClientEncoded); + }); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + stopListening(); + for (const fiber of sharedFibers.values()) yield* Fiber.interrupt(fiber); + // The server keeps streaming to an abandoned id until it hears an interrupt. + for (const hubId of forwarded.keys()) { + yield* protocol.send(clientId, { _tag: "Interrupt", requestId: hubId }).pipe(Effect.ignore); + } + forwarded.clear(); + yield* close("The main window closed this connection."); + port.close(); + }), + ); + + return { + close: Effect.fn("RelayHandle.close")(function* (detail: string) { + for (const fiber of sharedFibers.values()) yield* Fiber.interrupt(fiber); + yield* close(detail); + }), + } satisfies RelayHandle; +}); + +/** + * The secondary window's end: an RpcClient protocol whose requests travel over + * `port` to a relay in the hub. `onClosed` runs once when the relay goes away. + */ +export const makePortProtocol = (options: { + readonly port: RpcPort; + readonly onMessage?: () => void; + readonly onClosed: (detail: string) => Effect.Effect; +}): Effect.Effect => + RpcClient.Protocol.make( + Effect.fnUntraced(function* (writeResponse, clientIds) { + const { port } = options; + const runFork = Effect.runForkWith(yield* Effect.context()); + const requestClients = new Map(); + let closedError: RpcClientError.RpcClientError | undefined; + + const broadcast = (response: FromServerEncoded) => + Effect.forEach(Array.from(clientIds), (clientId) => writeResponse(clientId, response), { + discard: true, + }); + + const fail = (detail: string) => + Effect.suspend(() => { + if (closedError !== undefined) return Effect.void; + closedError = new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ message: detail, cause: undefined }), + }); + requestClients.clear(); + return broadcast({ _tag: "ClientProtocolError", error: closedError }).pipe( + Effect.uninterruptible, + Effect.andThen(options.onClosed(detail)), + ); + }); + + const receive = (message: unknown): Effect.Effect => { + if (isRelayClosedMessage(message)) return fail(message.detail); + if (isRelayRequestsFailedMessage(message)) { + const error = new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ + message: message.detail, + cause: undefined, + }), + }); + return Effect.forEach( + message.requestIds, + (requestId) => { + const clientId = requestClients.get(requestId); + requestClients.delete(requestId); + return clientId === undefined + ? Effect.void + : writeResponse(clientId, { + _tag: "ClientProtocolError", + error, + requestIds: [requestId], + }); + }, + { discard: true }, + ); + } + const response = message as FromServerEncoded; + if ("requestId" in response) { + const clientId = requestClients.get(response.requestId); + if (clientId === undefined) return Effect.void; + if (response._tag === "Exit") requestClients.delete(response.requestId); + return writeResponse(clientId, response); + } + return broadcast(response); + }; + + const enqueue = makeSerialRunner(runFork, receive); + const stopListening = port.onMessage((message) => { + options.onMessage?.(); + enqueue(message); + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + stopListening(); + port.close(); + }), + ); + + return { + send: (_clientId, request) => { + if (closedError !== undefined) return Effect.fail(closedError); + switch (request._tag) { + case "Request": + requestClients.set(request.id, _clientId); + break; + case "Interrupt": + requestClients.delete(request.requestId); + break; + case "Ping": + case "Eof": + return Effect.void; + } + return Effect.sync(() => port.postMessage(request)); + }, + supportsAck: true, + supportsTransferables: false, + codecFor: RpcSerialization.json.codecFor, + }; + }), + ); diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 27bb60f567e10..d7e0fb326e2c8 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -1,6 +1,10 @@ import { DEFAULT_SERVER_SETTINGS, EnvironmentId, + ORCHESTRATION_V2_WS_METHODS, + type OrchestrationV2SubscribeShellInput, + type OrchestrationV2SubscribeThreadInput, + ThreadId, ServerConfig, type ServerConfig as ServerConfigType, ServerConfigStreamEvent, @@ -20,6 +24,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Socket from "effect/socket/Socket"; @@ -34,7 +39,9 @@ import { } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as Persistence from "../platform/persistence.ts"; +import type { RpcPort } from "./relay.ts"; import * as RpcSession from "./session.ts"; +import { AHEAD_CURSOR_GRACE, SLOW_SUBSCRIBER_TIMEOUT } from "./sharedStreams.ts"; import { toServerClock } from "../clock.ts"; import { makeEnvironmentServerConfigState } from "../state/server.ts"; import { applyServerConfigProjection } from "../state/serverConfigProjection.ts"; @@ -1229,3 +1236,508 @@ describe("RpcSessionFactory", () => { }), ); }); + +/** An in-memory MessageChannel: delivery is async and structured-cloned, like a real port. */ +function makePortPair(): readonly [RpcPort, RpcPort] { + const listeners = [new Set<(message: unknown) => void>(), new Set<(message: unknown) => void>()]; + let closed = false; + const end = (self: 0 | 1): RpcPort => ({ + postMessage: (message) => { + if (closed) return; + const copy = structuredClone(message); + queueMicrotask(() => { + for (const listener of listeners[self === 0 ? 1 : 0]!) listener(copy); + }); + }, + onMessage: (listener) => { + listeners[self]!.add(listener); + return () => listeners[self]!.delete(listener); + }, + close: () => { + closed = true; + }, + }); + return [end(0), end(1)]; +} + +const connectHubAndWindows = Effect.fn("TestRpcSessionFactory.connectHubAndWindows")(function* ( + count: number, +) { + const { factory, sockets } = yield* makeFactory({ shareStreams: true }); + const hub = yield* factory.connect(PREPARED); + const hubReady = yield* Effect.forkChild(hub.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(hubReady); + const windows: Array = []; + for (let index = 0; index < count; index++) { + const [hubPort, windowPort] = makePortPair(); + yield* hub.relay!(hubPort); + const secondary = yield* factory.connectOverPort(PREPARED, windowPort); + yield* secondary.ready; + windows.push(secondary); + } + return { hub, windows, socket, sockets }; +}); + +const connectHubAndWindow = Effect.fn("TestRpcSessionFactory.connectHubAndWindow")(function* () { + const { hub, windows, socket, sockets } = yield* connectHubAndWindows(1); + return { hub, secondary: windows[0]!, socket, sockets }; +}); + +const sentRequests = (socket: TestWebSocket) => + socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest); + +const LEGACY_MIGRATION_EVENT = { + version: 1, + sequence: 1, + type: "legacyThreadMigration", + payload: { status: "running", totalThreadCount: 3 }, +}; + +describe("hub relay", () => { + it.effect("serves a window's config from the hub's replay without a second subscription", () => + Effect.gen(function* () { + const { secondary, socket, sockets } = yield* connectHubAndWindow(); + + expect(yield* secondary.initialConfig).toEqual(SERVER_CONFIG); + expect(sentRequests(socket).map((request) => request.tag)).toEqual([ + WS_METHODS.subscribeServerConfig, + ]); + expect(sockets).toHaveLength(1); + }).pipe(Effect.scoped), + ); + + it.effect("sends a window's requests over the hub's socket under ids the hub cannot reuse", () => + Effect.gen(function* () { + const { hub, secondary, socket } = yield* connectHubAndWindow(); + + const windowProbe = yield* Effect.forkChild(secondary.probe); + const relayed = yield* awaitRequest(socket, 1); + const hubProbe = yield* Effect.forkChild(hub.probe); + const native = yield* awaitRequest(socket, 2); + + expect(relayed.tag).toBe(WS_METHODS.serverProbe); + expect(String(relayed.id)).toMatch(/^relay\d+:/); + expect(relayed.id).not.toEqual(native.id); + socket.serverMessage( + encodeJson({ _tag: "Exit", requestId: relayed.id, exit: { _tag: "Success", value: {} } }), + ); + yield* Fiber.join(windowProbe); + expect(hubProbe.pollUnsafe()).toBeUndefined(); + socket.serverMessage( + encodeJson({ _tag: "Exit", requestId: native.id, exit: { _tag: "Success", value: {} } }), + ); + yield* Fiber.join(hubProbe); + }).pipe(Effect.scoped), + ); + + it.effect("forwards stream chunks, acks and interrupts under the relayed id", () => + Effect.gen(function* () { + const { secondary, socket } = yield* connectHubAndWindow(); + const received = yield* Queue.unbounded(); + const subscription = yield* secondary.client[WS_METHODS.subscribeServerLifecycle]({}).pipe( + Stream.runForEach((event) => Queue.offer(received, event)), + Effect.forkChild, + ); + const request = yield* awaitRequest(socket, 1); + socket.serverMessage( + encodeJson({ _tag: "Chunk", requestId: request.id, values: [LEGACY_MIGRATION_EVENT] }), + ); + + expect(yield* Queue.take(received)).toEqual(LEGACY_MIGRATION_EVENT); + const sentAfter = (tag: string) => + socket.sent + .map((message) => decodeJson(message) as { _tag: string; requestId?: unknown }) + .filter((message) => message._tag === tag && message.requestId === request.id); + while (sentAfter("Ack").length === 0) yield* Queue.take(socket.sentChanges); + expect(sentAfter("Ack")).toEqual([{ _tag: "Ack", requestId: request.id }]); + + yield* Fiber.interrupt(subscription); + while (sentAfter("Interrupt").length === 0) yield* Queue.take(socket.sentChanges); + expect(sentAfter("Interrupt")).toEqual([{ _tag: "Interrupt", requestId: request.id }]); + }).pipe(Effect.scoped), + ); + + it.effect("closes the window's session when the hub's socket drops", () => + Effect.gen(function* () { + const { secondary, socket } = yield* connectHubAndWindow(); + const pending = yield* Effect.forkChild(Effect.flip(secondary.probe)); + yield* awaitRequest(socket, 1); + + socket.close(1006); + + expect(yield* Effect.flip(secondary.closed)).toBeInstanceOf(ConnectionTransientError); + expect(yield* Fiber.join(pending)).toBeInstanceOf(ConnectionTransientError); + }).pipe(Effect.scoped), + ); + + it.effect("interrupts a window's open streams on the server when the relay ends", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const hub = yield* factory.connect(PREPARED); + const hubReady = yield* Effect.forkChild(hub.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(hubReady); + const [hubPort, windowPort] = makePortPair(); + const relayScope = yield* Scope.make(); + yield* hub.relay!(hubPort).pipe(Scope.provide(relayScope)); + const secondary = yield* factory.connectOverPort(PREPARED, windowPort); + yield* secondary.ready; + yield* secondary.client[WS_METHODS.subscribeServerLifecycle]({}).pipe( + Stream.runDrain, + Effect.forkChild, + ); + const request = yield* awaitRequest(socket, 1); + + yield* Scope.close(relayScope, Exit.void); + + expect( + socket.sent + .map((message) => decodeJson(message) as { _tag: string }) + .filter((message) => message._tag === "Interrupt"), + ).toEqual([{ _tag: "Interrupt", requestId: request.id }]); + expect(yield* Effect.flip(secondary.closed)).toBeInstanceOf(ConnectionTransientError); + }).pipe(Effect.scoped), + ); +}); + +const shellEvent = (sequence: number) => ({ + kind: "project.removed", + sequence, + projectId: `project-${sequence}`, +}); +const threadEvent = (sequence: number) => ({ + kind: "event", + sequence, + event: { type: "test.unknown-event" }, +}); +const SYNCHRONIZED = { kind: "synchronized" }; +const THREAD_ID = ThreadId.make("thread-1"); + +const followShell = Effect.fn("TestSharedStreams.followShell")(function* ( + session: RpcSession.RpcSession, + input: OrchestrationV2SubscribeShellInput, +) { + const items = yield* Queue.unbounded(); + const fiber = yield* session.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell](input).pipe( + Stream.runForEach((item) => Queue.offer(items, item)), + Effect.forkChild, + ); + return { items, fiber }; +}); + +const followThread = Effect.fn("TestSharedStreams.followThread")(function* ( + session: RpcSession.RpcSession, + input: OrchestrationV2SubscribeThreadInput, +) { + const items = yield* Queue.unbounded(); + const fiber = yield* session.client[ORCHESTRATION_V2_WS_METHODS.subscribeThread](input).pipe( + Stream.runForEach((item) => Queue.offer(items, item)), + Effect.forkChild, + ); + return { items, fiber }; +}); + +const takeItems = Effect.fn("TestSharedStreams.takeItems")(function* ( + items: Queue.Queue, + count: number, +) { + const taken: Array = []; + for (let index = 0; index < count; index++) taken.push(yield* Queue.take(items)); + return taken; +}); + +const serverChunk = (socket: TestWebSocket, requestId: unknown, values: ReadonlyArray) => + socket.serverMessage(encodeJson({ _tag: "Chunk", requestId, values })); + +const sentMessages = (socket: TestWebSocket) => + socket.sent.map((message) => decodeJson(message) as { _tag: string; requestId?: unknown }); + +const shellRequests = (socket: TestWebSocket) => + sentRequests(socket).filter( + (request) => request.tag === ORCHESTRATION_V2_WS_METHODS.subscribeShell, + ); +const activeUpstreams = (socket: TestWebSocket, tag: string) => { + const interrupted = new Set( + sentMessages(socket) + .filter((message) => message._tag === "Interrupt") + .map((message) => message.requestId), + ); + return sentRequests(socket).filter( + (request) => request.tag === tag && !interrupted.has(request.id), + ); +}; +const awaitShellRequest = Effect.fn("TestSharedStreams.awaitShellRequest")(function* ( + socket: TestWebSocket, + index: number, +) { + for (;;) { + const request = shellRequests(socket)[index]; + if (request) return request; + yield* Queue.take(socket.sentChanges); + } +}); +const acksFor = (socket: TestWebSocket, requestId: unknown) => + sentMessages(socket).filter( + (message) => message._tag === "Ack" && message.requestId === requestId, + ).length; +const awaitAcks = Effect.fn("TestSharedStreams.awaitAcks")(function* ( + socket: TestWebSocket, + requestId: unknown, + count: number, +) { + while (acksFor(socket, requestId) < count) yield* Queue.take(socket.sentChanges); +}); +const enrichment = (snapshotSequence: number) => ({ + kind: "snapshot", + snapshot: { schemaVersion: 1, snapshotSequence, threads: [], archivedThreads: [], projects: [] }, + resolvedRepositoryIdentityRoots: [], +}); +const authoritativeShell = (snapshotSequence: number) => ({ + kind: "snapshot", + snapshot: { schemaVersion: 1, snapshotSequence, threads: [], archivedThreads: [], projects: [] }, +}); + +describe("shared hub subscriptions", () => { + it.effect("leaves web and mobile sessions, and a lone subscriber, untouched", () => + Effect.gen(function* () { + const plain = yield* makeFactory(); + const session = yield* plain.factory.connect(PREPARED); + const plainSocket = yield* awaitSocket(plain.sockets); + plainSocket.open(); + yield* completeInitialConfig(plainSocket); + yield* followShell(session, { afterSequence: 5 }); + expect(typeof (yield* awaitRequest(plainSocket, 1)).id).toBe("number"); + + const { hub, socket } = yield* connectHubAndWindows(0); + const payload = { + afterSequence: 5, + httpSnapshotFallback: true, + knownProjectIdentities: "identities", + requestCompletionMarker: true, + } as const; + const lone = yield* followShell(hub, payload); + const request = yield* awaitShellRequest(socket, 0); + expect(request.payload).toEqual(payload); + serverChunk(socket, request.id, [shellEvent(6), SYNCHRONIZED]); + expect(yield* takeItems(lone.items, 2)).toMatchObject([{ sequence: 6 }, SYNCHRONIZED]); + yield* awaitAcks(socket, request.id, 1); + }).pipe(Effect.scoped), + ); + + it.effect("holds one shell and one thread subscription for the hub and two windows", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(2); + const [first, second] = [windows[0]!, windows[1]!]; + + const hubShell = yield* followShell(hub, { afterSequence: 5, requestCompletionMarker: true }); + const lone = yield* awaitShellRequest(socket, 0); + serverChunk(socket, lone.id, [shellEvent(6), shellEvent(7), SYNCHRONIZED]); + yield* takeItems(hubShell.items, 3); + + const firstShell = yield* followShell(first, { + afterSequence: 6, + requestCompletionMarker: true, + }); + const shared = yield* awaitShellRequest(socket, 1); + expect(shared.payload).toEqual({ afterSequence: 6, requestCompletionMarker: true }); + serverChunk(socket, shared.id, [shellEvent(7), SYNCHRONIZED]); + expect(yield* takeItems(firstShell.items, 2)).toMatchObject([{ sequence: 7 }, SYNCHRONIZED]); + + const secondShell = yield* followShell(second, { afterSequence: 7 }); + const reshared = yield* awaitShellRequest(socket, 2); + expect(reshared.payload).toEqual({ afterSequence: 7, requestCompletionMarker: true }); + serverChunk(socket, reshared.id, [SYNCHRONIZED]); + + const hubThread = yield* followThread(hub, { + threadId: THREAD_ID, + afterSequence: 1, + requestCompletionMarker: true, + }); + const loneThread = yield* awaitRequest(socket, 4); + serverChunk(socket, loneThread.id, [threadEvent(2), SYNCHRONIZED]); + yield* takeItems(hubThread.items, 2); + const firstThread = yield* followThread(first, { + threadId: THREAD_ID, + afterSequence: 1, + requestCompletionMarker: true, + }); + const sharedThread = yield* awaitRequest(socket, 5); + serverChunk(socket, sharedThread.id, [threadEvent(2), SYNCHRONIZED]); + expect(yield* takeItems(firstThread.items, 2)).toMatchObject([ + { kind: "unknown-event", sequence: 2 }, + SYNCHRONIZED, + ]); + + serverChunk(socket, reshared.id, [shellEvent(8)]); + serverChunk(socket, sharedThread.id, [threadEvent(3)]); + for (const shell of [hubShell, firstShell, secondShell]) { + expect(yield* Queue.take(shell.items)).toMatchObject({ sequence: 8 }); + } + for (const thread of [hubThread, firstThread]) { + expect(yield* Queue.take(thread.items)).toMatchObject({ sequence: 3 }); + } + // Nothing was delivered twice: the hub's replayed 7 and 2 were skipped. + expect(Queue.sizeUnsafe(hubShell.items)).toBe(0); + expect(Queue.sizeUnsafe(hubThread.items)).toBe(0); + expect(activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeShell)).toHaveLength(1); + expect(activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeThread)).toHaveLength(1); + }).pipe(Effect.scoped), + ); + + it.effect("keeps a resume replay that follows a project enrichment snapshot", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(1); + const hubShell = yield* followShell(hub, { afterSequence: 5 }); + yield* awaitShellRequest(socket, 0); + const late = yield* followShell(windows[0]!, { + afterSequence: 5, + requestCompletionMarker: true, + }); + const shared = yield* awaitShellRequest(socket, 1); + + serverChunk(socket, shared.id, [enrichment(9), shellEvent(6), shellEvent(7), SYNCHRONIZED]); + + expect(yield* takeItems(late.items, 4)).toMatchObject([ + { kind: "snapshot", resolvedRepositoryIdentityRoots: [] }, + { sequence: 6 }, + { sequence: 7 }, + SYNCHRONIZED, + ]); + expect(yield* takeItems(hubShell.items, 3)).toMatchObject([ + { kind: "snapshot" }, + { sequence: 6 }, + { sequence: 7 }, + ]); + }).pipe(Effect.scoped), + ); + + it.effect("gives a window that wants a fresh snapshot one, never snapshot-required", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(1); + yield* followShell(hub, { + afterSequence: 5, + httpSnapshotFallback: true, + requestCompletionMarker: true, + }); + yield* awaitShellRequest(socket, 0); + const fresh = yield* followShell(windows[0]!, { requestCompletionMarker: true }); + const shared = yield* awaitShellRequest(socket, 1); + + expect(shared.payload).toEqual({ requestCompletionMarker: true }); + serverChunk(socket, shared.id, [authoritativeShell(20), SYNCHRONIZED]); + expect(yield* takeItems(fresh.items, 2)).toMatchObject([ + { kind: "snapshot", snapshot: { snapshotSequence: 20 } }, + SYNCHRONIZED, + ]); + }).pipe(Effect.scoped), + ); + + it.effect("starts everyone over when a window's cursor is beyond the server's history", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(1); + yield* followShell(hub, { afterSequence: 5, requestCompletionMarker: true }); + const lone = yield* awaitShellRequest(socket, 0); + serverChunk(socket, lone.id, [shellEvent(6), SYNCHRONIZED]); + const ahead = yield* followShell(windows[0]!, { + afterSequence: 100, + requestCompletionMarker: true, + }); + const shared = yield* awaitShellRequest(socket, 1); + expect(shared.payload).toEqual({ afterSequence: 6, requestCompletionMarker: true }); + serverChunk(socket, shared.id, [SYNCHRONIZED]); + + yield* TestClock.adjust(AHEAD_CURSOR_GRACE); + const restarted = yield* awaitShellRequest(socket, 2); + expect(restarted.payload).toEqual({ requestCompletionMarker: true }); + serverChunk(socket, restarted.id, [authoritativeShell(7), SYNCHRONIZED]); + expect(yield* takeItems(ahead.items, 2)).toMatchObject([ + { kind: "snapshot", snapshot: { snapshotSequence: 7 } }, + SYNCHRONIZED, + ]); + }).pipe(Effect.scoped), + ); + + it.effect("acks upstream for the slowest subscriber and resyncs one that stays behind", () => + Effect.gen(function* () { + const { hub, socket } = yield* connectHubAndWindows(0); + const fast = yield* followShell(hub, { afterSequence: 1 }); + yield* awaitShellRequest(socket, 0); + const slow = yield* hub.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]( + { afterSequence: 1 }, + { asQueue: true, streamBufferSize: 1 }, + ); + const shared = yield* awaitShellRequest(socket, 1); + + serverChunk(socket, shared.id, [shellEvent(2)]); + yield* Queue.take(fast.items); + yield* awaitAcks(socket, shared.id, 1); + serverChunk(socket, shared.id, [shellEvent(3)]); + yield* Queue.take(fast.items); + yield* Effect.yieldNow; + expect(acksFor(socket, shared.id)).toBe(1); + + yield* TestClock.adjust(SLOW_SUBSCRIBER_TIMEOUT); + yield* awaitAcks(socket, shared.id, 2); + expect(yield* Stream.fromQueue(slow).pipe(Stream.runDrain, Effect.flip)).toMatchObject({ + _tag: "RpcClientError", + }); + serverChunk(socket, shared.id, [shellEvent(4)]); + expect(yield* Queue.take(fast.items)).toMatchObject({ sequence: 4 }); + }).pipe(Effect.scoped), + ); + + it.effect("keeps the stream for others when one leaves and closes it with the last", () => + Effect.gen(function* () { + const { hub, windows, socket } = yield* connectHubAndWindows(2); + const hubShell = yield* followShell(hub, { afterSequence: 1 }); + yield* awaitShellRequest(socket, 0); + const firstShell = yield* followShell(windows[0]!, { afterSequence: 1 }); + yield* awaitShellRequest(socket, 1); + const secondShell = yield* followShell(windows[1]!, { afterSequence: 1 }); + const shared = yield* awaitShellRequest(socket, 2); + serverChunk(socket, shared.id, [shellEvent(2)]); + for (const shell of [hubShell, firstShell, secondShell]) yield* Queue.take(shell.items); + + yield* Fiber.interrupt(firstShell.fiber); + yield* Fiber.interrupt(hubShell.fiber); + serverChunk(socket, shared.id, [shellEvent(3)]); + + expect(yield* Queue.take(secondShell.items)).toMatchObject({ sequence: 3 }); + expect(activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeShell)).toHaveLength(1); + + yield* Fiber.interrupt(secondShell.fiber); + while (activeUpstreams(socket, ORCHESTRATION_V2_WS_METHODS.subscribeShell).length > 0) { + yield* Queue.take(socket.sentChanges); + } + }).pipe(Effect.scoped), + ); + + it.effect("ends a window's relay and its config stream when the hub closes it", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory({ shareStreams: true }); + const hub = yield* factory.connect(PREPARED); + const hubReady = yield* Effect.forkChild(hub.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(hubReady); + const [hubPort, windowPort] = makePortPair(); + const relay = yield* hub.relay!(hubPort); + const secondary = yield* factory.connectOverPort(PREPARED, windowPort); + yield* secondary.ready; + const config = yield* secondary + .subscribeServerConfig() + .pipe(Stream.runDrain, Effect.forkChild); + + yield* relay.close("The main window's connection ended."); + + expect(yield* Effect.flip(secondary.closed)).toBeInstanceOf(ConnectionTransientError); + expect((yield* Fiber.await(config))._tag).toBe("Failure"); + }).pipe(Effect.scoped), + ); +}); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 148005df2124d..cbfa81ac1204a 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -2,7 +2,7 @@ import { msg } from "gt-i18n"; import { translatableDetail } from "../errors/translatable.ts"; import { type ServerConfig, - type ServerConfigStreamEvent, + ServerConfigStreamEvent, WsSubscribeServerConfigRpc, WS_METHODS, } from "@t3tools/contracts"; @@ -18,6 +18,7 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; +import { identity } from "effect/Function"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; @@ -33,6 +34,8 @@ import * as RpcSerialization from "effect/rpc/RpcSerialization"; import * as Socket from "effect/socket/Socket"; import { makeWsRpcProtocolClient, PING_TIMEOUT, type WsRpcProtocolClient } from "./protocol.ts"; +import { makePortProtocol, type RelayHandle, type RpcPort, serveRelay } from "./relay.ts"; +import { canonicalJson, makeSharedStreamProtocol } from "./sharedStreams.ts"; import { NETWORK_BLOCKING_HINT, UNRESPONSIVE_HOST_HINT } from "../errors/network.ts"; import type { ConnectionAttemptError, @@ -64,6 +67,8 @@ export interface RpcSession { /** Frames received so far: proof the socket is alive that needs no reply. */ readonly inboundFrames: Effect.Effect; readonly closed: Effect.Effect; + /** Serves another window's RpcClient over `port` through this session's socket. */ + readonly relay?: (port: RpcPort) => Effect.Effect; } export interface RpcSessionOptions { @@ -73,6 +78,8 @@ export interface RpcSessionOptions { readonly providerCatalogsOnDemand?: boolean; readonly providerCatalogDigests?: boolean; readonly providerStatusDeltas?: boolean; + /** Desktop hub only: clients of one session share identical subscriptions. */ + readonly shareStreams?: boolean; } export class RpcSessionFactory extends Context.Service< @@ -81,6 +88,11 @@ export class RpcSessionFactory extends Context.Service< readonly connect: ( connection: PreparedConnection, ) => Effect.Effect; + /** A session whose requests travel over `port` to a hub window's `relay`. */ + readonly connectOverPort: ( + connection: PreparedConnection, + port: RpcPort, + ) => Effect.Effect; } >()("@t3tools/client-runtime/rpc/session/RpcSessionFactory") {} @@ -178,6 +190,13 @@ function socketFailureLocation(via: "relay" | "direct") { return { hop: via === "relay" ? "tunnel" : "server", via } as const; } +const encodeServerConfigPayload = Schema.encodeUnknownSync( + Schema.toCodecJson(WsSubscribeServerConfigRpc.payloadSchema), +); +const encodeServerConfigEvents = Schema.encodeUnknownEffect( + Schema.toCodecJson(Schema.Array(ServerConfigStreamEvent)), +); + /** @public */ export const make = Effect.fn("RpcSessionFactory.make")(function* ( options: RpcSessionOptions = {}, @@ -196,6 +215,9 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ...input, workspaceSnapshotsOnDemand: true, }); + const sharedConfigInputKey = canonicalJson( + encodeServerConfigPayload(onDemandSnapshots(serverConfigInput)), + ); const connect = Effect.fnUntraced(function* (connection: PreparedConnection) { const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct"; @@ -275,13 +297,15 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( // Teardown sends an interrupt per open stream, and a write to a closed // socket waits out the client's 1s interrupt timeout before reconnecting. // Requests still go through, so they fail with the protocol error. - Effect.map((protocol) => ({ + Effect.map((protocol): RpcClient.Protocol["Service"] => ({ ...protocol, send: (clientId, request, transferables) => request._tag !== "Request" && Deferred.isDoneUnsafe(disconnected) ? Effect.void : protocol.send(clientId, request, transferables), })), + // A desktop hub's own client and every relayed window share each subscription. + options.shareStreams === true ? Effect.flatMap(makeSharedStreamProtocol) : identity, ), ).pipe( Layer.provide( @@ -303,6 +327,29 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( Effect.ignore, Effect.forkScoped, ); + return yield* finishSession({ + connection, + protocolContext, + via, + inboundFrames: Effect.sync(() => inboundFrames), + mapRpcError, + relayable: true, + }); + }); + + const finishSession = Effect.fnUntraced(function* (input: { + readonly connection: PreparedConnection; + readonly protocolContext: Context.Context; + readonly via: "relay" | "direct"; + /** Port sessions only: fails when the hub's relay goes away. */ + readonly relayClosed?: Effect.Effect; + readonly inboundFrames: Effect.Effect; + readonly mapRpcError: ( + error: Parameters[0], + ) => ConnectionAttemptError; + readonly relayable: boolean; + }) { + const { connection, protocolContext, via, mapRpcError } = input; const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); const initialConfigDeferred = yield* Deferred.make(); const serverConfigExit = yield* Deferred.make< @@ -538,13 +585,78 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( subscribeServerConfig, ready: initialConfig.pipe(Effect.asVoid), probe, - inboundFrames: Effect.sync(() => inboundFrames), + inboundFrames: input.inboundFrames, // The config stream also fails on disconnect, and only it can report a decode failure. - closed: Deferred.await(configSubscriptionClosed), + closed: + input.relayClosed === undefined + ? Deferred.await(configSubscriptionClosed) + : Effect.raceFirst(input.relayClosed, Deferred.await(configSubscriptionClosed)), + ...(input.relayable + ? { + relay: (port: RpcPort) => + serveRelay({ + protocol: Context.get(protocolContext, RpcClient.Protocol), + port, + // Every window subscribes with the same options, so the hub's + // replaying config stream answers them all. + shared: [ + { + tag: WS_METHODS.subscribeServerConfig, + matches: (payload) => canonicalJson(payload) === sharedConfigInputKey, + items: subscribeServerConfig().pipe(Stream.orDie), + encode: (events) => encodeServerConfigEvents(events).pipe(Effect.orDie), + }, + ], + }), + } + : {}), } satisfies RpcSession; }); - return RpcSessionFactory.of({ connect }); + const connectOverPort = Effect.fnUntraced(function* ( + connection: PreparedConnection, + port: RpcPort, + ) { + yield* Effect.annotateCurrentSpan({ + "connection.environment.id": connection.environmentId, + }); + const disconnected = yield* Deferred.make(); + let inboundMessages = 0; + const protocol = yield* makePortProtocol({ + port, + onMessage: () => { + inboundMessages += 1; + }, + onClosed: (detail) => + Deferred.fail( + disconnected, + new ConnectionTransientErrorClass({ + reason: "transport", + detail: `${connection.label}: ${detail}`, + }), + ).pipe(Effect.asVoid), + }); + return yield* finishSession({ + connection, + protocolContext: Context.make(RpcClient.Protocol, protocol), + via: "direct", + relayClosed: Deferred.await(disconnected), + inboundFrames: Effect.sync(() => inboundMessages), + mapRpcError: (error) => + mapSessionRpcError( + error, + "direct", + () => + new ConnectionTransientErrorClass({ + reason: "transport", + ...translatableDetail(msg("{host} disconnected.", { host: connection.label })), + }), + ), + relayable: false, + }); + }); + + return RpcSessionFactory.of({ connect, connectOverPort }); }); export const layer = (options: RpcSessionOptions) => Layer.effect(RpcSessionFactory, make(options)); diff --git a/packages/client-runtime/src/rpc/sharedStreams.ts b/packages/client-runtime/src/rpc/sharedStreams.ts new file mode 100644 index 0000000000000..a60a3fdf0fdca --- /dev/null +++ b/packages/client-runtime/src/rpc/sharedStreams.ts @@ -0,0 +1,529 @@ +import { ORCHESTRATION_V2_WS_METHODS, WS_METHODS } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import type * as Scope from "effect/Scope"; +import * as RpcClient from "effect/rpc/RpcClient"; +import * as RpcClientError from "effect/rpc/RpcClientError"; +import type { FromClientEncoded, FromServerEncoded, RequestEncoded } from "effect/rpc/RpcMessage"; + +type EncodedItem = { readonly [key: string]: unknown }; + +/** + * How a subscription is reopened when another subscriber joins it. Nothing is + * retained: the server replays from the earliest subscriber's cursor, or starts + * over from current state, and each subscriber skips what it already has. + */ +type ShareStrategy = + | { + readonly _tag: "sequenced"; + /** Payload fields that position one subscriber; they never split a shared stream. */ + readonly cursorFields: ReadonlyArray; + /** The sequence of a snapshot that replaces all state; null for anything else. */ + readonly authoritativeSnapshot: (item: EncodedItem) => number | null; + readonly eventSequence: (item: EncodedItem) => number | null; + } + /** A fresh subscription starts with the whole current state. */ + | { readonly _tag: "restartable" }; + +const numberField = (value: unknown): number | null => (typeof value === "number" ? value : null); +const SHELL_EVENT_KINDS = new Set([ + "project.updated", + "project.removed", + "thread.updated", + "thread.removed", +]); + +const STRATEGIES: ReadonlyMap = new Map([ + [ + ORCHESTRATION_V2_WS_METHODS.subscribeShell, + { + _tag: "sequenced", + cursorFields: [ + "afterSequence", + "requestCompletionMarker", + "httpSnapshotFallback", + "knownProjectIdentities", + ], + // Snapshots with resolved identity roots only enrich projects (see the ws.ts shell resume). + authoritativeSnapshot: (item) => + item.kind === "snapshot" && item.resolvedRepositoryIdentityRoots === undefined + ? numberField((item.snapshot as EncodedItem | undefined)?.snapshotSequence) + : null, + eventSequence: (item) => + SHELL_EVENT_KINDS.has(String(item.kind)) ? numberField(item.sequence) : null, + }, + ], + [ + ORCHESTRATION_V2_WS_METHODS.subscribeThread, + { + _tag: "sequenced", + cursorFields: ["afterSequence", "requestCompletionMarker"], + authoritativeSnapshot: (item) => + item.kind === "snapshot" ? numberField(item.snapshotSequence) : null, + eventSequence: (item) => (item.kind === "event" ? numberField(item.sequence) : null), + }, + ], + ...[ + WS_METHODS.subscribeVcsStatus, + WS_METHODS.subscribeAuthAccess, + WS_METHODS.subscribeTerminalMetadata, + ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput, + WS_METHODS.providerAuthSubscribe, + WS_METHODS.providerInstallSubscribe, + WS_METHODS.scheduledTasksSubscribe, + WS_METHODS.subscribeDiscoveredLocalServers, + WS_METHODS.subscribeDeviceState, + WS_METHODS.subscribeResourceTelemetry, + WS_METHODS.subscribeVcsBranch, + WS_METHODS.subscribeProjectClones, + WS_METHODS.subscribeWorktreeSetup, + WS_METHODS.pullRequestsSubscribeRefreshes, + WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes, + ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion, + ].map((tag): [string, ShareStrategy] => [tag, { _tag: "restartable" }]), +]); + +/** A subscriber that leaves a chunk unacknowledged this long resubscribes instead of stalling others. */ +export const SLOW_SUBSCRIBER_TIMEOUT = Duration.seconds(10); +/** How long a cursor ahead of the stream may wait for in-flight events before everyone resyncs. */ +export const AHEAD_CURSOR_GRACE = Duration.seconds(5); + +export function canonicalJson(value: unknown, omit: ReadonlyArray = []): string { + if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(",")}]`; + if (typeof value !== "object" || value === null) return JSON.stringify(value) ?? "null"; + const entries = Object.entries(value) + .filter(([key, entry]) => entry !== undefined && !omit.includes(key)) + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)); + return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; +} + +type RequestId = string | number; + +interface PendingAck { + readonly waiting: Set; + timer: Fiber.Fiber | null; +} + +interface Consumer { + readonly clientId: number; + readonly requestId: RequestId; + readonly wantsMarker: boolean; + markerSent: boolean; + /** Last sequence this subscriber has; null while it waits for a snapshot. */ + position: number | null; + /** Chunks delivered and not yet acknowledged, oldest first; null for a replaced upstream's. */ + readonly unacked: Array; + aheadTimer: Fiber.Fiber | null; +} + +interface Group { + readonly key: string; + readonly strategy: ShareStrategy; + readonly template: RequestEncoded; + readonly consumers: Map; + upstreamId: string; + /** One subscriber whose own request is the upstream: chunks and acks pass straight through. */ + passThrough: boolean; + head: number | null; + /** The current upstream has sent its completion marker. */ + live: boolean; + readonly pendingAcks: Array; +} + +let nextInstance = 0; + +/** + * One server subscription per stream and arguments for all clients of a desktop hub + * session. A lone subscriber passes through; a joiner reopens the upstream from the + * earliest cursor, so nothing is retained. Acks wait for the slowest subscriber. + */ +export const makeSharedStreamProtocol = ( + inner: RpcClient.Protocol["Service"], +): Effect.Effect => + RpcClient.Protocol.make( + Effect.fnUntraced(function* (writeResponse, clientIds) { + const runFork = Effect.runForkWith(yield* Effect.context()); + const instance = nextInstance++; + // Every client shares one inner client; request ids are unique in this realm. + const innerClientId = 2_000_000_000 + instance; + let nextUpstream = 0; + const routes = new Map(); + const groups = new Map(); + const groupsByUpstream = new Map(); + const consumerGroups = new Map(); + const outboxes = new Map>(); + let failure: RpcClientError.RpcClientError | undefined; + + // Per client and in order, so a chunk never overtakes an earlier one. + const deliver = (clientId: number, message: FromServerEncoded) => { + const existing = outboxes.get(clientId); + if (existing !== undefined) { + existing.push(message); + return; + } + const queue = [message]; + outboxes.set(clientId, queue); + runFork( + Effect.gen(function* () { + while (queue.length > 0) yield* writeResponse(clientId, queue.shift()!); + }).pipe(Effect.ensuring(Effect.sync(() => outboxes.delete(clientId)))), + ); + }; + const sendInner = (message: FromClientEncoded) => + runFork(inner.send(innerClientId, message).pipe(Effect.ignore)); + const newUpstreamId = () => `shared:${instance}:${nextUpstream++}`; + const cancelTimer = (fiber: Fiber.Fiber | null) => { + if (fiber !== null) runFork(Fiber.interrupt(fiber)); + }; + + const ackUpstream = (group: Group) => { + while (group.pendingAcks.length > 0 && group.pendingAcks[0]!.waiting.size === 0) { + cancelTimer(group.pendingAcks.shift()!.timer); + sendInner({ _tag: "Ack", requestId: group.upstreamId }); + } + }; + + const forgetConsumer = (group: Group, consumer: Consumer) => { + group.consumers.delete(consumer.requestId); + consumerGroups.delete(consumer.requestId); + cancelTimer(consumer.aheadTimer); + for (const pending of consumer.unacked) pending?.waiting.delete(consumer); + consumer.unacked.length = 0; + }; + + const closeGroup = (group: Group) => { + groups.delete(group.key); + groupsByUpstream.delete(group.upstreamId); + for (const consumer of group.consumers.values()) forgetConsumer(group, consumer); + for (const pending of group.pendingAcks) cancelTimer(pending.timer); + group.pendingAcks.length = 0; + }; + + const leave = (group: Group, consumer: Consumer) => { + forgetConsumer(group, consumer); + if (group.consumers.size === 0) { + sendInner({ _tag: "Interrupt", requestId: group.upstreamId }); + closeGroup(group); + return; + } + ackUpstream(group); + }; + + /** Fails only this subscriber's request; it resubscribes from its own cursor. */ + const resync = (group: Group, consumer: Consumer, detail: string) => { + leave(group, consumer); + deliver(consumer.clientId, { + _tag: "ClientProtocolError", + error: new RpcClientError.RpcClientError({ + reason: new RpcClientError.RpcClientDefect({ message: detail, cause: undefined }), + }), + requestIds: [consumer.requestId], + }); + }; + + /** Replaces the upstream with one every current subscriber can resume from. */ + const reopen = (group: Group, fromScratch: boolean) => { + sendInner({ _tag: "Interrupt", requestId: group.upstreamId }); + groupsByUpstream.delete(group.upstreamId); + for (const pending of group.pendingAcks) cancelTimer(pending.timer); + group.pendingAcks.length = 0; + for (const consumer of group.consumers.values()) consumer.unacked.fill(null); + group.passThrough = false; + group.live = false; + group.upstreamId = newUpstreamId(); + groupsByUpstream.set(group.upstreamId, group); + const strategy = group.strategy; + if (strategy._tag === "restartable") { + sendInner({ ...group.template, id: group.upstreamId }); + return; + } + const positions = Array.from(group.consumers.values(), (consumer) => consumer.position); + const cursor = + fromScratch || positions.includes(null) + ? null + : Math.min(...positions.filter((position) => position !== null)); + group.head = cursor; + if (fromScratch) { + for (const consumer of group.consumers.values()) { + consumer.position = null; + cancelTimer(consumer.aheadTimer); + consumer.aheadTimer = null; + } + } + const base = Object.fromEntries( + Object.entries(group.template.payload as EncodedItem).filter( + ([key]) => !strategy.cursorFields.includes(key), + ), + ); + sendInner({ + ...group.template, + id: group.upstreamId, + // Without `httpSnapshotFallback`: a gap answers with a snapshot every subscriber can use. + payload: { + ...base, + ...(cursor === null ? {} : { afterSequence: cursor }), + requestCompletionMarker: true, + }, + }); + }; + + const watchAhead = (group: Group, consumer: Consumer) => { + cancelTimer(consumer.aheadTimer); + consumer.aheadTimer = runFork( + Effect.sleep(AHEAD_CURSOR_GRACE).pipe( + Effect.andThen( + Effect.sync(() => { + consumer.aheadTimer = null; + if (!group.consumers.has(consumer.requestId) || consumer.position === null) return; + // The server never reached this cursor, so it lost history: everyone starts over. + if ((group.head ?? -1) < consumer.position) reopen(group, true); + }), + ), + ), + ); + }; + + const subscribe = (clientId: number, request: RequestEncoded, strategy: ShareStrategy) => { + const payload = request.payload as EncodedItem | null; + const key = `${request.tag}\u0000${canonicalJson( + request.payload, + strategy._tag === "sequenced" ? strategy.cursorFields : [], + )}`; + const consumer: Consumer = { + clientId, + requestId: request.id, + wantsMarker: payload?.requestCompletionMarker === true, + markerSent: false, + position: strategy._tag === "sequenced" ? numberField(payload?.afterSequence) : null, + unacked: [], + aheadTimer: null, + }; + const existing = groups.get(key); + if (existing === undefined) { + const group: Group = { + key, + strategy, + template: request, + consumers: new Map([[consumer.requestId, consumer]]), + upstreamId: newUpstreamId(), + passThrough: true, + head: consumer.position, + live: false, + pendingAcks: [], + }; + groups.set(key, group); + groupsByUpstream.set(group.upstreamId, group); + consumerGroups.set(consumer.requestId, group); + sendInner({ ...request, id: group.upstreamId }); + return; + } + const head = existing.head; + existing.consumers.set(consumer.requestId, consumer); + consumerGroups.set(consumer.requestId, existing); + reopen(existing, false); + if (consumer.position !== null && head !== null && head < consumer.position) { + watchAhead(existing, consumer); + } + }; + + const deliverChunks = (group: Group, perConsumer: Map>) => { + const pending: PendingAck = { waiting: new Set(), timer: null }; + for (const [consumer, values] of perConsumer) { + if (values.length === 0) continue; + pending.waiting.add(consumer); + consumer.unacked.push(pending); + deliver(consumer.clientId, { + _tag: "Chunk", + requestId: consumer.requestId, + values: values as never, + }); + } + group.pendingAcks.push(pending); + if (pending.waiting.size > 0) { + pending.timer = runFork( + Effect.sleep(SLOW_SUBSCRIBER_TIMEOUT).pipe( + Effect.andThen( + Effect.sync(() => { + pending.timer = null; + for (const consumer of pending.waiting) { + // Alone, a slow subscriber holds back only itself. + if (group.consumers.size < 2) break; + resync(group, consumer, "This subscriber fell behind the shared stream."); + } + }), + ), + ), + ); + } + ackUpstream(group); + }; + + const onSharedItems = (group: Group, items: ReadonlyArray) => { + const perConsumer = new Map>( + Array.from(group.consumers.values(), (consumer) => [consumer, []]), + ); + const strategy = group.strategy; + if (strategy._tag === "restartable") { + for (const values of perConsumer.values()) values.push(...items); + deliverChunks(group, perConsumer); + return; + } + // A subscriber is caught up once the stream is live and has reached its cursor. + const markCaughtUp = (consumer: Consumer, values: Array) => { + if (!group.live || consumer.position === null) return; + if (consumer.aheadTimer !== null) { + if ((group.head ?? -1) < consumer.position) return; + cancelTimer(consumer.aheadTimer); + consumer.aheadTimer = null; + } + if (consumer.wantsMarker && !consumer.markerSent) { + consumer.markerSent = true; + values.push({ kind: "synchronized" }); + } + }; + for (const item of items) { + if (item.kind === "synchronized") { + group.live = true; + for (const [consumer, values] of perConsumer) markCaughtUp(consumer, values); + continue; + } + const snapshotSequence = strategy.authoritativeSnapshot(item); + if (snapshotSequence !== null) { + group.head = snapshotSequence; + for (const [consumer, values] of perConsumer) { + values.push(item); + consumer.position = snapshotSequence; + } + continue; + } + const sequence = strategy.eventSequence(item); + if (sequence === null) { + // Project enrichment applies to everyone holding a shell; it moves no cursor. + for (const [consumer, values] of perConsumer) { + if (consumer.position !== null) values.push(item); + } + continue; + } + if (group.head === null || sequence > group.head) group.head = sequence; + for (const [consumer, values] of perConsumer) { + if (consumer.position !== null && sequence > consumer.position) { + values.push(item); + consumer.position = sequence; + } + markCaughtUp(consumer, values); + } + } + deliverChunks(group, perConsumer); + }; + + /** The single subscriber's own stream, forwarded as is; only its position is tracked. */ + const onPassThroughItems = ( + group: Group, + response: Extract, + ) => { + const consumer = group.consumers.values().next().value; + if (consumer === undefined) return; + const strategy = group.strategy; + if (strategy._tag === "sequenced") { + for (const item of response.values as ReadonlyArray) { + if (item.kind === "synchronized") { + if (consumer.wantsMarker) consumer.markerSent = true; + continue; + } + const sequence = strategy.authoritativeSnapshot(item) ?? strategy.eventSequence(item); + if (sequence !== null) { + group.head = sequence; + consumer.position = sequence; + } + } + } + deliver(consumer.clientId, { ...response, requestId: consumer.requestId }); + }; + + yield* inner + .run(innerClientId, (response) => + Effect.sync(() => { + const requestId = "requestId" in response ? response.requestId : undefined; + const group = + typeof requestId === "string" ? groupsByUpstream.get(requestId) : undefined; + switch (response._tag) { + case "Chunk": { + if (group === undefined) { + const clientId = routes.get(response.requestId); + if (clientId !== undefined) deliver(clientId, response); + } else if (group.passThrough) { + onPassThroughItems(group, response); + } else { + onSharedItems(group, response.values as ReadonlyArray); + } + return; + } + case "Exit": { + if (group !== undefined) { + for (const consumer of group.consumers.values()) { + deliver(consumer.clientId, { ...response, requestId: consumer.requestId }); + } + closeGroup(group); + return; + } + const clientId = routes.get(response.requestId); + routes.delete(response.requestId); + if (clientId !== undefined) deliver(clientId, response); + return; + } + case "ClientProtocolError": + case "Defect": { + if (response._tag === "ClientProtocolError") failure = response.error; + routes.clear(); + for (const open of groups.values()) closeGroup(open); + for (const clientId of clientIds) deliver(clientId, response); + return; + } + case "Pong": + return; + default: + for (const clientId of clientIds) deliver(clientId, response); + } + }), + ) + .pipe(Effect.forkScoped); + + return { + send: (clientId, request, transferables) => { + if (failure !== undefined) return Effect.fail(failure); + if (request._tag === "Request") { + const strategy = STRATEGIES.get(request.tag); + if (strategy !== undefined) { + return Effect.sync(() => subscribe(clientId, request, strategy)); + } + routes.set(request.id, clientId); + return inner + .send(innerClientId, request, transferables) + .pipe(Effect.onError(() => Effect.sync(() => routes.delete(request.id)))); + } + if (request._tag === "Ack" || request._tag === "Interrupt") { + const group = consumerGroups.get(request.requestId); + const consumer = group?.consumers.get(request.requestId); + if (group !== undefined && consumer !== undefined) { + return Effect.sync(() => { + if (request._tag === "Interrupt") { + leave(group, consumer); + } else if (group.passThrough) { + sendInner({ _tag: "Ack", requestId: group.upstreamId }); + } else { + consumer.unacked.shift()?.waiting.delete(consumer); + ackUpstream(group); + } + }); + } + if (request._tag === "Interrupt") routes.delete(request.requestId); + } + return inner.send(innerClientId, request, transferables); + }, + supportsAck: inner.supportsAck, + supportsTransferables: inner.supportsTransferables, + codecFor: inner.codecFor, + }; + }), + ); diff --git a/packages/contracts/src/desktopWindows.ts b/packages/contracts/src/desktopWindows.ts new file mode 100644 index 0000000000000..55f817e17ee1b --- /dev/null +++ b/packages/contracts/src/desktopWindows.ts @@ -0,0 +1,46 @@ +import * as Schema from "effect/Schema"; + +export const DesktopOpenWindowSchema = Schema.Struct({ + /** Electron's BrowserWindow id. */ + windowId: Schema.Int, + isMain: Schema.Boolean, +}); +export type DesktopOpenWindow = typeof DesktopOpenWindowSchema.Type; + +export const DesktopWindowsStateSchema = Schema.Struct({ + windows: Schema.Array(DesktopOpenWindowSchema), +}); +export type DesktopWindowsState = typeof DesktopWindowsStateSchema.Type; + +/** Read synchronously at preload time; a window keeps its id and role for its lifetime. */ +export const DesktopWindowContextSchema = Schema.Struct({ + windowId: Schema.Int, + isMain: Schema.Boolean, +}); +export type DesktopWindowContext = typeof DesktopWindowContextSchema.Type; + +/** + * `window.postMessage` payload the preload uses to hand a hub link port to the page, + * since a MessagePort cannot cross the context bridge. The port is `event.ports[0]`. + */ +export const DESKTOP_HUB_LINK_MESSAGE_TYPE = "t3code:desktop-hub-link"; +export interface DesktopHubLinkMessage { + readonly type: typeof DESKTOP_HUB_LINK_MESSAGE_TYPE; + /** The BrowserWindow id at the other end of the port. */ + readonly peerWindowId: number; +} + +export interface DesktopWindowsBridge { + getContext: () => DesktopWindowContext; + getState: () => Promise; + onState: (listener: (state: DesktopWindowsState) => void) => () => void; + openNew: () => Promise; + /** Main window only: its renderer serves secondary windows' environment connections. */ + registerHub: () => void; + /** Secondary windows only: asks for a port to the hub, delivered as a `DesktopHubLinkMessage`. */ + requestHubLink: () => void; + /** Hub side: a secondary window's renderer went away, so its links are dead. */ + onHubPeerGone: (listener: (windowId: number) => void) => () => void; + /** Secondary side: the hub's renderer went away; drop links and request a new one. */ + onHubReset: (listener: () => void) => () => void; +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 58863aaebd5e5..cd20a5882baec 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -11,6 +11,7 @@ export * from "./relayClient.ts"; export * from "./desktopBootstrap.ts"; export * from "./desktopBrowser.ts"; export * from "./desktopAppActivation.ts"; +export * from "./desktopWindows.ts"; export * from "./remoteAccess.ts"; export * from "./ipc.ts"; export * from "./terminal.ts"; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 962cfd089dd2b..d8556ea3002f6 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -20,6 +20,7 @@ import type { DesktopAppActivationRequest, DesktopAppActivationResponse, } from "./desktopAppActivation.ts"; +import type { DesktopWindowsBridge } from "./desktopWindows.ts"; export interface ContextMenuItem { id: T; @@ -1139,6 +1140,8 @@ export interface DesktopBridge { getLocalEnvironmentBearerToken: () => Promise; getClientSettings: () => Promise; setClientSettings: (settings: ClientSettings) => Promise; + /** Fires in every other app window after one window saves client settings. */ + onClientSettingsChanged?: (listener: () => void) => () => void; getConnectionCatalog: () => Promise; setConnectionCatalog: (catalog: string) => Promise; discoverSshHosts: () => Promise; @@ -1247,6 +1250,8 @@ export interface DesktopBridge { prepare: (locale: string) => Promise; transcribe: (input: { locale: string; pcm: Uint8Array }) => Promise; }; + /** Multi-window support; absent in shells that predate it. */ + windows?: DesktopWindowsBridge; } /** Renderer callback invoked by Electron with a fresh user gesture before display-media capture. */ diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index eda5138b760b9..4d93f13637f5a 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -85,6 +85,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "filePicker.toggle", "projectSearch.toggle", "usage.open", + "window.new", "theme.select", "appearance.cycle", "themeEditor.toggle", diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 3d9fcc0727d3d..ae055908aee1e 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -114,6 +114,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, { key: "mod+alt+n", command: "chat.newWithoutProject", when: "!terminalFocus" }, + { key: "mod+alt+shift+n", command: "window.new", when: "isDesktop" }, { key: "mod+f", command: "chat.find", when: "!terminalFocus && !previewFocus" }, { key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" }, { key: "mod+shift+h", command: "composer.host", when: "!terminalFocus" }, From cb56d57fe0246df96cbedd5e39ba961013757f71 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 22:37:30 -0500 Subject: [PATCH 02/20] docs: the hidden main window stays open on macOS Co-Authored-By: Claude Opus 5.5 --- docs/user/multiple-windows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user/multiple-windows.md b/docs/user/multiple-windows.md index 7a4934b817309..993aace5fdb9d 100644 --- a/docs/user/multiple-windows.md +++ b/docs/user/multiple-windows.md @@ -11,4 +11,4 @@ macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. Change the shortcut under **Settings → Keybindings** (`window.new`). Closing the main window while others are open hides it instead, since the other windows connect -through it. It closes once the last other window does. +through it. On Windows and Linux it closes once the last other window does. From 6546ea36e70aaece8e4291a610212eca138c8f03 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:18:41 -0500 Subject: [PATCH 03/20] refactor(client-runtime): socket sessions add the relay, and a lease reuses its supervisor Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/connection/hub.ts | 33 +++++++-------- packages/client-runtime/src/rpc/session.ts | 42 +++++++++---------- 2 files changed, 33 insertions(+), 42 deletions(-) diff --git a/packages/client-runtime/src/connection/hub.ts b/packages/client-runtime/src/connection/hub.ts index c6b48ca50dd39..b491a24f5dbe3 100644 --- a/packages/client-runtime/src/connection/hub.ts +++ b/packages/client-runtime/src/connection/hub.ts @@ -97,12 +97,12 @@ const makeHubDriver = Effect.gen(function* () { } satisfies ConnectionDriver.EnvironmentConnectionLease; }), // Route choice belongs to the hub, which owns the socket. - preflight: Effect.fn("HubConnectionDriver.preflight")(function* () { - return yield* Effect.succeed("unchecked" as const); - }), - checkHost: Effect.fn("HubConnectionDriver.checkHost")(function* () { - return yield* Effect.succeed("answered" as const); - }), + preflight: Effect.fn("HubConnectionDriver.preflight")(() => + Effect.succeed("unchecked" as const), + ), + checkHost: Effect.fn("HubConnectionDriver.checkHost")(() => + Effect.succeed("answered" as const), + ), }); }); @@ -113,6 +113,7 @@ type HubSessionState = readonly _tag: "Ready"; readonly prepared: PreparedConnection; readonly session: RpcSession.RpcSession; + readonly supervisor: EnvironmentSupervisor.EnvironmentSupervisor["Service"]; } | { readonly _tag: "Blocked"; readonly error: ConnectionAttemptError }; @@ -132,7 +133,12 @@ const hubSessionStates = Stream.unwrap( ), Stream.map(([session, prepared, state]): Option.Option => { if (Option.isSome(session) && Option.isSome(prepared)) { - return Option.some({ _tag: "Ready", prepared: prepared.value, session: session.value }); + return Option.some({ + _tag: "Ready", + prepared: prepared.value, + session: session.value, + supervisor, + }); } if (state.phase === "blocked" && state.lastFailure !== null) { return Option.some({ _tag: "Blocked", error: state.lastFailure }); @@ -164,7 +170,7 @@ export const serveHubLease = Effect.fn("HubConnection.serveLease")(function* ( } const state = head.value; if (state._tag === "Blocked") return yield* state.error; - const { prepared, session } = state; + const { prepared, session, supervisor } = state; if (session.relay === undefined) { return yield* new ConnectionTransientError({ reason: "transport", @@ -173,17 +179,6 @@ export const serveHubLease = Effect.fn("HubConnection.serveLease")(function* ( } const relay = yield* session.relay(port); // A session that ends or is replaced takes its relays with it, so the window reconnects at once. - const supervisor = yield* registry - .run(environmentId, EnvironmentSupervisor.EnvironmentSupervisor) - .pipe( - Effect.mapError( - () => - new ConnectionTransientError({ - reason: "endpoint-unavailable", - detail: "The main window no longer has this environment.", - }), - ), - ); yield* Effect.raceFirst( session.closed.pipe(Effect.ignore), SubscriptionRef.changes(supervisor.session).pipe( diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index cbfa81ac1204a..56f84272cef28 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -327,14 +327,31 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( Effect.ignore, Effect.forkScoped, ); - return yield* finishSession({ + const session = yield* finishSession({ connection, protocolContext, via, inboundFrames: Effect.sync(() => inboundFrames), mapRpcError, - relayable: true, }); + return { + ...session, + relay: (port: RpcPort) => + serveRelay({ + protocol: Context.get(protocolContext, RpcClient.Protocol), + port, + // Every window subscribes with the same options, so the hub's + // replaying config stream answers them all. + shared: [ + { + tag: WS_METHODS.subscribeServerConfig, + matches: (payload) => canonicalJson(payload) === sharedConfigInputKey, + items: session.subscribeServerConfig().pipe(Stream.orDie), + encode: (events) => encodeServerConfigEvents(events).pipe(Effect.orDie), + }, + ], + }), + } satisfies RpcSession; }); const finishSession = Effect.fnUntraced(function* (input: { @@ -347,7 +364,6 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( readonly mapRpcError: ( error: Parameters[0], ) => ConnectionAttemptError; - readonly relayable: boolean; }) { const { connection, protocolContext, via, mapRpcError } = input; const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); @@ -591,25 +607,6 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( input.relayClosed === undefined ? Deferred.await(configSubscriptionClosed) : Effect.raceFirst(input.relayClosed, Deferred.await(configSubscriptionClosed)), - ...(input.relayable - ? { - relay: (port: RpcPort) => - serveRelay({ - protocol: Context.get(protocolContext, RpcClient.Protocol), - port, - // Every window subscribes with the same options, so the hub's - // replaying config stream answers them all. - shared: [ - { - tag: WS_METHODS.subscribeServerConfig, - matches: (payload) => canonicalJson(payload) === sharedConfigInputKey, - items: subscribeServerConfig().pipe(Stream.orDie), - encode: (events) => encodeServerConfigEvents(events).pipe(Effect.orDie), - }, - ], - }), - } - : {}), } satisfies RpcSession; }); @@ -652,7 +649,6 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ...translatableDetail(msg("{host} disconnected.", { host: connection.label })), }), ), - relayable: false, }); }); From e4f1cd7751e036f933925e5144f6c8c43f95fa68 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:19:16 -0500 Subject: [PATCH 04/20] refactor(desktop): one forwarder routes per-tab preview events to their window Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/ipc/methods/preview.ts | 51 +++++++------------------ 1 file changed, 13 insertions(+), 38 deletions(-) diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 7690cad20f0fd..f937246705f84 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -55,20 +55,11 @@ import * as DesktopIpc from "../DesktopIpc.ts"; * A secondary window's tab ids are scoped to that window, so two windows can each show the * same thread's preview. The main window keeps its ids as they are. */ -function scopePreviewTabId(tabId: string, secondaryWindowId: number | null): string { - return secondaryWindowId === null ? tabId : `w${secondaryWindowId}:${tabId}`; -} - const senderTabId = (tabId: string) => Effect.map(DesktopIpc.DesktopIpcSender, ({ window, isMain }) => - scopePreviewTabId(tabId, isMain ? null : window.id), + isMain ? tabId : `w${window.id}:${tabId}`, ); -const withRendererTabId = (value: A, rendererTabId: string): A => - typeof value === "object" && value !== null && "tabId" in value - ? { ...value, tabId: rendererTabId } - : value; - /** Per-tab events go only to the window that shows the tab, under the id it knows. */ export const installPreviewEventForwarding = Effect.fn( "desktop.ipc.preview.installEventForwarding", @@ -84,38 +75,22 @@ export const installPreviewEventForwarding = Effect.fn( if (Option.isNone(window) || window.value.isDestroyed()) return; send(window.value.webContents, rendererTabId); }); + const forward = + (channel: string) => + (event: E) => + sendToOwner(event.tabId, (contents, tabId) => contents.send(channel, { ...event, tabId })); yield* manager.subscribeStateChanges((tabId, state) => sendToOwner(tabId, (contents, rendererTabId) => - contents.send( - IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, - rendererTabId, - withRendererTabId(state, rendererTabId), - ), - ), - ); - yield* manager.subscribeRecordingInputs((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, { - ...event, + contents.send(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, rendererTabId, { + ...state, tabId: rendererTabId, }), ), ); - yield* manager.subscribePointerEvents((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, { ...event, tabId: rendererTabId }), - ), - ); - yield* manager.subscribeOpenLinks((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, { ...event, tabId: rendererTabId }), - ), - ); - yield* manager.subscribeFindResults((event) => - sendToOwner(event.tabId, (contents, rendererTabId) => - contents.send(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, { ...event, tabId: rendererTabId }), - ), - ); + yield* manager.subscribeRecordingInputs(forward(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL)); + yield* manager.subscribePointerEvents(forward(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL)); + yield* manager.subscribeOpenLinks(forward(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL)); + yield* manager.subscribeFindResults(forward(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL)); const tunnel = yield* LoopbackTunnel.LoopbackTunnel; yield* tunnel.subscribeForwards((forwards) => electronWindow.sendAll(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, forwards), @@ -560,7 +535,7 @@ export const captureScreenshot = DesktopIpc.makeIpcMethod({ handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; return yield* manager.captureScreenshot(yield* senderTabId(tabId)).pipe( - Effect.map((artifact) => withRendererTabId(artifact, tabId)), + Effect.map((artifact) => ({ ...artifact, tabId })), Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot"))), ); }), @@ -593,7 +568,7 @@ const saveRecording = DesktopIpc.makeIpcMethod({ handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) { const manager = yield* PreviewManager.PreviewManager; const artifact = yield* manager.saveRecording(yield* senderTabId(tabId), mimeType, data); - return withRendererTabId(artifact, tabId); + return { ...artifact, tabId }; }), }); From 6c41553086fdc1130424372e8447dc7b80eaa6cd Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:21:13 -0500 Subject: [PATCH 05/20] refactor(web): read the window context directly instead of through component state Co-Authored-By: Claude Opus 5.5 --- apps/web/src/browser/ElectronBrowserHost.tsx | 2 +- apps/web/src/multiWindow/windowContext.ts | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/apps/web/src/browser/ElectronBrowserHost.tsx b/apps/web/src/browser/ElectronBrowserHost.tsx index ad9f60ff173dd..910334f208ca7 100644 --- a/apps/web/src/browser/ElectronBrowserHost.tsx +++ b/apps/web/src/browser/ElectronBrowserHost.tsx @@ -140,7 +140,7 @@ export function ElectronBrowserHost() { const previewByThreadKey = useActivePreviewSessions(); const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom); // Background previews belong to the main window; a secondary one hosts only what it shows. - const [secondaryWindow] = useState(isSecondaryDesktopWindow); + const secondaryWindow = isSecondaryDesktopWindow(); useDesktopHostedPreviewSessions(secondaryWindow ? null : primaryEnvironmentId); const hostedElsewhere = useThreadsHostedElsewhere(); const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId).filter( diff --git a/apps/web/src/multiWindow/windowContext.ts b/apps/web/src/multiWindow/windowContext.ts index c686fb0203787..0be4435ac6582 100644 --- a/apps/web/src/multiWindow/windowContext.ts +++ b/apps/web/src/multiWindow/windowContext.ts @@ -9,12 +9,7 @@ let cachedContext: DesktopWindowContext | null | undefined; /** Null outside a desktop shell with multi-window support. */ export function readDesktopWindowContext(): DesktopWindowContext | null { - if (cachedContext !== undefined) return cachedContext; - try { - cachedContext = desktopWindowsBridge()?.getContext() ?? null; - } catch { - cachedContext = null; - } + if (cachedContext === undefined) cachedContext = desktopWindowsBridge()?.getContext() ?? null; return cachedContext; } From b1e319da41bb39f408dae5fd2d971f3aec77ad22 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:21:59 -0500 Subject: [PATCH 06/20] test(client-runtime): relay tests share the hub setup Co-Authored-By: Claude Opus 5.5 --- .../client-runtime/src/rpc/session.test.ts | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index d7e0fb326e2c8..be8d02c1d104e 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -1262,8 +1262,9 @@ function makePortPair(): readonly [RpcPort, RpcPort] { const connectHubAndWindows = Effect.fn("TestRpcSessionFactory.connectHubAndWindows")(function* ( count: number, + options: RpcSession.RpcSessionOptions = { shareStreams: true }, ) { - const { factory, sockets } = yield* makeFactory({ shareStreams: true }); + const { factory, sockets } = yield* makeFactory(options); const hub = yield* factory.connect(PREPARED); const hubReady = yield* Effect.forkChild(hub.ready); const socket = yield* awaitSocket(sockets); @@ -1278,7 +1279,7 @@ const connectHubAndWindows = Effect.fn("TestRpcSessionFactory.connectHubAndWindo yield* secondary.ready; windows.push(secondary); } - return { hub, windows, socket, sockets }; + return { factory, hub, windows, socket, sockets }; }); const connectHubAndWindow = Effect.fn("TestRpcSessionFactory.connectHubAndWindow")(function* () { @@ -1375,13 +1376,7 @@ describe("hub relay", () => { it.effect("interrupts a window's open streams on the server when the relay ends", () => Effect.gen(function* () { - const { factory, sockets } = yield* makeFactory(); - const hub = yield* factory.connect(PREPARED); - const hubReady = yield* Effect.forkChild(hub.ready); - const socket = yield* awaitSocket(sockets); - socket.open(); - yield* completeInitialConfig(socket); - yield* Fiber.join(hubReady); + const { factory, hub, socket } = yield* connectHubAndWindows(0, {}); const [hubPort, windowPort] = makePortPair(); const relayScope = yield* Scope.make(); yield* hub.relay!(hubPort).pipe(Scope.provide(relayScope)); @@ -1719,13 +1714,7 @@ describe("shared hub subscriptions", () => { it.effect("ends a window's relay and its config stream when the hub closes it", () => Effect.gen(function* () { - const { factory, sockets } = yield* makeFactory({ shareStreams: true }); - const hub = yield* factory.connect(PREPARED); - const hubReady = yield* Effect.forkChild(hub.ready); - const socket = yield* awaitSocket(sockets); - socket.open(); - yield* completeInitialConfig(socket); - yield* Fiber.join(hubReady); + const { factory, hub } = yield* connectHubAndWindows(0); const [hubPort, windowPort] = makePortPair(); const relay = yield* hub.relay!(hubPort); const secondary = yield* factory.connectOverPort(PREPARED, windowPort); From bfcf1b28ccbededcf5b4bbcdf91d5fbc5c4adc89 Mon Sep 17 00:00:00 2001 From: Na0s Date: Thu, 19 Nov 2026 23:23:34 -0500 Subject: [PATCH 07/20] refactor(client-runtime): relay ports drain through an Effect queue Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/rpc/relay.ts | 37 ++++++------------------ 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/packages/client-runtime/src/rpc/relay.ts b/packages/client-runtime/src/rpc/relay.ts index cbceb3682a5b8..6d17f44972383 100644 --- a/packages/client-runtime/src/rpc/relay.ts +++ b/packages/client-runtime/src/rpc/relay.ts @@ -1,6 +1,7 @@ import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as RpcClient from "effect/rpc/RpcClient"; @@ -57,31 +58,12 @@ export interface SharedRelayStream { readonly encode: (values: ReadonlyArray) => Effect.Effect; } -/** Runs port messages one at a time and in arrival order, like a socket's frames. */ -const makeSerialRunner = ( - runFork: (effect: Effect.Effect) => unknown, - handle: (message: A) => Effect.Effect, -) => { - const queue: Array = []; - let draining = false; - const drain = Effect.gen(function* () { - while (queue.length > 0) { - yield* handle(queue.shift()!); - } - }).pipe( - Effect.ensuring( - Effect.sync(() => { - draining = false; - }), - ), - ); - return (message: A) => { - queue.push(message); - if (draining) return; - draining = true; - runFork(drain); - }; -}; +/** Handles port messages one at a time and in arrival order, like a socket's frames. */ +const makeInbox = Effect.fnUntraced(function* (handle: (message: A) => Effect.Effect) { + const inbox = yield* Queue.unbounded(); + yield* Queue.take(inbox).pipe(Effect.flatMap(handle), Effect.forever, Effect.forkScoped); + return (message: A) => Queue.offerUnsafe(inbox, message); +}); // RpcClient numbers its clients from 0 within one JavaScript realm, so relay // clients sharing the hub's protocol start far above any realistic count. @@ -225,7 +207,7 @@ export const serveRelay = Effect.fnUntraced(function* (options: { } }; - const enqueue = makeSerialRunner(runFork, handle); + const enqueue = yield* makeInbox(handle); const stopListening = port.onMessage((message) => { if (!closed) enqueue(message as FromClientEncoded); }); @@ -264,7 +246,6 @@ export const makePortProtocol = (options: { RpcClient.Protocol.make( Effect.fnUntraced(function* (writeResponse, clientIds) { const { port } = options; - const runFork = Effect.runForkWith(yield* Effect.context()); const requestClients = new Map(); let closedError: RpcClientError.RpcClientError | undefined; @@ -321,7 +302,7 @@ export const makePortProtocol = (options: { return broadcast(response); }; - const enqueue = makeSerialRunner(runFork, receive); + const enqueue = yield* makeInbox(receive); const stopListening = port.onMessage((message) => { options.onMessage?.(); enqueue(message); From 5dea0f002cd84216e5a502d2d0cd50e24797b16b Mon Sep 17 00:00:00 2001 From: Na0s Date: Sat, 21 Nov 2026 15:41:06 -0500 Subject: [PATCH 08/20] feat(contracts): bots setting marks projects as T3_BOT identities A bot is a project listed in server settings `bots` (role, main thread, order). The project keeps the name and icon; clients get `isBot` on the project like `isScratch`. No migration: settings already stream to every client. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/state/models.ts | 1 + .../src/state/projectEntities.ts | 20 +++++++++---------- packages/contracts/src/settings.ts | 15 ++++++++++++++ packages/shared/src/serverSettings.test.ts | 12 +++++++++++ packages/shared/src/serverSettings.ts | 2 ++ 5 files changed, 40 insertions(+), 10 deletions(-) diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index a57483fdd95c5..308980b992893 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -26,6 +26,7 @@ import { formatSubagentDisplayTitle } from "./subagentDisplay.ts"; export interface EnvironmentProject extends OrchestrationProjectShell { readonly environmentId: EnvironmentId; readonly isScratch?: true; + readonly isBot?: true; } /** diff --git a/packages/client-runtime/src/state/projectEntities.ts b/packages/client-runtime/src/state/projectEntities.ts index 313f845797e97..e4c5a46999dcd 100644 --- a/packages/client-runtime/src/state/projectEntities.ts +++ b/packages/client-runtime/src/state/projectEntities.ts @@ -24,7 +24,7 @@ export function createEnvironmentProjectAtoms(input: { ) => Atom.Atom; readonly serverConfigValueAtom?: ( environmentId: EnvironmentId, - ) => Atom.Atom | null>; + ) => Atom.Atom | null>; }) { const environmentProjectsAtom = Atom.family((environmentId: EnvironmentId) => Atom.make( @@ -62,28 +62,28 @@ export function createEnvironmentProjectAtoms(input: { const ref = parseProjectKey(key); let previousSource: OrchestrationProjectShell | null = null; let previousIsScratch = false; + let previousIsBot = false; let previousValue: EnvironmentProject | null = null; return Atom.make((get) => { const source = get(environmentProjectIndexAtom(ref.environmentId)).get(ref.projectId) ?? null; - const scratch = - source !== null && - isScratchProject( - source, - input.serverConfigValueAtom - ? get(input.serverConfigValueAtom(ref.environmentId))?.scratchWorkspaceRoot - : null, - ); - if (source === previousSource && scratch === previousIsScratch) { + const config = input.serverConfigValueAtom + ? get(input.serverConfigValueAtom(ref.environmentId)) + : null; + const scratch = source !== null && isScratchProject(source, config?.scratchWorkspaceRoot); + const bot = source !== null && Object.hasOwn(config?.settings.bots ?? {}, source.id); + if (source === previousSource && scratch === previousIsScratch && bot === previousIsBot) { return previousValue; } previousSource = source; previousIsScratch = scratch; + previousIsBot = bot; previousValue = source === null ? null : { ...scopeProject(ref.environmentId, source), ...(scratch ? { isScratch: true as const } : {}), + ...(bot ? { isBot: true as const } : {}), }; return previousValue; }).pipe(Atom.withLabel(`environment-project:${key}`)); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index e7887f88f0369..b73fea277448e 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1377,6 +1377,15 @@ export const CloudSpeechCredentials = Schema.Struct({ openrouter: CloudSpeechCredential, }); +/** A T3_BOT identity. The project carries the name and icon; its threads are the bot's conversations. */ +export const BotSettings = Schema.Struct({ + role: Schema.optionalKey(TrimmedString), + /** Conversation that receives mentions; null or missing uses the bot's most recent thread. */ + mainThreadId: Schema.optionalKey(Schema.NullOr(ThreadId)), + order: Schema.optionalKey(Schema.Number), +}); +export type BotSettings = typeof BotSettings.Type; + export const ServerSettings = Schema.Struct({ // Null means unmigrated; empty is authoritative and must not resurrect cleared preferences. favorites: Schema.NullOr(ModelFavorites).pipe(Schema.withDecodingDefault(Effect.succeed(null))), @@ -1622,6 +1631,9 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed({})), ), + /** Bot projects are hidden from the main project and thread lists and shown in the bot window. */ + bots: Schema.Record(ProjectId, BotSettings).pipe(Schema.withDecodingDefault(Effect.succeed({}))), + /** Sent by the Usage tab with each summary request to this environment; edit in settings.json. Invalid values are ignored. */ usageModelFilter: ForwardCompatibleOptional(UsageModelFilter), }); @@ -2014,6 +2026,9 @@ export const ServerSettingsPatch = Schema.Struct({ usageModelAliases: Schema.optionalKey( Schema.Record(TrimmedNonEmptyString, Schema.NullOr(TrimmedNonEmptyString)), ), + + /** Each entry replaces the stored bot; null turns the project back into a normal project. */ + bots: Schema.optionalKey(Schema.Record(ProjectId, Schema.NullOr(BotSettings))), }); export type ServerSettingsPatch = typeof ServerSettingsPatch.Type; diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts index 9836fe10fc77f..9a2539ed5e4bb 100644 --- a/packages/shared/src/serverSettings.test.ts +++ b/packages/shared/src/serverSettings.test.ts @@ -724,6 +724,18 @@ describe("serverSettings helpers", () => { expect(current.usagePriceOverrides["example-model"]?.cacheReadCostPerMillionTokens).toBe(0.5); }); + it("replaces and removes individual bots without clobbering other bots", () => { + const atlas = ProjectId.make("project-atlas"); + const warden = ProjectId.make("project-warden"); + const current = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { + bots: { [atlas]: { role: "Orchestrator", order: 0 }, [warden]: { role: "PR babysitter" } }, + }); + const replaced = applyServerSettingsPatch(current, { bots: { [atlas]: { order: 1 } } }); + expect(replaced.bots).toEqual({ [atlas]: { order: 1 }, [warden]: { role: "PR babysitter" } }); + const removed = applyServerSettingsPatch(replaced, { bots: { [atlas]: null } }); + expect(removed.bots).toEqual({ [warden]: { role: "PR babysitter" } }); + }); + it("stores background activity profiles as a versioned object and syncs legacy aliases", () => { const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { backgroundActivity: { diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 023c6eb74333e..6dc1e6744d84c 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -407,6 +407,7 @@ export function applyServerSettingsPatch( sourceControlHosts: sourceControlHostsPatch, usagePriceOverrides: usagePriceOverridesPatch, usageModelAliases: usageModelAliasesPatch, + bots: botsPatch, // Entry replacement: deepMerge would keep keys the client meant to clear. projectSettingsOverrides: projectSettingsOverridesPatch, projectAgentBrowserAccessOverrides: _legacyBrowserAccess, @@ -634,6 +635,7 @@ export function applyServerSettingsPatch( ), } : {}), + ...(botsPatch !== undefined ? { bots: mergeSettingsEntries(current.bots, botsPatch) } : {}), ...(usageModelAliasesPatch !== undefined ? { usageModelAliases: mergeSettingsEntries( From 26a4432071c61c0ae89163b06a87b7e662973930 Mon Sep 17 00:00:00 2001 From: Na0s Date: Sat, 21 Nov 2026 15:42:11 -0500 Subject: [PATCH 09/20] feat(contracts): desktop bridge for the T3_BOT window Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/desktopWindows.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/contracts/src/desktopWindows.ts b/packages/contracts/src/desktopWindows.ts index 55f817e17ee1b..feb01124f6809 100644 --- a/packages/contracts/src/desktopWindows.ts +++ b/packages/contracts/src/desktopWindows.ts @@ -30,6 +30,18 @@ export interface DesktopHubLinkMessage { readonly peerWindowId: number; } +export type DesktopBotWindowSize = "narrow" | "medium"; + +/** The single T3_BOT window: a floating, optionally always-on-top window showing the `/bot` route. */ +export interface DesktopBotWindowBridge { + /** Opens the bot window, or focuses it when it is already open. */ + open: () => Promise; + /** Bot window only: keep it above other apps' windows. */ + setPinned: (pinned: boolean) => Promise; + /** Bot window only. */ + setSize: (size: DesktopBotWindowSize) => Promise; +} + export interface DesktopWindowsBridge { getContext: () => DesktopWindowContext; getState: () => Promise; @@ -43,4 +55,6 @@ export interface DesktopWindowsBridge { 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; + /** Absent on desktop builds without the bot window. */ + bot?: DesktopBotWindowBridge; } From 0d024ba52a56e4a084b5fae18d6e033f0d72566f Mon Sep 17 00:00:00 2001 From: Na0s Date: Sat, 21 Nov 2026 15:59:42 -0500 Subject: [PATCH 10/20] feat(client-runtime): keep T3_BOT projects and threads out of the main lists Bot projects belong to the bot window, but every project and thread list in the main window still showed them. Client-runtime now derives `visibleProjectsAtom` (projects without `isBot`) and leaves bot-project threads out of the visible, quiet and navigation thread lists. Bot threads stay out of `hiddenThreadKeysAtom`, so notifications for them still show, and point reads and `threadShellsAtom` stay complete. The web sidebar, command palette, project pickers, new-thread defaults and prompt links, and the mobile home, sidebar, palette and new-task flow read the visible projects. Scheduled-task thread pickers keep bot threads, since a bot's tasks post to its own conversations. Co-Authored-By: Claude Opus 5.5 --- .../src/features/home/HomeRouteScreen.tsx | 4 +- .../src/features/keyboard/CommandPalette.tsx | 4 +- .../layout/AdaptiveWorkspaceLayout.tsx | 4 +- .../prompt-links/newTaskPromptLink.ts | 2 +- .../settings/ScheduledTaskPickerScreens.tsx | 16 +++-- .../features/threads/NewTaskDraftScreen.tsx | 4 +- .../threads/ThreadNavigationSidebar.tsx | 4 +- .../features/threads/ThreadRouteScreen.tsx | 4 +- .../threads/new-task-flow-provider.test.tsx | 2 +- .../threads/new-task-flow-provider.tsx | 4 +- apps/mobile/src/state/entities.ts | 7 +- apps/mobile/src/state/threads.ts | 2 + .../CommandPalette.browser.test.tsx | 1 + .../src/components/CommandPaletteLookups.ts | 4 +- .../promptLinks/NewThreadLinkView.tsx | 4 +- .../settings/ScheduledTasksSettings.tsx | 11 ++- apps/web/src/hooks/useHandleNewThread.ts | 4 +- apps/web/src/hooks/useSidebarProjectGroups.ts | 8 ++- apps/web/src/routes/_chat.index.tsx | 4 +- .../src/shortcuts/chatRouteCommands.test.ts | 2 +- apps/web/src/shortcuts/chatRouteCommands.ts | 6 +- apps/web/src/state/entities.ts | 11 ++- apps/web/src/state/threads.ts | 1 + .../src/state/projectEntities.test.ts | 51 ++++++++++++-- .../src/state/projectEntities.ts | 21 +++++- packages/client-runtime/src/state/server.ts | 14 ++++ .../src/state/threadShell.test.ts | 67 +++++++++++++++++++ .../client-runtime/src/state/threadShell.ts | 58 ++++++++++++++-- 28 files changed, 273 insertions(+), 51 deletions(-) diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index 2550f96508729..19d4065e25f0f 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -10,7 +10,7 @@ import { useGT, useMessages } from "gt-react-native"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; -import { useProjects } from "../../state/entities"; +import { useVisibleProjects } from "../../state/entities"; import { steadyNavigationThreadShellsAtom } from "../../state/threads"; import { useLaunchingThreads, usePendingNewTasks } from "../../state/use-pending-new-tasks"; import { useWorkspaceState } from "../../state/workspace"; @@ -49,7 +49,7 @@ export function HomeRouteScreen() { const { layout, setPrimarySidebarSearchQuery, startNewTask } = useAdaptiveWorkspaceLayout(); const { primarySidebarSearchQuery } = useWorkspacePaneState(); const selectDetail = useSelectWorkspaceDetail(); - const projects = useProjects(); + const projects = useVisibleProjects(); // Stop rebuilding the streaming thread list while Thread covers Home. const visible = useHomeRouteVisible(); const threads = useLaunchingThreads( diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx index 4be1c5d9032e8..cbc1b4fc7ad3a 100644 --- a/apps/mobile/src/features/keyboard/CommandPalette.tsx +++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx @@ -47,9 +47,9 @@ import { useNativeLayoutMetrics } from "../../native/native-layout-metrics"; import { T3KeyboardCommands } from "../../native/T3KeyboardCommands"; import { useDelegatedUnderParent, - useProjects, useServerConfigs, useThreadShell, + useVisibleProjects, useVisibleThreadShells, } from "../../state/entities"; import { useThreadSearch } from "../../state/queries"; @@ -232,7 +232,7 @@ export function CommandPalette(props: { const { themeVariables } = useAppearancePreferences(); const selectDetail = useSelectWorkspaceDetail(); const runCommand = props.onCommand; - const projects = useProjects(); + const projects = useVisibleProjects(); const threads = useVisibleThreadShells(); const delegatedUnderParent = useDelegatedUnderParent(); const activeThreadRef = parseActiveThreadPath(props.pathname); diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 629100e46bcc5..935179cf4221c 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -56,7 +56,7 @@ import { } from "../../lib/layout"; import type { ThreadListFilters } from "../../persistence/mobile-preferences"; import { appAtomRegistry } from "../../state/atom-registry"; -import { useProjects } from "../../state/entities"; +import { useVisibleProjects } from "../../state/entities"; import { environmentThreadShells } from "../../state/threads"; import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; import { mobilePreferencesAtom } from "../../state/preferences"; @@ -591,7 +591,7 @@ function AdaptiveWorkspaceLayoutContent( const handleSelectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) => handleSelectDetail({ name: "Thread", params }); - const projects = useProjects(); + const projects = useVisibleProjects(); const compactAndroidSettings = Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView; // Reads the open page when pressed, so the layout context doesn't change on every navigation. diff --git a/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts b/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts index b1e80081d8a4a..f6d96b705de82 100644 --- a/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts +++ b/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts @@ -402,7 +402,7 @@ function resolveLink(linkSearch: string) { const activityOf = (project: EnvironmentProject) => lastActivity.get(`${project.environmentId}:${project.id}`) ?? ""; const projects = findPromptLinkProjects( - [...appAtomRegistry.get(environmentProjects.projectsAtom)].sort((left, right) => + [...appAtomRegistry.get(environmentProjects.visibleProjectsAtom)].sort((left, right) => activityOf(right).localeCompare(activityOf(left)), ), repository, diff --git a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx index f07ffea096ec8..034cc2a41a9d9 100644 --- a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx +++ b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx @@ -1,8 +1,10 @@ import { msg, T, useGT, useMessages } from "gt-react-native"; import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { LegendList } from "@legendapp/list/react-native"; +import { useAtomValue } from "@effect/atom-react"; import { useNavigation } from "@react-navigation/native"; import { scheduledTaskWorktreeBaseRef } from "@t3tools/client-runtime/scheduled-task-worktree"; +import { threadKey } from "@t3tools/client-runtime/state/entities"; import { isListedThreadLineage } from "@t3tools/contracts"; import * as Haptics from "expo-haptics"; import { useMemo, useState } from "react"; @@ -14,11 +16,8 @@ import { SelectionRow } from "../../components/ui/SelectionRow"; import { useSearchToolbarInset } from "../../components/ui/useBarInset"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; -import { - useEnvironmentServerConfig, - useProjects, - useVisibleThreadShells, -} from "../../state/entities"; +import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities"; +import { environmentThreadShells } from "../../state/threads"; import { useDebouncedValue, usePaginatedBranches, useThreadSearch } from "../../state/queries"; import { BranchPickerScreen } from "../threads/NewTaskContextPickerScreens"; import { ThreadSettingsPickerScreen } from "../threads/ThreadSettingsSheet"; @@ -204,7 +203,12 @@ export function ScheduledTaskThreadPickerRouteScreen() { const projectId = editor?.draft.projectId ?? null; const threadId = editor?.draft.threadId ?? null; const currentLabel = useScheduledTaskDestinationLabel(environmentId, threadId); - const shells = useVisibleThreadShells(); + // Unlike other lists, bot threads stay pickable: a bot's tasks post to its own conversations. + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + const shells = useThreadShells().filter( + (shell) => + !hiddenKeys.has(threadKey({ environmentId: shell.environmentId, threadId: shell.id })), + ); const [query, setQuery] = useState(""); const search = { value: query, diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index c6fa629d18b43..0385fb492c906 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -65,7 +65,7 @@ import { updateComposerDraftSettings, scheduleUnusedComposerAttachmentCleanup, } from "../../state/use-composer-drafts"; -import { useEnvironmentServerConfig, useProjects } from "../../state/entities"; +import { useEnvironmentServerConfig, useVisibleProjects } from "../../state/entities"; import { useProjectClone } from "../../state/projectClones"; import { projectEnvironment } from "../../state/projects"; import { sourceControlEnvironment } from "../../state/sourceControl"; @@ -166,7 +166,7 @@ export function NewTaskDraftScreen(props: { const gt = useGT(); const m = useMessages(); const [creationMetadata] = useState(makeTurnCommandMetadata); - const projects = useProjects(); + const projects = useVisibleProjects(); const flow = useNewTaskFlow(); const navigation = useNavigation(); const isFocused = useIsFocused(); diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 681f5d3c6fa0a..dcc66407c906b 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -25,7 +25,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; -import { useProjects } from "../../state/entities"; +import { useVisibleProjects } from "../../state/entities"; import { steadyNavigationThreadShellsAtom } from "../../state/threads"; import { useThreadSearch } from "../../state/queries"; import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences"; @@ -129,7 +129,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { const insets = useSafeAreaInsets(); const { fabClearance, fabSize } = useAndroidControlSizing(); - const projects = useProjects(); + const projects = useVisibleProjects(); const threads = useAtomValue(steadyNavigationThreadShellsAtom); const selectedThreadKey = useSidebarRowThreadKey(props.selectedThreadKey); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 8f509de9e674a..fc7194059bcc0 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -102,7 +102,7 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE, threadErrorText, } from "@t3tools/client-runtime/state/threads"; -import { useProjects } from "../../state/entities"; +import { useVisibleProjects } from "../../state/entities"; import { projectThreadContentPresentation, threadSyncStatusLabel, @@ -215,7 +215,7 @@ function ThreadUnavailableScreen(props: { /** A thread that can't load opens a new task in its environment instead of a dead end. */ function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) { const navigation = useNavigation(); - const projects = useProjects(); + const projects = useVisibleProjects(); const openDraft = useEffectEvent(() => { const project = projects.find((candidate) => candidate.environmentId === props.environmentId); navigation.dispatch( diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx index cf7b35b05f45a..ddc35a5f80d93 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx @@ -45,7 +45,7 @@ vi.mock("../../state/atom-registry", () => ({ }, })); vi.mock("../../state/entities", () => ({ - useProjects: mocks.projects, + useVisibleProjects: mocks.projects, useThreadShells: () => [], useEnvironmentServerConfig: () => mocks.serverConfig() ?? null, useServerConfigs: () => new Map(), diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 33fbbd7e02b7f..d361f3c3caa4a 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -26,7 +26,7 @@ import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triag import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; -import { useProjects, useServerConfigs, useThreadShells } from "../../state/entities"; +import { useServerConfigs, useThreadShells, useVisibleProjects } from "../../state/entities"; import type { TurnCommandMetadata } from "../../lib/commandMetadata"; import type { DraftComposerAttachment } from "../../lib/composerImages"; import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; @@ -243,7 +243,7 @@ export function NewTaskFlowProvider( routeDraftId?: string; }>, ) { - const projects = useProjects(); + const projects = useVisibleProjects(); const messages = useMessages(); const threads = useThreadShells(); const { savedConnectionsById } = useSavedRemoteConnections(); diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts index cecb7fa84a446..67d527a09753b 100644 --- a/apps/mobile/src/state/entities.ts +++ b/apps/mobile/src/state/entities.ts @@ -197,11 +197,16 @@ export function useProjects(): ReadonlyArray { return useAtomValue(environmentProjects.projectsAtom); } +/** Projects without T3_BOT projects, for lists and pickers. */ +export function useVisibleProjects(): ReadonlyArray { + return useAtomValue(environmentProjects.visibleProjectsAtom); +} + export function useThreadShells(): ReadonlyArray { return useAtomValue(environmentThreadShells.threadShellsAtom); } -/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */ +/** Thread shells minus tag-hidden and T3_BOT threads, for lists that show threads to the user. */ export function useVisibleThreadShells(): ReadonlyArray { return useAtomValue(environmentThreadShells.visibleThreadShellsAtom); } diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index bf2013aef5398..c3796bcd76052 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -46,6 +46,7 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: threadEnvironment.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + botProjectIdsAtom: serverEnvironment.botProjectIdsAtom, }); const steadyShells = createSteadyShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, @@ -63,6 +64,7 @@ export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtom catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: steadyShells.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + botProjectIdsAtom: serverEnvironment.botProjectIdsAtom, }).navigationThreadShellsAtom; export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom, diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsx index f29feada58e0a..d796a4dc5b028 100644 --- a/apps/web/src/components/CommandPalette.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.browser.test.tsx @@ -47,6 +47,7 @@ vi.mock("../hooks/useHandleNewThread", async (original) => { vi.mock("../state/entities", async (original) => ({ ...(await original()), useProjects: () => entities.projects, + useVisibleProjects: () => entities.projects, useVisibleThreadShells: () => entities.threads, useDelegatedUnderParent: () => entities.delegatedUnderParent, })); diff --git a/apps/web/src/components/CommandPaletteLookups.ts b/apps/web/src/components/CommandPaletteLookups.ts index 75e94a33e0573..79288333f6032 100644 --- a/apps/web/src/components/CommandPaletteLookups.ts +++ b/apps/web/src/components/CommandPaletteLookups.ts @@ -8,7 +8,7 @@ import { useGT } from "gt-react"; import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal"; import { useClientSettings } from "../hooks/useSettings"; import { getProjectOrderKey } from "@t3tools/client-runtime/state/project-grouping"; -import { useProjects, useVisibleThreadShells } from "../state/entities"; +import { useProjects, useVisibleProjects, useVisibleThreadShells } from "../state/entities"; import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; @@ -60,7 +60,7 @@ export const selectCommandPaletteClientSettings = (settings: ClientSettings) => }); export function useSortedProjectGroups(environmentLabelById: ReadonlyMap) { - const projects = useProjects(); + const projects = useVisibleProjects(); const threads = useVisibleThreadShells(); const projectOrder = useUiStateStore((store) => store.projectOrder); const clientSettings = useClientSettings(selectCommandPaletteClientSettings); diff --git a/apps/web/src/components/promptLinks/NewThreadLinkView.tsx b/apps/web/src/components/promptLinks/NewThreadLinkView.tsx index b70b143fb618b..b48c361a734dc 100644 --- a/apps/web/src/components/promptLinks/NewThreadLinkView.tsx +++ b/apps/web/src/components/promptLinks/NewThreadLinkView.tsx @@ -34,7 +34,7 @@ import { isElectron } from "~/env"; import { useNewThreadHandler } from "~/hooks/useHandleNewThread"; import { useScratchProject } from "~/hooks/useScratchProject"; import { newProjectId } from "~/lib/utils"; -import { useProjects, useThreadShells, waitForProject } from "~/state/entities"; +import { useThreadShells, useVisibleProjects, waitForProject } from "~/state/entities"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments"; import { environmentPresentations } from "~/state/presentation"; @@ -109,7 +109,7 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) { const gt = useGT(); const navigate = useNavigate(); const ready = useAtomValue(allReachableShellsLiveAtom); - const projects = useProjects(); + const projects = useVisibleProjects(); const threads = useThreadShells(); const { environments } = useEnvironments(); const primaryEnvironmentId = usePrimaryEnvironmentId(); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index a2ffce32e68cd..42aaeaeebe8ae 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -69,13 +69,15 @@ import { type EnvironmentPresentation, } from "../../state/environments"; import { + useHiddenThreadKeys, useProjects, useQuietThreadShell, useThreadShell, - useVisibleThreadShells, + useThreadShells, } from "../../state/entities"; import { buildThreadRouteParams } from "../../threadRoutes"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { threadKey } from "@t3tools/client-runtime/state/entities"; import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList"; import { usePaginatedBranches, useThreadSearch } from "../../state/queries"; import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query"; @@ -1336,7 +1338,12 @@ function ScheduledTaskDestination({ : threadMode === "new_thread" ? gt("New thread each run") : gt("Started by the first run"); - const shells = useVisibleThreadShells(open); + // Unlike other lists, bot threads stay pickable: a bot's tasks post to its own conversations. + const hiddenKeys = useHiddenThreadKeys(); + const shells = useThreadShells(open).filter( + (shell) => + !hiddenKeys.has(threadKey({ environmentId: shell.environmentId, threadId: shell.id })), + ); // Mounts older settled threads matching the query, which shells may leave out. useThreadSearch(open && projectId ? [environmentId] : [], query, { titlesOnly: true, diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index ea9c42b2649b5..d42d54b50e673 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -34,8 +34,8 @@ import { readProjects, readThreadShell, readThreadShells, - useProjects, useQuietThreadShell, + useVisibleProjects, } from "../state/entities"; import { draftModelSelectionApplies, @@ -527,7 +527,7 @@ export function useHandleNewThread() { : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId) : null, ); - const projects = useProjects(); + const projects = useVisibleProjects(); const handleNewThread = useNewThreadHandler(); const groupingSettings = useClientSettings(selectProjectGroupingSettings); const defaultProjectRef = resolveDefaultProjectRef( diff --git a/apps/web/src/hooks/useSidebarProjectGroups.ts b/apps/web/src/hooks/useSidebarProjectGroups.ts index 7a0036d35786d..7eaeb354e27f9 100644 --- a/apps/web/src/hooks/useSidebarProjectGroups.ts +++ b/apps/web/src/hooks/useSidebarProjectGroups.ts @@ -7,12 +7,16 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping"; import { useEnvironmentIdentities, usePrimaryEnvironmentId } from "../state/environments"; -import { useDelegatedUnderParent, useProjects, useQuietThreadShells } from "../state/entities"; +import { + useDelegatedUnderParent, + useQuietThreadShells, + useVisibleProjects, +} from "../state/entities"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; import { useClientSettings } from "./useSettings"; export function useSidebarProjectGroups() { - const projects = useProjects(); + const projects = useVisibleProjects(); // Activity order lags a running thread's streaming ticks until its next // real change; reading every tick re-rendered the whole sidebar with it. const threads = useQuietThreadShells(); diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsx index 2e6ee53809310..102a5450a706c 100644 --- a/apps/web/src/routes/_chat.index.tsx +++ b/apps/web/src/routes/_chat.index.tsx @@ -17,7 +17,7 @@ import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { readProject, useAllEnvironmentShellsBootstrapped, - useProjects, + useVisibleProjects, useVisibleThreadShells, } from "../state/entities"; import { useEnvironments } from "../state/environments"; @@ -35,7 +35,7 @@ function ChatIndexRouteView() { } function IndexDraftLanding() { - const projects = useProjects(); + const projects = useVisibleProjects(); const threads = useVisibleThreadShells(); const bootstrapped = useAllEnvironmentShellsBootstrapped(); const handleNewThread = useNewThreadHandler(); diff --git a/apps/web/src/shortcuts/chatRouteCommands.test.ts b/apps/web/src/shortcuts/chatRouteCommands.test.ts index 3979368ff9032..9ec07005e2c19 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.test.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.test.ts @@ -42,7 +42,7 @@ describe("new thread commands", () => { boringSidebarEnabled: scenario.mode === "boring", }); using _projects = vi - .spyOn(entities, "readProjects") + .spyOn(entities, "readVisibleProjects") .mockReturnValue([project("active"), project("idle")].slice(0, scenario.count)); using _ready = vi .spyOn(projectsState, "defaultProjectFallbackReadyAtom") diff --git a/apps/web/src/shortcuts/chatRouteCommands.ts b/apps/web/src/shortcuts/chatRouteCommands.ts index 7cca45fbd81db..70d8947ef2aac 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.ts @@ -23,7 +23,7 @@ import { selectProjectGroupingSettings } from "@t3tools/client-runtime/state/pro import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping"; -import { readProjects, readThreadShell } from "../state/entities"; +import { readThreadShell, readVisibleProjects } from "../state/entities"; import { defaultProjectFallbackReadyAtom } from "../state/projects"; import { environmentPresentations } from "../state/presentation"; import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment"; @@ -87,7 +87,7 @@ export function installChatRouteCommands(router: AnyRouter): () => void { activeDraftThread, activeThread: activeThread ?? undefined, defaultProjectRef: resolveDefaultProjectRef( - readProjects(), + readVisibleProjects(), useUiStateStore.getState().projectOrder, lastUsedProjectKey, appAtomRegistry.get(defaultProjectFallbackReadyAtom(lastUsedProjectKey)), @@ -99,7 +99,7 @@ export function installChatRouteCommands(router: AnyRouter): () => void { // Grouped like the sidebar, so the shortcut and the New thread button agree. const readProjectGroups = () => buildSidebarProjectSnapshots({ - projects: readProjects(), + projects: readVisibleProjects(), groupScratchProjects: true, settings: selectProjectGroupingSettings(getClientSettings()), primaryEnvironmentId: appAtomRegistry.get(primaryEnvironmentIdAtom), diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index e2205c7c2d787..4b3cd61669414 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -104,6 +104,11 @@ export function useProjects(): ReadonlyArray { return useAtomValue(environmentProjects.projectsAtom); } +/** Projects without T3_BOT projects, for lists and pickers in the main window. */ +export function useVisibleProjects(): ReadonlyArray { + return useAtomValue(environmentProjects.visibleProjectsAtom); +} + /** Providers are left out; read them with `useEnvironmentProviders()`. */ export function useServerConfigs() { return useAtomValue(environmentPresentations.serverConfigsAtom); @@ -125,7 +130,7 @@ export function useHiddenThreadKeys(): ReadonlySet { return useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); } -/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */ +/** Thread shells minus tag-hidden and T3_BOT threads, for lists that show threads to the user. */ export function useVisibleThreadShells(enabled = true): ReadonlyArray { return useAtomValue( enabled ? environmentThreadShells.visibleThreadShellsAtom : EMPTY_THREAD_SHELLS_ATOM, @@ -305,6 +310,10 @@ export function readProjects(): ReadonlyArray { return appAtomRegistry.get(environmentProjects.projectsAtom); } +export function readVisibleProjects(): ReadonlyArray { + return appAtomRegistry.get(environmentProjects.visibleProjectsAtom); +} + export function waitForProject( ref: ScopedProjectRef, timeoutMs = 10_000, diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 6d2ce2a07c90b..b33246067a29e 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -41,6 +41,7 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: threadEnvironment.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + botProjectIdsAtom: serverEnvironment.botProjectIdsAtom, }); export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom, diff --git a/packages/client-runtime/src/state/projectEntities.test.ts b/packages/client-runtime/src/state/projectEntities.test.ts index c4e1d9cd55ec7..20317ea092aeb 100644 --- a/packages/client-runtime/src/state/projectEntities.test.ts +++ b/packages/client-runtime/src/state/projectEntities.test.ts @@ -9,6 +9,7 @@ import { v2Project, v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts"; const environmentId = EnvironmentId.make("local"); const remoteEnvironmentId = EnvironmentId.make("remote"); +const NO_BOTS = { bots: {} }; function makeHarness(withConfig = true) { const snapshotAtom = Atom.family((_environmentId: EnvironmentId) => @@ -26,7 +27,13 @@ function makeHarness(withConfig = true) { }), ); const configAtom = Atom.family((_environmentId: EnvironmentId) => - Atom.make<(Pick & { revision?: number }) | null>(null), + Atom.make< + | (Pick & { + settings: Pick; + revision?: number; + }) + | null + >(null), ); const catalogValueAtom = Atom.make({ isReady: true, @@ -59,7 +66,10 @@ describe("project scratch identity", () => { const { registry, projects, configAtom, catalogValueAtom } = makeHarness(); try { expect(registry.get(projects.projectConfigsReadyAtom)).toBe(false); - registry.set(configAtom(environmentId), { scratchWorkspaceRoot: v2Project.workspaceRoot }); + registry.set(configAtom(environmentId), { + scratchWorkspaceRoot: v2Project.workspaceRoot, + settings: NO_BOTS, + }); expect(registry.get(projects.projectConfigsReadyAtom)).toBe(false); const catalog = registry.get(catalogValueAtom); registry.set(catalogValueAtom, { @@ -74,7 +84,7 @@ describe("project scratch identity", () => { expect(registry.get(projects.projectConfigsReadyAtom)).toBe(true); registry.set(catalogValueAtom, catalog); expect(registry.get(projects.projectConfigsReadyAtom)).toBe(false); - registry.set(configAtom(remoteEnvironmentId), {}); + registry.set(configAtom(remoteEnvironmentId), { settings: NO_BOTS }); expect(registry.get(projects.projectConfigsReadyAtom)).toBe(true); registry.set(catalogValueAtom, { ...catalog, isReady: false }); expect(registry.get(projects.projectConfigsReadyAtom)).toBe(false); @@ -90,6 +100,7 @@ describe("project scratch identity", () => { const source = registry.get(snapshotAtom(environmentId)); registry.set(configAtom(environmentId), { scratchWorkspaceRoot: `${v2Project.workspaceRoot}/`, + settings: NO_BOTS, }); const next = registry.get(projects.projectsAtom); @@ -104,11 +115,12 @@ describe("project scratch identity", () => { registry.set(configAtom(environmentId), { scratchWorkspaceRoot: v2Project.workspaceRoot, + settings: NO_BOTS, revision: 1, }); expect(registry.get(projects.projectsAtom)).toBe(next); - registry.set(configAtom(environmentId), { scratchWorkspaceRoot: "/repo" }); + registry.set(configAtom(environmentId), { scratchWorkspaceRoot: "/repo", settings: NO_BOTS }); const changedRoot = registry.get(projects.projectsAtom); expect(changedRoot[0]).not.toHaveProperty("isScratch"); expect(changedRoot[1]?.isScratch).toBe(true); @@ -120,4 +132,35 @@ describe("project scratch identity", () => { registry.dispose(); } }); + + it("marks bot projects and leaves them out of the visible list only", () => { + const { registry, projects, configAtom } = makeHarness(); + const ordinary = ProjectId.make("ordinary"); + const ordinaryRef = { environmentId, projectId: ordinary }; + try { + const all = registry.get(projects.projectsAtom); + expect(registry.get(projects.visibleProjectsAtom)).toBe(all); + + registry.set(configAtom(environmentId), { settings: { bots: { [ordinary]: {} } } }); + expect(registry.get(projects.projectAtom(ordinaryRef))?.isBot).toBe(true); + expect( + registry.get( + projects.projectAtom({ environmentId: remoteEnvironmentId, projectId: ordinary }), + )?.isBot, + ).toBeUndefined(); + expect(registry.get(projects.projectsAtom)).toHaveLength(all.length); + const visible = registry.get(projects.visibleProjectsAtom); + expect(visible.map((project) => `${project.environmentId}:${project.id}`)).toEqual( + all + .filter((project) => project.environmentId !== environmentId || project.id !== ordinary) + .map((project) => `${project.environmentId}:${project.id}`), + ); + + registry.set(configAtom(environmentId), { settings: NO_BOTS }); + expect(registry.get(projects.projectAtom(ordinaryRef))).not.toHaveProperty("isBot"); + expect(registry.get(projects.visibleProjectsAtom)).toHaveLength(all.length); + } finally { + registry.dispose(); + } + }); }); diff --git a/packages/client-runtime/src/state/projectEntities.ts b/packages/client-runtime/src/state/projectEntities.ts index e4c5a46999dcd..b13d2972ffbcf 100644 --- a/packages/client-runtime/src/state/projectEntities.ts +++ b/packages/client-runtime/src/state/projectEntities.ts @@ -22,9 +22,12 @@ export function createEnvironmentProjectAtoms(input: { readonly snapshotAtom: ( environmentId: EnvironmentId, ) => Atom.Atom; - readonly serverConfigValueAtom?: ( - environmentId: EnvironmentId, - ) => Atom.Atom | null>; + readonly serverConfigValueAtom?: (environmentId: EnvironmentId) => Atom.Atom< + | (Pick & { + readonly settings: Pick; + }) + | null + >; }) { const environmentProjectsAtom = Atom.family((environmentId: EnvironmentId) => Atom.make( @@ -115,6 +118,17 @@ export function createEnvironmentProjectAtoms(input: { return previousProjects; }).pipe(Atom.withLabel("environment-project-list")); + /** projectsAtom without T3_BOT projects, for the main window's lists and pickers. */ + let previousVisibleProjects: ReadonlyArray = []; + const visibleProjectsAtom = Atom.make((get) => { + const projects = get(projectsAtom); + if (!projects.some((project) => project.isBot)) return projects; + const next = projects.filter((project) => !project.isBot); + if (arrayElementsEqual(previousVisibleProjects, next)) return previousVisibleProjects; + previousVisibleProjects = next; + return next; + }).pipe(Atom.withLabel("environment-visible-project-list")); + const projectConfigsReadyAtom = Atom.make((get) => { const catalog = get(input.catalogValueAtom); if (!catalog.isReady) return false; @@ -132,6 +146,7 @@ export function createEnvironmentProjectAtoms(input: { environmentProjectRefsAtom, projectRefsAtom, projectsAtom, + visibleProjectsAtom, projectConfigsReadyAtom, projectAtom: (ref: ScopedProjectRef) => projectAtomFamily(projectKey(ref)), }; diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 61bcd4bcac53a..4460fd600058e 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -9,6 +9,7 @@ import { import { type DesktopUpdateChannel, type EnvironmentId, + type ProjectId, type ProviderInstanceId, type ServerConfig, type ServerConfigStreamEvent, @@ -1372,6 +1373,18 @@ export function createServerEnvironmentAtoms( Atom.withLabel(`environment-data:server:hidden-thread-tags:${environmentId}`), ), ); + const botProjectIdsAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make( + (get): ReadonlySet => + new Set(Object.keys(get(settingsValueAtom(environmentId))?.bots ?? {}) as ProjectId[]), + ).pipe( + Atom.withEquality( + (a: ReadonlySet, b: ReadonlySet) => + a.size === b.size && [...a].every((id) => b.has(id)), + ), + Atom.withLabel(`environment-data:server:bot-project-ids:${environmentId}`), + ), + ); const usagePricesAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => { const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {}; @@ -1530,6 +1543,7 @@ export function createServerEnvironmentAtoms( updateStateAtom, settingsValueAtom, hiddenThreadTagsAtom, + botProjectIdsAtom, usageModelFilterAtom, providersValueAtom, providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, { diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 9210949afb737..a85d17038e580 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -48,14 +48,21 @@ function makeHarness(environmentIds: ReadonlyArray = [environment ]), ), }); + const botProjectsAtom = Atom.family((_environmentId: EnvironmentId) => + Atom.make>([]), + ); return { registry: AtomRegistry.make(), snapshotAtom, catalogValueAtom, + botProjectsAtom, threads: createEnvironmentThreadShellAtoms({ catalogValueAtom, snapshotAtom, hiddenThreadTagsAtom: () => Atom.make(null), + botProjectIdsAtom: Atom.family((id: EnvironmentId) => + Atom.make((get): ReadonlySet => new Set(get(botProjectsAtom(id)))), + ), }), }; } @@ -679,6 +686,66 @@ describe("v2 thread shell lists", () => { } }); + it("leaves bot project threads out of display lists but keeps them readable and notifiable", () => { + const harness = makeHarness([environmentId, remoteEnvironmentId]); + const botThread = { + ...v2ThreadShell, + id: ThreadId.make("bot-thread"), + projectId: otherProjectId, + }; + harness.registry.set(harness.snapshotAtom(environmentId), { + ...v2ShellSnapshot, + threads: [v2ThreadShell, botThread], + }); + harness.registry.set(harness.snapshotAtom(remoteEnvironmentId), { + ...v2ShellSnapshot, + threads: [botThread], + }); + const { threads, registry } = harness; + const ids = (atom: Atom.Atom>) => + registry.get(atom).map((thread) => thread.id); + const disposers = [ + threads.visibleThreadShellsAtom, + threads.quietThreadShellsAtom, + threads.navigationThreadShellsAtom, + ].map((atom) => registry.mount(atom)); + try { + const shownBefore = registry.get(threads.visibleThreadShellsAtom); + expect(shownBefore).toBe(registry.get(threads.threadShellsAtom)); + + // Bot status is per environment: the remote copy of the project stays a normal project. + registry.set(harness.botProjectsAtom(environmentId), [otherProjectId]); + for (const atom of [ + threads.visibleThreadShellsAtom, + threads.quietThreadShellsAtom, + threads.navigationThreadShellsAtom, + ]) { + expect(registry.get(atom).map((thread) => `${thread.environmentId}:${thread.id}`)).toEqual([ + `${environmentId}:${v2ThreadShell.id}`, + `${remoteEnvironmentId}:${botThread.id}`, + ]); + } + expect(ids(threads.threadShellsAtom)).toHaveLength(3); + expect( + ids(threads.threadShellsForProjectRefsAtom([{ environmentId, projectId: otherProjectId }])), + ).toEqual([botThread.id]); + expect( + registry.get(threads.threadShellAtom({ environmentId, threadId: botThread.id })), + ).not.toBeNull(); + expect(registry.get(threads.hiddenThreadKeysAtom).size).toBe(0); + + const shown = registry.get(threads.visibleThreadShellsAtom); + registry.set(harness.botProjectsAtom(environmentId), [otherProjectId]); + expect(registry.get(threads.visibleThreadShellsAtom)).toBe(shown); + + registry.set(harness.botProjectsAtom(environmentId), []); + expect(ids(threads.navigationThreadShellsAtom)).toHaveLength(3); + } finally { + for (const dispose of disposers) dispose(); + registry.dispose(); + } + }); + it("keeps the quiet shell list through streaming ticks", () => { const harness = makeHarness(); const runId = RunId.make("streaming-list-run"); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 3325346d5d153..fe2552abb5aa4 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -273,6 +273,8 @@ export function createEnvironmentThreadShellAtoms(input: { readonly hiddenThreadTagsAtom: ( environmentId: EnvironmentId, ) => Atom.Atom | null>; + /** T3_BOT projects, whose threads belong to the bot window instead of the main lists. */ + readonly botProjectIdsAtom?: (environmentId: EnvironmentId) => Atom.Atom>; }) { // Point reads and aggregate lists share values without keeping an atom alive // for every listed thread. Replaced source objects can be collected. @@ -705,17 +707,65 @@ export function createEnvironmentThreadShellAtoms(input: { return next; }).pipe(Atom.withLabel("environment-hidden-thread-keys")); + // Kept apart from hiddenThreadKeysAtom, which also suppresses notifications; bot threads keep theirs. + let previousBotThreadKeys: ReadonlySet = NO_HIDDEN_THREADS; + const botThreadKeysAtom = Atom.make((get) => { + const botProjectIdsAtom = input.botProjectIdsAtom; + if (botProjectIdsAtom === undefined) return NO_HIDDEN_THREADS; + const next = new Set(); + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + const botProjectIds = get(botProjectIdsAtom(environmentId)); + if (botProjectIds.size === 0) continue; + const refsByProject = get(environmentThreadRefsByProjectAtom(environmentId)); + for (const projectId of botProjectIds) { + for (const ref of refsByProject.get(projectId) ?? EMPTY_SCOPED_THREAD_REFS) { + next.add(threadKey(ref)); + } + } + } + if (next.size === 0) { + previousBotThreadKeys = NO_HIDDEN_THREADS; + return NO_HIDDEN_THREADS; + } + if ( + next.size === previousBotThreadKeys.size && + [...next].every((key) => previousBotThreadKeys.has(key)) + ) { + return previousBotThreadKeys; + } + previousBotThreadKeys = next; + return next; + }).pipe(Atom.withLabel("environment-bot-thread-keys")); + + /** Threads display lists leave out: the tag filter's and bot threads. */ + let previousUnlistedThreadKeys: ReadonlySet = NO_HIDDEN_THREADS; + const unlistedThreadKeysAtom = Atom.make((get) => { + const hidden = get(hiddenThreadKeysAtom); + const bots = get(botThreadKeysAtom); + if (bots.size === 0) return hidden; + if (hidden.size === 0) return bots; + const next = new Set([...hidden, ...bots]); + if ( + next.size === previousUnlistedThreadKeys.size && + [...next].every((key) => previousUnlistedThreadKeys.has(key)) + ) { + return previousUnlistedThreadKeys; + } + previousUnlistedThreadKeys = next; + return next; + }).pipe(Atom.withLabel("environment-unlisted-thread-keys")); + const anyEnvironmentHidingAtom = Atom.make((get) => Array.from(enabledEnvironmentIds(get(input.catalogValueAtom))).some( (environmentId) => get(input.hiddenThreadTagsAtom(environmentId)) !== null, ), ).pipe(Atom.withLabel("environment-any-hiding-thread-tags")); - /** threadShellsAtom without the threads the tag filter hides, for pickers and palettes. */ + /** threadShellsAtom without tag-hidden and bot threads, for pickers and palettes. */ let previousVisibleThreadShells: ReadonlyArray = []; const visibleThreadShellsAtom = Atom.make((get) => { const threads = get(threadShellsAtom); - const hidden = get(hiddenThreadKeysAtom); + const hidden = get(unlistedThreadKeysAtom); if (hidden.size === 0) return threads; const next = threads.filter( (thread) => @@ -731,7 +781,7 @@ export function createEnvironmentThreadShellAtoms(input: { let previousQuietThreadShells: ReadonlyArray = []; const quietThreadShellsAtom = Atom.make((get) => { const next: EnvironmentThreadShell[] = []; - const hidden = get(hiddenThreadKeysAtom); + const hidden = get(unlistedThreadKeysAtom); for (const ref of get(threadRefsAtom)) { if (hidden.has(threadKey(ref))) continue; const shell = get(quietThreadShellAtomFamily(threadKey(ref))); @@ -774,7 +824,7 @@ export function createEnvironmentThreadShellAtoms(input: { const navigationThreadShellsAtom = Atom.make((get) => { const next: EnvironmentThreadShell[] = []; const underParent = get(delegatedUnderParentAtom); - const hidden = get(hiddenThreadKeysAtom); + const hidden = get(unlistedThreadKeysAtom); for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); for (const thread of get(environmentThreadsAtom(environmentId))) { From 22780600956836d41e190d7569f373d9965944d7 Mon Sep 17 00:00:00 2001 From: Na0s Date: Sat, 21 Nov 2026 15:59:55 -0500 Subject: [PATCH 11/20] feat(web): T3_BOT section in project settings Project settings gain a T3_BOT section: a switch that adds or removes the project in server settings `bots`, and a Role field. Edits keep the bot's main thread and order, since `bots` patch entries replace. Settings project menus mark bot projects with "T3_BOT" so they stay findable and manageable. Co-Authored-By: Claude Opus 5.5 --- .../settings/ProjectBotSettings.tsx | 107 ++++++++++++++++++ .../ProjectSettingsPanel.logic.test.ts | 17 +++ .../settings/ProjectSettingsPanel.logic.ts | 13 ++- .../settings/ProjectSettingsPanel.tsx | 4 + .../settings/SettingsScopeNotice.tsx | 2 + .../settings/SettingsScopeSentence.tsx | 11 +- .../components/settings/settingsScopeAxis.ts | 5 + 7 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/components/settings/ProjectBotSettings.tsx diff --git a/apps/web/src/components/settings/ProjectBotSettings.tsx b/apps/web/src/components/settings/ProjectBotSettings.tsx new file mode 100644 index 0000000000000..c4854b43b21a8 --- /dev/null +++ b/apps/web/src/components/settings/ProjectBotSettings.tsx @@ -0,0 +1,107 @@ +import { AuthSettingsWriteScope } from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { useState } from "react"; + +import type { SidebarProjectGroupMember } from "../../sidebarProjectGrouping"; +import { useEnvironments } from "../../state/environments"; +import { serverEnvironment } from "../../state/server"; +import { useEnvironmentsWithScope } from "../../state/session"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { Input } from "../ui/input"; +import { Switch } from "../ui/switch"; +import { nextBotSettings } from "./ProjectSettingsPanel.logic"; +import { SettingsRow, SettingsSection } from "./settingsLayout"; + +/** Turns the project into a T3_BOT identity, which moves it out of the main window's lists. */ +export function ProjectBotSettings({ + members, +}: { + members: ReadonlyArray; +}) { + const gt = useGT(); + const { environments } = useEnvironments(); + const writableIds = useEnvironmentsWithScope(members, AuthSettingsWriteScope); + const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { + label: "T3_BOT update", + }); + const [saving, setSaving] = useState(false); + const botsByEnvironment = new Map( + environments.map((environment) => [ + environment.environmentId, + environment.serverConfig?.settings.bots, + ]), + ); + const entries = members.map((member) => botsByEnvironment.get(member.environmentId)?.[member.id]); + const isBot = entries.every((entry) => entry !== undefined); + const role = entries.find((entry) => entry?.role !== undefined)?.role ?? ""; + const canEdit = members.every( + (member) => + writableIds.has(member.environmentId) && + botsByEnvironment.get(member.environmentId) !== undefined, + ); + + const save = async (edit: Parameters[1]) => { + setSaving(true); + for (const member of members) { + const current = botsByEnvironment.get(member.environmentId)?.[member.id]; + const result = await updateSettings({ + environmentId: member.environmentId, + input: { patch: { bots: { [member.id]: nextBotSettings(current, edit) } } }, + }); + if (result._tag === "Failure") break; + } + setSaving(false); + }; + + return ( + // oxlint-disable-next-line t3code/no-untranslated-copy -- T3_BOT is the feature's name + + {!canEdit ? ( +

+ This connection cannot change environment settings. +

+ ) : null} + void save({ enabled: Boolean(checked) })} + aria-label={gt("Use as a T3_BOT")} + /> + } + /> + { + const next = event.currentTarget.value; + if (next.trim() !== role) void save({ role: next }); + }} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; + if (event.key === "Enter") event.currentTarget.blur(); + }} + /> + } + /> +
+ ); +} diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts index c42c375a5e154..cf636264d1dfd 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts +++ b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts @@ -5,6 +5,7 @@ import { planProjectRemoval } from "@t3tools/client-runtime/state/projects"; import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; import type { Project } from "../../types"; import { + nextBotSettings, projectGroupTitleNeedsUpdate, scopeProjectSettingsGroup, } from "./ProjectSettingsPanel.logic"; @@ -191,3 +192,19 @@ describe("projectGroupTitleNeedsUpdate", () => { expect(projectGroupTitleNeedsUpdate([renamed, renamed], "repo", true)).toBe(false); }); }); + +describe("nextBotSettings", () => { + it("keeps the main thread and order through role edits and removes the bot when turned off", () => { + const mainThreadId = ThreadId.make("main"); + const current = { role: "Orchestrator", mainThreadId, order: 2 }; + expect(nextBotSettings(current, { role: " PR babysitter " })).toEqual({ + role: "PR babysitter", + mainThreadId, + order: 2, + }); + expect(nextBotSettings(current, { role: " " })).toEqual({ mainThreadId, order: 2 }); + expect(nextBotSettings(undefined, { enabled: true })).toEqual({}); + expect(nextBotSettings(current, { enabled: true })).toBe(current); + expect(nextBotSettings(current, { enabled: false })).toBeNull(); + }); +}); diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.logic.ts b/apps/web/src/components/settings/ProjectSettingsPanel.logic.ts index 706162be00457..9b4b6252fa0f3 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.logic.ts +++ b/apps/web/src/components/settings/ProjectSettingsPanel.logic.ts @@ -1,4 +1,4 @@ -import type { ProjectIconOverride } from "@t3tools/contracts"; +import type { BotSettings, ProjectIconOverride } from "@t3tools/contracts"; import type { SidebarProjectGroupMember, @@ -51,3 +51,14 @@ export function hasDefaultProjectIcon( icon.color === SCRATCH_PROJECT_ICON.color ); } + +/** The `bots` entry a T3_BOT edit writes. Patch entries replace, so unedited fields carry over. */ +export function nextBotSettings( + current: BotSettings | undefined, + edit: { readonly enabled: boolean } | { readonly role: string }, +): BotSettings | null { + if ("enabled" in edit) return edit.enabled ? (current ?? {}) : null; + const { role: _role, ...rest } = current ?? {}; + const role = edit.role.trim(); + return role === "" ? rest : { ...rest, role }; +} diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index c4ed6e4ff33b1..05fd45600966a 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -53,6 +53,7 @@ import { ProjectFaviconPickerDialog, } from "./ProjectFaviconPickerDialog"; import { ProjectActionsSettings } from "./ProjectActionsSettings"; +import { ProjectBotSettings } from "./ProjectBotSettings"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; import { ProjectRepositoriesSettings } from "./ProjectRepositoriesSettings"; import { @@ -691,6 +692,9 @@ function ProjectDetail({ ) : null} + {group.memberProjects.some((member) => member.isScratch) ? null : ( + + )} diff --git a/apps/web/src/components/settings/SettingsScopeNotice.tsx b/apps/web/src/components/settings/SettingsScopeNotice.tsx index fc74e2765100a..b5a6062378ec1 100644 --- a/apps/web/src/components/settings/SettingsScopeNotice.tsx +++ b/apps/web/src/components/settings/SettingsScopeNotice.tsx @@ -17,6 +17,7 @@ import { useSettingsScope } from "./SettingsScopeContext"; import type { SettingsScopeSearch } from "./settingsScope"; import { projectScopeMenuGroups, + projectScopeIsBot, selectProjectAxis, settingsScopeEnvironmentAddress, settingsScopeEnvironmentLabels, @@ -90,6 +91,7 @@ export function SettingsScopeNotice({ label: group.displayName, secondary: [ ...(group.archived ? [gt("Archived", { $context: "project state" })] : []), + ...(projectScopeIsBot(group) ? ["T3_BOT"] : []), ...(projectGroups.some( (other) => other.projectKey !== group.projectKey && other.displayName === group.displayName, diff --git a/apps/web/src/components/settings/SettingsScopeSentence.tsx b/apps/web/src/components/settings/SettingsScopeSentence.tsx index 356b4ca9fcf58..7031e8db293d4 100644 --- a/apps/web/src/components/settings/SettingsScopeSentence.tsx +++ b/apps/web/src/components/settings/SettingsScopeSentence.tsx @@ -37,6 +37,7 @@ import { environmentAxisValue, projectAxisValue, projectScopeMenuGroups, + projectScopeIsBot, selectCheckoutAxis, selectEnvironmentAxis, selectProjectAxis, @@ -436,9 +437,13 @@ function ProjectScopeMenu({ value, groups, environments, onChange }: SettingsSco return { value: group.projectKey, label: group.displayName, - secondary: group.archived - ? [gt("Archived", { $context: "project state" }), location].filter(Boolean).join(" · ") - : location, + secondary: [ + ...(group.archived ? [gt("Archived", { $context: "project state" })] : []), + ...(projectScopeIsBot(group) ? ["T3_BOT"] : []), + location, + ] + .filter(Boolean) + .join(" · "), icon: , }; })} diff --git a/apps/web/src/components/settings/settingsScopeAxis.ts b/apps/web/src/components/settings/settingsScopeAxis.ts index 9ef532d6953aa..5e2e4640a385d 100644 --- a/apps/web/src/components/settings/settingsScopeAxis.ts +++ b/apps/web/src/components/settings/settingsScopeAxis.ts @@ -72,6 +72,11 @@ export function projectAxisValue(search: SettingsScopeSearch): string { return search.project ?? ALL_PROJECTS_VALUE; } +/** Whether a settings project menu row is a T3_BOT, which it labels "T3_BOT" beside where it lives. */ +export function projectScopeIsBot(group: Pick): boolean { + return group.memberProjects.some((member) => member.isBot); +} + export function projectScopeMenuGroups( groups: readonly SidebarProjectSnapshot[], search: Pick, From a525937ca6168f5c5e05fc1a17c5599ea5aa2a75 Mon Sep 17 00:00:00 2001 From: Na0s Date: Sat, 21 Nov 2026 15:56:23 -0500 Subject: [PATCH 12/20] feat: fold T3_BOT conversation sections on web and mobile An assistant message carrying `` now opens a section that starts at its turn's prompt and runs to the next section marker, a `` marker (inclusive), or the end of the thread. The whole span folds under one "Status Check - HH:MM:SS" row that reuses the turn fold row and expanded-run state. Closed sections start collapsed; the latest open section, or one ended inside a still-running turn, starts expanded. The marker parser and span derivation live in @t3tools/shared/botSections. Web folds sections in deriveMessagesTimelineRows, keeps nested work folds, rebuilds the streaming fast path when a marker appears, shows all sections while thread find is open, and opens a cited message's section. Mobile folds the presented feed and opens the section of a message it jumps to. Both renderers already drop HTML comments, so markers stay invisible. Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/ThreadFeed.tsx | 52 +++-- .../threads/threadFeedSections.test.ts | 90 ++++++++ .../features/threads/threadFeedSections.ts | 134 ++++++++++++ .../chat/MessagesTimeline.logic.test.ts | 207 ++++++++++++++++++ .../components/chat/MessagesTimeline.logic.ts | 103 ++++++++- .../src/components/chat/MessagesTimeline.tsx | 15 ++ packages/shared/package.json | 4 + packages/shared/src/botSections.test.ts | 119 ++++++++++ packages/shared/src/botSections.ts | 116 ++++++++++ 9 files changed, 826 insertions(+), 14 deletions(-) create mode 100644 apps/mobile/src/features/threads/threadFeedSections.test.ts create mode 100644 apps/mobile/src/features/threads/threadFeedSections.ts create mode 100644 packages/shared/src/botSections.test.ts create mode 100644 packages/shared/src/botSections.ts diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 005a6fb8f30c1..9b0c4d40bce2c 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -274,6 +274,7 @@ import { } from "./pending-thread-feed"; import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size"; +import { foldThreadFeedSections, threadFeedSectionFolds } from "./threadFeedSections"; import { htmlRenderFrameHeight } from "@t3tools/shared/htmlRender"; import { htmlRenderRowHeight, ThreadHtmlRender } from "./HtmlRenderWebView"; import { ThreadMcpApp } from "./McpAppWebView"; @@ -3037,28 +3038,41 @@ function useThreadFeedPresentation( const [feedCache] = useState(createThreadFeedCache); const messages = useMessages(); const locale = useLocale(); + const [sectionFoldRows] = useState( + () => new Map>(), + ); return appendPendingThreadMessages( - deriveThreadFeedPresentation( + foldThreadFeedSections( + deriveThreadFeedPresentation( + props.feed, + props.latestRun, + expandedTurnIds, + new Set( + Object.entries(expandedWorkGroups) + .filter(([, expanded]) => expanded) + .map(([groupId]) => groupId), + ), + props.activeWorkStartedAt, + props.runlessWorkActive ?? false, + feedCache, + { toolCallVisibility: props.toolCallVisibility ?? "showAll", revealedMessageId }, + messages, + locale, + ), props.feed, - props.latestRun, + threadFeedSectionFolds(props.feed, threadFeedIsWorking(props)), expandedTurnIds, - new Set( - Object.entries(expandedWorkGroups) - .filter(([, expanded]) => expanded) - .map(([groupId]) => groupId), - ), - props.activeWorkStartedAt, - props.runlessWorkActive ?? false, - feedCache, - { toolCallVisibility: props.toolCallVisibility ?? "showAll", revealedMessageId }, - messages, - locale, + sectionFoldRows, ), props.feed, props.queuedMessages, ); } +function threadFeedIsWorking(props: Pick) { + return props.activeWorkStartedAt !== null && props.latestRun?.status !== "preparing"; +} + type DisclosureLayout = { /** Each row's top relative to the anchor row's top, before the toggle. */ positions: ReadonlyMap; @@ -3921,6 +3935,18 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { expandedTurnIds: new Set(current.expandedTurnIds).add(jumpRunId), })); } + const jumpSection = + jumpReady && !presentedFeed.some((entry) => entry.id === jumpToMessageId) + ? threadFeedSectionFolds(props.feed, threadFeedIsWorking(props)).get(jumpToMessageId) + : undefined; + if (jumpSection && expandedTurnIds.has(jumpSection.key) === jumpSection.expandedByDefault) { + setInteractionState((current) => { + const next = new Set(current.expandedTurnIds); + if (jumpSection.expandedByDefault) next.delete(jumpSection.key); + else next.add(jumpSection.key); + return { ...current, expandedTurnIds: next }; + }); + } const setupAnchorIndex = presentedFeed.findIndex( (entry) => entry.type === "message" && entry.message.role === "user", ); diff --git a/apps/mobile/src/features/threads/threadFeedSections.test.ts b/apps/mobile/src/features/threads/threadFeedSections.test.ts new file mode 100644 index 0000000000000..7b14ddc4b6d7d --- /dev/null +++ b/apps/mobile/src/features/threads/threadFeedSections.test.ts @@ -0,0 +1,90 @@ +import { MessageId, RunId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { ThreadFeedEntry } from "../../lib/threadActivity"; +import { foldThreadFeedSections, threadFeedSectionFolds } from "./threadFeedSections"; + +const at = "2026-01-01T11:18:04.000Z"; +const message = (id: string, role: "user" | "assistant", text = id): ThreadFeedEntry => ({ + type: "message", + id, + createdAt: at, + message: { + id: MessageId.make(id), + role, + text, + attachments: [], + runId: null, + streaming: false, + visibility: "local", + sourceThreadId: ThreadId.make("thread"), + createdAt: at, + updatedAt: at, + }, +}); +const runFold = (id: string): ThreadFeedEntry => ({ + type: "run-fold", + id: `run-fold:${id}`, + createdAt: at, + runId: RunId.make(id), + label: "Worked for 3s", + expanded: false, +}); +const thinking: ThreadFeedEntry = { + type: "thinking", + id: "live-activity-row", + createdAt: at, + runId: null, +}; + +describe("foldThreadFeedSections", () => { + const exchange = [ + message("before", "user"), + message("ask", "user"), + message("relay", "assistant", '\nAll green.'), + message("reply", "user"), + message("done", "assistant", "Done.\n"), + ]; + const feed = [...exchange, message("after", "user")]; + // The presentation adds rows of its own between the feed's entries. + const presented = (entries: ReadonlyArray) => [ + ...entries.slice(0, 4), + runFold("r2"), + ...entries.slice(4), + thinking, + ]; + const expandedSection = ["ask", "relay", "reply", "run-fold:r2", "done"]; + + it.each<[string, ReadonlyArray, boolean, ReadonlyArray, string[]]>([ + [ + "folds a closed section with the rows derived inside it", + feed, + false, + [], + ["before", "run-fold:section:relay", "after", "live-activity-row"], + ], + [ + "opens a closed section from the expanded set", + feed, + false, + ["section:relay"], + ["before", "run-fold:section:relay", ...expandedSection, "after", "live-activity-row"], + ], + [ + "keeps a section open while the turn that ends it runs", + exchange, + true, + [], + ["before", "run-fold:section-open:relay", ...expandedSection, "live-activity-row"], + ], + ])("%s", (_name, entries, isWorking, expanded, expected) => { + const folded = foldThreadFeedSections( + presented(entries), + entries, + threadFeedSectionFolds(entries, isWorking), + new Set(expanded.map((id) => RunId.make(id))), + new Map(), + ); + expect(folded.map((row) => row.id)).toEqual(expected); + }); +}); diff --git a/apps/mobile/src/features/threads/threadFeedSections.ts b/apps/mobile/src/features/threads/threadFeedSections.ts new file mode 100644 index 0000000000000..e7645f477cf06 --- /dev/null +++ b/apps/mobile/src/features/threads/threadFeedSections.ts @@ -0,0 +1,134 @@ +import { RunId } from "@t3tools/contracts"; +import { + deriveBotSectionSpans, + formatBotSectionLabel, + parseBotSectionMarkers, + type BotSectionMessageMarkers, +} from "@t3tools/shared/botSections"; + +import type { ThreadFeedEntry } from "../../lib/threadActivity"; + +type ThreadFeedMessage = Extract["message"]; +type RunFoldRow = Extract; + +export interface ThreadFeedSectionFold { + /** Toggled-from-default key in the expanded run set; open and closed sections use separate keys. */ + readonly key: RunId; + readonly label: string; + readonly createdAt: string; + readonly expandedByDefault: boolean; +} + +const markersByMessage = new WeakMap(); + +function entryMarkers(entry: ThreadFeedEntry): BotSectionMessageMarkers | null { + if (entry.type !== "message" || entry.message.role !== "assistant") return null; + let markers = markersByMessage.get(entry.message); + if (markers === undefined) { + markers = parseBotSectionMarkers(entry.message.text); + markersByMessage.set(entry.message, markers); + } + return markers; +} + +function startsTurn(entry: ThreadFeedEntry): boolean { + if (entry.type === "message") { + return ( + entry.message.role === "user" && + entry.message.inputIntent !== "steer" && + entry.message.inputIntent !== "promoted_queued_to_steer" + ); + } + return ( + entry.type === "activity-group" && + entry.activities.some((activity) => activity.projectedItem.item.type === "notification") + ); +} + +/** Bot section folds by member entry id, from the unfiltered feed so zen cannot drop a marker. */ +export function threadFeedSectionFolds( + feed: ReadonlyArray, + isWorking: boolean, +): ReadonlyMap { + const byEntryId = new Map(); + const spans = deriveBotSectionSpans(feed, { markers: entryMarkers, startsTurn }); + if (spans.length === 0) return byEntryId; + const activeTurnStart = isWorking ? feed.findLastIndex(startsTurn) : feed.length; + for (const span of spans) { + // A section ended inside the running turn stays open until that turn settles. + const open = !span.closed || span.endIndex >= activeTurnStart; + const startEntry = feed[span.startIndex]!; + const fold: ThreadFeedSectionFold = { + key: RunId.make(`${open ? "section-open" : "section"}:${feed[span.markerIndex]!.id}`), + label: formatBotSectionLabel(span.marker, startEntry.createdAt), + createdAt: startEntry.createdAt, + expandedByDefault: open, + }; + for (let index = span.startIndex; index <= span.endIndex; index += 1) { + byEntryId.set(feed[index]!.id, fold); + } + } + return byEntryId; +} + +export function threadFeedSectionExpanded( + fold: ThreadFeedSectionFold, + expandedRunIds: ReadonlySet, +): boolean { + return fold.expandedByDefault !== expandedRunIds.has(fold.key); +} + +/** + * Folds presented rows under their section's run-fold row. Rows the + * presentation derived (folds, toggles, split groups) belong to the entry + * row above them; the live thinking row always stays visible. + */ +export function foldThreadFeedSections( + rows: ReadonlyArray, + feed: ReadonlyArray, + folds: ReadonlyMap, + expandedRunIds: ReadonlySet, + foldRows: Map, +): ReadonlyArray { + if (folds.size === 0) return rows; + const feedIds = new Set(feed.map((entry) => entry.id)); + const emitted = new Set(); + const result: ThreadFeedEntry[] = []; + let current: ThreadFeedSectionFold | undefined; + for (const row of rows) { + if (row.type === "thinking") { + result.push(row); + continue; + } + if (folds.has(row.id)) current = folds.get(row.id); + else if (feedIds.has(row.id)) current = undefined; + if (current === undefined) { + result.push(row); + continue; + } + const expanded = threadFeedSectionExpanded(current, expandedRunIds); + if (!emitted.has(current.key)) { + emitted.add(current.key); + let foldRow = foldRows.get(current.key); + if ( + foldRow === undefined || + foldRow.label !== current.label || + foldRow.createdAt !== current.createdAt || + foldRow.expanded !== expanded + ) { + foldRow = { + type: "run-fold", + id: `run-fold:${current.key}`, + createdAt: current.createdAt, + runId: current.key, + label: current.label, + expanded, + }; + foldRows.set(current.key, foldRow); + } + result.push(foldRow); + } + if (expanded) result.push(row); + } + return result; +} diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index f1726cbbb92b2..0c7395fc376fb 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -3787,6 +3787,28 @@ describe("streaming v2 row projection", () => { } }); + it("rebuilds rows when a streamed reply gains a section marker", () => { + const initial = fixture("Status"); + const previous = deriveMessagesTimelineRowsWithState(initial.input); + const timelineInput = { + ...initial.timelineInput, + visibleTurnItems: updateText( + initial.visibleTurnItems, + '\nStatus', + ), + }; + const input = { + ...initial.input, + timelineEntries: deriveTimelineEntriesFromVisibleTurnItemsWithState( + timelineInput, + initial.timeline, + ).entries, + }; + const next = deriveMessagesTimelineRowsWithState(input, previous); + expect(next.rows).toEqual(deriveMessagesTimelineRows(input)); + expect(next.rows.some((row) => row.id.startsWith("turn-fold:section-open:"))).toBe(true); + }); + it.each(["file", "image", "handoff", "streaming-image"] as const)( "keeps history references with %s previews through the v2 materializer", (kind) => { @@ -5207,6 +5229,191 @@ describe("subagent continued by a later turn", () => { }); }); +describe("bot sections", () => { + // Local wall-clock times, so labels read the same in every time zone. + const time = (second: number) => new Date(2026, 0, 1, 11, 18, second).toISOString(); + const statusCheck = '\n'; + const user = (id: string, run: string, second: number): TimelineEntry => ({ + kind: "message", + id, + createdAt: time(second), + message: { + id: MessageId.make(id), + role: "user", + text: id, + runId: RunId.make(run), + createdAt: time(second), + updatedAt: time(second), + streaming: false, + }, + }); + const answer = (id: string, run: string, second: number, text = id): TimelineEntry => ({ + kind: "message", + id, + createdAt: time(second), + message: { + id: MessageId.make(id), + role: "assistant", + text, + runId: RunId.make(run), + createdAt: time(second), + updatedAt: time(second), + streaming: false, + }, + }); + const work = (id: string, run: string, second: number): TimelineEntry => ({ + kind: "work", + id, + createdAt: time(second), + entry: { + id, + runId: RunId.make(run), + createdAt: time(second), + label: "Ran command", + tone: "tool", + itemType: "command_execution", + toolLifecycleStatus: "completed", + }, + }); + const statusExchange = [ + user("ask", "r1", 4), + answer("relay", "r1", 6, `${statusCheck}Ryder App: checks green.`), + user("reply", "r2", 10), + work("merge", "r2", 11), + answer("resumed", "r2", 14, "Done. Both threads resumed."), + ]; + const rowsFor = ( + timelineEntries: ReadonlyArray, + options: { + expandedRunIds?: ReadonlyArray; + isWorking?: boolean; + expandAllSections?: boolean; + toolCallVisibility?: "zen"; + } = {}, + ) => + deriveMessagesTimelineRows({ + timelineEntries, + expandedRunIds: new Set((options.expandedRunIds ?? []).map((id) => RunId.make(id))), + isWorking: options.isWorking ?? false, + activeTurnStartedAt: null, + turnDiffSummaries: [], + supportsConversationRollback: false, + ...(options.expandAllSections ? { expandAllSections: true } : {}), + ...(options.toolCallVisibility ? { toolCallVisibility: options.toolCallVisibility } : {}), + }); + + it.each<[string, ReadonlyArray, Parameters[1], string[]]>([ + [ + "keeps the latest open section expanded with its work folds", + statusExchange, + {}, + ["turn-fold:section-open:relay", "ask", "relay", "reply", "turn-fold:r2", "resumed"], + ], + [ + "folds the open section when toggled", + statusExchange, + { expandedRunIds: ["section-open:relay"] }, + ["turn-fold:section-open:relay"], + ], + [ + "folds a section the next marker closed", + [ + ...statusExchange, + user("later", "r3", 30), + answer("beat", "r3", 31, '\nQuiet.'), + ], + {}, + ["turn-fold:section:relay", "turn-fold:section-open:beat", "later", "beat"], + ], + [ + "opens a closed section from the expanded set, nested folds intact", + [...statusExchange, user("later", "r3", 30), answer("beat", "r3", 31, statusCheck)], + { expandedRunIds: ["section:relay"] }, + [ + "turn-fold:section:relay", + "ask", + "relay", + "reply", + "turn-fold:r2", + "resumed", + "turn-fold:section-open:beat", + "later", + "beat", + ], + ], + [ + "closes at an end marker, inclusive", + [ + user("before", "r0", 1), + answer("plain", "r0", 2), + ...statusExchange.slice(0, 4), + answer("resumed", "r2", 14, "Done.\n"), + user("after", "r3", 30), + answer("chat", "r3", 31), + ], + {}, + ["before", "plain", "turn-fold:section:relay", "after", "chat"], + ], + [ + "stays open while the turn that ends it still runs", + [ + ...statusExchange.slice(0, 3), + answer("resumed", "r2", 14, "Done.\n"), + ], + { isWorking: true }, + [ + "turn-fold:section-open:relay", + "ask", + "relay", + "reply", + "working-indicator-row", + "resumed", + "live-activity-row", + ], + ], + [ + "shows every section while find is open", + [...statusExchange, user("later", "r3", 30), answer("beat", "r3", 31, statusCheck)], + { expandAllSections: true, toolCallVisibility: "zen" }, + [ + "turn-fold:section:relay", + "ask", + "relay", + "reply", + "resumed", + "turn-fold:section-open:beat", + "later", + "beat", + ], + ], + [ + "finds a marker that zen hides", + [ + user("ask", "r1", 4), + answer("opening", "r1", 5, statusCheck), + work("lookup", "r1", 6), + answer("summary", "r1", 7), + user("later", "r3", 30), + answer("beat", "r3", 31, statusCheck), + ], + { toolCallVisibility: "zen" }, + ["turn-fold:section:opening", "turn-fold:section-open:beat", "later", "beat"], + ], + ])("%s", (_name, timelineEntries, options, expected) => { + expect(rowsFor(timelineEntries, options).map((row) => row.id)).toEqual(expected); + }); + + it("labels the fold with the section start in local time", () => { + const [fold] = rowsFor(statusExchange); + expect(fold).toMatchObject({ + kind: "turn-fold", + label: "Status Check - 11:18:04", + createdAt: time(4), + expanded: true, + }); + }); +}); + describe("isTimelineMinimapTurnVisible", () => { it("keeps a turn lit while only its reply is on screen", () => { // Turn rows 10..499, viewport inside the reply. diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 6bd30f1ac3212..e1d1bc0fd33ff 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -15,6 +15,12 @@ import { } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; +import { + deriveBotSectionSpans, + formatBotSectionLabel, + parseBotSectionMarkers, + type BotSectionMessageMarkers, +} from "@t3tools/shared/botSections"; import { commandDisplayText, commandProgramName, @@ -1575,6 +1581,71 @@ function timelineRowEntries( return withoutSubagentDelegationRows(settleSupersededReasoning(shown)); } +const botSectionMarkersByMessage = new WeakMap(); + +function messageBotSectionMarkers(message: ChatMessage): BotSectionMessageMarkers | null { + if (message.role !== "assistant") return null; + let markers = botSectionMarkersByMessage.get(message); + if (markers === undefined) { + markers = parseBotSectionMarkers(message.text); + botSectionMarkersByMessage.set(message, markers); + } + return markers; +} + +function sameBotSectionMarkers(previous: ChatMessage, next: ChatMessage): boolean { + const before = messageBotSectionMarkers(previous); + const after = messageBotSectionMarkers(next); + return ( + before === after || + (before !== null && + after !== null && + before.end === after.end && + before.start?.kind === after.start?.kind && + before.start?.label === after.start?.label) + ); +} + +export interface TimelineSectionFold { + /** Toggled-from-default key in the expanded run set; open and closed sections use separate keys. */ + readonly key: RunId; + readonly label: string; + readonly createdAt: string; + readonly expandedByDefault: boolean; +} + +/** Bot section folds by member entry id. Pass unfiltered entries so zen cannot drop a marker. */ +export function timelineSectionFoldsByEntryId( + timelineEntries: ReadonlyArray, + isWorking: boolean, +): ReadonlyMap { + const byEntryId = new Map(); + const spans = deriveBotSectionSpans(timelineEntries, { + markers: (entry) => (entry.kind === "message" ? messageBotSectionMarkers(entry.message) : null), + startsTurn: timelineEntryStartsResponse, + }); + if (spans.length === 0) return byEntryId; + const activeTurnStart = isWorking + ? lastResponseBoundaryIndex(timelineEntries) + : timelineEntries.length; + for (const span of spans) { + // A section ended inside the running turn stays open until that turn settles. + const open = !span.closed || span.endIndex >= activeTurnStart; + const markerEntry = timelineEntries[span.markerIndex]!; + const startEntry = timelineEntries[span.startIndex]!; + const fold: TimelineSectionFold = { + key: RunId.make(`${open ? "section-open" : "section"}:${markerEntry.id}`), + label: formatBotSectionLabel(span.marker, startEntry.createdAt), + createdAt: startEntry.createdAt, + expandedByDefault: open, + }; + for (let index = span.startIndex; index <= span.endIndex; index += 1) { + byEntryId.set(timelineEntries[index]!.id, fold); + } + } + return byEntryId; +} + function deriveTimelineTurnFolds( input: Pick< MessagesTimelineRowsInput, @@ -1630,10 +1701,17 @@ export function deriveMessagesTimelineRows( worktreeSetup?: WorktreeSetupSnapshot | null; toolCallVisibility?: ToolCallVisibility; revealedMessageId?: MessageId | null; + /** Thread find shows every bot section so its matches stay reachable. */ + expandAllSections?: boolean; }, resolve: MessageResolver = m, ): MessagesTimelineRow[] { const timelineEntries = timelineRowEntries(input); + const sectionFoldsByEntryId = timelineSectionFoldsByEntryId( + input.timelineEntries, + input.isWorking, + ); + const emittedSectionKeys = new Set(); const embeddedResultRunIds = new Set(); for (const entry of timelineEntries) { if ((entry.kind === "html-render" || entry.kind === "mcp-app") && entry.runId !== null) { @@ -1948,6 +2026,27 @@ export function deriveMessagesTimelineRows( appendActiveWorkRows(); } + const sectionFold = sectionFoldsByEntryId.get(timelineEntry.id); + if (sectionFold) { + const expanded = + input.expandAllSections === true || + sectionFold.expandedByDefault !== (input.expandedRunIds?.has(sectionFold.key) ?? false); + if (!emittedSectionKeys.has(sectionFold.key)) { + emittedSectionKeys.add(sectionFold.key); + nextRows.push({ + kind: "turn-fold", + id: `turn-fold:${sectionFold.key}`, + createdAt: sectionFold.createdAt, + runId: sectionFold.key, + label: sectionFold.label, + expanded, + }); + } + if (!expanded && !(timelineEntry.kind === "work" && isPendingApproval(timelineEntry.entry))) { + continue; + } + } + // A stopped compaction's own divider already says it stopped. if ( timelineEntry.kind === "event" && @@ -2103,7 +2202,8 @@ export function deriveMessagesTimelineRows( foldsByAnchorEntryId.has(nextEntry.id) || supersededFoldsByAnchorEntryId.has(nextEntry.id) || (nextEntry.entry.runId ?? null) !== (timelineEntry.entry.runId ?? null) || - nextEntry.attempt?.id !== timelineEntry.attempt?.id + nextEntry.attempt?.id !== timelineEntry.attempt?.id || + sectionFoldsByEntryId.get(nextEntry.id) !== sectionFold ) { break; } @@ -2649,6 +2749,7 @@ function replaceStreamingMessageRows( ) continue; if (!isStreamingMessageTextUpdate(previousEntry.message, entry.message)) return null; + if (!sameBotSectionMarkers(previousEntry.message, entry.message)) return null; replacements.set(previousEntry.message, entry); } if (replacements.size === 0 && thoughts.size === 0 && plans.size === 0) return previous.rows; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index aaaba1d4bc921..669a2193d09aa 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -90,6 +90,7 @@ import { resolveTimelineMinimapVisibleRange, resolveTimelineMinimapHitStripWidth, TIMELINE_MINIMAP_TARGET_OFFSET, + timelineSectionFoldsByEntryId, timelineTurnFoldRunIdsByEntryId, liveAnswerPreview, type MessagesTimelineRow, @@ -718,6 +719,19 @@ const ConversationTimeline = memo(function ConversationTimeline({ previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId), ); } + const citedSection = timelineSectionFoldsByEntryId(timelineEntries, isWorking).get( + citedEntry.id, + ); + if (citedSection) { + const { key, expandedByDefault } = citedSection; + setExpandedRunIds((previous) => { + if (previous.has(key) !== expandedByDefault) return previous; + const next = new Set(previous); + if (expandedByDefault) next.delete(key); + else next.add(key); + return next; + }); + } const citedAttempt = citedEntry.attempt; if (citedAttempt?.status === "superseded") { setExpandedAttemptIds((previous) => @@ -771,6 +785,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ worktreeSetup, toolCallVisibility, revealedMessageId, + expandAllSections: findActive, }); const rows = useStableRows(rawRows, listIdentityKey); const matchedApprovalRequestIds = new Set(); diff --git a/packages/shared/package.json b/packages/shared/package.json index d12cd9b003982..8c42f6ee52a2e 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -515,6 +515,10 @@ "types": "./src/codexFileCitations.ts", "import": "./src/codexFileCitations.ts" }, + "./botSections": { + "types": "./src/botSections.ts", + "import": "./src/botSections.ts" + }, "./codexMarkdownDirectives": { "types": "./src/codexMarkdownDirectives.ts", "import": "./src/codexMarkdownDirectives.ts" diff --git a/packages/shared/src/botSections.test.ts b/packages/shared/src/botSections.test.ts new file mode 100644 index 0000000000000..c221a1d889410 --- /dev/null +++ b/packages/shared/src/botSections.test.ts @@ -0,0 +1,119 @@ +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { + deriveBotSectionSpans, + formatBotSectionLabel, + parseBotSectionMarkers, + type BotSectionMessageMarkers, +} from "./botSections.ts"; + +describe("parseBotSectionMarkers", () => { + it.each<[string, BotSectionMessageMarkers | null]>([ + ["No markers here.", null], + ["Mentions t3bot:section outside a comment.", null], + [ + '\nAll green.', + { start: { kind: "status-check", label: null }, end: false }, + ], + [ + 'Intro text', + { start: { kind: "heartbeat", label: "Morning sweep" }, end: false }, + ], + ["Done.\n\n", { start: null, end: true }], + [ + '\nHandled.\n', + { start: { kind: "webhook", label: null }, end: true }, + ], + // An end before a start only closes the previous section. + [ + '\n', + { start: { kind: "tagged", label: null }, end: false }, + ], + // The last opening marker wins. + [ + '', + { start: { kind: "b-c", label: null }, end: false }, + ], + ['', null], + ['', null], + ["", null], + ])("parses %j", (text, expected) => { + expect(parseBotSectionMarkers(text)).toEqual(expected); + }); +}); + +describe("formatBotSectionLabel", () => { + // Built from local wall-clock parts, so the label reads the same in every zone. + const startedAt = DateTime.formatIso( + DateTime.makeZonedUnsafe( + { year: 2026, month: 11, day: 21, hour: 9, minute: 8, second: 4 }, + { timeZone: DateTime.zoneMakeLocal(), adjustForTimeZone: true }, + ), + ); + + it.each([ + [{ kind: "status-check", label: null }, "Status Check - 09:08:04"], + [{ kind: "heartbeat", label: "Morning sweep" }, "Morning sweep - 09:08:04"], + ])("labels %j in local time", (marker, expected) => { + expect(formatBotSectionLabel(marker, startedAt)).toBe(expected); + }); + + it("drops an unreadable time", () => { + expect(formatBotSectionLabel({ kind: "tagged", label: null }, "not a date")).toBe("Tagged"); + }); +}); + +describe("deriveBotSectionSpans", () => { + // u = user prompt, a = plain reply, w = work, S = opening marker, E = end marker, X = both. + const spans = (items: string) => + deriveBotSectionSpans([...items], { + startsTurn: (item) => item === "u", + markers: (item) => + item === "S" + ? { start: { kind: "status-check", label: null }, end: false } + : item === "E" + ? { start: null, end: true } + : item === "X" + ? { start: { kind: "status-check", label: null }, end: true } + : null, + }).map((span) => [span.startIndex, span.endIndex, span.closed]); + + it.each<[string, Array<[number, number, boolean]>]>([ + ["uaua", []], + // Opens at the prompt of its own turn and stays open to the end. + ["uauwSua", [[2, 6, false]]], + // The next marker's turn closes it. + [ + "uSuauS", + [ + [0, 3, true], + [4, 5, false], + ], + ], + // An end marker closes it, inclusive; later turns stay outside. + ["uSuEua", [[0, 3, true]]], + ["uXua", [[0, 1, true]]], + // A marker before any prompt starts at the first item. + ["wSua", [[0, 3, false]]], + // Two markers in one turn split after the first. + [ + "uSwS", + [ + [0, 1, true], + [2, 3, false], + ], + ], + // A marker right after an end in the same turn starts after the end. + [ + "uSEwS", + [ + [0, 2, true], + [3, 4, false], + ], + ], + ["uEua", []], + ])("spans %j", (items, expected) => { + expect(spans(items)).toEqual(expected); + }); +}); diff --git a/packages/shared/src/botSections.ts b/packages/shared/src/botSections.ts new file mode 100644 index 0000000000000..ef55f28ecbc50 --- /dev/null +++ b/packages/shared/src/botSections.ts @@ -0,0 +1,116 @@ +/** + * T3_BOT section markers fold a whole exchange under one timeline row: + * `` opens one + * at the turn that carries it; `` closes it. + */ +import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; + +export interface BotSectionMarker { + /** Kebab-case section kind, such as `status-check`. */ + readonly kind: string; + readonly label: string | null; +} + +export interface BotSectionMessageMarkers { + /** The last section opened by the message, if any. */ + readonly start: BotSectionMarker | null; + /** Whether the message closes its section; an end before its own start only ends the previous one. */ + readonly end: boolean; +} + +export interface BotSectionSpan { + readonly marker: BotSectionMarker; + /** Index of the item carrying the opening marker. */ + readonly markerIndex: number; + readonly startIndex: number; + /** Inclusive. */ + readonly endIndex: number; + /** False only for a final section with no end marker. */ + readonly closed: boolean; +} + +const MARKER_PREFIX = "t3bot:section"; +const MARKER = //g; +const ATTRIBUTE = /([a-z]+)="([^"]*)"/g; +const KEBAB_CASE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + +export function parseBotSectionMarkers(text: string): BotSectionMessageMarkers | null { + if (!text.includes(MARKER_PREFIX)) return null; + let start: BotSectionMarker | null = null; + let end = false; + for (const match of text.matchAll(MARKER)) { + if (match[1] !== undefined) { + end = true; + continue; + } + let kind: string | null = null; + let label: string | null = null; + for (const [, name, value] of match[2]!.matchAll(ATTRIBUTE)) { + if (name === "kind") kind = value!; + else if (name === "label") label = value!.trim() || null; + } + if (kind === null || !KEBAB_CASE.test(kind)) continue; + start = { kind, label }; + end = false; + } + return start === null && !end ? null : { start, end }; +} + +function botSectionTitle(marker: BotSectionMarker): string { + return ( + marker.label ?? + marker.kind + .split("-") + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(" ") + ); +} + +/** "Status Check - 11:18:04", in the client's local time. */ +export function formatBotSectionLabel(marker: BotSectionMarker, startedAt: string): string { + const title = botSectionTitle(marker); + const instant = DateTime.make(startedAt); + if (Option.isNone(instant)) return title; + const { hour, minute, second } = DateTime.toParts( + DateTime.setZone(instant.value, DateTime.zoneMakeLocal()), + ); + const pad = (value: number) => String(value).padStart(2, "0"); + return `${title} - ${pad(hour)}:${pad(minute)}:${pad(second)}`; +} + +/** + * A section starts at the turn whose reply opens it, and runs until the next + * opening marker's turn, an end marker (inclusive), or the last item. + */ +export function deriveBotSectionSpans( + items: ReadonlyArray, + read: { + readonly markers: (item: T) => BotSectionMessageMarkers | null; + readonly startsTurn: (item: T) => boolean; + }, +): BotSectionSpan[] { + const spans: BotSectionSpan[] = []; + let open: Omit | null = null; + let turnStart = 0; + // Sections never overlap: a later one starts after the previous marker or end. + let floor = 0; + for (const [index, item] of items.entries()) { + if (read.startsTurn(item)) turnStart = index; + const markers = read.markers(item); + if (markers === null) continue; + if (markers.start !== null) { + const startIndex = Math.max(turnStart, floor); + if (open !== null) spans.push({ ...open, endIndex: startIndex - 1, closed: true }); + open = { marker: markers.start, markerIndex: index, startIndex }; + floor = index + 1; + } + if (markers.end && open !== null) { + spans.push({ ...open, endIndex: index, closed: true }); + open = null; + floor = index + 1; + } + } + if (open !== null) spans.push({ ...open, endIndex: items.length - 1, closed: false }); + return spans; +} From b16017609e4ffdc1bf52aade71c7bc176e3abd2e Mon Sep 17 00:00:00 2001 From: Na0s Date: Sat, 21 Nov 2026 15:56:29 -0500 Subject: [PATCH 13/20] feat(desktop): T3_BOT opens in its own floating window `windows.bot` opens a single bot window at `#/bot` (Electron renderers use hash history, so dev and packaged URLs both work) or brings it forward. It is a secondary window, so it connects through the main window's hub and the main window hides rather than closes while it is open. The window starts narrow (380x720) and `setSize` switches to medium (900x760), pulled back onto the display's work area. `setPinned` keeps it above other windows, at the floating level on macOS like the preview picture-in-picture window. Bounds, size and pin persist in desktop settings under `botWindow`; the bot window's context carries its size and pin state. The Window menu gains "Open T3_BOT", the `bot.open` keybinding defaults to mod+alt+shift+b on desktop, and the command palette lists it next to New Window. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/ipc/channels.ts | 3 + apps/desktop/src/ipc/methods/windows.ts | 45 ++++- apps/desktop/src/preload.ts | 5 + .../src/settings/DesktopAppSettings.test.ts | 27 +++ .../src/settings/DesktopAppSettings.ts | 84 ++++++++++ .../desktop/src/updates/updatesTestHarness.ts | 1 + .../src/window/DesktopApplicationMenu.test.ts | 18 +- .../src/window/DesktopApplicationMenu.ts | 11 ++ apps/desktop/src/window/DesktopWindow.test.ts | 87 ++++++++++ apps/desktop/src/window/DesktopWindow.ts | 155 +++++++++++++++--- .../src/window/DesktopWindowProfiles.test.ts | 34 +++- .../src/window/DesktopWindowProfiles.ts | 29 ++++ .../components/CommandPaletteWindowItems.tsx | 21 ++- .../settings/KeybindingsSettings.logic.ts | 1 + apps/web/src/keybindings.test.ts | 56 ++++--- apps/web/src/multiWindow/ui/windowActions.ts | 39 +++-- docs/user/keybindings.md | 3 +- docs/user/multiple-windows.md | 7 + packages/contracts/src/desktopWindows.ts | 13 +- packages/contracts/src/keybindings.ts | 1 + packages/shared/src/keybindings.ts | 1 + 21 files changed, 570 insertions(+), 71 deletions(-) diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 072915f952e48..b9452236fa1f4 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -161,6 +161,9 @@ 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_BOT_OPEN_CHANNEL = "desktop:windows-bot-open"; +export const WINDOWS_BOT_SET_SIZE_CHANNEL = "desktop:windows-bot-set-size"; +export const WINDOWS_BOT_SET_PINNED_CHANNEL = "desktop:windows-bot-set-pinned"; export const WINDOWS_REGISTER_HUB_CHANNEL = "desktop:windows-register-hub"; export const WINDOWS_REQUEST_HUB_LINK_CHANNEL = "desktop:windows-request-hub-link"; export const WINDOWS_HUB_LINK_CHANNEL = "desktop:windows-hub-link"; diff --git a/apps/desktop/src/ipc/methods/windows.ts b/apps/desktop/src/ipc/methods/windows.ts index a2ce8200510a4..a22643583f383 100644 --- a/apps/desktop/src/ipc/methods/windows.ts +++ b/apps/desktop/src/ipc/methods/windows.ts @@ -1,4 +1,8 @@ -import { DesktopWindowContextSchema, DesktopWindowsStateSchema } from "@t3tools/contracts"; +import { + DesktopBotWindowSizeSchema, + DesktopWindowContextSchema, + DesktopWindowsStateSchema, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -55,4 +59,41 @@ const requestHubLink = DesktopIpc.makeIpcMethod({ }), }); -export const methods = [getState, openNew, registerHub, requestHubLink] as const; +const openBot = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_BOT_OPEN_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openBot")(function* () { + yield* (yield* DesktopWindow.DesktopWindow).openBot; + }), +}); + +const setBotSize = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_BOT_SET_SIZE_CHANNEL, + payload: DesktopBotWindowSizeSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setBotSize")(function* (size) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setBotSize(window, size); + }), +}); + +const setBotPinned = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_BOT_SET_PINNED_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setBotPinned")(function* (pinned) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setBotPinned(window, pinned); + }), +}); + +export const methods = [ + getState, + openNew, + registerHub, + requestHubLink, + openBot, + setBotSize, + setBotPinned, +] as const; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 65c714f87dbdb..5aa154191ad98 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -148,6 +148,11 @@ const windows: DesktopWindowsBridge = { ), onHubReset: (listener) => subscribe(IpcChannels.WINDOWS_HUB_RESET_CHANNEL, () => true)(() => listener()), + bot: { + open: () => ipcRenderer.invoke(IpcChannels.WINDOWS_BOT_OPEN_CHANNEL), + setSize: (size) => ipcRenderer.invoke(IpcChannels.WINDOWS_BOT_SET_SIZE_CHANNEL, size), + setPinned: (pinned) => ipcRenderer.invoke(IpcChannels.WINDOWS_BOT_SET_PINNED_CHANNEL, pinned), + }, }; function unwrapEnsureSshEnvironmentResult(result: unknown) { diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 04406f63c6b3d..3129752a0ed8a 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -13,6 +13,20 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopAppSettings from "./DesktopAppSettings.ts"; const DesktopSettingsPatch = Schema.Struct({ + botWindow: Schema.optionalKey( + Schema.Struct({ + bounds: Schema.optionalKey( + Schema.Struct({ + x: Schema.Number, + y: Schema.Number, + width: Schema.Number, + height: Schema.Number, + }), + ), + size: Schema.optionalKey(Schema.Literals(["narrow", "medium"])), + pinned: Schema.optionalKey(Schema.Boolean), + }), + ), linuxPasswordStore: Schema.optionalKey( Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]), ), @@ -223,6 +237,7 @@ describe("DesktopSettings", () => { ); assert.deepEqual(yield* settings.load, { + botWindow: { bounds: null, size: "narrow", pinned: false }, linuxPasswordStore: "auto", localEnvironmentEnabled: true, mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 }, @@ -295,11 +310,16 @@ describe("DesktopSettings", () => { yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 400, height: 360 }, true); yield* settings.setServerExposureMode("network-accessible"); + // Narrower than any main window may be. + yield* settings.updateBotWindow({ bounds: { x: 1500, y: 60, width: 380, height: 720 } }); + yield* settings.updateBotWindow({ pinned: true }); + assert.isFalse((yield* settings.updateBotWindow({ pinned: true })).changed); const persisted = yield* decodeDesktopSettingsPatch( yield* fileSystem.readFileString(environment.desktopSettingsPath), ); assert.deepEqual(persisted, { + botWindow: { bounds: { x: 1500, y: 60, width: 380, height: 720 }, pinned: true }, mainWindowBounds: { x: -1200, y: 40, width: 400, height: 360 }, mainWindowMaximized: true, serverExposureMode: "network-accessible", @@ -311,6 +331,11 @@ describe("DesktopSettings", () => { }).pipe(Effect.provide(DesktopAppSettings.layer)); assert.deepEqual(restored.mainWindowBounds, persisted.mainWindowBounds); assert.isTrue(restored.mainWindowMaximized); + assert.deepEqual(restored.botWindow, { + bounds: { x: 1500, y: 60, width: 380, height: 720 }, + size: "narrow", + pinned: true, + }); }), ), ); @@ -376,6 +401,7 @@ describe("DesktopSettings", () => { }); assert.deepEqual(yield* settings.load, { + botWindow: { bounds: null, size: "narrow", pinned: false }, linuxPasswordStore: "auto", localEnvironmentEnabled: true, mainWindowBounds: null, @@ -405,6 +431,7 @@ describe("DesktopSettings", () => { }); assert.deepEqual(yield* settings.load, { + botWindow: { bounds: null, size: "narrow", pinned: false }, linuxPasswordStore: "auto", localEnvironmentEnabled: true, mainWindowBounds: null, diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index e81da70660648..a5e592f3adb37 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -1,6 +1,8 @@ import { + DesktopBotWindowSizeSchema, DesktopServerExposureModeSchema, DesktopUpdateChannelSchema, + type DesktopBotWindowSize, type DesktopServerExposureMode, type DesktopUpdateChannel, } from "@t3tools/contracts"; @@ -27,7 +29,14 @@ import { import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; import { isValidDistroName } from "../wsl/wslPathParsing.ts"; +export interface DesktopBotWindowSettings { + readonly bounds: DesktopBotWindowBounds | null; + readonly size: DesktopBotWindowSize; + readonly pinned: boolean; +} + export interface DesktopSettings { + readonly botWindow: DesktopBotWindowSettings; readonly localEnvironmentEnabled: boolean; readonly linuxPasswordStore: LinuxPasswordStorePreference; readonly mainWindowBounds: DesktopWindowBounds | null; @@ -68,7 +77,29 @@ export const DEFAULT_MAIN_WINDOW_SIZE = { height: 780, } as const; +export const MIN_BOT_WINDOW_SIZE = { + width: 320, + height: 420, +} as const; +export const BOT_WINDOW_SIZES = { + narrow: { width: 380, height: 720 }, + medium: { width: 900, height: 760 }, +} as const satisfies Record; +export const DesktopBotWindowBoundsSchema = Schema.Struct({ + x: Schema.Int, + y: Schema.Int, + width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_BOT_WINDOW_SIZE.width)), + height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_BOT_WINDOW_SIZE.height)), +}); +export type DesktopBotWindowBounds = typeof DesktopBotWindowBoundsSchema.Type; +const DEFAULT_BOT_WINDOW_SETTINGS: DesktopBotWindowSettings = { + bounds: null, + size: "narrow", + pinned: false, +}; + export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { + botWindow: DEFAULT_BOT_WINDOW_SETTINGS, localEnvironmentEnabled: true, linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE, mainWindowBounds: null, @@ -95,7 +126,14 @@ const DesktopWindowBoundsDocument = Schema.Struct({ const optionalReadableKey = (schema: S) => Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone))); +const DesktopBotWindowDocument = Schema.Struct({ + bounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), + size: optionalReadableKey(DesktopBotWindowSizeSchema), + pinned: optionalReadableKey(Schema.Boolean), +}); + const DesktopSettingsDocument = Schema.Struct({ + botWindow: optionalReadableKey(DesktopBotWindowDocument), localEnvironmentEnabled: optionalReadableKey(Schema.Boolean), linuxPasswordStore: optionalReadableKey(Schema.Unknown), mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), @@ -119,6 +157,8 @@ const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson); const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson); const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema); const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema); +const decodeDesktopBotWindowBounds = Schema.decodeUnknownOption(DesktopBotWindowBoundsSchema); +const desktopBotWindowBoundsEquivalence = Schema.toEquivalence(DesktopBotWindowBoundsSchema); const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({ settings, @@ -160,6 +200,9 @@ export class DesktopAppSettings extends Context.Service< bounds: DesktopWindowBounds, isMaximized: boolean, ) => Effect.Effect; + readonly updateBotWindow: ( + update: Partial, + ) => Effect.Effect; readonly setServerExposureMode: ( mode: DesktopServerExposureMode, ) => Effect.Effect; @@ -208,6 +251,10 @@ export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | return Option.getOrNull(decodeDesktopWindowBounds(value)); } +export function normalizeBotWindowBounds(value: unknown): DesktopBotWindowBounds | null { + return Option.getOrNull(decodeDesktopBotWindowBounds(value)); +} + function normalizeDesktopSettingsDocument( parsed: DesktopSettingsDocument, appVersion: string, @@ -225,6 +272,11 @@ function normalizeDesktopSettingsDocument( (parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl"); return { + botWindow: { + bounds: normalizeBotWindowBounds(parsed.botWindow?.bounds), + size: parsed.botWindow?.size ?? DEFAULT_BOT_WINDOW_SETTINGS.size, + pinned: parsed.botWindow?.pinned === true, + }, localEnvironmentEnabled: parsed.localEnvironmentEnabled !== false, linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore), mainWindowBounds, @@ -249,6 +301,16 @@ function toDesktopSettingsDocument( ): DesktopSettingsDocument { const document: Mutable = {}; + const { botWindow } = settings; + const botWindowDocument = { + ...(botWindow.bounds === null ? {} : { bounds: botWindow.bounds }), + ...(botWindow.size === DEFAULT_BOT_WINDOW_SETTINGS.size ? {} : { size: botWindow.size }), + ...(botWindow.pinned ? { pinned: true } : {}), + }; + if (Object.keys(botWindowDocument).length > 0) { + document.botWindow = botWindowDocument; + } + if (settings.localEnvironmentEnabled !== defaults.localEnvironmentEnabled) { document.localEnvironmentEnabled = settings.localEnvironmentEnabled; } @@ -318,6 +380,22 @@ function setMainWindowBounds( }; } +function updateBotWindow( + settings: DesktopSettings, + update: Partial, +): DesktopSettings { + const current = settings.botWindow; + const next = { ...current, ...update }; + const boundsUnchanged = + next.bounds === current.bounds || + (next.bounds !== null && + current.bounds !== null && + desktopBotWindowBoundsEquivalence(next.bounds, current.bounds)); + return boundsUnchanged && next.size === current.size && next.pinned === current.pinned + ? settings + : { ...settings, botWindow: next }; +} + function setTailscaleServe( settings: DesktopSettings, input: { readonly enabled: boolean; readonly port: Option.Option }, @@ -562,6 +640,9 @@ export const make = Effect.gen(function* () { return yield* persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)); }, ), + updateBotWindow: Effect.fn("desktop.settings.updateBotWindow")(function* (patch) { + return yield* persist((settings) => updateBotWindow(settings, patch)); + }), setServerExposureMode: Effect.fn("desktop.settings.setServerExposureMode")(function* (mode) { yield* Effect.annotateCurrentSpan({ mode }); @@ -635,6 +716,9 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET return update((settings) => setMainWindowBounds(settings, bounds, isMaximized)); }, ), + updateBotWindow: Effect.fn("DesktopAppSettings.updateBotWindow")(function (patch) { + return update((settings) => updateBotWindow(settings, patch)); + }), setServerExposureMode: Effect.fn("DesktopAppSettings.setServerExposureMode")( function (mode) { return update((settings) => setServerExposureMode(settings, mode)); diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index 480a4496553b7..9c2b8e0d15cd6 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -218,6 +218,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { get: Effect.sync(() => testSettings), load: Effect.sync(() => testSettings), setMainWindowBounds: () => Effect.die("unexpected main window bounds update"), + updateBotWindow: () => Effect.die("unexpected bot window update"), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: (channel) => diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 2166d7c9cb97d..df488889b5b20 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -110,6 +110,7 @@ const layerDesktopWindow = (selectedAction: Deferred.Deferred) => runFocusedContentsCommand: (command) => Deferred.succeed(selectedAction, `main-${command}`).pipe(Effect.asVoid), syncAppearance: Effect.void, + openBot: Deferred.succeed(selectedAction, "open-bot").pipe(Effect.asVoid), }); const layerElectronMenu = ( @@ -347,7 +348,10 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); - it.effect("leads the Window menu with New Window and leaves its chord to the renderer", () => + it.effect.each([ + { index: 0, label: "New Window", accelerator: "CmdOrCtrl+Alt+Shift+N", action: "new-window" }, + { index: 1, label: "Open T3_BOT", accelerator: "CmdOrCtrl+Alt+Shift+B", action: "open-bot" }, + ])("leads the Window menu with $label and leaves its chord to the renderer", (expected) => Effect.gen(function* () { const selectedAction = yield* Deferred.make(); const applicationMenuTemplate = @@ -360,14 +364,14 @@ describe("DesktopApplicationMenu", () => { if (!Array.isArray(windowMenu?.submenu)) { throw new Error("Expected the Window menu submenu to be an array."); } - const [newWindow] = windowMenu.submenu; + const item = windowMenu.submenu[expected.index]; assert.deepEqual( - { label: newWindow?.label, accelerator: newWindow?.accelerator }, - { label: "New Window", accelerator: "CmdOrCtrl+Alt+Shift+N" }, + { label: item?.label, accelerator: item?.accelerator }, + { label: expected.label, accelerator: expected.accelerator }, ); - assert.equal(newWindow?.registerAccelerator, false); - newWindow?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); - assert.equal(yield* Deferred.await(selectedAction), "new-window"); + assert.equal(item?.registerAccelerator, false); + item?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + assert.equal(yield* Deferred.await(selectedAction), expected.action); }), ); diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 524471920374b..689d74d0bef4f 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -74,6 +74,10 @@ const trackLabel = (channel: DesktopUpdateChannel) => ? m(msg("Nightly", { $context: "release track" })) : m(msg("Stable", { $context: "release track" })); +const openBotWindow = Effect.gen(function* () { + yield* (yield* DesktopWindow.DesktopWindow).openBot; +}).pipe(Effect.withSpan("desktop.menu.openBotWindow")); + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -403,6 +407,13 @@ export const make = Effect.gen(function* () { registerAccelerator: false, click: () => runMenuEffect("new-window", dispatchMenuAction("new-window")), }, + { + label: m(msg("Open T3_BOT", { $context: "Window menu item" })), + // The renderer's bot.open keybinding owns the chord. + accelerator: "CmdOrCtrl+Alt+Shift+B", + registerAccelerator: false, + click: () => runMenuEffect("open-bot", openBotWindow), + }, { type: "separator" }, { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) }, { diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 3d812c82aa5f8..5f4e9512e0f25 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -29,6 +29,7 @@ vi.mock("electron", async (importOriginal) => ({ getAllDisplays: vi.fn(() => [ { bounds: { x: 0, y: 0, width: 1920, height: 1080 }, + workArea: { x: 0, y: 25, width: 1920, height: 1055 }, }, ]), }, @@ -135,7 +136,9 @@ function makeFakeBrowserWindow() { }), restore: vi.fn(), setBackgroundColor: vi.fn(), + setAlwaysOnTop: vi.fn(), setAutoHideCursor: vi.fn(), + setBounds: vi.fn(), setFullScreen: vi.fn(), setOpacity: vi.fn(), setTitle: vi.fn(), @@ -165,7 +168,9 @@ function makeFakeBrowserWindow() { setZoomLevel: webContents.setZoomLevel, setWindowButtonPosition: window.setWindowButtonPosition, setBackgroundThrottling: webContents.setBackgroundThrottling, + setAlwaysOnTop: window.setAlwaysOnTop, setAutoHideCursor: window.setAutoHideCursor, + setBounds: window.setBounds, setFullScreen: window.setFullScreen, setOpacity: window.setOpacity, webContentsListeners, @@ -247,6 +252,7 @@ function layerTest(input: { readonly desktopSettings?: DesktopAppSettings.DesktopSettings; readonly mainWindowBoundsUpdates?: DesktopAppSettings.DesktopWindowBounds[]; readonly mainWindowMaximizedUpdates?: boolean[]; + readonly botWindowUpdates?: Partial[]; readonly beforeMainWindowBoundsUpdate?: ( bounds: DesktopAppSettings.DesktopWindowBounds, ) => Effect.Effect; @@ -294,6 +300,15 @@ function layerTest(input: { } return { settings: desktopSettings, changed }; }), + updateBotWindow: (patch) => + Effect.sync(() => { + input.botWindowUpdates?.push(patch); + desktopSettings = { + ...desktopSettings, + botWindow: { ...desktopSettings.botWindow, ...patch }, + }; + return { settings: desktopSettings, changed: true }; + }), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: () => Effect.die("unexpected update channel change"), @@ -1520,6 +1535,78 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens one bot window at /bot that resizes, pins, and keeps its placement", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const bot = makeFakeBrowserWindow(); + const savedBounds = { x: 1500, y: 60, width: 380, height: 720 }; + bot.getBounds.mockReturnValue(savedBounds); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = []; + const botWindowUpdates: Partial[] = []; + const revealed: Electron.BrowserWindow[] = []; + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, bot.window], + createCount, + mainWindow, + createdWindowOptions, + botWindowUpdates, + onReveal: (window) => revealed.push(window), + desktopSettings: { + ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, + botWindow: { bounds: savedBounds, size: "narrow", pinned: true }, + }, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* windows.openBot; + yield* windows.openBot; + assert.equal(yield* Ref.get(createCount), 2); + assert.deepEqual(revealed, [bot.window]); + assert.deepEqual(bot.loadURL.mock.calls, [["t3code-dev://app/#/bot"]]); + assert.deepInclude(createdWindowOptions[1], { + ...savedBounds, + minWidth: DesktopAppSettings.MIN_BOT_WINDOW_SIZE.width, + maximizable: false, + titleBarStyle: "hiddenInset", + }); + assert.deepEqual(bot.setAlwaysOnTop.mock.calls, [[true, "floating"]]); + // Not the main window: the main window hides instead of closing while the bot needs it. + assert.deepEqual((yield* windows.windowsState).windows, [ + { windowId: main.window.id, isMain: true }, + { windowId: bot.window.id, isMain: false }, + ]); + + yield* windows.setBotSize(bot.window, "medium"); + // Grown in place, then pulled left onto the display's work area. + assert.deepEqual(bot.setBounds.mock.calls, [[{ x: 1020, y: 60, width: 900, height: 760 }]]); + yield* windows.setBotPinned(bot.window, false); + assert.deepEqual(bot.setAlwaysOnTop.mock.calls.at(-1), [false]); + yield* windows.setBotPinned(main.window, true); + yield* windows.setBotSize(main.window, "narrow"); + assert.equal(main.setAlwaysOnTop.mock.calls.length + main.setBounds.mock.calls.length, 0); + assert.deepEqual(Option.getOrThrow(yield* windows.windowContext(bot.window)), { + windowId: bot.window.id, + isMain: false, + bot: { size: "medium", pinned: false }, + }); + + bot.getBounds.mockReturnValue({ x: 1020, y: 60, width: 900, height: 760 }); + bot.windowListeners.get("move")?.(); + yield* TestClock.adjust(500); + assert.deepEqual(botWindowUpdates, [ + { size: "medium" }, + { pinned: false }, + { bounds: { x: 1020, y: 60, width: 900, height: 760 } }, + ]); + }).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 6b3aa5b82e655..31e9fc796df63 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -12,6 +12,8 @@ import * as Electron from "electron"; import { msg } from "gt-i18n"; import { + type DesktopBotWindowSize, + type DesktopBotWindowState, type DesktopSnapShotEvent, type DesktopWindowContext, type DesktopWindowsState, @@ -57,7 +59,7 @@ import { copyContextMenuImage } from "./ContextMenuImage.ts"; import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; import { setUnthrottledHold } from "./BackgroundThrottling.ts"; import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; -import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; +import { cascadeWindowBounds, resizeWithinDisplay } from "./DesktopWindowProfiles.ts"; const TITLEBAR_HEIGHT = 40; @@ -166,6 +168,15 @@ export class DesktopWindow extends Context.Service< window: Electron.BrowserWindow, ) => Effect.Effect>; readonly openNewWindow: Effect.Effect; + /** Opens the single bot window, or brings it forward. */ + readonly openBot: Effect.Effect; + /** No-ops unless `window` is the bot window. */ + readonly setBotSize: ( + window: Electron.BrowserWindow, + size: DesktopBotWindowSize, + ) => Effect.Effect; + /** No-ops unless `window` is the bot window. */ + readonly setBotPinned: (window: Electron.BrowserWindow, pinned: boolean) => Effect.Effect; readonly registerHub: (window: Electron.BrowserWindow) => Effect.Effect; readonly requestHubLink: (window: Electron.BrowserWindow) => Effect.Effect; } @@ -260,6 +271,14 @@ function readDisplayBoundsOrEmpty(): readonly DisplayBounds[] { } } +function readDisplayWorkAreasOrEmpty(): readonly DisplayBounds[] { + try { + return Electron.screen.getAllDisplays().map((display) => display.workArea); + } catch { + return []; + } +} + function windowBoundsEqual( left: DesktopAppSettings.DesktopWindowBounds, right: DesktopAppSettings.DesktopWindowBounds, @@ -272,17 +291,20 @@ function windowBoundsEqual( ); } +type WindowSize = { readonly width: number; readonly height: number }; + export function resolveInitialMainWindowBounds( persistedBounds: DesktopAppSettings.DesktopWindowBounds | null, displays: readonly DisplayBounds[], -): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE { + defaultSize: WindowSize = DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, +): DesktopAppSettings.DesktopWindowBounds | WindowSize { if ( persistedBounds !== null && displays.some((display) => windowFitsWithinDisplay(persistedBounds, display)) ) { return persistedBounds; } - return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE; + return defaultSize; } function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string { @@ -404,12 +426,14 @@ function bindFirstRevealTrigger( type AppWindowSpec = | { readonly role: "main" } - | { readonly role: "secondary"; readonly anchorBounds: DisplayBounds | null }; + | { readonly role: "secondary"; readonly anchorBounds: DisplayBounds | null } + | { readonly role: "bot" }; interface AppWindowEntry { readonly window: Electron.BrowserWindow; readonly windowId: number; readonly isMain: boolean; + readonly isBot: boolean; rendererLive: boolean; hubUnthrottled: boolean; } @@ -441,6 +465,12 @@ export const make = Effect.gen(function* () { const runPromise = Effect.runPromiseWith(context); const runSync = Effect.runSyncWith(context); const mainWindowMutex = yield* Semaphore.make(1); + const botWindowMutex = yield* Semaphore.make(1); + // The bot window's renderer reads this at load; settings may refuse writes. + let botState: DesktopBotWindowState = { + size: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.botWindow.size, + pinned: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.botWindow.pinned, + }; const pendingMainReveals = new WeakMap>(); const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) => Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), @@ -448,6 +478,11 @@ export const make = Effect.gen(function* () { let flushMainWindowBounds: Effect.Effect = Effect.void; let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; const entries = new Map(); + // macOS: float above other apps' windows, as the preview picture-in-picture window does. + const applyBotPinned = (window: Electron.BrowserWindow, pinned: boolean) => { + if (!pinned) window.setAlwaysOnTop(false); + else window.setAlwaysOnTop(true, environment.platform === "darwin" ? "floating" : "normal"); + }; let lastBroadcastState = ""; const hubLinks = new HubLinkBroker( () => new Electron.MessageChannelMain(), @@ -456,6 +491,7 @@ export const make = Effect.gen(function* () { const liveEntries = () => [...entries.values()].filter((entry) => !entry.window.isDestroyed()); const mainEntry = () => liveEntries().find((entry) => entry.isMain); const secondaryEntries = () => liveEntries().filter((entry) => !entry.isMain); + const botEntry = () => liveEntries().find((entry) => entry.isBot); const entryOf = (window: Electron.BrowserWindow) => { const entry = entries.get(window.id); return entry !== undefined && entry.window === window && !window.isDestroyed() @@ -571,20 +607,33 @@ export const make = Effect.gen(function* () { ): Effect.fn.Return, DesktopWindowError> { if (yield* Ref.get(desktopState.quitting)) return Option.none(); const isMain = spec.role === "main"; + const isBot = spec.role === "bot"; 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; + // Only the main and bot windows keep their placement. + const persistedBounds = isMain + ? persistedSettings.mainWindowBounds + : isBot + ? persistedSettings.botWindow.bounds + : null; const displayBounds = yield* readDisplayBounds; - const restorableBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds); + const restorableBounds = resolveInitialMainWindowBounds( + persistedBounds, + displayBounds, + isBot + ? DesktopAppSettings.BOT_WINDOW_SIZES[persistedSettings.botWindow.size] + : DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, + ); const restoredPersistedBounds = persistedBounds !== null && restorableBounds === persistedBounds; if (persistedBounds !== null && !restoredPersistedBounds) { - yield* logWindowWarning("saved main window bounds could not be restored; using defaults"); + yield* logWindowWarning("saved window bounds could not be restored; using defaults", { + role: spec.role, + }); } const initialBounds = spec.role === "secondary" @@ -595,10 +644,15 @@ export const make = Effect.gen(function* () { }) : restorableBounds; if (yield* Ref.get(desktopState.quitting)) return Option.none(); + const minimumSize = isBot + ? DesktopAppSettings.MIN_BOT_WINDOW_SIZE + : DesktopAppSettings.MIN_MAIN_WINDOW_SIZE; const window = yield* electronWindow.create({ ...initialBounds, - minWidth: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width, - minHeight: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height, + minWidth: minimumSize.width, + minHeight: minimumSize.height, + // The bot window stays compact; its sizes are presets. + ...(isBot ? { maximizable: false, fullscreenable: false } : {}), show: false, autoHideMenuBar: true, ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}), @@ -625,6 +679,13 @@ export const make = Effect.gen(function* () { } if (isMain) pendingMainReveals.set(window, Effect.void); + if (isBot) { + botState = { + size: persistedSettings.botWindow.size, + pinned: persistedSettings.botWindow.pinned, + }; + if (botState.pinned) applyBotPinned(window, true); + } setUnthrottledHold(window, "first-reveal", true); yield* rendererHistory.register(window.webContents, { surface: "main" }); if (environment.platform === "darwin") { @@ -634,6 +695,7 @@ export const make = Effect.gen(function* () { window, windowId: window.id, isMain, + isBot, rendererLive: false, hubUnthrottled: false, }; @@ -662,7 +724,10 @@ export const make = Effect.gen(function* () { readDisplayBoundsOrEmpty(), ) : window.getBounds(); - const persistableBounds = DesktopAppSettings.normalizeMainWindowBounds({ + const normalizeBounds = isBot + ? DesktopAppSettings.normalizeBotWindowBounds + : DesktopAppSettings.normalizeMainWindowBounds; + const persistableBounds = normalizeBounds({ x: Math.round(bounds.x), y: Math.round(bounds.y), width: Math.round(bounds.width), @@ -675,9 +740,9 @@ export const make = Effect.gen(function* () { const fallbackWindowBounds = boundsPersistenceEnabled ? null : (readPersistableState()?.bounds ?? null); - const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; + const fallbackWindowMaximized = isMain && persistedSettings.mainWindowMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { - if (!isMain || !boundsPersistenceEnabled) { + if ((!isMain && !isBot) || !boundsPersistenceEnabled) { return pendingBoundsPersistFiber; } const state = readPersistableState(); @@ -685,10 +750,14 @@ export const make = Effect.gen(function* () { return pendingBoundsPersistFiber; } pendingBoundsPersistFiber = runFork( - desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe( + (isBot + ? desktopSettings.updateBotWindow({ bounds: state.bounds }) + : desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized) + ).pipe( Effect.asVoid, Effect.catch((error) => - logWindowWarning("failed to persist main window bounds", { + logWindowWarning("failed to persist window bounds", { + role: spec.role, message: error.message, }), ), @@ -1036,11 +1105,13 @@ export const make = Effect.gen(function* () { developmentLoadRetryFiber = undefined; runFork(Fiber.interrupt(retryFiber)); }; + // Electron renderers use hash history, so a route is the URL fragment. + const windowUrl = isBot ? `${applicationUrl}#/bot` : applicationUrl; const loadApplication = () => { if (window.isDestroyed()) { return; } - void window.loadURL(applicationUrl).catch(() => undefined); + void window.loadURL(windowUrl).catch(() => undefined); }; const scheduleDevelopmentLoadRetry = () => { if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) { @@ -1281,6 +1352,27 @@ export const make = Effect.gen(function* () { }); }).pipe(Effect.withSpan("desktop.window.openSecondary")); + const openBot = Effect.gen(function* () { + const existing = botEntry(); + if (existing !== undefined) { + yield* electronWindow.reveal(existing.window); + return; + } + // Like menu actions, wait for the backend rather than strand a new main window on auth. + if (Option.isNone(yield* electronWindow.main) && (yield* waitingForBackend)) return; + // The bot window reaches environments through the main window's renderer. + if (Option.isNone(yield* ensureMain)) return; + yield* buildAppWindow({ role: "bot" }); + }).pipe(botWindowMutex.withPermits(1), Effect.withSpan("desktop.window.openBot")); + + const persistBotWindow = (patch: Partial) => + desktopSettings.updateBotWindow(patch).pipe( + Effect.asVoid, + Effect.catch((error) => + logWindowWarning("failed to persist bot window settings", { message: error.message }), + ), + ); + const handleSecondaryClosed = Effect.gen(function* () { if (yield* Ref.get(desktopState.quitting)) return; const main = mainEntry(); @@ -1506,12 +1598,37 @@ export const make = Effect.gen(function* () { 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 }); + if (entry === undefined) return Option.none(); + return Option.some({ + windowId: entry.windowId, + isMain: entry.isMain, + ...(entry.isBot ? { bot: botState } : {}), + }); }); }), openNewWindow: openSecondary, + openBot, + setBotSize: Effect.fn("desktop.window.setBotSize")(function* (window, size) { + yield* Effect.annotateCurrentSpan({ size }); + if (entryOf(window)?.isBot !== true) return; + botState = { ...botState, size }; + if (window.isMinimized()) window.restore(); + window.setBounds( + resizeWithinDisplay({ + bounds: window.getBounds(), + size: DesktopAppSettings.BOT_WINDOW_SIZES[size], + displays: readDisplayWorkAreasOrEmpty(), + }), + ); + yield* persistBotWindow({ size }); + }), + setBotPinned: Effect.fn("desktop.window.setBotPinned")(function* (window, pinned) { + yield* Effect.annotateCurrentSpan({ pinned }); + if (entryOf(window)?.isBot !== true) return; + botState = { ...botState, pinned }; + applyBotPinned(window, pinned); + yield* persistBotWindow({ pinned }); + }), registerHub: Effect.fn("desktop.window.registerHub")(function (window) { return Effect.sync(() => { const entry = entryOf(window); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.test.ts b/apps/desktop/src/window/DesktopWindowProfiles.test.ts index f1a8a93b10634..b86557b60ca72 100644 --- a/apps/desktop/src/window/DesktopWindowProfiles.test.ts +++ b/apps/desktop/src/window/DesktopWindowProfiles.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { cascadeWindowBounds } from "./DesktopWindowProfiles.ts"; +import { cascadeWindowBounds, resizeWithinDisplay } from "./DesktopWindowProfiles.ts"; describe("cascadeWindowBounds", () => { const display = { x: 0, y: 0, width: 1920, height: 1080 }; @@ -24,3 +24,35 @@ describe("cascadeWindowBounds", () => { expect(cascadeWindowBounds({ anchor: null, size, displays: [display] })).toEqual(size); }); }); + +describe("resizeWithinDisplay", () => { + const left = { x: 0, y: 25, width: 1920, height: 1055 }; + const right = { x: 1920, y: 0, width: 1280, height: 800 }; + + it("keeps the origin when the new size fits, and pulls the window back onto its display", () => { + const medium = { width: 900, height: 760 }; + expect( + resizeWithinDisplay({ + bounds: { x: 200, y: 100, width: 380, height: 720 }, + size: medium, + displays: [left, right], + }), + ).toEqual({ x: 200, y: 100, ...medium }); + // A narrow window at the right edge of the second display grows to the left. + expect( + resizeWithinDisplay({ + bounds: { x: 2800, y: 40, width: 380, height: 720 }, + size: medium, + displays: [left, right], + }), + ).toEqual({ x: 2300, y: 40, ...medium }); + // Larger than the display: as large as it allows. + expect( + resizeWithinDisplay({ + bounds: { x: 2000, y: 0, width: 380, height: 720 }, + size: { width: 900, height: 1000 }, + displays: [left, right], + }), + ).toEqual({ x: 2000, y: 0, width: 900, height: 800 }); + }); +}); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.ts b/apps/desktop/src/window/DesktopWindowProfiles.ts index 9e0e07c757bf4..652d9eefe51ef 100644 --- a/apps/desktop/src/window/DesktopWindowProfiles.ts +++ b/apps/desktop/src/window/DesktopWindowProfiles.ts @@ -39,3 +39,32 @@ export function cascadeWindowBounds(input: { height, }; } + +/** Resizes a window in place, moving it only as far as it takes to stay on its display. */ +export function resizeWithinDisplay(input: { + readonly bounds: Rectangle; + readonly size: { readonly width: number; readonly height: number }; + readonly displays: readonly Rectangle[]; +}): Rectangle { + const { bounds } = input; + const centerX = bounds.x + bounds.width / 2; + const centerY = bounds.y + bounds.height / 2; + const display = + input.displays.find( + (candidate) => + centerX >= candidate.x && + centerY >= candidate.y && + centerX < candidate.x + candidate.width && + centerY < candidate.y + candidate.height, + ) ?? input.displays[0]; + if (display === undefined) return { x: bounds.x, y: bounds.y, ...input.size }; + const width = Math.min(input.size.width, display.width); + const height = Math.min(input.size.height, display.height); + const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max); + return { + x: Math.round(clamp(bounds.x, display.x, display.x + display.width - width)), + y: Math.round(clamp(bounds.y, display.y, display.y + display.height - height)), + width, + height, + }; +} diff --git a/apps/web/src/components/CommandPaletteWindowItems.tsx b/apps/web/src/components/CommandPaletteWindowItems.tsx index f38e3ecb476f9..9370bc6a5ac34 100644 --- a/apps/web/src/components/CommandPaletteWindowItems.tsx +++ b/apps/web/src/components/CommandPaletteWindowItems.tsx @@ -1,17 +1,17 @@ import { useGT } from "gt-react"; -import { AppWindowIcon } from "lucide-react"; +import { AppWindowIcon, BotIcon } from "lucide-react"; import { useState } from "react"; import { desktopWindowsBridge } from "../multiWindow/windowContext"; -import { openNewDesktopWindow } from "../multiWindow/ui/windowActions"; +import { openDesktopBotWindow, 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. */ +/** Desktop 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 [ + const items: CommandPaletteActionItem[] = [ { kind: "action", value: "action:window-new", @@ -22,4 +22,17 @@ export function useCommandPaletteWindowItems(): ReadonlyArray openNewDesktopWindow(bridge), }, ]; + const bot = bridge.bot; + if (bot !== undefined) { + items.push({ + kind: "action", + value: "action:bot-open", + title: gt("Open T3_BOT"), + searchTerms: ["bot", "t3_bot", "assistant", "open bot"], + icon: , + shortcutCommand: "bot.open", + run: async () => openDesktopBotWindow(bot), + }); + } + return items; } diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 9907448c60914..f069ac8f0d377 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -518,6 +518,7 @@ const USAGE_COMMAND_LABELS: Record< const LATE_COMMAND_LABELS: Partial> = { "view.reopenClosed": msg("Reopen Closed Tab"), "window.new": msg("New Window"), + "bot.open": msg("Open T3_BOT"), "preview.focusUrl": msg("Preview: Focus URL"), "preview.find": msg("Preview: Find on Page"), }; diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 2ce2fe870540c..d3d41b76e5be6 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -400,31 +400,37 @@ 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("desktop window shortcuts", () => { + it.each([ + { key: "n", command: "window.new", neighbour: "chat.newWithoutProject" }, + { key: "b", command: "bot.open", neighbour: "rightPanel.toggle" }, + ] as const)( + "$command opens a window only in the desktop app, apart from $neighbour", + ({ key, command, neighbour }) => { + const shortcut = event({ key, ctrlKey: true, altKey: true, shiftKey: true }); + assert.strictEqual( + resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context: { isDesktop: true }, + }), + command, + ); + assert.isNull( + resolveShortcutCommand(shortcut, DEFAULT_RESOLVED_KEYBINDINGS, { + platform: "Linux", + context: { isDesktop: false }, + }), + ); + assert.strictEqual( + resolveShortcutCommand( + event({ key, ctrlKey: true, altKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { platform: "Linux", context: { isDesktop: true } }, + ), + neighbour, + ); + }, + ); }); describe("model picker navigation helpers", () => { diff --git a/apps/web/src/multiWindow/ui/windowActions.ts b/apps/web/src/multiWindow/ui/windowActions.ts index c8d75683481f7..3328434237614 100644 --- a/apps/web/src/multiWindow/ui/windowActions.ts +++ b/apps/web/src/multiWindow/ui/windowActions.ts @@ -1,9 +1,13 @@ -import type { DesktopWindowsBridge } from "@t3tools/contracts"; +import type { DesktopBotWindowBridge, 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 { + type CommandHandlers, + registerCommands, + registerMenuAction, +} from "../../shortcuts/dispatcher"; import { desktopWindowsBridge } from "../windowContext"; function notifyWindowActionFailure(title: string, cause: unknown): void { @@ -21,18 +25,33 @@ export function openNewDesktopWindow(bridge: DesktopWindowsBridge): void { }); } -/** The New Window shortcut and menu item; a no-op outside a multi-window desktop shell. */ +export function openDesktopBotWindow(bot: DesktopBotWindowBridge): void { + bot.open().catch((cause: unknown) => { + notifyWindowActionFailure(m(msg("Couldn't open T3_BOT")), cause); + }); +} + +/** The New Window and Open T3_BOT shortcuts and menu items; no-ops outside a desktop shell that has them. */ export function registerDesktopWindowCommands(): () => void { const bridge = desktopWindowsBridge(); if (bridge === null) return () => {}; + const commands: CommandHandlers = { + "window.new": (event) => { + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) openNewDesktopWindow(bridge); + }, + }; + const bot = bridge.bot; + if (bot !== undefined) { + commands["bot.open"] = (event) => { + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) openDesktopBotWindow(bot); + }; + } const disposers = [ - registerCommands({ - "window.new": (event) => { - event.preventDefault(); - event.stopPropagation(); - if (!event.repeat) openNewDesktopWindow(bridge); - }, - }), + registerCommands(commands), registerMenuAction("new-window", () => openNewDesktopWindow(bridge)), ]; return () => { diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index b77939bbb6c3b..3e1875264c3b8 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -195,7 +195,8 @@ 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 +`window.new` (`mod+alt+shift+n`) opens another window in the desktop app, and +`bot.open` (`mod+alt+shift+b`) opens or brings forward the T3_BOT window. See [Multiple windows](./multiple-windows.md). ## Reserved shortcuts diff --git a/docs/user/multiple-windows.md b/docs/user/multiple-windows.md index 993aace5fdb9d..abf6d51d72eff 100644 --- a/docs/user/multiple-windows.md +++ b/docs/user/multiple-windows.md @@ -12,3 +12,10 @@ macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. Change the shortcut under Closing the main window while others are open hides it instead, since the other windows connect through it. On Windows and Linux it closes once the last other window does. + +## T3_BOT window + +Choose **Open T3_BOT** in the command palette or the Window menu, or press **Cmd+Option+Shift+B** on +macOS or **Ctrl+Alt+Shift+B** on Windows and Linux (`bot.open`). There is one T3_BOT window; opening +it again brings it forward. It remembers its position, its size, and whether it stays above other +apps' windows. diff --git a/packages/contracts/src/desktopWindows.ts b/packages/contracts/src/desktopWindows.ts index feb01124f6809..f6bb823083fbc 100644 --- a/packages/contracts/src/desktopWindows.ts +++ b/packages/contracts/src/desktopWindows.ts @@ -12,10 +12,21 @@ export const DesktopWindowsStateSchema = Schema.Struct({ }); export type DesktopWindowsState = typeof DesktopWindowsStateSchema.Type; +export const DesktopBotWindowSizeSchema = Schema.Literals(["narrow", "medium"]); +export type DesktopBotWindowSize = typeof DesktopBotWindowSizeSchema.Type; + +export const DesktopBotWindowStateSchema = Schema.Struct({ + size: DesktopBotWindowSizeSchema, + pinned: Schema.Boolean, +}); +export type DesktopBotWindowState = typeof DesktopBotWindowStateSchema.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, + /** Only in the bot window: its size and pin state when the page loaded. */ + bot: Schema.optional(DesktopBotWindowStateSchema), }); export type DesktopWindowContext = typeof DesktopWindowContextSchema.Type; @@ -30,8 +41,6 @@ export interface DesktopHubLinkMessage { readonly peerWindowId: number; } -export type DesktopBotWindowSize = "narrow" | "medium"; - /** The single T3_BOT window: a floating, optionally always-on-top window showing the `/bot` route. */ export interface DesktopBotWindowBridge { /** Opens the bot window, or focuses it when it is already open. */ diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 4d93f13637f5a..6fb5fc675e7de 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -86,6 +86,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "projectSearch.toggle", "usage.open", "window.new", + "bot.open", "theme.select", "appearance.cycle", "themeEditor.toggle", diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index ae055908aee1e..1216bf85827a9 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -115,6 +115,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { 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+alt+shift+b", command: "bot.open", 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 0d30cce13853c722678962e8c3a84ad4b6659a02 Mon Sep 17 00:00:00 2001 From: Na0s Date: Sat, 21 Nov 2026 16:06:40 -0500 Subject: [PATCH 14/20] feat(web): /bot route for the T3_BOT window Implements the A3 bot stack outside the _chat layout: a header with the active bot card, unread bots stacked behind it, a slide-out card for a bot that needs the user, and a switcher that takes over the top bar. The hamburger shows a sidebar-style thread list (forks nested under their parent, other bots folded with status, archived count, routines, settings, pin and expand); at 720px and up it stays open beside the chat. The chat is an embedded ChatView, and + opens a draft through the existing new-thread flow without leaving the route. New bot creates a managed project and lists it in settings.bots. Shared changes: createNewThreadHandler takes navigate: false, ChatView accepts embedded for drafts, and the root leaves out the main sidebar on /bot. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 4 +- apps/web/src/components/bot/BotChatPane.tsx | 174 +++++++ apps/web/src/components/bot/BotHeader.tsx | 284 ++++++++++ apps/web/src/components/bot/BotIcon.tsx | 79 +++ .../src/components/bot/BotShell.logic.test.ts | 347 ++++++++++++ apps/web/src/components/bot/BotShell.logic.ts | 344 ++++++++++++ apps/web/src/components/bot/BotShell.tsx | 281 ++++++++++ apps/web/src/components/bot/BotThreadList.tsx | 493 ++++++++++++++++++ apps/web/src/components/bot/NewBotDialog.tsx | 186 +++++++ apps/web/src/components/bot/botState.ts | 40 ++ apps/web/src/hooks/useHandleNewThread.ts | 22 +- apps/web/src/routeTree.gen.ts | 21 + apps/web/src/routes/__root.tsx | 4 +- apps/web/src/routes/bot.tsx | 20 + 14 files changed, 2285 insertions(+), 14 deletions(-) create mode 100644 apps/web/src/components/bot/BotChatPane.tsx create mode 100644 apps/web/src/components/bot/BotHeader.tsx create mode 100644 apps/web/src/components/bot/BotIcon.tsx create mode 100644 apps/web/src/components/bot/BotShell.logic.test.ts create mode 100644 apps/web/src/components/bot/BotShell.logic.ts create mode 100644 apps/web/src/components/bot/BotShell.tsx create mode 100644 apps/web/src/components/bot/BotThreadList.tsx create mode 100644 apps/web/src/components/bot/NewBotDialog.tsx create mode 100644 apps/web/src/components/bot/botState.ts create mode 100644 apps/web/src/routes/bot.tsx diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 10cbb215c9e0f..fc1d3a640b3f0 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -436,7 +436,7 @@ type ChatViewProps = onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; forceExpandedMobileComposer?: boolean; - /** A side chat in its parent's right panel; the parent keeps the keyboard and workspace UI. */ + /** Shown inside another view (a side chat, the bot window), which keeps the workspace UI. */ embedded?: SideChatParentPanel; routeKind: "server"; draftId?: never; @@ -447,7 +447,7 @@ type ChatViewProps = onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; forceExpandedMobileComposer?: boolean; - embedded?: never; + embedded?: SideChatParentPanel; routeKind: "draft"; draftId: DraftId; }; diff --git a/apps/web/src/components/bot/BotChatPane.tsx b/apps/web/src/components/bot/BotChatPane.tsx new file mode 100644 index 0000000000000..924d7275cd4a5 --- /dev/null +++ b/apps/web/src/components/bot/BotChatPane.tsx @@ -0,0 +1,174 @@ +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { Navigate, useNavigate } from "@tanstack/react-router"; +import { msg, T, Var } from "gt-react"; +import { useState } from "react"; + +import { useComposerDraftStore, type DraftId } from "../../composerDraftStore"; +import { useDiffPanelStore, type ToolCallDiffTarget } from "../../diffPanelStore"; +import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; +import { useStableCallback } from "../../hooks/useStableCallback"; +import { m } from "../../i18n/messages"; +import type { SideChatParentPanel } from "../../lib/sideChatPane"; +import { useRightPanelStore } from "../../rightPanelStore"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import ChatView from "../ChatView"; +import { Button } from "../ui/button"; +import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty"; +import { toastManager } from "../ui/toast"; +import type { Bot } from "./BotShell.logic"; + +/** + * The selected conversation, as an embedded ChatView: the bot window has no right panel or + * terminal drawer, so those actions open the thread in the full T3 view. + */ +export function BotChatPane(props: { + readonly bot: Bot; + readonly threadId: ThreadId | null; + readonly draftId: DraftId | null; + readonly onNewThread: () => void; +}) { + const { bot, draftId } = props; + const environmentId = bot.project.environmentId; + const navigate = useNavigate(); + const draftSession = useComposerDraftStore((store) => + draftId === null ? null : store.getDraftSession(draftId), + ); + const draftRedirect = useComposerDraftStore((store) => + draftId === null ? null : store.getPromotedDraftRedirect(draftId), + ); + const serverThreadRef = + draftId === null && props.threadId !== null + ? scopeThreadRef(environmentId, props.threadId) + : null; + // Keeps the draft's ChatView instance through its promotion, as ThreadRouteView does. + const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null); + const nextHandoffKey = + draftId !== null && draftSession === null && draftRedirect + ? handoffKey?.key === draftId + ? handoffKey + : { threadKey: scopedThreadKey(draftRedirect), key: draftId } + : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef) + ? handoffKey + : null; + if (nextHandoffKey !== handoffKey) setHandoffKey(nextHandoffKey); + + const openInT3 = (threadRef: ScopedThreadRef) => { + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef) }); + }; + const { copyToClipboard } = useCopyToClipboard({ + target: { + target: "command", + unavailableMessage: msg("Clipboard API is unavailable while copying command."), + failureMessage: msg("Failed to copy command to the clipboard."), + }, + onCopy: (threadRef) => { + toastManager.add({ + type: "success", + title: m(msg("Command copied")), + description: m(msg("The bot window has no terminal. Run it from the thread in T3.")), + actionProps: { children: m(msg("Open in T3")), onClick: () => openInT3(threadRef) }, + }); + }, + }); + const shownThreadRef = + serverThreadRef ?? + (draftSession ? scopeThreadRef(draftSession.environmentId, draftSession.threadId) : null) ?? + draftRedirect; + // Stable, so shell updates that re-render this pane do not re-render ChatView. + const openToolDiff = useStableCallback((target: ToolCallDiffTarget) => { + const threadRef = scopeThreadRef(environmentId, target.threadId); + useDiffPanelStore.getState().selectToolCall(threadRef, target); + useRightPanelStore.getState().open(threadRef, "diff"); + openInT3(threadRef); + }); + const runShellCommand = useStableCallback((command: string) => { + if (shownThreadRef !== null) copyToClipboard(command, shownThreadRef); + }); + // The bot window has no thread around the chat, so the shown thread hosts itself. + const embeddedIn = (hostRef: ScopedThreadRef): SideChatParentPanel => ({ + hostRef, + openToolDiff, + runShellCommand, + }); + + let view: React.ReactNode = null; + let redirect: React.ReactNode = null; + if (draftId !== null) { + if (draftSession) { + view = ( + + ); + } else if (draftRedirect) { + view = ( + + ); + } + // Promoted, the draft's thread takes over its place in the URL; discarded, the bot's default does. + if (!draftSession) { + redirect = ( + + ); + } + } else if (serverThreadRef !== null) { + view = ( + + ); + } else { + view = ( + + + + No conversations yet + + + + Start one to talk with {bot.project.title}. + + + + + + + + ); + } + + return ( + // Embedded chats key their shortcuts and focus checks to this marker. +
+ {view} + {redirect} +
+ ); +} diff --git a/apps/web/src/components/bot/BotHeader.tsx b/apps/web/src/components/bot/BotHeader.tsx new file mode 100644 index 0000000000000..77ee367d67bb4 --- /dev/null +++ b/apps/web/src/components/bot/BotHeader.tsx @@ -0,0 +1,284 @@ +import type { ThreadId } from "@t3tools/contracts"; +import { T, useGT, useMessages } from "gt-react"; +import { MenuIcon, PlusIcon, SearchIcon, XIcon } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; + +import { isElectron } from "../../env"; +import { cn } from "~/lib/utils"; +import { projectIconColorClassName } from "../../projectIconColors"; +import { Button } from "../ui/button"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { BOT_HEALTH_LABEL, BotIcon } from "./BotIcon"; +import { + botColor, + deriveBotStack, + IDLE_BOT_ACTIVITY, + type Bot, + type BotActivity, + type BotStackCard, +} from "./BotShell.logic"; + +// Fading cards behind the active one, nearest first. +const STACK_CARD_CLASS = ["translate-x-2 opacity-70", "translate-x-4 opacity-40"] as const; + +export function BotHeader(props: { + readonly bots: ReadonlyArray; + readonly activeBot: Bot; + readonly activityByKey: ReadonlyMap; + /** Under the active card: the open conversation, or what the body shows. */ + readonly subtitle: string; + /** Hamburger and search; the medium layout moves them into the open thread list. */ + readonly showNav: boolean; + readonly listOpen: boolean; + readonly onToggleList: () => void; + readonly onSearch: () => void; + readonly onNewThread: () => void; + readonly onSelectBot: (bot: Bot, threadId?: ThreadId) => void; + readonly onNewBot: () => void; +}) { + const { activeBot, activityByKey } = props; + const gt = useGT(); + const [switcherOpen, setSwitcherOpen] = useState(false); + const headerRef = useRef(null); + const activity = (bot: Bot) => activityByKey.get(bot.key) ?? IDLE_BOT_ACTIVITY; + const stack = deriveBotStack({ bots: props.bots, activeKey: activeBot.key, activityByKey }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- document listeners close the switcher on Escape or a click outside the header + useEffect(() => { + if (!switcherOpen) return; + const onPointerDown = (event: PointerEvent) => { + if (event.target instanceof Node && headerRef.current?.contains(event.target)) return; + setSwitcherOpen(false); + }; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== "Escape" || event.defaultPrevented) return; + event.preventDefault(); + setSwitcherOpen(false); + }; + document.addEventListener("pointerdown", onPointerDown, true); + document.addEventListener("keydown", onKeyDown); + return () => { + document.removeEventListener("pointerdown", onPointerDown, true); + document.removeEventListener("keydown", onKeyDown); + }; + }, [switcherOpen]); + + const pick = (bot: Bot) => { + setSwitcherOpen(false); + props.onSelectBot(bot); + }; + + return ( +
+ {switcherOpen ? ( + { + setSwitcherOpen(false); + props.onNewBot(); + }} + /> + ) : ( +
+
+ {props.showNav ? ( + <> + + + + ) : null} +
+
+ setSwitcherOpen(true)} + onSelectBot={props.onSelectBot} + /> + + {props.subtitle} + +
+
+ + + + + } + /> + + New conversation + + +
+
+ )} +
+ ); +} + +function BotCardStack(props: { + readonly activeBot: Bot; + readonly activeActivity: BotActivity; + readonly stack: ReadonlyArray; + readonly onOpenSwitcher: () => void; + readonly onSelectBot: (bot: Bot, threadId?: ThreadId) => void; +}) { + const { activeBot } = props; + const gt = useGT(); + const messages = useMessages(); + return ( +
+ {props.stack.toReversed().map((card) => { + const index = props.stack.indexOf(card); + const colorClassName = projectIconColorClassName(botColor(card.bot.project)); + const label = card.attention + ? gt("{name}: {status}", { name: card.bot.project.title, status: card.attention.label }) + : gt("{name} has unread replies", { name: card.bot.project.title }); + return ( + + props.onSelectBot(card.bot, card.attention?.threadId)} + className={cn( + "absolute top-0 left-full z-0 -ml-5 flex h-full items-center rounded-r-full border border-current bg-background pr-3 pl-6 text-2xs font-medium whitespace-nowrap transition-[translate,opacity] duration-200 ease-out starting:-translate-x-6 starting:opacity-0", + colorClassName, + )} + > + {card.attention?.label} + + ) : ( + +
+ ); +} + +function BotSwitcher(props: { + readonly bots: ReadonlyArray; + readonly activeKey: string; + readonly activity: (bot: Bot) => BotActivity; + readonly onPick: (bot: Bot) => void; + readonly onNewBot: () => void; +}) { + const gt = useGT(); + const messages = useMessages(); + return ( +
+ {props.bots.map((bot) => { + const active = bot.key === props.activeKey; + const health = props.activity(bot).health; + return ( + + ); + })} + +
+ ); +} diff --git a/apps/web/src/components/bot/BotIcon.tsx b/apps/web/src/components/bot/BotIcon.tsx new file mode 100644 index 0000000000000..fa87ca533f551 --- /dev/null +++ b/apps/web/src/components/bot/BotIcon.tsx @@ -0,0 +1,79 @@ +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { msg } from "gt-react"; + +import { cn } from "~/lib/utils"; +import { projectIconColorClassName } from "../../projectIconColors"; +import { ProjectFavicon } from "../ProjectFavicon"; +import { botColor, type BotHealth } from "./BotShell.logic"; + +const HEALTH_DOT_CLASS: Record = { + attention: "bg-warning", + failed: "bg-destructive", + unread: "bg-success", + working: "bg-info", + idle: "bg-muted-foreground/50", +}; + +/** `msg()` labels; resolve them with `useMessages()` where they render. */ +export const BOT_HEALTH_LABEL: Record = { + attention: msg("Needs you"), + failed: msg("Failed", { $context: "bot status" }), + unread: msg("Unread", { $context: "bot status" }), + working: msg("Working", { $context: "bot status" }), + idle: msg("Idle", { $context: "bot status" }), +}; + +const SIZE_CLASS = { + sm: { box: "size-5 text-3xs", art: "size-3", dot: "size-1.5" }, + md: { box: "size-7 text-xs", art: "size-4", dot: "size-2" }, + lg: { box: "size-10 text-base", art: "size-6", dot: "size-2.5" }, +} as const; + +/** + * A bot's icon in a square box. A monogram, or no icon, draws as the circle inscribed in that + * square; a chosen icon or favicon fills the square itself. + */ +export function BotIcon(props: { + readonly project: Pick< + EnvironmentProject, + "environmentId" | "workspaceRoot" | "title" | "faviconPath" | "projectIcon" + >; + readonly size?: keyof typeof SIZE_CLASS; + readonly health?: BotHealth | null; + readonly className?: string; +}) { + const { project } = props; + const size = SIZE_CLASS[props.size ?? "md"]; + const colorClassName = projectIconColorClassName(botColor(project)); + const icon = project.projectIcon; + const circle = icon == null || icon.kind === "monogram"; + const letters = + icon?.kind === "monogram" + ? Array.from(icon.text).slice(0, 2).join("") + : (Array.from(project.title.trim())[0] ?? "?"); + return ( +