diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index e11e946dd41ba..43952cd6f772d 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), @@ -87,10 +89,10 @@ function layerElectronWindow(destroyAll: Effect.Effect = Effect.void) { function layerDesktopWindow( input: { readonly activate?: Effect.Effect; - readonly flushMainWindowBounds?: Effect.Effect; + readonly flushWindowState?: 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"), @@ -99,11 +101,10 @@ function layerDesktopWindow( showConnectingSplash: Effect.void, handleBackendReady: () => Effect.void, handleBackendNotReady: Effect.void, - flushMainWindowBounds: input.flushMainWindowBounds ?? Effect.void, + flushWindowState: input.flushWindowState ?? Effect.void, prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.void, dispatchSnapShotEvent: () => Effect.void, - zoomMain: () => Effect.void, runMainContentsCommand: () => Effect.void, syncAppearance: Effect.void, }); @@ -180,7 +181,7 @@ describe("DesktopLifecycle", () => { const destroyAll = Effect.sync(() => { events.push("destroy"); }); - const flushMainWindowBounds = Effect.sync(() => { + const flushWindowState = Effect.sync(() => { events.push("flush"); }); @@ -203,7 +204,7 @@ describe("DesktopLifecycle", () => { Layer.provideMerge(layerElectronApp(appListeners, quit)), Layer.provideMerge(layerElectronTheme), Layer.provideMerge(layerElectronWindow(destroyAll)), - Layer.provideMerge(layerDesktopWindow({ flushMainWindowBounds })), + Layer.provideMerge(layerDesktopWindow({ flushWindowState })), Layer.provideMerge(layerEnvironment), Layer.provideMerge(layerDesktopShutdown), Layer.provideMerge(DesktopState.layer), diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts index 9568e72dde310..7567505bf389d 100644 --- a/apps/desktop/src/app/DesktopLifecycle.ts +++ b/apps/desktop/src/app/DesktopLifecycle.ts @@ -97,7 +97,7 @@ const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdo ): Effect.fn.Return { const shutdown = yield* DesktopShutdown.DesktopShutdown; const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.flushMainWindowBounds; + yield* desktopWindow.flushWindowState; yield* afterBoundsFlush; yield* shutdown.request; yield* shutdown.awaitComplete; diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 005a1cde1224a..1656299e8dd52 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"), @@ -212,15 +212,14 @@ function layerPool( showConnectingSplash: Effect.void, handleBackendReady: () => options.onReady ?? Effect.void, handleBackendNotReady: Effect.void, - flushMainWindowBounds: Effect.void, + flushWindowState: Effect.void, prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.die("unexpected menu action"), dispatchSnapShotEvent: () => Effect.void, - 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..e5ba2df4f420b 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "Verkleinern", "50fe114d093a5bc7": "Vollbildmodus ein/aus", "d8c6d6d9845353da": "Fenster", + "c015841b7b2523c6": "Neues Fenster", + "d5203c78d46e1282": "Hauptfenster", + "f8e9094362fa962a": "Mini-Modus", "f184aa190588625e": "Minimieren", "c20a9deaed71bd1c": "Zoomen", "d207ba3a23f94223": "Alle nach vorne bringen", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "Link kopieren", "8af79268f2349f4c": "E-Mail-Adresse kopieren", "a9f9254d458e49fe": "Bild kopieren", + "0ec1ce287d61c59a": "Fenster {number}", "9c1b20fbc881de5d": "Desktop-Konfiguration", "1b14230874f19eb9": "Bilder" } diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 9a07ef060cbc9..003abd97c04d3 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "Zoom Out", "50fe114d093a5bc7": "Toggle Full Screen", "d8c6d6d9845353da": "Window", + "c015841b7b2523c6": "New Window", + "d5203c78d46e1282": "Main Window", + "f8e9094362fa962a": "Mini Mode", "f184aa190588625e": "Minimize", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Bring All to Front", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "Copy Link", "8af79268f2349f4c": "Copy Email Address", "a9f9254d458e49fe": "Copy Image", + "0ec1ce287d61c59a": "Window {number}", "9c1b20fbc881de5d": "Desktop config", "1b14230874f19eb9": "Images" } diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index f891e9eaf850b..c379187e60c87 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "Alejar", "50fe114d093a5bc7": "Activar/desactivar pantalla completa", "d8c6d6d9845353da": "Ventana", + "c015841b7b2523c6": "Nueva ventana", + "d5203c78d46e1282": "Ventana principal", + "f8e9094362fa962a": "Modo mini", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Traer todo al frente", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "Copiar enlace", "8af79268f2349f4c": "Copiar dirección de correo", "a9f9254d458e49fe": "Copiar imagen", + "0ec1ce287d61c59a": "Ventana {number}", "9c1b20fbc881de5d": "Configuración de escritorio", "1b14230874f19eb9": "Imágenes" } diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 0bb5a47518581..dbc94b18801f4 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "Zoom arrière", "50fe114d093a5bc7": "Activer/désactiver le plein écran", "d8c6d6d9845353da": "Fenêtre", + "c015841b7b2523c6": "Nouvelle fenêtre", + "d5203c78d46e1282": "Fenêtre principale", + "f8e9094362fa962a": "Mode mini", "f184aa190588625e": "Réduire", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Tout ramener au premier plan", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "Copier le lien", "8af79268f2349f4c": "Copier l’adresse e-mail", "a9f9254d458e49fe": "Copier l’image", + "0ec1ce287d61c59a": "Fenêtre {number}", "9c1b20fbc881de5d": "Configuration du bureau", "1b14230874f19eb9": "Images" } diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index df89efe466261..75b8922c407c3 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "縮小", "50fe114d093a5bc7": "フルスクリーンに切り替え", "d8c6d6d9845353da": "ウインドウ", + "c015841b7b2523c6": "新規ウインドウ", + "d5203c78d46e1282": "メインウインドウ", + "f8e9094362fa962a": "ミニモード", "f184aa190588625e": "しまう", "c20a9deaed71bd1c": "拡大/縮小", "d207ba3a23f94223": "すべてを手前に移動", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "リンクをコピー", "8af79268f2349f4c": "メールアドレスをコピー", "a9f9254d458e49fe": "画像をコピー", + "0ec1ce287d61c59a": "ウインドウ {number}", "9c1b20fbc881de5d": "デスクトップの構成", "1b14230874f19eb9": "画像" } diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index 566724b9b91c1..d8c0629d18668 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "축소", "50fe114d093a5bc7": "전체 화면 전환", "d8c6d6d9845353da": "윈도우", + "c015841b7b2523c6": "새 윈도우", + "d5203c78d46e1282": "메인 윈도우", + "f8e9094362fa962a": "미니 모드", "f184aa190588625e": "최소화", "c20a9deaed71bd1c": "확대/축소", "d207ba3a23f94223": "모두 앞으로 가져오기", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "링크 복사", "8af79268f2349f4c": "이메일 주소 복사", "a9f9254d458e49fe": "이미지 복사", + "0ec1ce287d61c59a": "윈도우 {number}", "9c1b20fbc881de5d": "데스크톱 구성", "1b14230874f19eb9": "이미지" } diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 67f4eefd1c9ec..7e15d42fd9231 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "Diminuir zoom", "50fe114d093a5bc7": "Alternar tela cheia", "d8c6d6d9845353da": "Janela", + "c015841b7b2523c6": "Nova janela", + "d5203c78d46e1282": "Janela principal", + "f8e9094362fa962a": "Modo mini", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Trazer tudo para a frente", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "Copiar link", "8af79268f2349f4c": "Copiar endereço de e-mail", "a9f9254d458e49fe": "Copiar imagem", + "0ec1ce287d61c59a": "Janela {number}", "9c1b20fbc881de5d": "Configuração do desktop", "1b14230874f19eb9": "Imagens" } diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index 46364dfabe488..d7ee16c6c6216 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "Уменьшить", "50fe114d093a5bc7": "Полноэкранный режим", "d8c6d6d9845353da": "Окно", + "c015841b7b2523c6": "Новое окно", + "d5203c78d46e1282": "Главное окно", + "f8e9094362fa962a": "Мини-режим", "f184aa190588625e": "Свернуть", "c20a9deaed71bd1c": "Масштаб", "d207ba3a23f94223": "Все окна на передний план", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "Копировать ссылку", "8af79268f2349f4c": "Копировать адрес электронной почты", "a9f9254d458e49fe": "Копировать изображение", + "0ec1ce287d61c59a": "Окно {number}", "9c1b20fbc881de5d": "Конфигурация десктопа", "1b14230874f19eb9": "Изображения" } diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index 67bcaf6a380aa..089ce99563dcd 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "Zooma ut", "50fe114d093a5bc7": "Växla helskärm", "d8c6d6d9845353da": "Fönster", + "c015841b7b2523c6": "Nytt fönster", + "d5203c78d46e1282": "Huvudfönster", + "f8e9094362fa962a": "Miniläge", "f184aa190588625e": "Minimera", "c20a9deaed71bd1c": "Zooma", "d207ba3a23f94223": "Lägg alla överst", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "Kopiera länk", "8af79268f2349f4c": "Kopiera e-postadress", "a9f9254d458e49fe": "Kopiera bild", + "0ec1ce287d61c59a": "Fönster {number}", "9c1b20fbc881de5d": "Skrivbordskonfiguration", "1b14230874f19eb9": "Bilder" } diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index 72122de01df62..66c42efdc40ef 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -114,6 +114,9 @@ "df6ed2014f1737a8": "缩小", "50fe114d093a5bc7": "切换全屏", "d8c6d6d9845353da": "窗口", + "c015841b7b2523c6": "新建窗口", + "d5203c78d46e1282": "主窗口", + "f8e9094362fa962a": "迷你模式", "f184aa190588625e": "最小化", "c20a9deaed71bd1c": "缩放", "d207ba3a23f94223": "前置全部窗口", @@ -122,6 +125,7 @@ "202e13f15a3dcd30": "复制链接", "8af79268f2349f4c": "复制邮箱地址", "a9f9254d458e49fe": "复制图片", + "0ec1ce287d61c59a": "窗口 {number}", "9c1b20fbc881de5d": "桌面配置", "1b14230874f19eb9": "图片" } 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..48153f62400a1 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -154,3 +154,27 @@ 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_OPEN_PROFILE_CHANNEL = "desktop:windows-open-profile"; +export const WINDOWS_FOCUS_CHANNEL = "desktop:windows-focus"; +export const WINDOWS_CREATE_PROFILE_CHANNEL = "desktop:windows-create-profile"; +export const WINDOWS_SAVE_AS_PROFILE_CHANNEL = "desktop:windows-save-as-profile"; +export const WINDOWS_UPDATE_PROFILE_CHANNEL = "desktop:windows-update-profile"; +export const WINDOWS_DELETE_PROFILE_CHANNEL = "desktop:windows-delete-profile"; +export const WINDOWS_SET_PROJECT_SCOPE_KEYS_CHANNEL = "desktop:windows-set-project-scope-keys"; +export const WINDOWS_CLOSE_REQUEST_CHANNEL = "desktop:windows-close-request"; +export const WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL = "desktop:windows-close-request-listening"; +export const WINDOWS_RESOLVE_CLOSE_REQUEST_CHANNEL = "desktop:windows-resolve-close-request"; +export const WINDOWS_SET_MINI_MODE_CHANNEL = "desktop:windows-set-mini-mode"; +export const WINDOWS_SET_MULTI_WINDOW_ENABLED_CHANNEL = "desktop:windows-set-multi-window-enabled"; +export const WINDOWS_REGISTER_HUB_CHANNEL = "desktop:windows-register-hub"; +export const WINDOWS_REQUEST_HUB_LINK_CHANNEL = "desktop:windows-request-hub-link"; +export const WINDOWS_HUB_LINK_CHANNEL = "desktop:windows-hub-link"; +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..f937246705f84 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,26 +51,46 @@ 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. + */ +const senderTabId = (tabId: string) => + Effect.map(DesktopIpc.DesktopIpcSender, ({ window, isMain }) => + isMain ? tabId : `w${window.id}:${tabId}`, + ); + +/** 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); + }); + const forward = + (channel: string) => + (event: E) => + sendToOwner(event.tabId, (contents, tabId) => contents.send(channel, { ...event, tabId })); yield* manager.subscribeStateChanges((tabId, state) => - electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state), - ); - yield* manager.subscribeRecordingInputs((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_INPUT_CHANNEL, event), - ); - yield* manager.subscribePointerEvents((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event), - ); - yield* manager.subscribeOpenLinks((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_OPEN_LINK_CHANNEL, event), - ); - yield* manager.subscribeFindResults((event) => - electronWindow.sendAll(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, event), + sendToOwner(tabId, (contents, rendererTabId) => + contents.send(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, rendererTabId, { + ...state, + 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), @@ -85,7 +107,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 +118,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 +133,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 +143,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 +153,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 +168,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 +186,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 +241,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 +250,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 +259,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 +268,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 +277,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 +304,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 +501,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 +511,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 +524,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 +534,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) => ({ ...artifact, tabId })), + Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot"))), + ); }), }); @@ -539,7 +567,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 { ...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..eee63f59e392a 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -46,6 +46,7 @@ import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as Electron from "electron"; import { msg } from "gt-i18n"; import * as MacPermissions from "../../permissions/MacPermissions.ts"; +import * as DesktopWindow from "../../window/DesktopWindow.ts"; import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts"; import { m } from "../../i18n/messages.ts"; import * as IpcChannels from "../channels.ts"; @@ -142,9 +143,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 +237,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 +268,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 +306,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: [ @@ -331,6 +331,13 @@ export const setTheme = DesktopIpc.makeIpcMethod({ payload: DesktopThemeSchema, result: Schema.Void, handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) { + const sender = yield* DesktopIpc.DesktopIpcSender; + // A secondary window can use another profile's theme, so it only restyles its own frame. + if (!sender.isMain) { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.setWindowAppearance(sender.window, theme); + return; + } const electronTheme = yield* ElectronTheme.ElectronTheme; yield* electronTheme.setSource(theme); }), @@ -342,14 +349,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 +387,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 +464,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 +484,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 +509,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 +542,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 +550,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..af237b56c85f3 --- /dev/null +++ b/apps/desktop/src/ipc/methods/windows.ts @@ -0,0 +1,191 @@ +import { + DesktopCreateWindowProfileInputSchema, + DesktopOpenWindowInputSchema, + DesktopResolveWindowCloseInputSchema, + DesktopUpdateWindowProfileInputSchema, + DesktopWindowContextSchema, + DesktopWindowProfileIdSchema, + DesktopWindowProfileNameSchema, + DesktopWindowProfileSchema, + DesktopWindowProjectScopeKeysSchema, + DesktopWindowsStateSchema, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +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.UndefinedOr(DesktopOpenWindowInputSchema), + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openNew")(function* (input) { + yield* (yield* DesktopWindow.DesktopWindow).openNewWindow(input ?? {}); + }), +}); + +const openProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_OPEN_PROFILE_CHANNEL, + payload: DesktopWindowProfileIdSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openProfile")(function* (profileId) { + yield* (yield* DesktopWindow.DesktopWindow).openProfile(profileId); + }), +}); + +const focus = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_FOCUS_CHANNEL, + payload: Schema.Int, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.focus")(function* (windowId) { + yield* (yield* DesktopWindow.DesktopWindow).focusWindow(windowId); + }), +}); + +const createProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_CREATE_PROFILE_CHANNEL, + payload: DesktopCreateWindowProfileInputSchema, + result: DesktopWindowProfileSchema, + handler: Effect.fn("desktop.ipc.windows.createProfile")(function* (input) { + return yield* (yield* DesktopWindow.DesktopWindow).createProfile(input); + }), +}); + +const saveAsProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SAVE_AS_PROFILE_CHANNEL, + payload: DesktopWindowProfileNameSchema, + result: DesktopWindowProfileSchema, + handler: Effect.fn("desktop.ipc.windows.saveAsProfile")(function* (name) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + return yield* (yield* DesktopWindow.DesktopWindow).saveWindowAsProfile(window, name); + }), +}); + +const updateProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_UPDATE_PROFILE_CHANNEL, + payload: DesktopUpdateWindowProfileInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.updateProfile")(function* (input) { + yield* (yield* DesktopWindow.DesktopWindow).updateProfile(input); + }), +}); + +const deleteProfile = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_DELETE_PROFILE_CHANNEL, + payload: DesktopWindowProfileIdSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.deleteProfile")(function* (profileId) { + yield* (yield* DesktopWindow.DesktopWindow).deleteProfile(profileId); + }), +}); + +const setProjectScopeKeys = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SET_PROJECT_SCOPE_KEYS_CHANNEL, + payload: DesktopWindowProjectScopeKeysSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setProjectScopeKeys")(function* (projectScopeKeys) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setWindowProjectScopeKeys(window, projectScopeKeys); + }), +}); + +const setCloseRequestListening = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setCloseRequestListening")(function* (listening) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setCloseRequestListening(window, listening); + }), +}); + +const resolveCloseRequest = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_RESOLVE_CLOSE_REQUEST_CHANNEL, + payload: DesktopResolveWindowCloseInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.resolveCloseRequest")(function* ({ + requestId, + decision, + }) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).resolveCloseRequest(window, requestId, decision); + }), +}); + +const setMiniMode = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SET_MINI_MODE_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setMiniMode")(function* (enabled) { + yield* (yield* DesktopWindow.DesktopWindow).setMiniMode(enabled); + }), +}); + +const setMultiWindowEnabled = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_SET_MULTI_WINDOW_ENABLED_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setMultiWindowEnabled")(function* (enabled) { + yield* (yield* DesktopWindow.DesktopWindow).setMultiWindowEnabled(enabled); + }), +}); + +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, + openProfile, + focus, + createProfile, + saveAsProfile, + updateProfile, + deleteProfile, + setProjectScopeKeys, + setCloseRequestListening, + resolveCloseRequest, + setMiniMode, + setMultiWindowEnabled, + registerHub, + requestHubLink, +] as const; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ac52fbc73d868..67929652c8b49 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,10 @@ import type { DesktopPreviewRecordingInputEvent, DesktopPreviewTabState, DesktopSnapShotEvent, + DesktopWindowCloseRequest, + DesktopWindowContext, + DesktopWindowsBridge, + DesktopWindowsState, } from "@t3tools/contracts"; import { exposeClerkBridge } from "@clerk/electron/preload"; import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron"; @@ -87,6 +93,102 @@ 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, profileId: null, projectScopeKeys: [], theme: null }; +})(); + +// 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); + }; + }; + +let closeRequestListeners = 0; +const windows: DesktopWindowsBridge = { + getContext: () => windowContext, + getState: () => ipcRenderer.invoke(IpcChannels.WINDOWS_GET_STATE_CHANNEL), + onState: subscribe(IpcChannels.WINDOWS_STATE_CHANNEL, (state) => + typeof state === "object" && state !== null ? (state as DesktopWindowsState) : undefined, + ), + openNew: (input) => ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_NEW_CHANNEL, input), + openProfile: (profileId) => + ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_PROFILE_CHANNEL, profileId), + focus: (windowId) => ipcRenderer.invoke(IpcChannels.WINDOWS_FOCUS_CHANNEL, windowId), + createProfile: (input) => ipcRenderer.invoke(IpcChannels.WINDOWS_CREATE_PROFILE_CHANNEL, input), + saveAsProfile: (name) => ipcRenderer.invoke(IpcChannels.WINDOWS_SAVE_AS_PROFILE_CHANNEL, name), + updateProfile: (input) => ipcRenderer.invoke(IpcChannels.WINDOWS_UPDATE_PROFILE_CHANNEL, input), + deleteProfile: (profileId) => + ipcRenderer.invoke(IpcChannels.WINDOWS_DELETE_PROFILE_CHANNEL, profileId), + setProjectScopeKeys: (projectScopeKeys) => + ipcRenderer.invoke(IpcChannels.WINDOWS_SET_PROJECT_SCOPE_KEYS_CHANNEL, projectScopeKeys), + // The main process closes without asking while no listener could answer. + onCloseRequest: (listener) => { + const unsubscribe = subscribe(IpcChannels.WINDOWS_CLOSE_REQUEST_CHANNEL, (request) => + typeof request === "object" && request !== null + ? (request as DesktopWindowCloseRequest) + : undefined, + )(listener); + closeRequestListeners += 1; + if (closeRequestListeners === 1) { + void ipcRenderer.invoke(IpcChannels.WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL, true); + } + let subscribed = true; + return () => { + if (!subscribed) return; + subscribed = false; + unsubscribe(); + closeRequestListeners -= 1; + if (closeRequestListeners === 0) { + void ipcRenderer.invoke(IpcChannels.WINDOWS_CLOSE_REQUEST_LISTENING_CHANNEL, false); + } + }; + }, + resolveCloseRequest: (requestId, decision) => + ipcRenderer.invoke(IpcChannels.WINDOWS_RESOLVE_CLOSE_REQUEST_CHANNEL, { requestId, decision }), + setMiniMode: (enabled) => ipcRenderer.invoke(IpcChannels.WINDOWS_SET_MINI_MODE_CHANNEL, enabled), + setMultiWindowEnabled: (enabled) => + ipcRenderer.invoke(IpcChannels.WINDOWS_SET_MULTI_WINDOW_ENABLED_CHANNEL, enabled), + registerHub: () => { + void ipcRenderer.invoke(IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL).catch(() => undefined); + }, + 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 +266,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 +674,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/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 04406f63c6b3d..692d367b3702c 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -27,6 +27,8 @@ const DesktopSettingsPatch = Schema.Struct({ ), ), mainWindowMaximized: Schema.optionalKey(Schema.Boolean), + windowProfiles: Schema.optionalKey(Schema.Array(Schema.Unknown)), + multiWindowEnabled: Schema.optionalKey(Schema.Boolean), serverExposureMode: Schema.optionalKey(Schema.Literals(["local-only", "network-accessible"])), tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean), tailscaleServePort: Schema.optionalKey(Schema.Number), @@ -110,14 +112,19 @@ describe("DesktopSettings", () => { yield* withSettings( Effect.gen(function* () { const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, true); + yield* settings.setWindowProfilePlacement( + "main", + { x: 10, y: 20, width: 900, height: 600 }, + true, + ); }), ).pipe(Effect.provideService(Tracer.Tracer, tracer)); const operationSpans = spans.filter( - (span) => span.name === "desktop.settings.setMainWindowBounds", + (span) => span.name === "desktop.settings.setWindowProfilePlacement", ); assert.lengthOf(operationSpans, 1); assert.deepEqual(Object.fromEntries(operationSpans[0]!.attributes), { + profileId: "main", x: 10, y: 20, width: 900, @@ -193,7 +200,11 @@ describe("DesktopSettings", () => { yield* Effect.exit(settings.load); yield* Effect.exit( - settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, false), + settings.setWindowProfilePlacement( + "main", + { x: 10, y: 20, width: 900, height: 600 }, + false, + ), ); const persisted = yield* decodeDesktopSettingsPatch( @@ -225,8 +236,13 @@ describe("DesktopSettings", () => { assert.deepEqual(yield* settings.load, { linuxPasswordStore: "auto", localEnvironmentEnabled: true, - mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 }, - mainWindowMaximized: false, + multiWindowEnabled: true, + windowProfiles: [ + { + ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, + bounds: { x: 120, y: 80, width: 1280, height: 900 }, + }, + ], serverExposureMode: "network-accessible", tailscaleServeEnabled: true, tailscaleServePort: 8443, @@ -253,7 +269,11 @@ describe("DesktopSettings", () => { ); assert.isFalse((yield* settings.load).localEnvironmentEnabled); - yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 800, height: 600 }, false); + yield* settings.setWindowProfilePlacement( + "main", + { x: 10, y: 20, width: 800, height: 600 }, + false, + ); assert.include( yield* fileSystem.readFileString(environment.desktopSettingsPath), `"localEnvironmentEnabled":false`, @@ -277,10 +297,10 @@ describe("DesktopSettings", () => { serverExposureMode: "network-accessible", }); - const loaded = yield* settings.load; - assert.isNull(loaded.mainWindowBounds); - assert.isFalse(loaded.mainWindowMaximized); - assert.equal(loaded.serverExposureMode, "network-accessible"); + const loaded = DesktopAppSettings.defaultWindowProfile(yield* settings.load); + assert.isNull(loaded.bounds); + assert.isFalse(loaded.maximized); + assert.equal((yield* settings.get).serverExposureMode, "network-accessible"); } }), ), @@ -293,8 +313,13 @@ describe("DesktopSettings", () => { const fileSystem = yield* FileSystem.FileSystem; const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 400, height: 360 }, true); + yield* settings.setWindowProfilePlacement( + "main", + { x: -1200, y: 40, width: 400, height: 360 }, + true, + ); yield* settings.setServerExposureMode("network-accessible"); + yield* settings.setMultiWindowEnabled(false); const persisted = yield* decodeDesktopSettingsPatch( yield* fileSystem.readFileString(environment.desktopSettingsPath), @@ -302,6 +327,7 @@ describe("DesktopSettings", () => { assert.deepEqual(persisted, { mainWindowBounds: { x: -1200, y: 40, width: 400, height: 360 }, mainWindowMaximized: true, + multiWindowEnabled: false, serverExposureMode: "network-accessible", } satisfies typeof DesktopSettingsPatch.Type); @@ -309,8 +335,17 @@ describe("DesktopSettings", () => { const freshSettings = yield* DesktopAppSettings.DesktopAppSettings; return yield* freshSettings.load; }).pipe(Effect.provide(DesktopAppSettings.layer)); - assert.deepEqual(restored.mainWindowBounds, persisted.mainWindowBounds); - assert.isTrue(restored.mainWindowMaximized); + const restoredMain = DesktopAppSettings.defaultWindowProfile(restored); + assert.deepEqual(restoredMain.bounds, persisted.mainWindowBounds); + assert.isTrue(restoredMain.maximized); + assert.isFalse(restored.multiWindowEnabled); + + // The default leaves the key out, so an older build's file stays as it was. + yield* settings.setMultiWindowEnabled(true); + const reenabled = yield* decodeDesktopSettingsPatch( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + ); + assert.isUndefined(reenabled.multiWindowEnabled); }), ), ); @@ -378,8 +413,8 @@ describe("DesktopSettings", () => { assert.deepEqual(yield* settings.load, { linuxPasswordStore: "auto", localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, + multiWindowEnabled: true, + windowProfiles: [DesktopAppSettings.DEFAULT_WINDOW_PROFILE], serverExposureMode: "local-only", tailscaleServeEnabled: false, tailscaleServePort: 443, @@ -407,8 +442,8 @@ describe("DesktopSettings", () => { assert.deepEqual(yield* settings.load, { linuxPasswordStore: "auto", localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, + multiWindowEnabled: true, + windowProfiles: [DesktopAppSettings.DEFAULT_WINDOW_PROFILE], serverExposureMode: "local-only", tailscaleServeEnabled: false, tailscaleServePort: 443, @@ -483,6 +518,102 @@ describe("DesktopSettings", () => { ), ); + it.effect("moves the legacy main window placement into the default profile and mirrors it", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const settings = yield* DesktopAppSettings.DesktopAppSettings; + const legacyBounds = { x: 40, y: 30, width: 1200, height: 800 }; + yield* writeSettingsPatch({ mainWindowBounds: legacyBounds, mainWindowMaximized: true }); + + assert.deepEqual((yield* settings.load).windowProfiles, [ + { ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, bounds: legacyBounds, maximized: true }, + ]); + + const work = { + id: "work", + name: "Work", + projectScopeKeys: ["env:/repo"], + theme: "dracula", + bounds: { x: 60, y: 50, width: 900, height: 700 }, + maximized: false, + openAtQuit: true, + }; + yield* settings.updateWindowProfiles(([main, ...rest]) => [ + { ...main!, name: "Primary" }, + ...rest, + work, + ]); + yield* settings.setWindowProfilePlacement("main", { ...legacyBounds, x: 80 }, false); + + const persisted = yield* decodeDesktopSettingsPatch( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + ); + // An older build reads only the legacy keys, so they keep the main window's placement. + assert.deepEqual(persisted.mainWindowBounds, { ...legacyBounds, x: 80 }); + assert.isUndefined(persisted.mainWindowMaximized); + assert.deepEqual(persisted.windowProfiles, [{ id: "main", name: "Primary" }, work]); + assert.deepEqual((yield* settings.load).windowProfiles, [ + { + ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, + name: "Primary", + bounds: { ...legacyBounds, x: 80 }, + }, + work, + ]); + }), + ), + ); + + it.effect("keeps only valid, unique window profiles with the default one first", () => + withSettings( + Effect.gen(function* () { + const settings = yield* DesktopAppSettings.DesktopAppSettings; + yield* writeSettingsPatch({ + serverExposureMode: "network-accessible", + windowProfiles: [ + "not a profile", + { name: "No id" }, + { + id: "side", + name: "Side", + projectScopeKeys: ["a", "", "a", 7, "b"], + theme: "", + bounds: { x: 0, y: 0, width: 10, height: 10 }, + maximized: true, + openAtQuit: "yes", + }, + { id: "side", name: "Duplicate" }, + { id: "long", name: "x".repeat(81) }, + { id: "main", name: "Desk", theme: "dark", projectScopeKeys: ["a"], openAtQuit: true }, + ], + }); + + const loaded = yield* settings.load; + assert.equal(loaded.serverExposureMode, "network-accessible"); + assert.deepEqual(loaded.windowProfiles, [ + { ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, name: "Desk" }, + { + id: "side", + name: "Side", + projectScopeKeys: ["a", "b"], + theme: null, + bounds: null, + maximized: false, + openAtQuit: false, + }, + ]); + + // Profile edits normalize the same way, so the default profile cannot be removed. + yield* settings.updateWindowProfiles(() => []); + assert.deepEqual((yield* settings.get).windowProfiles, [ + { ...DesktopAppSettings.DEFAULT_WINDOW_PROFILE, name: "Desk" }, + ]); + }), + ), + ); + it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () => withSettings( Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index e81da70660648..8807ec5981cfd 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -1,6 +1,11 @@ import { + DEFAULT_DESKTOP_WINDOW_PROFILE_ID, DesktopServerExposureModeSchema, DesktopUpdateChannelSchema, + DesktopWindowProfileIdSchema, + DesktopWindowProfileNameSchema, + DesktopWindowProfileThemeSchema, + DesktopWindowProjectScopeKeysSchema, type DesktopServerExposureMode, type DesktopUpdateChannel, } from "@t3tools/contracts"; @@ -30,8 +35,9 @@ import { isValidDistroName } from "../wsl/wslPathParsing.ts"; export interface DesktopSettings { readonly localEnvironmentEnabled: boolean; readonly linuxPasswordStore: LinuxPasswordStorePreference; - readonly mainWindowBounds: DesktopWindowBounds | null; - readonly mainWindowMaximized: boolean; + /** The default (main window) profile is always first. */ + readonly windowProfiles: ReadonlyArray; + readonly multiWindowEnabled: boolean; readonly serverExposureMode: DesktopServerExposureMode; readonly tailscaleServeEnabled: boolean; readonly tailscaleServePort: number; @@ -43,6 +49,17 @@ export interface DesktopSettings { readonly wslOnly: boolean; } +export interface DesktopWindowProfileSettings { + readonly id: string; + readonly name: string; + readonly projectScopeKeys: ReadonlyArray; + readonly theme: string | null; + readonly bounds: DesktopWindowBounds | null; + readonly maximized: boolean; + /** Reopen this profile's window on the next launch; set for windows open when the app quit. */ + readonly openAtQuit: boolean; +} + export interface DesktopSettingsChange { readonly settings: DesktopSettings; readonly changed: boolean; @@ -68,11 +85,23 @@ export const DEFAULT_MAIN_WINDOW_SIZE = { height: 780, } as const; +const DEFAULT_WINDOW_PROFILE_NAME = "Main"; + +export const DEFAULT_WINDOW_PROFILE: DesktopWindowProfileSettings = { + id: DEFAULT_DESKTOP_WINDOW_PROFILE_ID, + name: DEFAULT_WINDOW_PROFILE_NAME, + projectScopeKeys: [], + theme: null, + bounds: null, + maximized: false, + openAtQuit: false, +}; + export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { localEnvironmentEnabled: true, linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE, - mainWindowBounds: null, - mainWindowMaximized: false, + windowProfiles: [DEFAULT_WINDOW_PROFILE], + multiWindowEnabled: true, serverExposureMode: "local-only", tailscaleServeEnabled: false, tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT, @@ -95,11 +124,25 @@ const DesktopWindowBoundsDocument = Schema.Struct({ const optionalReadableKey = (schema: S) => Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone))); +const DesktopWindowProfileDocument = Schema.Struct({ + id: optionalReadableKey(Schema.String), + name: optionalReadableKey(Schema.String), + projectScopeKeys: optionalReadableKey(Schema.Array(Schema.Unknown)), + theme: optionalReadableKey(Schema.NullOr(Schema.String)), + bounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), + maximized: optionalReadableKey(Schema.Boolean), + openAtQuit: optionalReadableKey(Schema.Boolean), +}); +type DesktopWindowProfileDocument = typeof DesktopWindowProfileDocument.Type; + const DesktopSettingsDocument = Schema.Struct({ localEnvironmentEnabled: optionalReadableKey(Schema.Boolean), linuxPasswordStore: optionalReadableKey(Schema.Unknown), + // Mirrors the default profile's placement so an older build keeps the main window where it was. mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), mainWindowMaximized: optionalReadableKey(Schema.Boolean), + windowProfiles: optionalReadableKey(Schema.Array(Schema.Unknown)), + multiWindowEnabled: optionalReadableKey(Schema.Boolean), serverExposureMode: optionalReadableKey(DesktopServerExposureModeSchema), tailscaleServeEnabled: optionalReadableKey(Schema.Boolean), tailscaleServePort: optionalReadableKey(Schema.Number), @@ -119,6 +162,13 @@ const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson); const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson); const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema); const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema); +const decodeWindowProfileDocument = Schema.decodeUnknownOption(DesktopWindowProfileDocument); +const isWindowProfileId = Schema.is(DesktopWindowProfileIdSchema); +const isWindowProfileName = Schema.is(DesktopWindowProfileNameSchema); +const isWindowProfileTheme = Schema.is(DesktopWindowProfileThemeSchema); +const isProjectScopeKeys = Schema.is(DesktopWindowProjectScopeKeysSchema); +const isProjectScopeKey = (key: unknown): key is string => isProjectScopeKeys([key]); +const MAX_PROJECT_SCOPE_KEYS = 1000; const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({ settings, @@ -156,10 +206,20 @@ export class DesktopAppSettings extends Context.Service< readonly setLocalEnvironmentEnabled: ( enabled: boolean, ) => Effect.Effect; - readonly setMainWindowBounds: ( + readonly setMultiWindowEnabled: ( + enabled: boolean, + ) => Effect.Effect; + readonly setWindowProfilePlacement: ( + profileId: string, bounds: DesktopWindowBounds, isMaximized: boolean, ) => Effect.Effect; + /** The result is normalized: invalid and duplicate profiles drop, the default one stays. */ + readonly updateWindowProfiles: ( + update: ( + profiles: ReadonlyArray, + ) => ReadonlyArray, + ) => Effect.Effect; readonly setServerExposureMode: ( mode: DesktopServerExposureMode, ) => Effect.Effect; @@ -208,12 +268,83 @@ export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | return Option.getOrNull(decodeDesktopWindowBounds(value)); } +export function normalizeProjectScopeKeys(value: ReadonlyArray): ReadonlyArray { + const keys = new Set(); + for (const key of value) { + if (keys.size >= MAX_PROJECT_SCOPE_KEYS) break; + if (isProjectScopeKey(key)) keys.add(key); + } + return [...keys]; +} + +function normalizeWindowProfile( + document: DesktopWindowProfileDocument, +): DesktopWindowProfileSettings | null { + const { id, name } = document; + if (!isWindowProfileId(id)) return null; + const isDefault = id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID; + const validName = isWindowProfileName(name) && name.trim() !== "" ? name : null; + if (validName === null && !isDefault) return null; + const bounds = normalizeMainWindowBounds(document.bounds); + return { + id, + name: validName ?? DEFAULT_WINDOW_PROFILE_NAME, + projectScopeKeys: isDefault ? [] : normalizeProjectScopeKeys(document.projectScopeKeys ?? []), + theme: !isDefault && isWindowProfileTheme(document.theme) ? document.theme : null, + bounds, + maximized: bounds !== null && document.maximized === true, + openAtQuit: !isDefault && document.openAtQuit === true, + }; +} + +/** + * Keeps valid profiles in order with unique ids and the default profile first. The default + * profile cannot carry a theme, filter or reopen flag. + */ +export function normalizeWindowProfiles( + profiles: ReadonlyArray, +): ReadonlyArray { + const seen = new Set(); + let defaultProfile: DesktopWindowProfileSettings = DEFAULT_WINDOW_PROFILE; + const others: DesktopWindowProfileSettings[] = []; + for (const candidate of profiles) { + const profile = normalizeWindowProfile(candidate); + if (profile === null || seen.has(profile.id)) continue; + seen.add(profile.id); + if (profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) defaultProfile = profile; + else others.push(profile); + } + return [defaultProfile, ...others]; +} + +function readWindowProfiles(parsed: DesktopSettingsDocument) { + const documents: DesktopWindowProfileDocument[] = []; + for (const entry of parsed.windowProfiles ?? []) { + const decoded = decodeWindowProfileDocument(entry); + if (Option.isSome(decoded)) documents.push(decoded.value); + } + const [defaultProfile = DEFAULT_WINDOW_PROFILE, ...others] = normalizeWindowProfiles(documents); + // The default profile's placement lives in the legacy keys, which older builds also read and write. + const bounds = normalizeMainWindowBounds(parsed.mainWindowBounds); + return [ + { + ...defaultProfile, + bounds, + maximized: bounds !== null && parsed.mainWindowMaximized === true, + }, + ...others, + ]; +} + +export function defaultWindowProfile(settings: DesktopSettings): DesktopWindowProfileSettings { + return settings.windowProfiles[0] ?? DEFAULT_WINDOW_PROFILE; +} + function normalizeDesktopSettingsDocument( parsed: DesktopSettingsDocument, appVersion: string, ): DesktopSettings { const defaultSettings = resolveDefaultDesktopSettings(appVersion); - const mainWindowBounds = normalizeMainWindowBounds(parsed.mainWindowBounds); const parsedUpdateChannel = Option.fromNullishOr(parsed.updateChannel); const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined; const updateChannelConfiguredByUser = @@ -227,8 +358,8 @@ function normalizeDesktopSettingsDocument( return { localEnvironmentEnabled: parsed.localEnvironmentEnabled !== false, linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore), - mainWindowBounds, - mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true, + windowProfiles: readWindowProfiles(parsed), + multiWindowEnabled: parsed.multiWindowEnabled !== false, serverExposureMode: parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only", tailscaleServeEnabled: parsed.tailscaleServeEnabled === true, @@ -256,12 +387,23 @@ function toDesktopSettingsDocument( if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) { document.linuxPasswordStore = settings.linuxPasswordStore; } - if (settings.mainWindowBounds !== null) { - document.mainWindowBounds = settings.mainWindowBounds; + const [defaultProfile = DEFAULT_WINDOW_PROFILE, ...otherProfiles] = settings.windowProfiles; + if (defaultProfile.bounds !== null) { + document.mainWindowBounds = defaultProfile.bounds; } - if (settings.mainWindowMaximized) { + if (defaultProfile.maximized) { document.mainWindowMaximized = true; } + if (otherProfiles.length > 0 || defaultProfile.name !== DEFAULT_WINDOW_PROFILE_NAME) { + document.windowProfiles = [ + // The legacy keys carry the default profile's placement. + { id: defaultProfile.id, name: defaultProfile.name }, + ...otherProfiles, + ]; + } + if (settings.multiWindowEnabled !== defaults.multiWindowEnabled) { + document.multiWindowEnabled = settings.multiWindowEnabled; + } if (settings.serverExposureMode !== defaults.serverExposureMode) { document.serverExposureMode = settings.serverExposureMode; } @@ -302,20 +444,45 @@ function setServerExposureMode( }; } -function setMainWindowBounds( +function setWindowProfilePlacement( settings: DesktopSettings, + profileId: string, bounds: DesktopWindowBounds, isMaximized: boolean, ): DesktopSettings { - return settings.mainWindowBounds !== null && - desktopWindowBoundsEquivalence(settings.mainWindowBounds, bounds) && - settings.mainWindowMaximized === isMaximized + const profile = settings.windowProfiles.find((candidate) => candidate.id === profileId); + if ( + profile === undefined || + (profile.bounds !== null && + desktopWindowBoundsEquivalence(profile.bounds, bounds) && + profile.maximized === isMaximized) + ) { + return settings; + } + return { + ...settings, + windowProfiles: settings.windowProfiles.map((candidate) => + candidate === profile ? { ...candidate, bounds, maximized: isMaximized } : candidate, + ), + }; +} + +function updateWindowProfiles( + settings: DesktopSettings, + update: ( + profiles: ReadonlyArray, + ) => ReadonlyArray, +): DesktopSettings { + const updated = update(settings.windowProfiles); + // Dropping the default profile keeps it as it was; it can only be renamed or moved. + const windowProfiles = normalizeWindowProfiles( + updated.some((profile) => profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) + ? updated + : [defaultWindowProfile(settings), ...updated], + ); + return JSON.stringify(windowProfiles) === JSON.stringify(settings.windowProfiles) ? settings - : { - ...settings, - mainWindowBounds: bounds, - mainWindowMaximized: isMaximized, - }; + : { ...settings, windowProfiles }; } function setTailscaleServe( @@ -376,6 +543,12 @@ function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSetting }; } +function setMultiWindowEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings { + return settings.multiWindowEnabled === enabled + ? settings + : { ...settings, multiWindowEnabled: enabled }; +} + function setLocalEnvironmentEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings { return settings.localEnvironmentEnabled === enabled ? settings @@ -549,9 +722,10 @@ export const make = Effect.gen(function* () { ); return yield* SynchronizedRef.setAndGet(settingsRef, settings); }).pipe(Effect.withSpan("desktop.settings.load")), - setMainWindowBounds: Effect.fn("desktop.settings.setMainWindowBounds")( - function* (bounds, isMaximized) { + setWindowProfilePlacement: Effect.fn("desktop.settings.setWindowProfilePlacement")( + function* (profileId, bounds, isMaximized) { yield* Effect.annotateCurrentSpan({ + profileId, x: bounds.x, y: bounds.y, width: bounds.width, @@ -559,9 +733,14 @@ export const make = Effect.gen(function* () { isMaximized, }); - return yield* persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)); + return yield* persist((settings) => + setWindowProfilePlacement(settings, profileId, bounds, isMaximized), + ); }, ), + updateWindowProfiles: Effect.fn("desktop.settings.updateWindowProfiles")(function* (update) { + return yield* persist((settings) => updateWindowProfiles(settings, update)); + }), setServerExposureMode: Effect.fn("desktop.settings.setServerExposureMode")(function* (mode) { yield* Effect.annotateCurrentSpan({ mode }); @@ -599,6 +778,10 @@ export const make = Effect.gen(function* () { return yield* persist((settings) => setLocalEnvironmentEnabled(settings, enabled)); }, ), + setMultiWindowEnabled: Effect.fn("desktop.settings.setMultiWindowEnabled")(function* (enabled) { + yield* Effect.annotateCurrentSpan({ enabled }); + return yield* persist((settings) => setMultiWindowEnabled(settings, enabled)); + }), applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe( Effect.withSpan("desktop.settings.applyWslWindowsFallback"), ), @@ -630,9 +813,16 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET return DesktopAppSettings.of({ get: SynchronizedRef.get(settingsRef), load: SynchronizedRef.get(settingsRef), - setMainWindowBounds: Effect.fn("DesktopAppSettings.setMainWindowBounds")( - function (bounds, isMaximized) { - return update((settings) => setMainWindowBounds(settings, bounds, isMaximized)); + setWindowProfilePlacement: Effect.fn("DesktopAppSettings.setWindowProfilePlacement")( + function (profileId, bounds, isMaximized) { + return update((settings) => + setWindowProfilePlacement(settings, profileId, bounds, isMaximized), + ); + }, + ), + updateWindowProfiles: Effect.fn("DesktopAppSettings.updateWindowProfiles")( + function (profilesUpdate) { + return update((settings) => updateWindowProfiles(settings, profilesUpdate)); }, ), setServerExposureMode: Effect.fn("DesktopAppSettings.setServerExposureMode")( @@ -662,6 +852,11 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET return update((settings) => setLocalEnvironmentEnabled(settings, enabled)); }, ), + setMultiWindowEnabled: Effect.fn("DesktopAppSettings.setMultiWindowEnabled")( + function (enabled) { + return update((settings) => setMultiWindowEnabled(settings, enabled)); + }, + ), applyWslWindowsFallback: update(applyWslWindowsFallback), applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback), }); diff --git a/apps/desktop/src/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..acca841f6f945 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), @@ -215,7 +217,8 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { ? Layer.succeed(DesktopAppSettings.DesktopAppSettings, { get: Effect.sync(() => testSettings), load: Effect.sync(() => testSettings), - setMainWindowBounds: () => Effect.die("unexpected main window bounds update"), + setWindowProfilePlacement: () => Effect.die("unexpected window bounds update"), + updateWindowProfiles: () => Effect.die("unexpected window profile update"), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: (channel) => @@ -237,6 +240,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"), setWslDistro: () => Effect.die("unexpected WSL distro change"), setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"), + setMultiWindowEnabled: () => Effect.die("unexpected multi-window toggle"), setWslOnly: () => Effect.die("unexpected WSL-only toggle"), applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"), applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"), diff --git a/apps/desktop/src/window/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..d1ba722a7f229 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -5,7 +5,11 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import type { DesktopUpdateCheckResult, DesktopUpdateState } from "@t3tools/contracts"; +import type { + DesktopUpdateCheckResult, + DesktopUpdateState, + DesktopWindowsState, +} from "@t3tools/contracts"; import * as Electron from "electron"; import { vi } from "vite-plus/test"; @@ -91,8 +95,36 @@ const layerDesktopUpdates = ({ checkResult }: MenuServices) => installPrepared: () => Effect.die("unexpected installPrepared"), } satisfies DesktopUpdates.DesktopUpdates["Service"]); -const layerDesktopWindow = (selectedAction: Deferred.Deferred) => - Layer.succeed(DesktopWindow.DesktopWindow, { +const emptyWindowsState: DesktopWindowsState = { + profiles: [], + windows: [], + miniMode: false, + multiWindowEnabled: true, +}; + +const windowProfile = (id: string, name: string) => ({ + id, + name, + projectScopeKeys: [], + theme: null, + isDefault: id === "main", +}); + +const openWindow = (windowId: number, profileId: string) => ({ + windowId, + isMain: profileId === "main", + profileId, + name: profileId, + title: "", + focused: false, + projectScopeKeys: [], +}); + +const layerDesktopWindow = ( + selectedAction: Deferred.Deferred, + windowsState: DesktopWindowsState = emptyWindowsState, +) => + Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected createMain"), ensureMain: Effect.die("unexpected ensureMain"), revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"), @@ -101,16 +133,20 @@ const layerDesktopWindow = (selectedAction: Deferred.Deferred) => showConnectingSplash: Effect.void, handleBackendReady: () => Effect.void, handleBackendNotReady: Effect.void, - flushMainWindowBounds: Effect.void, + flushWindowState: Effect.void, prepareCaptureReveal: Effect.void, dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid), dispatchSnapShotEvent: () => Effect.void, - 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"]); + windowsState: Effect.succeed(windowsState), + subscribeWindowsState: () => Effect.void, + openProfile: (profileId) => + Deferred.succeed(selectedAction, `open-${profileId}`).pipe(Effect.asVoid), + }); const layerElectronMenu = ( applicationMenuTemplate: Deferred.Deferred, @@ -127,6 +163,7 @@ const configureMenu = ( applicationMenuTemplate: Deferred.Deferred, environment: Partial = {}, services: MenuServices = {}, + windowsState?: DesktopWindowsState, ) => Effect.gen(function* () { const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu; @@ -135,7 +172,7 @@ const configureMenu = ( Effect.provide( DesktopApplicationMenu.layer.pipe( Layer.provideMerge(layerElectronMenu(applicationMenuTemplate)), - Layer.provideMerge(layerDesktopWindow(selectedAction)), + Layer.provideMerge(layerDesktopWindow(selectedAction, windowsState)), Layer.provideMerge(layerDesktopUpdates(services)), Layer.provideMerge(layerElectronDialog(services)), Layer.provideMerge(layerElectronApp), @@ -347,6 +384,86 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); + it.effect("lists saved windows, marks open ones, and leaves New Window to the renderer", () => + Effect.gen(function* () { + const selectedAction = yield* Deferred.make(); + const applicationMenuTemplate = + yield* Deferred.make(); + yield* configureMenu( + selectedAction, + applicationMenuTemplate, + {}, + {}, + { + profiles: [ + windowProfile("main", "Main"), + windowProfile("work", "Work"), + windowProfile("side", "Side"), + ], + windows: [openWindow(1, "main"), openWindow(2, "work")], + miniMode: true, + multiWindowEnabled: true, + }, + ); + + 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 items = windowMenu.submenu.filter((item) => item.label !== undefined); + assert.deepEqual( + items.slice(0, 5).map(({ label, checked }) => ({ label, checked })), + [ + { label: "New Window", checked: undefined }, + { label: "Main Window", checked: undefined }, + { label: "Work", checked: true }, + { label: "Side", checked: false }, + { label: "Mini Mode", checked: true }, + ], + ); + assert.deepEqual( + { accelerator: items[0]?.accelerator, registerAccelerator: items[0]?.registerAccelerator }, + { accelerator: "CmdOrCtrl+Alt+Shift+N", registerAccelerator: false }, + ); + items[0]?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + assert.equal(yield* Deferred.await(selectedAction), "new-window"); + }), + ); + + it.effect( + "drops New Window and saved windows from the Window menu when multi-window is off", + () => + Effect.gen(function* () { + const applicationMenuTemplate = + yield* Deferred.make(); + yield* configureMenu( + yield* Deferred.make(), + applicationMenuTemplate, + {}, + {}, + { + ...emptyWindowsState, + profiles: [windowProfile("main", "Main"), windowProfile("work", "Work")], + multiWindowEnabled: false, + }, + ); + + const windowMenu = (yield* Deferred.await(applicationMenuTemplate)).find( + (item) => item.role === "windowMenu", + ); + if (!Array.isArray(windowMenu?.submenu)) { + throw new Error("Expected the Window menu submenu to be an array."); + } + assert.deepEqual( + windowMenu.submenu.flatMap((item) => (item.label === undefined ? [] : [item.label])), + // The role items carry translated labels too. + ["Mini Mode", "Minimize", "Zoom"], + ); + }), + ); + 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..34ee8e21690ae 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -4,7 +4,11 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import type { DesktopUpdateChannel } from "@t3tools/contracts"; +import { + DEFAULT_DESKTOP_WINDOW_PROFILE_ID, + type DesktopUpdateChannel, + type DesktopWindowsState, +} from "@t3tools/contracts"; import * as Electron from "electron"; import { msg } from "gt-i18n"; @@ -55,18 +59,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) => @@ -74,6 +78,15 @@ const trackLabel = (channel: DesktopUpdateChannel) => ? m(msg("Nightly", { $context: "release track" })) : m(msg("Stable", { $context: "release track" })); +// Only what the Window menu shows; focus and title changes do not rebuild the menu. +const windowMenuKey = (state: DesktopWindowsState) => + JSON.stringify({ + profiles: state.profiles.map((profile) => [profile.id, profile.name]), + open: state.windows.flatMap((window) => (window.profileId === null ? [] : [window.profileId])), + miniMode: state.miniMode, + multiWindowEnabled: state.multiWindowEnabled, + }); + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -187,9 +200,11 @@ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const electronApp = yield* ElectronApp.ElectronApp; const clientSettings = yield* Effect.serviceOption(DesktopClientSettings.DesktopClientSettings); + const desktopWindow = yield* DesktopWindow.DesktopWindow; const context = yield* Effect.context(); const runPromise = Effect.runPromiseWith(context); const runFork = Effect.runForkWith(context); + let configuredWindowMenuKey: string | null = null; const runMenuEffect = ( action: string, @@ -207,7 +222,24 @@ export const make = Effect.gen(function* () { ); }; - const configure = Effect.gen(function* () { + const configure: Effect.Effect = Effect.gen(function* () { + const windowsState = yield* desktopWindow.windowsState; + configuredWindowMenuKey = windowMenuKey(windowsState); + // Electron flips a clicked checkbox itself; rebuilding restores the real open state. + const windowMenuClick = + (action: string, effect: Effect.Effect) => () => { + runMenuEffect(action, effect.pipe(Effect.ensuring(configure))); + }; + const openProfileClick = (profileId: string) => + windowMenuClick( + "open-window-profile", + Effect.flatMap(DesktopWindow.DesktopWindow, (windows) => windows.openProfile(profileId)), + ); + const openWindowProfileIds = new Set( + windowsState.windows.flatMap((window) => + window.profileId === null ? [] : [window.profileId], + ), + ); const checkForUpdatesClick = () => { runMenuEffect("check-for-updates", handleCheckForUpdatesMenuClick); }; @@ -224,10 +256,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 +428,43 @@ export const make = Effect.gen(function* () { role: "windowMenu", label: m(msg("Window", { $context: "menu bar title" })), submenu: [ + ...(windowsState.multiWindowEnabled + ? ([ + { + label: m(msg("New Window", { $context: "Window menu item" })), + // The renderer's window.new keybinding owns the chord and adds its project filter. + accelerator: "CmdOrCtrl+Alt+Shift+N", + registerAccelerator: false, + click: () => runMenuEffect("new-window", dispatchMenuAction("new-window")), + }, + { type: "separator" }, + { + label: m(msg("Main Window", { $context: "Window menu item" })), + click: openProfileClick(DEFAULT_DESKTOP_WINDOW_PROFILE_ID), + }, + ...windowsState.profiles + .filter((profile) => !profile.isDefault) + .map((profile): Electron.MenuItemConstructorOptions => ({ + label: profile.name, + type: "checkbox", + checked: openWindowProfileIds.has(profile.id), + click: openProfileClick(profile.id), + })), + { type: "separator" }, + ] satisfies Electron.MenuItemConstructorOptions[]) + : []), + { + label: m(msg("Mini Mode", { $context: "Window menu item" })), + type: "checkbox", + checked: windowsState.miniMode, + click: windowMenuClick( + "mini-mode", + Effect.flatMap(DesktopWindow.DesktopWindow, (windows) => + windows.setMiniMode(!windowsState.miniMode), + ), + ), + }, + { type: "separator" }, { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) }, { role: "zoom", @@ -436,6 +505,12 @@ export const make = Effect.gen(function* () { }); let rebuildsOnLocaleChange = false; + yield* desktopWindow.subscribeWindowsState((state) => { + if (configuredWindowMenuKey === null || windowMenuKey(state) === configuredWindowMenuKey) + return; + void runPromise(configure); + }); + return DesktopApplicationMenu.of({ configure: applySavedLanguage.pipe( Effect.andThen(configure), diff --git a/apps/desktop/src/window/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..0148ddbdf3a2f 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -11,6 +11,7 @@ import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as TestClock from "effect/testing/TestClock"; import * as Electron from "electron"; @@ -47,7 +48,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; -import { SNAP_SHOT_EVENT_CHANNEL } from "../ipc/channels.ts"; +import { SNAP_SHOT_EVENT_CHANNEL, WINDOWS_CLOSE_REQUEST_CHANNEL } from "../ipc/channels.ts"; import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; import * as DesktopWindow from "./DesktopWindow.ts"; import { @@ -69,6 +70,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 +115,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 +172,8 @@ function makeFakeBrowserWindow() { webContentsListeners, webContentsOnce: webContents.once, windowListeners, + close: window.close, + hide: window.hide, }; } @@ -233,6 +240,21 @@ const desktopWindowBoundsEquivalence = Schema.toEquivalence( DesktopAppSettings.DesktopWindowBoundsSchema, ); +function withMainPlacement( + settings: DesktopAppSettings.DesktopSettings, + bounds: DesktopAppSettings.DesktopWindowBounds | null, + maximized: boolean, +): DesktopAppSettings.DesktopSettings { + const [main, ...others] = settings.windowProfiles; + return { ...settings, windowProfiles: [{ ...main!, bounds, maximized }, ...others] }; +} + +let randomByte = 0; +const layerSecureRandom = Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(++randomByte % 256)), +); + function layerTest(input: { readonly window: Electron.BrowserWindow; readonly createCount: Ref.Ref; @@ -252,6 +274,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; @@ -266,26 +290,34 @@ function layerTest(input: { const layerDesktopAppSettings = Layer.succeed(DesktopAppSettings.DesktopAppSettings, { get: Effect.sync(() => desktopSettings), load: Effect.sync(() => desktopSettings), - setMainWindowBounds: (bounds, isMaximized) => + setWindowProfilePlacement: (profileId, bounds, isMaximized) => Effect.gen(function* () { if (input.beforeMainWindowBoundsUpdate) { yield* input.beforeMainWindowBoundsUpdate(bounds); } + const main = DesktopAppSettings.defaultWindowProfile(desktopSettings); const changed = - desktopSettings.mainWindowBounds === null || - !desktopWindowBoundsEquivalence(desktopSettings.mainWindowBounds, bounds) || - desktopSettings.mainWindowMaximized !== isMaximized; + profileId === main.id && + (main.bounds === null || + !desktopWindowBoundsEquivalence(main.bounds, bounds) || + main.maximized !== isMaximized); if (changed) { - desktopSettings = { - ...desktopSettings, - mainWindowBounds: bounds, - mainWindowMaximized: isMaximized, - }; + desktopSettings = withMainPlacement(desktopSettings, bounds, isMaximized); input.mainWindowBoundsUpdates?.push(bounds); input.mainWindowMaximizedUpdates?.push(isMaximized); } return { settings: desktopSettings, changed }; }), + updateWindowProfiles: (update) => + Effect.sync(() => { + desktopSettings = { + ...desktopSettings, + windowProfiles: DesktopAppSettings.normalizeWindowProfiles( + update(desktopSettings.windowProfiles), + ), + }; + return { settings: desktopSettings, changed: true }; + }), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: () => Effect.die("unexpected update channel change"), @@ -293,6 +325,12 @@ function layerTest(input: { setWslDistro: () => Effect.die("unexpected WSL distro change"), setWslOnly: () => Effect.die("unexpected WSL-only toggle"), setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"), + setMultiWindowEnabled: (enabled) => + Effect.sync(() => { + const changed = desktopSettings.multiWindowEnabled !== enabled; + desktopSettings = { ...desktopSettings, multiWindowEnabled: enabled }; + return { settings: desktopSettings, changed }; + }), applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"), applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"), } satisfies DesktopAppSettings.DesktopAppSettings["Service"]); @@ -304,16 +342,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), @@ -362,6 +404,7 @@ function layerTest(input: { copyText: input.onCopyText ?? (() => Effect.void), } satisfies ElectronShell.ElectronShell["Service"]), layerElectronTheme, + layerSecureRandom, layerElectronWindow, Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: input.primaryPasteEnabled ?? true, @@ -374,6 +417,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 +487,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), @@ -476,6 +522,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n copyText: () => Effect.void, } satisfies ElectronShell.ElectronShell["Service"]), layerElectronTheme, + layerSecureRandom, Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape), Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), Layer.mock(PreviewPasskeys.PreviewPasskeys)({ @@ -807,10 +854,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), @@ -1241,10 +1288,11 @@ describe("DesktopWindow", () => { createCount, mainWindow, mainWindowBoundsUpdates, - desktopSettings: { - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - mainWindowBounds: { x: 2040, y: 80, width: 1320, height: 880 }, - }, + desktopSettings: withMainPlacement( + DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, + { x: 2040, y: 80, width: 1320, height: 880 }, + false, + ), }); yield* Effect.gen(function* () { @@ -1298,7 +1346,7 @@ describe("DesktopWindow", () => { fakeWindow.isMinimized.mockReturnValue(true); fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 }); - yield* desktopWindow.flushMainWindowBounds; + yield* desktopWindow.flushWindowState; resize(); yield* TestClock.adjust(500); yield* Effect.promise(() => Promise.resolve()); @@ -1422,7 +1470,7 @@ describe("DesktopWindow", () => { yield* TestClock.adjust(250); yield* Effect.promise(() => Promise.resolve()); } - yield* desktopWindow.flushMainWindowBounds; + yield* desktopWindow.flushWindowState; assert.deepEqual(mainWindowBoundsUpdates, [ maximized @@ -1470,6 +1518,125 @@ describe("DesktopWindow", () => { }), ); + it.effect("asks before closing an unsaved window and saves it as a profile", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const secondary = makeFakeBrowserWindow(); + secondary.getBounds.mockReturnValue({ x: 60, y: 50, width: 1000, height: 700 }); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const promptRevealed = yield* Deferred.make(); + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, secondary.window], + createCount, + mainWindow, + onReveal: (window) => { + if (window === secondary.window) Deferred.doneUnsafe(promptRevealed, Exit.void); + }, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* windows.openNewWindow({ projectScopeKeys: ["env:/repo"] }); + assert.equal(yield* Ref.get(createCount), 2); + secondary.webContentsListeners.get("did-finish-load")?.(); + yield* windows.setCloseRequestListening(secondary.window, true); + yield* windows.setWindowProjectScopeKeys(secondary.window, ["env:/hobby"]); + const reloadedContext = Option.getOrThrow(yield* windows.windowContext(secondary.window)); + assert.deepEqual(reloadedContext.projectScopeKeys, ["env:/hobby"]); + assert.equal(reloadedContext.profileId, null); + + const preventSecondaryClose = vi.fn(); + secondary.windowListeners.get("close")?.({ preventDefault: preventSecondaryClose }); + yield* Deferred.await(promptRevealed); + assert.equal(preventSecondaryClose.mock.calls.length, 1); + const request = secondary.send.mock.calls.find( + ([channel]) => channel === WINDOWS_CLOSE_REQUEST_CHANNEL, + )?.[1] as { readonly requestId: string; readonly suggestedName: string }; + assert.equal(request.suggestedName, "Window 2"); + + // The main window keeps serving the secondary window, so closing it only hides it. + const preventMainClose = vi.fn(); + main.windowListeners.get("close")?.({ preventDefault: preventMainClose }); + assert.equal(preventMainClose.mock.calls.length, 1); + assert.equal(main.hide.mock.calls.length, 1); + + yield* windows.resolveCloseRequest(secondary.window, "stale", { action: "discard" }); + assert.equal(secondary.close.mock.calls.length, 0); + yield* windows.resolveCloseRequest(secondary.window, request.requestId, { + action: "save", + name: " Work ", + }); + assert.equal(secondary.close.mock.calls.length, 1); + const state = yield* windows.windowsState; + const saved = state.profiles.find((profile) => profile.name === "Work"); + assert.deepEqual(saved?.projectScopeKeys, ["env:/hobby"]); + const savedContext = Option.getOrThrow(yield* windows.windowContext(secondary.window)); + assert.equal(savedContext.profileId, saved?.id); + assert.deepEqual( + state.windows.map(({ isMain, profileId, name }) => ({ isMain, profileId, name })), + [ + { isMain: true, profileId: "main", name: "Main" }, + { isMain: false, profileId: saved?.id ?? null, name: "Work" }, + ], + ); + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect("opens no secondary window while multi-window is off and saves new profiles", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const secondary = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, secondary.window], + createCount, + mainWindow, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + const saved = yield* windows.createProfile({ + name: " Hobby ", + projectScopeKeys: ["env:/hobby", "env:/hobby"], + theme: null, + }); + assert.deepEqual( + { + name: saved.name, + projectScopeKeys: saved.projectScopeKeys, + isDefault: saved.isDefault, + }, + { name: "Hobby", projectScopeKeys: ["env:/hobby"], isDefault: false }, + ); + + yield* windows.setMultiWindowEnabled(false); + assert.isFalse((yield* windows.windowsState).multiWindowEnabled); + const blocked = [ + yield* Effect.flip(windows.openNewWindow({})), + yield* Effect.flip(windows.openProfile(saved.id)), + ]; + assert.deepEqual( + blocked.map((error) => error._tag === "DesktopWindowProfileError" && error.reason), + ["multi-window-disabled", "multi-window-disabled"], + ); + // The main window still opens from its own profile. + yield* windows.openProfile("main"); + assert.equal(yield* Ref.get(createCount), 1); + + yield* windows.setMultiWindowEnabled(true); + yield* windows.openProfile(saved.id); + assert.equal(yield* Ref.get(createCount), 2); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("persists the current main window bounds before the window closes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1504,7 +1671,7 @@ describe("DesktopWindow", () => { yield* Deferred.await(writeStarted); fakeWindow.isDestroyed.mockReturnValue(true); - const flushFiber = yield* desktopWindow.flushMainWindowBounds.pipe( + const flushFiber = yield* desktopWindow.flushWindowState.pipe( Effect.andThen(Deferred.succeed(flushCompleted, undefined)), Effect.forkChild({ startImmediately: true }), ); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index c99fbb52c49e2..c43b0bd808bf5 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -1,17 +1,31 @@ import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; import { msg } from "gt-i18n"; -import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; +import { + type DesktopCreateWindowProfileInput, + type DesktopOpenWindowInput, + type DesktopSnapShotEvent, + type DesktopTheme, + type DesktopUpdateWindowProfileInput, + type DesktopWindowCloseDecision, + type DesktopWindowContext, + type DesktopWindowProfile, + type DesktopWindowsState, + DEFAULT_CLIENT_SETTINGS, + DEFAULT_DESKTOP_WINDOW_PROFILE_ID, +} from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; import * as DesktopClerk from "../app/DesktopClerk.ts"; @@ -31,6 +45,11 @@ import { TRACKPAD_SCROLL_BEGIN_CHANNEL, TRACKPAD_SCROLL_END_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL, + WINDOWS_CLOSE_REQUEST_CHANNEL, + WINDOWS_HUB_LINK_CHANNEL, + WINDOWS_HUB_PEER_GONE_CHANNEL, + WINDOWS_HUB_RESET_CHANNEL, + WINDOWS_STATE_CHANNEL, } from "../ipc/channels.ts"; import { PASSKEY_BRIDGE_ARGUMENT, @@ -46,6 +65,14 @@ 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, + composeWindowTitle, + nextUnsavedWindowName, + resolveWindowCloseAction, +} from "./DesktopWindowProfiles.ts"; const TITLEBAR_HEIGHT = 40; @@ -96,6 +123,9 @@ const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500; const RENDERER_RECOVERY_MAX_ATTEMPTS = 3; const RENDERER_RECOVERY_WINDOW_MS = 60_000; const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]); +const MINI_WINDOW_SIZE = { width: 320, height: 184 } as const; +const MINI_WINDOW_MIN_SIZE = { width: 240, height: 160 } as const; +const HUB_UNTHROTTLED_REASON = "hub-serving-windows"; type WindowTitleBarOptions = Pick< Electron.BrowserWindowConstructorOptions, @@ -120,6 +150,37 @@ export type DesktopWindowError = | ElectronWindow.ElectronWindowCreateError | PreviewManager.PreviewManagerError; +export class DesktopWindowProfileError extends Schema.TaggedError()( + "DesktopWindowProfileError", + { + reason: Schema.Literals([ + "profile-not-found", + "default-profile", + "not-a-secondary-window", + "multi-window-disabled", + ]), + profileId: Schema.NullOr(Schema.String), + }, +) { + override get message(): string { + switch (this.reason) { + case "profile-not-found": + return `Window profile ${JSON.stringify(this.profileId)} does not exist.`; + case "default-profile": + return "The main window's profile cannot be deleted."; + case "not-a-secondary-window": + return "Only a secondary window can do this."; + case "multi-window-disabled": + return "Multiple windows are turned off in Settings."; + } + } +} + +export type DesktopWindowsOperationError = + | DesktopWindowError + | DesktopAppSettings.DesktopSettingsWriteError + | DesktopWindowProfileError; + export type MainWindowZoomDirection = "in" | "out" | "reset"; export type MainWindowContentsCommand = "reload" | "forceReload" | "toggleDevTools"; @@ -134,7 +195,8 @@ export class DesktopWindow extends Context.Service< readonly showConnectingSplash: Effect.Effect; readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect; readonly handleBackendNotReady: Effect.Effect; - readonly flushMainWindowBounds: Effect.Effect; + /** Before quitting: saves every window's placement and which saved profiles to reopen. */ + readonly flushWindowState: Effect.Effect; readonly prepareCaptureReveal: Effect.Effect; readonly dispatchMenuAction: ( action: string, @@ -143,10 +205,61 @@ 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; + /** A secondary window's own light/dark frame, which can differ from the main window's. */ + readonly setWindowAppearance: ( + window: Electron.BrowserWindow, + theme: DesktopTheme, + ) => Effect.Effect; + readonly windowsState: Effect.Effect; + readonly subscribeWindowsState: ( + listener: (state: DesktopWindowsState) => void, + ) => Effect.Effect; + readonly windowContext: ( + window: Electron.BrowserWindow, + ) => Effect.Effect>; + readonly openNewWindow: ( + input: DesktopOpenWindowInput, + ) => Effect.Effect; + readonly openProfile: (profileId: string) => Effect.Effect; + readonly focusWindow: (windowId: number) => Effect.Effect; + readonly createProfile: ( + input: DesktopCreateWindowProfileInput, + ) => Effect.Effect; + readonly saveWindowAsProfile: ( + window: Electron.BrowserWindow, + name: string, + ) => Effect.Effect; + readonly updateProfile: ( + input: DesktopUpdateWindowProfileInput, + ) => Effect.Effect; + readonly deleteProfile: ( + profileId: string, + ) => Effect.Effect; + readonly setWindowProjectScopeKeys: ( + window: Electron.BrowserWindow, + projectScopeKeys: ReadonlyArray, + ) => Effect.Effect; + readonly setCloseRequestListening: ( + window: Electron.BrowserWindow, + listening: boolean, + ) => Effect.Effect; + readonly resolveCloseRequest: ( + window: Electron.BrowserWindow, + requestId: string, + decision: DesktopWindowCloseDecision, + ) => Effect.Effect; + readonly setMiniMode: (enabled: boolean) => Effect.Effect; + /** Turning it off blocks new secondary windows and leaves open ones open. */ + readonly setMultiWindowEnabled: ( + enabled: boolean, + ) => Effect.Effect; + readonly registerHub: (window: Electron.BrowserWindow) => Effect.Effect; + readonly requestHubLink: (window: Electron.BrowserWindow) => Effect.Effect; } >()("@t3tools/desktop/window/DesktopWindow") {} @@ -346,7 +459,7 @@ function getWindowTitleBarOptions( } function syncWindowAppearance( - window: Electron.BrowserWindow, + window: Pick, hasTitleBarOverlay: boolean, shouldUseDarkColors: boolean, platform: NodeJS.Platform, @@ -381,6 +494,55 @@ function bindFirstRevealTrigger( } } +type AppWindowSpec = + | { readonly role: "main" } + | { + readonly role: "secondary"; + readonly profile: DesktopAppSettings.DesktopWindowProfileSettings | null; + readonly projectScopeKeys: ReadonlyArray; + readonly unsavedName: string; + readonly anchorBounds: DisplayBounds | null; + }; + +interface AppWindowEntry { + readonly window: Electron.BrowserWindow; + readonly windowId: number; + readonly isMain: boolean; + /** Null while a secondary window is unsaved; the main window holds the default profile. */ + profileId: string | null; + unsavedName: string; + /** An unsaved window's filter, kept for saving it as a profile. */ + projectScopeKeys: ReadonlyArray; + name: string; + rendererTitle: string; + appliedTitle: string; + focused: boolean; + rendererLive: boolean; + responsive: boolean; + closeRequestListening: boolean; + pendingCloseRequestId: string | null; + closeApproved: boolean; + appearance: DesktopTheme | null; + hubUnthrottled: boolean; + readPlacement: () => { + readonly bounds: DesktopAppSettings.DesktopWindowBounds; + readonly isMaximized: boolean; + } | null; + flushPlacement: Effect.Effect; +} + +const serializeWindowsState = (state: DesktopWindowsState) => JSON.stringify(state); + +const toWindowProfile = ( + profile: DesktopAppSettings.DesktopWindowProfileSettings, +): DesktopWindowProfile => ({ + id: profile.id, + name: profile.name, + projectScopeKeys: profile.projectScopeKeys, + theme: profile.theme, + isDefault: profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID, +}); + /** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -397,20 +559,43 @@ export const make = Effect.gen(function* () { const clientSettings = yield* DesktopClientSettings.DesktopClientSettings; const electronApp = yield* ElectronApp.ElectronApp; const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory; + const random = yield* SecureRandom.SecureRandom; const backendReadyRef = yield* Ref.make(false); let backendHasStarted = false; let mainClosedDuringStartup = false; + let reopenedProfilesAtLaunch = false; const splashWindowRef = yield* Ref.make>(Option.none()); const context = yield* Effect.context(); const runFork = Effect.runForkWith(context); 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) => Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), ); - let flushMainWindowBounds: Effect.Effect = Effect.void; let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; + const entries = new Map(); + // Placement writes still running for windows that already closed; quitting waits for them. + const closedPlacementWrites = new Set>(); + const stateListeners = new Set<(state: DesktopWindowsState) => void>(); + let lastBroadcastState = ""; + // The main window's placement before mini mode, restored when it ends and saved instead of the panel. + let miniPlacement: { readonly bounds: DisplayBounds; readonly isMaximized: boolean } | null = + null; + const hubLinks = new HubLinkBroker( + () => new Electron.MessageChannelMain(), + ); + + 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 +629,105 @@ 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 nextUnsavedName = () => + nextUnsavedWindowName( + liveEntries().flatMap((entry) => (entry.profileId === null ? [entry.unsavedName] : [])), + ); + + const titleFor = (entry: AppWindowEntry) => + composeWindowTitle({ + rendererTitle: entry.rendererTitle, + fallbackTitle: environment.displayName, + isMain: entry.isMain, + windowName: entry.name, + secondaryWindowCount: secondaryEntries().length, + }); + + const computeWindowsState = Effect.gen(function* () { + const settings = yield* desktopSettings.get; + const live = liveEntries().sort((left, right) => Number(right.isMain) - Number(left.isMain)); + return { + profiles: settings.windowProfiles.map(toWindowProfile), + windows: live.map((entry) => ({ + windowId: entry.windowId, + isMain: entry.isMain, + profileId: entry.profileId, + name: entry.name, + title: entry.appliedTitle, + focused: entry.focused, + projectScopeKeys: entry.projectScopeKeys, + })), + miniMode: miniPlacement !== null, + multiWindowEnabled: settings.multiWindowEnabled, + } satisfies DesktopWindowsState; + }); + + // The hub must keep serving secondary windows while it is hidden, minimized or a mini panel. + const syncHubThrottling = () => { + const main = mainEntry(); + if (main === undefined) return; + const held = secondaryEntries().length > 0 || miniPlacement !== null; + if (held === main.hubUnthrottled) return; + main.hubUnthrottled = held; + setUnthrottledHold(main.window, HUB_UNTHROTTLED_REASON, held); + }; + + // Names, titles, renderers and menu listeners all follow from the open windows and profiles. + const syncWindows = Effect.fn("desktop.window.syncWindows")(function* () { + const settings = yield* desktopSettings.get; + for (const entry of liveEntries()) { + // The main window always holds the default profile, which cannot be deleted. + const profile = settings.windowProfiles.find((candidate) => candidate.id === entry.profileId); + entry.name = profile?.name ?? entry.unsavedName; + const title = titleFor(entry); + if (title !== entry.appliedTitle) { + entry.appliedTitle = title; + entry.window.setTitle(title); + } + } + 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); + } + for (const listener of stateListeners) listener(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 updateProfiles = ( + update: ( + profiles: ReadonlyArray, + ) => ReadonlyArray, + ) => desktopSettings.updateWindowProfiles(update).pipe(Effect.andThen(syncWindows())); + + const readDisplayBounds = Effect.gen(function* () { const displayBoundsResult = yield* Effect.sync(() => { try { return { @@ -466,17 +738,47 @@ 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) { - yield* logWindowWarning("saved main window bounds could not be restored; using defaults"); + 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; + const persistedProfile = + spec.role === "main" + ? DesktopAppSettings.defaultWindowProfile(persistedSettings) + : spec.profile; + const persistedBounds = persistedProfile?.bounds ?? null; + const persistedMaximized = persistedProfile?.maximized ?? false; + const displayBounds = yield* readDisplayBounds; + const restorableBounds = resolveInitialMainWindowBounds(persistedBounds, displayBounds); + const restoredPersistedBounds = + persistedBounds !== null && restorableBounds === persistedBounds; + if (persistedBounds !== null && !restoredPersistedBounds) { + yield* logWindowWarning("saved window bounds could not be restored; using defaults", { + role: spec.role, + }); } + const initialBounds = + spec.role === "secondary" && !restoredPersistedBounds + ? 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 +809,34 @@ 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, + profileId: + spec.role === "main" ? DEFAULT_DESKTOP_WINDOW_PROFILE_ID : (spec.profile?.id ?? null), + unsavedName: spec.role === "main" ? "" : spec.unsavedName, + projectScopeKeys: spec.role === "main" ? [] : spec.projectScopeKeys, + name: "", + rendererTitle: environment.displayName, + appliedTitle: environment.displayName, + focused: false, + rendererLive: false, + responsive: true, + closeRequestListening: false, + pendingCloseRequestId: null, + closeApproved: false, + appearance: null, + hubUnthrottled: false, + readPlacement: () => null, + flushPlacement: Effect.void, + }; let boundsPersistFiber: Fiber.Fiber | undefined; let pendingBoundsPersistFiber: Fiber.Fiber | undefined; let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds; @@ -523,6 +848,10 @@ export const make = Effect.gen(function* () { if (window.isDestroyed()) { return null; } + if (isMain && miniPlacement !== null) { + const bounds = DesktopAppSettings.normalizeMainWindowBounds(miniPlacement.bounds); + return bounds === null ? null : { bounds, isMaximized: miniPlacement.isMaximized }; + } // Minimized windows report stale state on some platforms (macOS: not maximized, the // pre-move normal frame; Windows: -32000), so they keep the state seen before minimizing. if (window.isMinimized()) { @@ -547,12 +876,15 @@ export const make = Effect.gen(function* () { persistableBounds === null ? null : { bounds: persistableBounds, isMaximized }; return lastPersistableState; }; + entry.readPlacement = readPersistableState; const fallbackWindowBounds = boundsPersistenceEnabled ? null : (readPersistableState()?.bounds ?? null); - const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; + const fallbackWindowMaximized = persistedMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { - if (!boundsPersistenceEnabled) { + // Unsaved windows keep no placement until they are saved as a profile. + const profileId = entry.profileId; + if (!boundsPersistenceEnabled || profileId === null) { return pendingBoundsPersistFiber; } const state = readPersistableState(); @@ -560,10 +892,10 @@ export const make = Effect.gen(function* () { return pendingBoundsPersistFiber; } pendingBoundsPersistFiber = runFork( - desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe( + desktopSettings.setWindowProfilePlacement(profileId, state.bounds, state.isMaximized).pipe( Effect.asVoid, Effect.catch((error) => - logWindowWarning("failed to persist main window bounds", { + logWindowWarning("failed to persist window bounds", { message: error.message, }), ), @@ -615,9 +947,13 @@ export const make = Effect.gen(function* () { fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid), ), ); - flushMainWindowBounds = flushBoundsPersist; + entry.flushPlacement = 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 +1130,18 @@ export const make = Effect.gen(function* () { void runPromise(electronShell.openExternal(url)); } }); + // A new document drops the old renderer's hub links and close-request listener. + const rendererGone = () => { + entry.rendererLive = false; + entry.closeRequestListening = false; + entry.pendingCloseRequestId = null; + if (isMain) notifyHubReset(); + else notifyHubPeerGone(entry.windowId); + }; + window.webContents.on("did-start-navigation", (event) => { + if (event.isMainFrame && !event.isSameDocument) rendererGone(); + }); + window.webContents.on("destroyed", rendererGone); const quitShortcutHandler = makeQuitShortcutHandler({ platform: environment.platform, @@ -849,19 +1197,59 @@ export const make = Effect.gen(function* () { runFork(zoomWindow(window, direction)); }); - // The renderer titles the window after the open thread; only a blank title - // falls back to the app name. + // The renderer titles the window after the open thread; a blank title falls back to the + // app name, and the window's name is appended once several windows are open. window.on("page-title-updated", (event, title) => { - if (title.trim() !== "") return; - event.preventDefault(); - window.setTitle(environment.displayName); + entry.rendererTitle = title; + const composed = titleFor(entry); + const changed = composed !== entry.appliedTitle; + entry.appliedTitle = composed; + if (composed !== title) { + event.preventDefault(); + window.setTitle(composed); + } + if (changed && entries.size > 1) requestSync(); }); window.on("resize", scheduleBoundsPersist); window.on("move", scheduleBoundsPersist); window.on("maximize", scheduleBoundsPersist); window.on("unmaximize", scheduleBoundsPersist); - window.on("close", () => { - runFork(flushBoundsPersist); + // Focus only matters to the list of other windows. + window.on("focus", () => { + entry.focused = true; + if (entries.size > 1) requestSync(); + }); + window.on("blur", () => { + entry.focused = false; + if (entries.size > 1) requestSync(); + }); + window.on("unresponsive", () => { + entry.responsive = false; + }); + window.on("responsive", () => { + entry.responsive = true; + }); + window.on("close", (event) => { + const action = resolveWindowCloseAction({ + isMain, + quitting: runSync(Ref.get(desktopState.quitting)), + saved: entry.profileId !== null, + secondaryWindowCount: secondaryEntries().length, + closeApproved: entry.closeApproved, + rendererCanPrompt: entry.rendererLive && entry.responsive && entry.closeRequestListening, + promptPending: entry.pendingCloseRequestId !== null, + }); + if (action === "close") { + runFork(flushBoundsPersist); + return; + } + event.preventDefault(); + if (action === "hide") { + window.hide(); + requestSync(); + } else if (action === "prompt") { + runFork(requestClose(entry)); + } }); if (environment.platform === "darwin") { @@ -936,6 +1324,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 +1347,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 +1358,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 +1387,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,61 +1422,93 @@ 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 (persistedMaximized && (isMain || restoredPersistedBounds)) 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 (pendingBoundsPersistFiber !== undefined) { + const write = pendingBoundsPersistFiber; + closedPlacementWrites.add(write); + write.addObserver(() => closedPlacementWrites.delete(write)); + } + if (isMain) { + if (!backendHasStarted) mainClosedDuringStartup = true; + miniPlacement = null; + notifyHubReset(); + void runPromise(electronWindow.clearMain(Option.some(window))); + } else { + notifyHubPeerGone(entry.windowId); + runFork(handleSecondaryClosed(entry)); + } + requestSync(); }); return Option.some(window); }); - const createMain = Effect.gen(function* () { - const window = yield* createWindow(); + const createMain: Effect.Effect< + Option.Option, + DesktopWindowError + > = Effect.gen(function* () { + const window = yield* buildAppWindow({ role: "main" }); if (Option.isSome(window)) { mainClosedDuringStartup = false; yield* logWindowInfo("main window created"); + if (!reopenedProfilesAtLaunch) { + reopenedProfilesAtLaunch = true; + yield* Effect.forkDetach(reopenProfilesOpenAtQuit); + } } return window; }).pipe(Effect.withSpan("desktop.window.createMain")); - const ensureMain = Effect.gen(function* () { + const ensureMain: Effect.Effect< + Option.Option, + DesktopWindowError + > = Effect.gen(function* () { if (yield* Ref.get(desktopState.quitting)) return Option.none(); const existingWindow = yield* electronWindow.main; if (Option.isSome(existingWindow)) { @@ -1101,6 +1529,162 @@ export const make = Effect.gen(function* () { return window; }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain")); + const openSecondary = Effect.fn("desktop.window.openSecondary")(function* (input: { + readonly profile: DesktopAppSettings.DesktopWindowProfileSettings | null; + readonly projectScopeKeys: ReadonlyArray; + }): Effect.fn.Return { + // Secondary windows reach environments through the main window's renderer. + if (Option.isNone(yield* ensureMain)) return; + const anchor = yield* electronWindow.focusedApp; + yield* buildAppWindow({ + role: "secondary", + profile: input.profile, + projectScopeKeys: input.projectScopeKeys, + unsavedName: nextUnsavedName(), + anchorBounds: + Option.isSome(anchor) && !anchor.value.isDestroyed() ? anchor.value.getBounds() : null, + }); + }); + + const reopenProfilesOpenAtQuit: Effect.Effect = Effect.gen(function* () { + const settings = yield* desktopSettings.get; + if (!settings.multiWindowEnabled) return; + for (const profile of settings.windowProfiles) { + if (!profile.openAtQuit || profile.id === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) continue; + yield* openSecondary({ profile, projectScopeKeys: profile.projectScopeKeys }); + } + }).pipe( + Effect.catchCause((cause) => logWindowWarning("failed to reopen saved windows", { cause })), + Effect.withSpan("desktop.window.reopenProfilesOpenAtQuit"), + ); + + const handleSecondaryClosed = Effect.fn("desktop.window.handleSecondaryClosed")(function* ( + entry: AppWindowEntry, + ) { + if (yield* Ref.get(desktopState.quitting)) return; + const profileId = entry.profileId; + if (profileId !== null) { + yield* updateProfiles((profiles) => + profiles.map((profile) => + profile.id === profileId ? { ...profile, openAtQuit: false } : profile, + ), + ).pipe( + Effect.catch((error) => + logWindowWarning("failed to save a closed window's profile", { message: error.message }), + ), + ); + } + const main = mainEntry(); + if (secondaryEntries().length > 0 || main === undefined || main.window.isVisible()) return; + // The hidden main window kept the app alive for its secondary windows; without them, quit + // as closing the last window always has. macOS apps outlive their windows. + if (environment.platform !== "darwin") main.window.close(); + }); + + const newId = Effect.map(random.uuidV4(), (uuid) => uuid.replace(/-/g, "")); + + /** Saves a new profile, as normalized; fails if normalizing dropped it. */ + const addProfile = Effect.fn("desktop.window.addProfile")(function* ( + profile: Omit, + ) { + const id = yield* newId; + const { settings } = yield* desktopSettings.updateWindowProfiles((profiles) => [ + ...profiles, + { ...profile, id, name: profile.name.trim(), openAtQuit: false }, + ]); + const saved = settings.windowProfiles.find((candidate) => candidate.id === id); + if (saved === undefined) { + return yield* new DesktopWindowProfileError({ reason: "profile-not-found", profileId: id }); + } + return saved; + }); + + const createProfileFor = Effect.fn("desktop.window.createProfileFor")(function* ( + entry: AppWindowEntry, + name: string, + ) { + const placement = entry.readPlacement(); + const saved = yield* addProfile({ + name, + projectScopeKeys: entry.projectScopeKeys, + theme: null, + bounds: placement?.bounds ?? null, + maximized: placement?.isMaximized ?? false, + }); + entry.profileId = saved.id; + yield* syncWindows(); + return saved; + }); + + const requestClose = Effect.fn("desktop.window.requestClose")(function* (entry: AppWindowEntry) { + const requestId = yield* newId; + entry.pendingCloseRequestId = requestId; + if (entry.window.isDestroyed()) return; + entry.window.webContents.send(WINDOWS_CLOSE_REQUEST_CHANNEL, { + requestId, + suggestedName: entry.unsavedName, + }); + yield* electronWindow.reveal(entry.window); + }); + + const requireMultiWindowEnabled = Effect.gen(function* () { + if ((yield* desktopSettings.get).multiWindowEnabled) return; + return yield* new DesktopWindowProfileError({ + reason: "multi-window-disabled", + profileId: null, + }); + }); + + const requireSecondary = (window: Electron.BrowserWindow) => { + const entry = entryOf(window); + return entry === undefined || entry.isMain + ? Effect.fail( + new DesktopWindowProfileError({ reason: "not-a-secondary-window", profileId: null }), + ) + : Effect.succeed(entry); + }; + + const setMiniMode = Effect.fn("desktop.window.setMiniMode")(function* (enabled: boolean) { + yield* Effect.annotateCurrentSpan({ enabled }); + const main = mainEntry(); + if (main === undefined || enabled === (miniPlacement !== null)) return; + const window = main.window; + if (enabled) { + const isMaximized = window.isMaximized(); + const bounds = + isMaximized || window.isFullScreen() ? window.getNormalBounds() : window.getBounds(); + miniPlacement = { bounds, isMaximized }; + if (window.isFullScreen()) window.setFullScreen(false); + if (isMaximized) window.unmaximize(); + window.setMinimumSize(MINI_WINDOW_MIN_SIZE.width, MINI_WINDOW_MIN_SIZE.height); + window.setBounds({ + x: bounds.x + Math.max(0, bounds.width - MINI_WINDOW_SIZE.width), + y: bounds.y, + ...MINI_WINDOW_SIZE, + }); + } else { + const previous = miniPlacement; + miniPlacement = null; + window.setMinimumSize( + DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width, + DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height, + ); + if (previous !== null) { + window.setBounds(previous.bounds); + if (previous.isMaximized) window.maximize(); + } + } + // The panel's top bar stands in for the traffic lights. Windows and Linux keep the title bar + // overlay, which Electron cannot take off a created window, so the panel keeps only Close. + if (environment.platform === "darwin") window.setWindowButtonVisibility(!enabled); + else { + window.setMinimizable(!enabled); + window.setMaximizable(!enabled); + } + yield* electronWindow.reveal(window); + yield* syncWindows(); + }); + const waitingForBackend = Effect.gen(function* () { if (yield* Ref.get(backendReadyRef)) return false; return (yield* desktopSettings.get).localEnvironmentEnabled; @@ -1166,14 +1750,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 +1776,38 @@ 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(); + }; + + const appearanceDark = (theme: DesktopTheme, systemDark: boolean) => + theme === "system" ? systemDark : theme === "dark"; return DesktopWindow.of({ createMain: createMain.pipe(Effect.flatMap(requireWindow)), ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)), 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); } @@ -1231,9 +1844,22 @@ export const make = Effect.gen(function* () { handleBackendNotReady: Ref.set(backendReadyRef, false).pipe( Effect.withSpan("desktop.window.handleBackendNotReady"), ), - flushMainWindowBounds: Effect.suspend(() => flushMainWindowBounds).pipe( - Effect.withSpan("desktop.window.flushMainWindowBounds"), - ), + flushWindowState: Effect.gen(function* () { + const openProfileIds = new Set( + secondaryEntries().flatMap((entry) => (entry.profileId === null ? [] : [entry.profileId])), + ); + yield* desktopSettings + .updateWindowProfiles((profiles) => + profiles.map((profile) => ({ ...profile, openAtQuit: openProfileIds.has(profile.id) })), + ) + .pipe( + Effect.catch((error) => + logWindowWarning("failed to save which windows to reopen", { message: error.message }), + ), + ); + yield* Effect.forEach(entries.values(), (entry) => entry.flushPlacement, { discard: true }); + yield* Fiber.joinAll([...closedPlacementWrites]); + }).pipe(Effect.withSpan("desktop.window.flushWindowState")), dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action, options) { yield* Effect.annotateCurrentSpan({ action }); yield* dispatchRendererEvent(MENU_ACTION_CHANNEL, action, options); @@ -1243,13 +1869,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 +1896,212 @@ 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), - ); + yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) => { + const appearance = entries.get(window.id)?.appearance ?? null; + return syncWindowAppearance( + window, + titleBarOverlay, + appearance === null + ? shouldUseDarkColors + : appearanceDark(appearance, shouldUseDarkColors), + environment.platform, + ); + }); }).pipe(Effect.withSpan("desktop.window.syncAppearance")), + setWindowAppearance: Effect.fn("desktop.window.setWindowAppearance")(function* (window, theme) { + const entry = entryOf(window); + if (entry === undefined) return; + entry.appearance = theme; + yield* syncWindowAppearance( + window, + environment.platform !== "darwin", + appearanceDark(theme, yield* electronTheme.shouldUseDarkColors), + environment.platform, + ); + }), + windowsState: computeWindowsState, + subscribeWindowsState: Effect.fn("desktop.window.subscribeWindowsState")(function* (listener) { + yield* Effect.acquireRelease( + Effect.sync(() => void stateListeners.add(listener)), + () => Effect.sync(() => void stateListeners.delete(listener)), + ); + }), + windowContext: Effect.fn("desktop.window.windowContext")(function* (window) { + const entry = entryOf(window); + if (entry === undefined) return Option.none(); + // A reloaded secondary window resumes its live filter and profile, not its opening ones. + const profile = (yield* desktopSettings.get).windowProfiles.find( + (candidate) => candidate.id === entry.profileId, + ); + return Option.some({ + windowId: entry.windowId, + isMain: entry.isMain, + profileId: entry.profileId, + projectScopeKeys: entry.projectScopeKeys, + theme: profile?.theme ?? null, + }); + }), + openNewWindow: Effect.fn("desktop.window.openNewWindow")(function* (input) { + yield* requireMultiWindowEnabled; + yield* openSecondary({ + profile: null, + projectScopeKeys: DesktopAppSettings.normalizeProjectScopeKeys( + input.projectScopeKeys ?? [], + ), + }); + }), + openProfile: Effect.fn("desktop.window.openProfile")(function* (profileId) { + yield* Effect.annotateCurrentSpan({ profileId }); + if (profileId === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) { + yield* revealOrCreateMain; + return; + } + const open = secondaryEntries().find((entry) => entry.profileId === profileId); + if (open !== undefined) { + yield* electronWindow.reveal(open.window); + return; + } + const profile = (yield* desktopSettings.get).windowProfiles.find( + (candidate) => candidate.id === profileId, + ); + if (profile === undefined) { + return yield* new DesktopWindowProfileError({ reason: "profile-not-found", profileId }); + } + yield* requireMultiWindowEnabled; + yield* openSecondary({ profile, projectScopeKeys: profile.projectScopeKeys }); + }), + focusWindow: Effect.fn("desktop.window.focusWindow")(function* (windowId) { + const entry = liveEntries().find((candidate) => candidate.windowId === windowId); + if (entry !== undefined) yield* electronWindow.reveal(entry.window); + }), + saveWindowAsProfile: Effect.fn("desktop.window.saveWindowAsProfile")(function* (window, name) { + const entry = yield* requireSecondary(window); + if (entry.profileId !== null) { + const current = (yield* desktopSettings.get).windowProfiles.find( + (profile) => profile.id === entry.profileId, + ); + // Saving a saved window as another profile starts from its current filter. + if (current !== undefined) entry.projectScopeKeys = current.projectScopeKeys; + } + return toWindowProfile(yield* createProfileFor(entry, name)); + }), + createProfile: Effect.fn("desktop.window.createProfile")(function* (input) { + const saved = yield* addProfile({ + name: input.name, + projectScopeKeys: input.projectScopeKeys, + theme: input.theme, + bounds: null, + maximized: false, + }); + yield* syncWindows(); + return toWindowProfile(saved); + }), + updateProfile: Effect.fn("desktop.window.updateProfile")(function* (input) { + yield* Effect.annotateCurrentSpan({ profileId: input.profileId }); + const settings = yield* desktopSettings.get; + if (!settings.windowProfiles.some((profile) => profile.id === input.profileId)) { + return yield* new DesktopWindowProfileError({ + reason: "profile-not-found", + profileId: input.profileId, + }); + } + yield* updateProfiles((profiles) => + profiles.map((profile) => + profile.id === input.profileId + ? { + ...profile, + ...(input.name === undefined ? {} : { name: input.name.trim() }), + ...(input.theme === undefined ? {} : { theme: input.theme }), + } + : profile, + ), + ); + }), + deleteProfile: Effect.fn("desktop.window.deleteProfile")(function* (profileId) { + yield* Effect.annotateCurrentSpan({ profileId }); + if (profileId === DEFAULT_DESKTOP_WINDOW_PROFILE_ID) { + return yield* new DesktopWindowProfileError({ reason: "default-profile", profileId }); + } + const profile = (yield* desktopSettings.get).windowProfiles.find( + (candidate) => candidate.id === profileId, + ); + if (profile === undefined) return; + // Its open window stays open as an unsaved window with the same filter. + for (const entry of secondaryEntries()) { + if (entry.profileId !== profileId) continue; + entry.profileId = null; + entry.projectScopeKeys = profile.projectScopeKeys; + entry.unsavedName = nextUnsavedName(); + } + yield* updateProfiles((profiles) => + profiles.filter((candidate) => candidate.id !== profileId), + ); + }), + setWindowProjectScopeKeys: Effect.fn("desktop.window.setWindowProjectScopeKeys")( + function* (window, projectScopeKeys) { + const entry = entryOf(window); + if (entry === undefined || entry.isMain) return; + const keys = DesktopAppSettings.normalizeProjectScopeKeys(projectScopeKeys); + entry.projectScopeKeys = keys; + const profileId = entry.profileId; + if (profileId === null) return yield* syncWindows(); + yield* updateProfiles((profiles) => + profiles.map((profile) => + profile.id === profileId ? { ...profile, projectScopeKeys: keys } : profile, + ), + ); + }, + ), + setCloseRequestListening: Effect.fn("desktop.window.setCloseRequestListening")( + function (window, listening) { + return Effect.sync(() => { + const entry = entryOf(window); + if (entry !== undefined) entry.closeRequestListening = listening; + }); + }, + ), + resolveCloseRequest: Effect.fn("desktop.window.resolveCloseRequest")( + function* (window, requestId, decision) { + const entry = entryOf(window); + if (entry === undefined || entry.pendingCloseRequestId !== requestId) return; + entry.pendingCloseRequestId = null; + if (decision.action === "cancel") return; + if (decision.action === "save") yield* createProfileFor(entry, decision.name); + entry.closeApproved = true; + window.close(); + }, + ), + setMiniMode, + setMultiWindowEnabled: Effect.fn("desktop.window.setMultiWindowEnabled")(function* (enabled) { + yield* Effect.annotateCurrentSpan({ enabled }); + yield* desktopSettings.setMultiWindowEnabled(enabled); + yield* syncWindows(); + }), + registerHub: Effect.fn("desktop.window.registerHub")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + 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..5a2b60ca8e72a --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + cascadeWindowBounds, + composeWindowTitle, + nextUnsavedWindowName, + resolveWindowCloseAction, + type DesktopWindowCloseInput, +} from "./DesktopWindowProfiles.ts"; + +const unsavedSecondary: DesktopWindowCloseInput = { + isMain: false, + quitting: false, + saved: false, + secondaryWindowCount: 1, + closeApproved: false, + rendererCanPrompt: true, + promptPending: false, +}; + +describe("resolveWindowCloseAction", () => { + it.each([ + ["asks before closing an unsaved window", {}, "prompt"], + ["waits for the answer to an open prompt", { promptPending: true }, "keep-open"], + ["closes a saved window without asking", { saved: true }, "close"], + ["closes without asking while the app quits", { quitting: true }, "close"], + [ + "closes once save or discard approved it", + { closeApproved: true, promptPending: true }, + "close", + ], + ["closes when the renderer cannot answer", { rendererCanPrompt: false }, "close"], + ["hides the main window while it serves others", { isMain: true }, "hide"], + ["closes the main window when it is alone", { isMain: true, secondaryWindowCount: 0 }, "close"], + ["closes the main window on quit", { isMain: true, quitting: true }, "close"], + ] as const)("%s", (_name, overrides, expected) => { + expect(resolveWindowCloseAction({ ...unsavedSecondary, ...overrides })).toBe(expected); + }); + + it("never prompts for the main window, a saved window, or during quit", () => { + const flags = [false, true]; + for (const isMain of flags) + for (const quitting of flags) + for (const saved of flags) + for (const closeApproved of flags) + for (const rendererCanPrompt of flags) + for (const promptPending of flags) { + const action = resolveWindowCloseAction({ + isMain, + quitting, + saved, + secondaryWindowCount: 1, + closeApproved, + rendererCanPrompt, + promptPending, + }); + if (isMain || quitting || saved || closeApproved || !rendererCanPrompt) { + expect(action === "prompt" || action === "keep-open").toBe(false); + } + if (quitting) expect(action).toBe("close"); + } + }); +}); + +describe("nextUnsavedWindowName", () => { + it("takes the lowest free number after the main window", () => { + expect(nextUnsavedWindowName([])).toBe("Window 2"); + expect(nextUnsavedWindowName(["Window 2", "Window 4"])).toBe("Window 3"); + }); +}); + +describe("composeWindowTitle", () => { + const title = (overrides: Partial[0]>) => + composeWindowTitle({ + rendererTitle: "Fix login", + fallbackTitle: "T3 Code", + isMain: true, + windowName: "Main", + secondaryWindowCount: 0, + ...overrides, + }); + + it("names the main window only while other windows are open", () => { + expect(title({})).toBe("Fix login"); + expect(title({ rendererTitle: " " })).toBe("T3 Code"); + expect(title({ secondaryWindowCount: 1 })).toBe("Fix login - Main"); + }); + + it("always names a secondary window", () => { + expect(title({ isMain: false, windowName: "Window 2" })).toBe("Fix login - Window 2"); + }); +}); + +describe("cascadeWindowBounds", () => { + const display = { x: 0, y: 0, width: 1920, height: 1080 }; + + 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..f7a334a84c2e4 --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.ts @@ -0,0 +1,100 @@ +import { msg } from "gt-i18n"; + +import { m } from "../i18n/messages.ts"; + +type DesktopWindowCloseAction = + /** Let the window close. */ + | "close" + /** Keep the main window's renderer running for the secondary windows it serves. */ + | "hide" + /** Ask the renderer whether to save the unsaved window first. */ + | "prompt" + /** A prompt is already open; the renderer's answer decides. */ + | "keep-open"; + +export interface DesktopWindowCloseInput { + readonly isMain: boolean; + readonly quitting: boolean; + readonly saved: boolean; + readonly secondaryWindowCount: number; + /** A save or discard decision already approved this close. */ + readonly closeApproved: boolean; + /** Loaded, not crashed, responsive, and listening for close requests. */ + readonly rendererCanPrompt: boolean; + readonly promptPending: boolean; +} + +export function resolveWindowCloseAction(input: DesktopWindowCloseInput): DesktopWindowCloseAction { + if (input.quitting || input.closeApproved) return "close"; + if (input.isMain) return input.secondaryWindowCount > 0 ? "hide" : "close"; + if (input.saved || !input.rendererCanPrompt) return "close"; + return input.promptPending ? "keep-open" : "prompt"; +} + +/** The main window is the first window, so unsaved secondary windows count from 2. */ +export function nextUnsavedWindowName(usedNames: Iterable): string { + const used = new Set(usedNames); + for (let index = 2; ; index++) { + const name = m( + msg("Window {number}", { + $context: "name of an unsaved app window", + number: String(index), + }), + ); + if (!used.has(name)) return name; + } +} + +export function composeWindowTitle(input: { + readonly rendererTitle: string; + readonly fallbackTitle: string; + readonly isMain: boolean; + readonly windowName: string; + readonly secondaryWindowCount: number; +}): string { + const base = input.rendererTitle.trim() === "" ? input.fallbackTitle : input.rendererTitle; + const showName = !input.isMain || input.secondaryWindowCount > 0; + return showName ? `${base} - ${input.windowName}` : base; +} + +interface Rectangle { + readonly x: number; + readonly y: number; + 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..910334f208ca7 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 = 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/CommandPaletteThemeItems.tsx b/apps/web/src/components/CommandPaletteThemeItems.tsx index 4fde126c8c4b9..65a491d8e11be 100644 --- a/apps/web/src/components/CommandPaletteThemeItems.tsx +++ b/apps/web/src/components/CommandPaletteThemeItems.tsx @@ -39,7 +39,7 @@ export function notifyThemeSaveFailure(): void { // Reads its own source hooks so the compiler caches the cards on them. Taking the // sources as arguments would leave it hook-free, and the compiler would cache nothing. -function useThemeCards() { +export function useThemeCards() { const customThemes = useCustomThemes(); const environmentThemes = useEnvironmentThemeDefinitions(); const seen = new Set(); diff --git a/apps/web/src/components/CommandPaletteWindowItems.tsx b/apps/web/src/components/CommandPaletteWindowItems.tsx new file mode 100644 index 0000000000000..a551cb35fd3b9 --- /dev/null +++ b/apps/web/src/components/CommandPaletteWindowItems.tsx @@ -0,0 +1,68 @@ +import { useGT } from "gt-react"; +import { AppWindowIcon, Maximize2Icon, PictureInPicture2Icon } from "lucide-react"; +import { useState } from "react"; + +import { desktopWindowsBridge, readDesktopWindowContext } from "../multiWindow/windowContext"; +import { selectCurrentWindowProfile, useDesktopWindowsState } from "../multiWindow/windowsState"; +import { notifyWindowActionFailure, openNewDesktopWindow } from "../multiWindow/ui/windowActions"; +import { ITEM_ICON_CLASS, type CommandPaletteActionItem } from "./CommandPalette.logic"; + +/** Desktop multi-window actions; empty on the web and in shells without multi-window support. */ +export function useCommandPaletteWindowItems(): ReadonlyArray { + const [bridge] = useState(desktopWindowsBridge); + const gt = useGT(); + const windowsState = useDesktopWindowsState(); + if (bridge === null) return []; + const context = readDesktopWindowContext(); + const currentProfileId = selectCurrentWindowProfile(windowsState, context)?.id ?? null; + + // Off, the saved windows cannot open either. + const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; + const items: CommandPaletteActionItem[] = []; + if (multiWindowEnabled) { + items.push({ + kind: "action", + value: "action:window-new", + title: gt("New Window"), + searchTerms: ["new window", "window", "open window", "multiple windows"], + icon: , + shortcutCommand: "window.new", + run: async () => openNewDesktopWindow(bridge), + }); + for (const profile of windowsState?.profiles ?? []) { + if (profile.isDefault || profile.id === currentProfileId) continue; + items.push({ + kind: "action", + value: `action:window-open:${profile.id}`, + title: gt("Open window: {name}", { name: profile.name }), + searchTerms: ["window", "open window", "saved window", profile.name], + icon: , + run: async () => { + await bridge.openProfile(profile.id).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't open the window"), cause); + }); + }, + }); + } + } + if (context?.isMain === true) { + const miniMode = windowsState?.miniMode === true; + items.push({ + kind: "action", + value: "action:window-mini-mode", + title: miniMode ? gt("Exit Mini Mode") : gt("Enter Mini Mode"), + searchTerms: ["mini mode", "compact", "windows", "usage limits", "collapse", "expand"], + icon: miniMode ? ( + + ) : ( + + ), + run: async () => { + await bridge.setMiniMode(!miniMode).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't change Mini Mode"), cause); + }); + }, + }); + } + return items; +} 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/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 97b278a463e9e..dcffeb3211fd2 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -125,6 +125,7 @@ import { AdvancedSettings } from "./AdvancedSettings"; import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings"; import { StorageCleanupSections } from "./StorageSettings"; import { UpdateTrackSwitchDialog } from "./UpdateTrackSwitchDialog"; +import { WindowsSettingsSection } from "./WindowsSettings"; import { environmentIdsKey } from "~/state/environmentAtomList"; import { environmentSessionStatesAtom } from "~/state/session"; import { useCheckProviderUpdates } from "../ProviderUpdatesAction"; @@ -1131,6 +1132,8 @@ export function GeneralSettingsPanel() { ) : null} + + ; + +// The theme's accent, or its projects' colours, washes a window's row this strongly at the right. +const ROW_THEME_WASH_PERCENT = 16; + +// Select values cannot be null, so following the main window gets a value no theme id has. +const FOLLOW_MAIN_WINDOW_THEME = ":follow-main-window"; +const themeSelectValue = (theme: string | null) => theme ?? FOLLOW_MAIN_WINDOW_THEME; + +/** Saved desktop windows; renders nothing outside a multi-window desktop shell. */ +export function WindowsSettingsSection() { + const [bridge] = useState(desktopWindowsBridge); + return bridge === null ? null : ; +} + +function WindowsSettingsContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const gt = useGT(); + const windowsState = useDesktopWindowsState(); + const projectGroups = useProjectScopeGroups(); + const [creating, setCreating] = useState(false); + const context = readDesktopWindowContext(); + const currentWindow = selectCurrentWindow(windowsState, context); + const profiles = windowsState?.profiles ?? []; + const mainProfile = profiles.find((profile) => profile.isDefault); + const savedProfiles = profiles.filter((profile) => !profile.isDefault); + const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; + const currentProfileId = selectCurrentWindowProfile(windowsState, context)?.id; + + return ( + setCreating(true)} + > + + Add saved window + + } + > + + Open more windows that share this app's connections. Turning this off keeps open windows + open. + + } + control={ + { + bridge.setMultiWindowEnabled(checked).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't change multiple windows"), cause); + }); + }} + /> + } + /> + {currentWindow !== null && !currentWindow.isMain && currentWindow.profileId === null ? ( + + ) : null} + {mainProfile === undefined ? null : ( + + )} + {savedProfiles.length > 0 || creating ? ( + // Saved windows nest under the main window, whose renderer serves them. +
+
+ {savedProfiles.map((profile) => ( + window.profileId === profile.id) ?? false + } + isCurrentWindow={currentProfileId === profile.id} + canOpen={multiWindowEnabled} + /> + ))} + {creating ? ( + setCreating(false)} + /> + ) : null} +
+
+ ) : null} +
+ ); +} + +function SaveCurrentWindowRow({ + bridge, + suggestedName, +}: { + readonly bridge: DesktopWindowsBridge; + readonly suggestedName: string; +}) { + const gt = useGT(); + const [name, setName] = useState(suggestedName); + const [saving, setSaving] = useState(false); + const normalized = normalizeWindowProfileName(name); + const save = () => { + if (normalized === null || saving) return; + setSaving(true); + bridge + .saveAsProfile(normalized) + .catch((cause: unknown) => notifyWindowActionFailure(gt("Couldn't save this window"), cause)) + .finally(() => setSaving(false)); + }; + return ( + Keep this window's project filter and theme so you can reopen it later.} + control={ +
+ setName(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + event.preventDefault(); + save(); + }} + /> + +
+ } + /> + ); +} + +function projectFilterSummary( + projectGroups: ProjectScopeGroups, + keys: readonly string[], + resolve: MessageResolver = resolveMessage, +): string { + const names = projectGroups.groupsForKeys(keys).map((group) => group.displayName); + return names.length === 0 ? resolve(msg("All projects")) : names.join(", "); +} + +interface WindowThemeOption { + readonly value: string; + readonly label: string; + /** A theme's light and dark previews; the project colour option has none. */ + readonly previews: ThemeCardDefinition["previews"]; + /** What a window with this theme shows of it: the theme's accent, or its projects' colours. */ + readonly colors: readonly string[]; +} + +function useWindowThemeOptions(projects: readonly SidebarProjectSnapshot[]): WindowThemeOption[] { + const gt = useGT(); + const themeCards = useThemeCards(); + const appearance = useRenderedAppearance(); + const projectColors = useProjectTintColors(projects); + return [ + // Without a project filter there is no project colour to take on. + { + value: FOLLOW_MAIN_WINDOW_THEME, + label: projects.length > 0 ? gt("Project colour") : gt("Follow main window"), + previews: [], + colors: projectColors, + }, + ...themeCards.map((card) => { + const preview = + card.previews.find((candidate) => candidate.mode === appearance) ?? card.previews[0]; + return { + value: card.id ?? "system", + label: card.label, + previews: card.previews, + colors: preview === undefined ? [] : [preview.colors.accent], + }; + }), + ]; +} + +/** + * The row's wash of its theme's colours, strongest at the right edge and fading to nothing at the + * left. Several colours keep their left-to-right order, each fainter than the one to its right. + */ +function themeWashStyle(options: readonly WindowThemeOption[], theme: string | null) { + const colors = options.find((option) => option.value === themeSelectValue(theme))?.colors ?? []; + if (colors.length === 0) return undefined; + const stops = colors.toReversed().map((color, index) => { + const share = index / colors.length; + return `color-mix(in oklab, ${color} ${ROW_THEME_WASH_PERCENT * (1 - share)}%, transparent) ${share * 100}%`; + }); + return { backgroundImage: `linear-gradient(to left, ${[...stops, "transparent"].join(", ")})` }; +} + +function WindowProfileRow({ + bridge, + profile, + projectGroups, + isOpen, + isCurrentWindow, + canOpen, +}: { + readonly bridge: DesktopWindowsBridge; + readonly profile: DesktopWindowProfile; + readonly projectGroups: ProjectScopeGroups; + readonly isOpen: boolean; + readonly isCurrentWindow: boolean; + readonly canOpen: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const themeOptions = useWindowThemeOptions(projectGroups.groupsForKeys(profile.projectScopeKeys)); + const deleteProfile = async () => { + const confirmed = await requestConfirmDialog( + gt('Delete the saved window "{name}"?\nIf it is open, it stays open as an unsaved window.', { + name: profile.name, + }), + { variant: "destructive" }, + ); + if (confirmed !== true) return; + await bridge.deleteProfile(profile.id).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't delete the saved window"), cause); + }); + }; + + return ( + + + {profile.isDefault ? ( + + {" "} + (main window) + + ) : null} + + } + description={ + profile.isDefault ? ( + Holds the connections and drafts every window shares. + ) : ( + projectFilterSummary(projectGroups, profile.projectScopeKeys, m) + ) + } + style={profile.isDefault ? undefined : themeWashStyle(themeOptions, profile.theme)} + control={ +
+ {profile.isDefault ? null : ( + + )} + {isCurrentWindow || !canOpen ? null : ( + + )} + {profile.isDefault ? null : ( + + void deleteProfile()} + /> + } + > + + + + Delete saved window + + + )} +
+ } + /> + ); +} + +function NewWindowProfileRow({ + bridge, + projectGroups, + onDone, +}: { + readonly bridge: DesktopWindowsBridge; + readonly projectGroups: ProjectScopeGroups; + readonly onDone: () => void; +}) { + const gt = useGT(); + const [name, setName] = useState(""); + const [projectScopeKeys, setProjectScopeKeys] = useState([]); + const [theme, setTheme] = useState(null); + const [saving, setSaving] = useState(false); + const themeOptions = useWindowThemeOptions(projectGroups.groupsForKeys(projectScopeKeys)); + const normalized = normalizeWindowProfileName(name); + const create = () => { + if (normalized === null || saving) return; + setSaving(true); + bridge.createProfile({ name: normalized, projectScopeKeys, theme }).then( + () => onDone(), + (cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't save the window"), cause); + setSaving(false); + }, + ); + }; + return ( + setName(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + event.preventDefault(); + create(); + }} + /> + } + description={Open it later from here, the command palette or the Window menu.} + style={themeWashStyle(themeOptions, theme)} + control={ +
+ + +
+ } + > +
+
+ + +
+
+ + +
+
+
+ ); +} + +function ProjectFilterSelect({ + projectGroups, + value, + onChange, +}: { + readonly projectGroups: ProjectScopeGroups; + readonly value: readonly string[]; + readonly onChange: (keys: readonly string[]) => void; +}) { + const gt = useGT(); + const m = useMessages(); + return ( + + ); +} + +/** A theme's name with swatches of its light and dark colours, or of its projects' colours. */ +function ThemeOptionLabel({ option }: { readonly option: WindowThemeOption }) { + return ( + + {option.label} + + {option.previews.length > 0 + ? option.previews.map((preview) => ( + + )) + : option.colors.map((color) => ( + + ))} + + + ); +} + +function WindowThemeSelect({ + options, + value, + ariaLabel, + fullWidth = false, + onChange, +}: { + readonly options: readonly WindowThemeOption[]; + readonly value: string | null; + readonly ariaLabel: string; + readonly fullWidth?: boolean; + readonly onChange: (theme: string | null) => void; +}) { + const selectValue = themeSelectValue(value); + const selected = options.find((option) => option.value === selectValue); + return ( + + ); +} + +/** A window's name, edited in place where it is shown. */ +function WindowNameInput(props: ComponentProps<"input">) { + return ( + + ); +} + +function ProfileNameInput({ + bridge, + profile, +}: { + readonly bridge: DesktopWindowsBridge; + readonly profile: DesktopWindowProfile; +}) { + const gt = useGT(); + const [draft, setDraft] = useState({ base: profile.name, value: profile.name }); + if (draft.base !== profile.name) setDraft({ base: profile.name, value: profile.name }); + const commit = () => { + const name = normalizeWindowProfileName(draft.value); + if (name === null || name === profile.name) { + setDraft({ base: profile.name, value: profile.name }); + return; + } + bridge.updateProfile({ profileId: profile.id, name }).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't rename the window"), cause); + setDraft({ base: profile.name, value: profile.name }); + }); + }; + return ( + setDraft({ base: profile.name, value: event.target.value })} + onBlur={commit} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing) return; + if (event.key === "Enter") { + event.preventDefault(); + event.currentTarget.blur(); + } else if (event.key === "Escape") { + event.preventDefault(); + setDraft({ base: profile.name, value: profile.name }); + } + }} + /> + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 1f38ed958d368..6400af85dba98 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -933,6 +933,13 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: ["ask before delete stop process shell console history"], }, + { + id: "windows", + title: msg("Windows", { $context: "settings section about the app's windows" }), + to: "/settings/general", + searchTerms: [msg("multiple windows saved window profile theme mini mode new window")], + desktopOnly: true, + }, { id: "quit-confirmation", title: msg("Quit shortcut"), diff --git a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx index 185f8fc8487a5..d7d7a6679ca97 100644 --- a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx @@ -139,7 +139,7 @@ export function SidebarHeaderIconButton({ children?: ReactNode; } & Omit< ComponentProps, - "children" | "className" | "tooltip" | "isActive" | "aria-label" + "children" | "className" | "tooltip" | "aria-label" >) { return ( diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsx index a36b220ee3efa..7cf25ddd295d3 100644 --- a/apps/web/src/components/usage/UsageLimits.tsx +++ b/apps/web/src/components/usage/UsageLimits.tsx @@ -23,6 +23,7 @@ import { Fragment, useLayoutEffect, useState } from "react"; import { usePrimarySettings } from "../../hooks/useSettings"; import { observeResize } from "../../lib/observeResize"; +import { cn } from "../../lib/utils"; import { environmentPresentations } from "../../state/presentation"; import { useEnvironmentScope, readEnvironmentScope } from "../../state/session"; import { serverEnvironment } from "../../state/server"; @@ -125,10 +126,12 @@ function WindowBar({ color, window, now, + className, }: { readonly color: string; readonly window: ServerProviderUsageWindow; readonly now: number; + readonly className?: string; }) { const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); const gt = useGT(); @@ -168,7 +171,10 @@ function WindowBar({ role="img" aria-label={summary} tabIndex={0} - className="relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background" + className={cn( + "relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background", + className, + )} /> } > @@ -262,6 +268,35 @@ export function LimitWindows({ ); } +/** Two limits to a line, each a label, a bar and the percent left; the bar's tooltip says the rest. */ +export function LimitMeters({ + driver, + accentColor, + windows, + now, +}: { + readonly driver: ServerProvider["driver"]; + readonly accentColor?: string | undefined; + readonly windows: ReadonlyArray; + readonly now: number; +}) { + const color = normalizeProviderAccentColor(accentColor) ?? barColor(driver); + return ( +
    + {windows.map((window) => ( +
  • + {window.label} + + {remainingPercent(window)}% +
  • + ))} +
+ ); +} + const OUTCOME_TEXT: Record = { reset: msg("Reset applied. Your windows have cleared."), nothingToReset: msg("Nothing to reset right now."), diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index c6942b7e01c88..4bfcefe2271b9 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -756,6 +756,63 @@ 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, + profileId: null, + projectScopeKeys: [], + theme: null, + }; + 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/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts index 2467d89091b24..9f5acecc6f20e 100644 --- a/apps/web/src/hooks/useTheme.ts +++ b/apps/web/src/hooks/useTheme.ts @@ -130,6 +130,27 @@ let lastDesktopTheme: "light" | "dark" | "system" | null = null; let lastAppliedTheme: Omit | null = null; let themeStorageReadFailure: ThemeStorageError | null = null; +interface WindowThemeOverride { + readonly theme: Theme; + readonly save: (theme: Theme) => void; +} + +// A desktop window with its own theme reads and writes it here, never the shared storage. +let windowThemeOverride: WindowThemeOverride | null = null; + +/** Null makes this window follow the shared theme preference again. */ +export function setWindowThemeOverride(next: WindowThemeOverride | null): void { + const previousTheme = windowThemeOverride?.theme ?? null; + windowThemeOverride = next; + if ((next?.theme ?? null) === previousTheme) return; + applyTheme(getStored(), { suppressTransitions: true }); + emitChange(); +} + +function readEffectiveThemeHalves(): ThemeHalves | null { + return windowThemeOverride === null ? readStoredThemeHalves() : null; +} + function emitChange() { snapshotStale = true; for (const listener of listeners) listener(); @@ -218,6 +239,7 @@ function writeThemePreference(theme: Theme): void { } function getStored(): Theme { + if (windowThemeOverride !== null) return canonicalThemePreference(windowThemeOverride.theme); if (themeStorageReadFailure !== null) { return DEFAULT_THEME_SNAPSHOT.theme; } @@ -311,7 +333,7 @@ function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview const appearanceMode = readAppearanceModePreference(theme); const followSystem = appearanceMode === "system"; const systemDark = followSystem ? getSystemDark() : false; - const themeHalves = readStoredThemeHalves(); + const themeHalves = readEffectiveThemeHalves(); if ( lastAppliedTheme?.theme === theme && lastAppliedTheme.systemDark === systemDark && @@ -366,7 +388,8 @@ function syncDesktopTheme( followSystem?: boolean, appearanceMode?: ThemePreferenceMode, ) { - if (typeof window === "undefined") return; + // The native theme is app-wide, so a window with its own theme must not push it. + if (typeof window === "undefined" || windowThemeOverride !== null) return; const bridge = window.desktopBridge; const halves = readStoredThemeHalves(); const desktopTheme = resolveDesktopTheme(theme, followSystem, appearanceMode, halves); @@ -404,7 +427,7 @@ function getSnapshot(): ThemeSnapshot { const appearanceMode = readAppearanceModePreference(theme); const followSystem = appearanceMode === "system"; const systemDark = followSystem ? getSystemDark() : false; - const themeHalves = readStoredThemeHalves(); + const themeHalves = readEffectiveThemeHalves(); const resolvedTheme = resolveThemeAppearance( theme, @@ -517,6 +540,12 @@ export function useRenderedAppearance() { export function setTheme(next: Theme): boolean { if (typeof window === "undefined") return false; + if (windowThemeOverride !== null) { + const { save } = windowThemeOverride; + setWindowThemeOverride({ theme: next, save }); + save(next); + return true; + } try { // Save the current mode first; inferring it from the new theme can switch dark to light. pipe(getStored(), readAppearanceModePreference, writeAppearanceModePreference); @@ -582,6 +611,8 @@ export function setAppearanceMode(nextAppearanceMode: ThemePreferenceMode): bool function setThemeHalf(appearance: ThemeAppearance, themeId: string | null): boolean { if (typeof window === "undefined") return false; + // A window's own theme is one preference id, so a half choice becomes the whole theme. + if (windowThemeOverride !== null) return themeId === null || setTheme(themeId); try { const current = readStoredThemeHalvesRaw(); const next: { light?: string; dark?: string } = { ...current }; @@ -612,6 +643,7 @@ function setThemeHalf(appearance: ThemeAppearance, themeId: string | null): bool function clearThemeHalves(): boolean { if (typeof window === "undefined") return false; + if (windowThemeOverride !== null) return true; try { window.localStorage.removeItem(THEME_HALVES_STORAGE_KEY); } catch (cause) { diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7900e73186091..95217ac8abd3f 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1969,6 +1969,12 @@ "9c6962c66efa5668": "Darstellung ändern", "074c1660aac1c7cf": "Design-Editor umschalten", "02c340f8d0bb7649": "Aktuell", + "9268423936e5989f": "Neues Fenster", + "a2f254e4f19e2fe4": "Fenster öffnen: {name}", + "188538ba87e9652e": "Fenster konnte nicht geöffnet werden", + "92c1c0f097a72cca": "Mini-Modus beenden", + "320cc15e79d58d96": "Mini-Modus starten", + "e380fd3d2c06377c": "Mini-Modus konnte nicht geändert werden", "b8ec049821ce511c": "Berechtigungen: {label}", "f0d4573b2e03e2a7": "Berechtigungen", "38695f22426981d6": "Vorschau von {path}", @@ -11679,6 +11685,36 @@ ], "625f25278bc683ba": "Gewählte Umgebung (nicht verfügbar)", "e69e34d4f44d4136": "Integriert", + "839ddd6e58f3d585": "Fenster", + "52131da2b0adefe9": "Mehrere Fenster", + "c01fda7b8376b13d": "Mehrere Fenster konnten nicht umgeschaltet werden", + "3caa89d3bd6855e6": "Dieses Fenster konnte nicht gespeichert werden", + "267c6c89c7c660bf": "Dieses Fenster speichern", + "84dcab349acc5493": "Fenstername", + "431911fee26dc1a1": "Projektfarbe", + "4b91dc8c5794c2be": "Wie Hauptfenster", + "e0dd6f7c7f0ff443": "Gespeichertes Fenster „{name}“ löschen?\nWenn es geöffnet ist, bleibt es als nicht gespeichertes Fenster offen.", + "89935e0fe713b694": "Gespeichertes Fenster konnte nicht gelöscht werden", + "ea344357d4e940cc": "Design von {name}", + "45502d1da6eb4a22": "Design des Fensters konnte nicht geändert werden", + "1aec90409a876b7a": "In den Vordergrund", + "d6535a1b0a6be500": "Öffnen", + "3e827ce1777a2c26": "Fenster konnte nicht gespeichert werden", + "61113c0adb210c5b": "Name des neuen Fensters", + "c07399a76925488b": "Neues gespeichertes Fenster", + "30f801cb98794666": "Design des neuen Fensters", + "bd9cc67de51c6bad": "Projekte des neuen Fensters", + "158b4c6263400d75": "Fenster konnte nicht umbenannt werden", + "2166524596f06e50": "Name von {name}", + "20fa0d173479f038": "Gespeichertes Fenster hinzufügen", + "6fdff5142be87c75": "Öffne weitere Fenster, die die Verbindungen dieser App teilen. Beim Ausschalten bleiben geöffnete Fenster offen.", + "fa5a272ce126e94f": "Behalte den Projektfilter und das Design dieses Fensters, um es später wieder zu öffnen.", + "80170559eb36e39b": "(Hauptfenster)", + "e9b167119ae9c73a": "Hält die Verbindungen und Entwürfe, die alle Fenster teilen.", + "20529ca475e73f99": "Design", + "b16163a63f671aec": "Gespeichertes Fenster löschen", + "f9bac4a057bed34d": "Öffne es später hier, über die Befehlspalette oder das Fenster-Menü.", + "3a16e63273d7d383": "Projekte", "ae0b91ed52736998": "Verwendet den neuesten Commit des verfolgten Remote-Branches des Basis-Branches, auch wenn der Name abweicht. Andernfalls den gleichnamigen Branch auf origin. Fehlt dieser Remote-Branch, wird dein lokaler Branch verwendet.", "81f82840d9589bc9": "Neue Worktrees starten vom Remote auf Standard zurücksetzen", "f68e05c50f67ab91": "Neue Worktrees standardmäßig vom Remote starten", @@ -11908,6 +11944,7 @@ "2bb905a7e7cddff7": "vorher fragen thread angeheftet bereich", "53390c9ebb75f5d3": "vorher fragen thread zweiter klick inline aktion", "a26bd55959bfa3d3": "vorher fragen thread chatverlauf", + "e4fed2a24eb4dbcd": "mehrere Fenster gespeichertes Fenster Profil Design Mini-Modus neues Fenster", "de504407a9dfe3bd": "bestätigung desktop app beenden direkt halten doppelklick zweimal drücken", "a8a6da6439b8333e": "generierte thread-titel versionskontrolle inhalt standard anbieter", "0c5fc3b5e41e1956": "generierte thread-titel prompt benutzerdefiniert stil benennung umbenennen neu generieren", @@ -12669,6 +12706,25 @@ "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.", + "0abe9c295ac554fe": "Fenster konnte nicht geschlossen werden", + "87b07debb269d8b7": "Dieses Fenster speichern?", + "b0efb26131c569e7": "Ein gespeichertes Fenster behält seinen Projektfilter und sein Design. Öffne es über die Befehlspalette oder die Einstellungen erneut.", + "a708d8d44263e84d": "Nicht speichern", + "d346177041591bb6": "Mini-Modus konnte nicht verlassen werden", + "834e138d2b26cd6b": "Fenster konnte nicht fokussiert werden", + "fe859444472c3fc5": "Tabs des Mini-Modus", + "d73799a1a5dcdf8e": "Fenster", + "ba6e9ca3c387a18a": "Nutzung", + "cfeadf6c739273b9": "Update", + "15cd4faf32acd232": "Erweitern", + "342704a7a178e7fb": "Keine Pull Requests entsprechen dem Filter der Pull-Request-Seite.", + "478e85d1f1cc8d2d": "Nutzung nicht verfügbar", + "2385e81b6c12dcb9": "Fenster werden geladen", + "2735332f75a23d00": "Im Fokus", + "4dc8634c75ecf2b9": "Nicht gespeichert", + "e99bc76101a1d90c": "Gespeichert", + "737c1e72eafe8151": "Keine weiteren Fenster geöffnet.", + "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..4d063e30f7ec3 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1970,6 +1970,12 @@ "9c6962c66efa5668": "Change appearance", "074c1660aac1c7cf": "Toggle theme editor", "02c340f8d0bb7649": "Current", + "9268423936e5989f": "New Window", + "a2f254e4f19e2fe4": "Open window: {name}", + "188538ba87e9652e": "Couldn't open the window", + "92c1c0f097a72cca": "Exit Mini Mode", + "320cc15e79d58d96": "Enter Mini Mode", + "e380fd3d2c06377c": "Couldn't change Mini Mode", "b8ec049821ce511c": "Permissions: {label}", "f0d4573b2e03e2a7": "Permissions", "38695f22426981d6": "Preview {path}", @@ -11687,6 +11693,36 @@ ], "625f25278bc683ba": "Chosen environment (unavailable)", "e69e34d4f44d4136": "Built-in", + "839ddd6e58f3d585": "Windows", + "52131da2b0adefe9": "Multiple windows", + "c01fda7b8376b13d": "Couldn't change multiple windows", + "3caa89d3bd6855e6": "Couldn't save this window", + "267c6c89c7c660bf": "Save this window", + "84dcab349acc5493": "Window name", + "431911fee26dc1a1": "Project colour", + "4b91dc8c5794c2be": "Follow main window", + "e0dd6f7c7f0ff443": "Delete the saved window \"{name}\"?\nIf it is open, it stays open as an unsaved window.", + "89935e0fe713b694": "Couldn't delete the saved window", + "ea344357d4e940cc": "Theme of {name}", + "45502d1da6eb4a22": "Couldn't change the window theme", + "1aec90409a876b7a": "Focus", + "d6535a1b0a6be500": "Open", + "3e827ce1777a2c26": "Couldn't save the window", + "61113c0adb210c5b": "Name of the new window", + "c07399a76925488b": "New saved window", + "30f801cb98794666": "Theme of the new window", + "bd9cc67de51c6bad": "Projects of the new window", + "158b4c6263400d75": "Couldn't rename the window", + "2166524596f06e50": "Name of {name}", + "20fa0d173479f038": "Add saved window", + "6fdff5142be87c75": "Open more windows that share this app's connections. Turning this off keeps open windows open.", + "fa5a272ce126e94f": "Keep this window's project filter and theme so you can reopen it later.", + "80170559eb36e39b": "(main window)", + "e9b167119ae9c73a": "Holds the connections and drafts every window shares.", + "20529ca475e73f99": "Theme", + "b16163a63f671aec": "Delete saved window", + "f9bac4a057bed34d": "Open it later from here, the command palette or the Window menu.", + "3a16e63273d7d383": "Projects", "ae0b91ed52736998": "Uses the latest commit of the base branch’s tracked remote branch, even if its name differs. Otherwise uses the same-named branch on origin. Uses your local branch if that remote branch is missing.", "81f82840d9589bc9": "Reset new worktrees start from remote to default", "f68e05c50f67ab91": "Start new worktrees from remote by default", @@ -11916,6 +11952,7 @@ "2bb905a7e7cddff7": "ask before thread pinned section", "53390c9ebb75f5d3": "ask before thread second click inline action", "a26bd55959bfa3d3": "ask before thread chat history", + "e4fed2a24eb4dbcd": "multiple windows saved window profile theme mini mode new window", "de504407a9dfe3bd": "confirmation desktop app exit direct hold double click press twice", "a8a6da6439b8333e": "generated thread titles source control content default provider", "0c5fc3b5e41e1956": "generated thread titles prompt custom style naming rename regenerate", @@ -12677,6 +12714,25 @@ "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", "d7ffde2874d60d4f": "Enter a pairing token to continue.", "5d18537f82794deb": "The local environment is disabled.", + "0abe9c295ac554fe": "Couldn't close the window", + "87b07debb269d8b7": "Save this window?", + "b0efb26131c569e7": "A saved window keeps its project filter and theme. Reopen it from the command palette or Settings.", + "a708d8d44263e84d": "Don't Save", + "d346177041591bb6": "Couldn't leave Mini Mode", + "834e138d2b26cd6b": "Couldn't focus the window", + "fe859444472c3fc5": "Mini Mode tabs", + "d73799a1a5dcdf8e": "Windows", + "ba6e9ca3c387a18a": "Usage", + "cfeadf6c739273b9": "Update", + "15cd4faf32acd232": "Expand", + "342704a7a178e7fb": "No pull requests match your Pull requests page filter.", + "478e85d1f1cc8d2d": "Usage unavailable", + "2385e81b6c12dcb9": "Loading windows", + "2735332f75a23d00": "Focused", + "4dc8634c75ecf2b9": "Unsaved", + "e99bc76101a1d90c": "Saved", + "737c1e72eafe8151": "No other windows are open.", + "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..7f5e76850c508 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1970,6 +1970,12 @@ "9c6962c66efa5668": "Cambiar apariencia", "074c1660aac1c7cf": "Mostrar u ocultar el editor de temas", "02c340f8d0bb7649": "Actual", + "9268423936e5989f": "Nueva ventana", + "a2f254e4f19e2fe4": "Abrir ventana: {name}", + "188538ba87e9652e": "No se pudo abrir la ventana", + "92c1c0f097a72cca": "Salir del modo mini", + "320cc15e79d58d96": "Entrar en el modo mini", + "e380fd3d2c06377c": "No se pudo cambiar el modo mini", "b8ec049821ce511c": "Permisos: {label}", "f0d4573b2e03e2a7": "Permisos", "38695f22426981d6": "Vista previa de {path}", @@ -11672,6 +11678,36 @@ ], "625f25278bc683ba": "Entorno elegido (no disponible)", "e69e34d4f44d4136": "Integrado", + "839ddd6e58f3d585": "Ventanas", + "52131da2b0adefe9": "Varias ventanas", + "c01fda7b8376b13d": "No se pudo cambiar la opción de varias ventanas", + "3caa89d3bd6855e6": "No se pudo guardar esta ventana", + "267c6c89c7c660bf": "Guardar esta ventana", + "84dcab349acc5493": "Nombre de la ventana", + "431911fee26dc1a1": "Color del proyecto", + "4b91dc8c5794c2be": "Igual que la ventana principal", + "e0dd6f7c7f0ff443": "¿Eliminar la ventana guardada «{name}»?\nSi está abierta, seguirá abierta como ventana sin guardar.", + "89935e0fe713b694": "No se pudo eliminar la ventana guardada", + "ea344357d4e940cc": "Tema de {name}", + "45502d1da6eb4a22": "No se pudo cambiar el tema de la ventana", + "1aec90409a876b7a": "Mostrar", + "d6535a1b0a6be500": "Abrir", + "3e827ce1777a2c26": "No se pudo guardar la ventana", + "61113c0adb210c5b": "Nombre de la ventana nueva", + "c07399a76925488b": "Nueva ventana guardada", + "30f801cb98794666": "Tema de la ventana nueva", + "bd9cc67de51c6bad": "Proyectos de la ventana nueva", + "158b4c6263400d75": "No se pudo cambiar el nombre de la ventana", + "2166524596f06e50": "Nombre de {name}", + "20fa0d173479f038": "Añadir ventana guardada", + "6fdff5142be87c75": "Abre más ventanas que comparten las conexiones de esta app. Al desactivarlo, las ventanas abiertas siguen abiertas.", + "fa5a272ce126e94f": "Conserva el filtro de proyectos y el tema de esta ventana para volver a abrirla más tarde.", + "80170559eb36e39b": "(ventana principal)", + "e9b167119ae9c73a": "Mantiene las conexiones y los borradores que comparten todas las ventanas.", + "20529ca475e73f99": "Tema", + "b16163a63f671aec": "Eliminar ventana guardada", + "f9bac4a057bed34d": "Ábrela más tarde desde aquí, la paleta de comandos o el menú Ventana.", + "3a16e63273d7d383": "Proyectos", "ae0b91ed52736998": "Usa el último commit de la rama remota a la que sigue la rama base, aunque su nombre sea distinto. Si no, usa la rama con el mismo nombre en origin. Usa tu rama local si falta esa rama remota.", "81f82840d9589bc9": "Restablecer los worktrees nuevos empiezan desde el remoto al valor predeterminado", "f68e05c50f67ab91": "Crear los worktrees nuevos desde el remoto por defecto", @@ -11901,6 +11937,7 @@ "2bb905a7e7cddff7": "preguntar antes hilo sección fijados", "53390c9ebb75f5d3": "preguntar antes hilo segundo clic acción en línea", "a26bd55959bfa3d3": "preguntar antes hilo historial de chat", + "e4fed2a24eb4dbcd": "varias ventanas ventana guardada perfil tema modo mini nueva ventana", "de504407a9dfe3bd": "confirmación app de escritorio salir directo mantener doble clic pulsar dos veces", "a8a6da6439b8333e": "títulos de hilos generados control de versiones contenido proveedor predeterminado", "0c5fc3b5e41e1956": "títulos de hilos generados prompt estilo personalizado nombres renombrar regenerar", @@ -12662,6 +12699,25 @@ "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.", + "0abe9c295ac554fe": "No se pudo cerrar la ventana", + "87b07debb269d8b7": "¿Guardar esta ventana?", + "b0efb26131c569e7": "Una ventana guardada conserva su filtro de proyectos y su tema. Vuelve a abrirla desde la paleta de comandos o Ajustes.", + "a708d8d44263e84d": "No guardar", + "d346177041591bb6": "No se pudo salir del modo mini", + "834e138d2b26cd6b": "No se pudo enfocar la ventana", + "fe859444472c3fc5": "Pestañas del modo mini", + "d73799a1a5dcdf8e": "Ventanas", + "ba6e9ca3c387a18a": "Uso", + "cfeadf6c739273b9": "Actualización", + "15cd4faf32acd232": "Expandir", + "342704a7a178e7fb": "Ningún pull request coincide con el filtro de la página Pull requests.", + "478e85d1f1cc8d2d": "Uso no disponible", + "2385e81b6c12dcb9": "Cargando ventanas", + "2735332f75a23d00": "Activa", + "4dc8634c75ecf2b9": "Sin guardar", + "e99bc76101a1d90c": "Guardada", + "737c1e72eafe8151": "No hay otras ventanas abiertas.", + "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..91d2627f73cdb 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1970,6 +1970,12 @@ "9c6962c66efa5668": "Changer l’apparence", "074c1660aac1c7cf": "Afficher/masquer l’éditeur de thème", "02c340f8d0bb7649": "Actuel", + "9268423936e5989f": "Nouvelle fenêtre", + "a2f254e4f19e2fe4": "Ouvrir la fenêtre : {name}", + "188538ba87e9652e": "Impossible d’ouvrir la fenêtre", + "92c1c0f097a72cca": "Quitter le mode mini", + "320cc15e79d58d96": "Passer en mode mini", + "e380fd3d2c06377c": "Impossible de changer le mode mini", "b8ec049821ce511c": "Autorisations : {label}", "f0d4573b2e03e2a7": "Autorisations", "38695f22426981d6": "Aperçu de {path}", @@ -11677,6 +11683,36 @@ ], "625f25278bc683ba": "Environnement choisi (indisponible)", "e69e34d4f44d4136": "Intégrées", + "839ddd6e58f3d585": "Fenêtres", + "52131da2b0adefe9": "Plusieurs fenêtres", + "c01fda7b8376b13d": "Impossible de modifier l’option Plusieurs fenêtres", + "3caa89d3bd6855e6": "Impossible d’enregistrer cette fenêtre", + "267c6c89c7c660bf": "Enregistrer cette fenêtre", + "84dcab349acc5493": "Nom de la fenêtre", + "431911fee26dc1a1": "Couleur du projet", + "4b91dc8c5794c2be": "Comme la fenêtre principale", + "e0dd6f7c7f0ff443": "Supprimer la fenêtre enregistrée « {name} » ?\nSi elle est ouverte, elle reste ouverte comme fenêtre non enregistrée.", + "89935e0fe713b694": "Impossible de supprimer la fenêtre enregistrée", + "ea344357d4e940cc": "Thème de {name}", + "45502d1da6eb4a22": "Impossible de changer le thème de la fenêtre", + "1aec90409a876b7a": "Afficher", + "d6535a1b0a6be500": "Ouvrir", + "3e827ce1777a2c26": "Impossible d’enregistrer la fenêtre", + "61113c0adb210c5b": "Nom de la nouvelle fenêtre", + "c07399a76925488b": "Nouvelle fenêtre enregistrée", + "30f801cb98794666": "Thème de la nouvelle fenêtre", + "bd9cc67de51c6bad": "Projets de la nouvelle fenêtre", + "158b4c6263400d75": "Impossible de renommer la fenêtre", + "2166524596f06e50": "Nom de {name}", + "20fa0d173479f038": "Ajouter une fenêtre enregistrée", + "6fdff5142be87c75": "Ouvrez d’autres fenêtres qui partagent les connexions de cette app. Désactiver l’option laisse les fenêtres ouvertes.", + "fa5a272ce126e94f": "Conservez le filtre de projets et le thème de cette fenêtre pour la rouvrir plus tard.", + "80170559eb36e39b": "(fenêtre principale)", + "e9b167119ae9c73a": "Contient les connexions et les brouillons partagés par toutes les fenêtres.", + "20529ca475e73f99": "Thème", + "b16163a63f671aec": "Supprimer la fenêtre enregistrée", + "f9bac4a057bed34d": "Ouvrez-la plus tard d’ici, depuis la palette de commandes ou le menu Fenêtre.", + "3a16e63273d7d383": "Projets", "ae0b91ed52736998": "Utilise le dernier commit de la branche distante suivie par la branche de base, même si son nom diffère. Sinon, utilise la branche du même nom sur origin. Utilise votre branche locale si cette branche distante n’existe pas.", "81f82840d9589bc9": "Réinitialiser le démarrage des nouveaux worktrees depuis le remote à la valeur par défaut", "f68e05c50f67ab91": "Faire partir les nouveaux worktrees du distant par défaut", @@ -11906,6 +11942,7 @@ "2bb905a7e7cddff7": "demander avant fil section épinglée", "53390c9ebb75f5d3": "demander avant fil second clic action en ligne", "a26bd55959bfa3d3": "demander avant fil historique de discussion", + "e4fed2a24eb4dbcd": "plusieurs fenêtres fenêtre enregistrée profil thème mode mini nouvelle fenêtre", "de504407a9dfe3bd": "confirmation app de bureau quitter direct maintenir double clic appuyer deux fois", "a8a6da6439b8333e": "titres de fils générés gestion de versions contenu fournisseur par défaut", "0c5fc3b5e41e1956": "titres de fils générés prompt style personnalisé nommage renommer régénérer", @@ -12667,6 +12704,25 @@ "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é.", + "0abe9c295ac554fe": "Impossible de fermer la fenêtre", + "87b07debb269d8b7": "Enregistrer cette fenêtre ?", + "b0efb26131c569e7": "Une fenêtre enregistrée conserve son filtre de projets et son thème. Rouvrez-la depuis la palette de commandes ou les Paramètres.", + "a708d8d44263e84d": "Ne pas enregistrer", + "d346177041591bb6": "Impossible de quitter le mode mini", + "834e138d2b26cd6b": "Impossible d’afficher la fenêtre", + "fe859444472c3fc5": "Onglets du mode mini", + "d73799a1a5dcdf8e": "Fenêtres", + "ba6e9ca3c387a18a": "Utilisation", + "cfeadf6c739273b9": "Mise à jour", + "15cd4faf32acd232": "Agrandir", + "342704a7a178e7fb": "Aucune pull request ne correspond au filtre de la page Pull requests.", + "478e85d1f1cc8d2d": "Utilisation indisponible", + "2385e81b6c12dcb9": "Chargement des fenêtres", + "2735332f75a23d00": "Active", + "4dc8634c75ecf2b9": "Non enregistrée", + "e99bc76101a1d90c": "Enregistrée", + "737c1e72eafe8151": "Aucune autre fenêtre n’est ouverte.", + "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..d98d5cad00014 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1968,6 +1968,12 @@ "9c6962c66efa5668": "外観を変更", "074c1660aac1c7cf": "テーマエディターの切り替え", "02c340f8d0bb7649": "使用中", + "9268423936e5989f": "新しいウィンドウ", + "a2f254e4f19e2fe4": "ウィンドウを開く: {name}", + "188538ba87e9652e": "ウィンドウを開けませんでした", + "92c1c0f097a72cca": "ミニモードを終了", + "320cc15e79d58d96": "ミニモードに切り替え", + "e380fd3d2c06377c": "ミニモードを切り替えられませんでした", "b8ec049821ce511c": "権限: {label}", "f0d4573b2e03e2a7": "権限", "38695f22426981d6": "{path} をプレビュー", @@ -11628,6 +11634,36 @@ ], "625f25278bc683ba": "選択した環境 (利用不可)", "e69e34d4f44d4136": "組み込み", + "839ddd6e58f3d585": "ウィンドウ", + "52131da2b0adefe9": "複数のウィンドウ", + "c01fda7b8376b13d": "複数のウィンドウの設定を変更できませんでした", + "3caa89d3bd6855e6": "このウィンドウを保存できませんでした", + "267c6c89c7c660bf": "このウィンドウを保存", + "84dcab349acc5493": "ウィンドウ名", + "431911fee26dc1a1": "プロジェクトの色", + "4b91dc8c5794c2be": "メインウィンドウに合わせる", + "e0dd6f7c7f0ff443": "保存済みウィンドウ「{name}」を削除しますか?\n開いている場合は、未保存のウィンドウとして開いたままになります。", + "89935e0fe713b694": "保存済みウィンドウを削除できませんでした", + "ea344357d4e940cc": "{name} のテーマ", + "45502d1da6eb4a22": "ウィンドウのテーマを変更できませんでした", + "1aec90409a876b7a": "前面に表示", + "d6535a1b0a6be500": "開く", + "3e827ce1777a2c26": "ウィンドウを保存できませんでした", + "61113c0adb210c5b": "新しいウィンドウの名前", + "c07399a76925488b": "新しい保存済みウィンドウ", + "30f801cb98794666": "新しいウィンドウのテーマ", + "bd9cc67de51c6bad": "新しいウィンドウのプロジェクト", + "158b4c6263400d75": "ウィンドウの名前を変更できませんでした", + "2166524596f06e50": "{name} の名前", + "20fa0d173479f038": "保存済みウィンドウを追加", + "6fdff5142be87c75": "このアプリの接続を共有するウィンドウを追加で開けます。オフにしても、開いているウィンドウはそのまま開いています。", + "fa5a272ce126e94f": "このウィンドウのプロジェクトフィルターとテーマを保存して、あとで開き直せるようにします。", + "80170559eb36e39b": "(メインウィンドウ)", + "e9b167119ae9c73a": "すべてのウィンドウが共有する接続と下書きを保持します。", + "20529ca475e73f99": "テーマ", + "b16163a63f671aec": "保存済みウィンドウを削除", + "f9bac4a057bed34d": "あとでここ、コマンドパレット、またはウィンドウメニューから開けます。", + "3a16e63273d7d383": "プロジェクト", "ae0b91ed52736998": "ベースブランチが追跡しているリモートブランチの最新コミットを使用します (名前が異なる場合も含む)。それ以外の場合は origin 上の同名ブランチを使用します。そのリモートブランチがない場合はローカルブランチを使用します。", "81f82840d9589bc9": "「新しいワークツリーをリモートから開始」をデフォルトにリセット", "f68e05c50f67ab91": "デフォルトで新しいワークツリーをリモートから開始", @@ -11857,6 +11893,7 @@ "2bb905a7e7cddff7": "確認 スレッド ピン留め セクション unpin", "53390c9ebb75f5d3": "確認 スレッド 2 回目のクリック インライン 操作 archive", "a26bd55959bfa3d3": "確認 スレッド チャット履歴 delete", + "e4fed2a24eb4dbcd": "複数のウィンドウ 保存済みウィンドウ プロファイル テーマ ミニモード 新しいウィンドウ", "de504407a9dfe3bd": "確認 デスクトップアプリ 終了 即時 長押し ダブルクリック 2 回押し quit", "a8a6da6439b8333e": "生成 スレッドタイトル ソース管理 コンテンツ デフォルト プロバイダー titles", "0c5fc3b5e41e1956": "生成 スレッドタイトル プロンプト カスタム スタイル 命名 名前の変更 再生成 titles", @@ -12610,6 +12647,25 @@ "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", "d7ffde2874d60d4f": "続行するにはペアリングトークンを入力してください。", "5d18537f82794deb": "ローカル環境は無効になっています。", + "0abe9c295ac554fe": "ウィンドウを閉じられませんでした", + "87b07debb269d8b7": "このウィンドウを保存しますか?", + "b0efb26131c569e7": "保存したウィンドウはプロジェクトフィルターとテーマを保持します。コマンドパレットまたは設定から開き直せます。", + "a708d8d44263e84d": "保存しない", + "d346177041591bb6": "ミニモードを終了できませんでした", + "834e138d2b26cd6b": "ウィンドウを前面に表示できませんでした", + "fe859444472c3fc5": "ミニモードのタブ", + "d73799a1a5dcdf8e": "ウィンドウ", + "ba6e9ca3c387a18a": "使用量", + "cfeadf6c739273b9": "アップデート", + "15cd4faf32acd232": "展開", + "342704a7a178e7fb": "プルリクエストページのフィルターに一致するプルリクエストはありません。", + "478e85d1f1cc8d2d": "使用量を取得できません", + "2385e81b6c12dcb9": "ウィンドウを読み込み中", + "2735332f75a23d00": "フォーカス中", + "4dc8634c75ecf2b9": "未保存", + "e99bc76101a1d90c": "保存済み", + "737c1e72eafe8151": "ほかに開いているウィンドウはありません。", + "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..d087f0893aa53 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1970,6 +1970,12 @@ "9c6962c66efa5668": "모양 변경", "074c1660aac1c7cf": "테마 편집기 전환", "02c340f8d0bb7649": "현재", + "9268423936e5989f": "새 창", + "a2f254e4f19e2fe4": "창 열기: {name}", + "188538ba87e9652e": "창을 열 수 없습니다", + "92c1c0f097a72cca": "미니 모드 종료", + "320cc15e79d58d96": "미니 모드 시작", + "e380fd3d2c06377c": "미니 모드를 변경할 수 없습니다", "b8ec049821ce511c": "권한: {label}", "f0d4573b2e03e2a7": "권한", "38695f22426981d6": "{path} 미리 보기", @@ -11624,6 +11630,36 @@ ], "625f25278bc683ba": "선택한 환경(사용할 수 없음)", "e69e34d4f44d4136": "기본 제공", + "839ddd6e58f3d585": "창", + "52131da2b0adefe9": "여러 창", + "c01fda7b8376b13d": "여러 창 설정을 변경할 수 없습니다", + "3caa89d3bd6855e6": "이 창을 저장할 수 없습니다", + "267c6c89c7c660bf": "이 창 저장", + "84dcab349acc5493": "창 이름", + "431911fee26dc1a1": "프로젝트 색상", + "4b91dc8c5794c2be": "기본 창과 동일", + "e0dd6f7c7f0ff443": "저장된 창 \"{name}\"을(를) 삭제할까요?\n열려 있으면 저장되지 않은 창으로 계속 열려 있습니다.", + "89935e0fe713b694": "저장된 창을 삭제할 수 없습니다", + "ea344357d4e940cc": "{name}의 테마", + "45502d1da6eb4a22": "창 테마를 변경할 수 없습니다", + "1aec90409a876b7a": "앞으로 가져오기", + "d6535a1b0a6be500": "열기", + "3e827ce1777a2c26": "창을 저장할 수 없습니다", + "61113c0adb210c5b": "새 창 이름", + "c07399a76925488b": "새로 저장된 창", + "30f801cb98794666": "새 창 테마", + "bd9cc67de51c6bad": "새 창의 프로젝트", + "158b4c6263400d75": "창 이름을 바꿀 수 없습니다", + "2166524596f06e50": "{name}의 이름", + "20fa0d173479f038": "저장된 창 추가", + "6fdff5142be87c75": "이 앱의 연결을 공유하는 창을 더 엽니다. 끄더라도 열려 있는 창은 그대로 열려 있습니다.", + "fa5a272ce126e94f": "이 창의 프로젝트 필터와 테마를 저장해 나중에 다시 열 수 있습니다.", + "80170559eb36e39b": "(기본 창)", + "e9b167119ae9c73a": "모든 창이 공유하는 연결과 초안을 보관합니다.", + "20529ca475e73f99": "테마", + "b16163a63f671aec": "저장된 창 삭제", + "f9bac4a057bed34d": "나중에 여기, 명령 팔레트 또는 창 메뉴에서 열 수 있습니다.", + "3a16e63273d7d383": "프로젝트", "ae0b91ed52736998": "기준 브랜치가 추적하는 원격 브랜치의 최신 커밋을 사용하며, 이름이 달라도 마찬가지입니다. 그렇지 않으면 origin의 같은 이름 브랜치를 사용합니다. 해당 원격 브랜치가 없으면 로컬 브랜치를 사용합니다.", "81f82840d9589bc9": "새 워크트리를 원격에서 시작 기본값으로 재설정", "f68e05c50f67ab91": "기본적으로 새 워크트리를 원격에서 시작", @@ -11853,6 +11889,7 @@ "2bb905a7e7cddff7": "스레드 확인 요청 고정 섹션", "53390c9ebb75f5d3": "스레드 확인 요청 두 번 클릭 인라인 작업", "a26bd55959bfa3d3": "스레드 확인 요청 채팅 기록", + "e4fed2a24eb4dbcd": "여러 창 저장된 창 프로필 테마 미니 모드 새 창", "de504407a9dfe3bd": "확인 데스크톱 앱 종료 바로 길게 누르기 두 번 클릭 두 번 누르기", "a8a6da6439b8333e": "생성된 스레드 제목 소스 제어 콘텐츠 기본 제공자", "0c5fc3b5e41e1956": "생성된 스레드 제목 프롬프트 사용자 지정 스타일 이름 지정 이름 바꾸기 다시 생성", @@ -12607,6 +12644,25 @@ "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", "d7ffde2874d60d4f": "계속하려면 페어링 토큰을 입력하세요.", "5d18537f82794deb": "로컬 환경이 꺼져 있습니다.", + "0abe9c295ac554fe": "창을 닫을 수 없습니다", + "87b07debb269d8b7": "이 창을 저장할까요?", + "b0efb26131c569e7": "저장된 창은 프로젝트 필터와 테마를 유지합니다. 명령 팔레트나 설정에서 다시 열 수 있습니다.", + "a708d8d44263e84d": "저장 안 함", + "d346177041591bb6": "미니 모드를 종료할 수 없습니다", + "834e138d2b26cd6b": "창으로 전환할 수 없습니다", + "fe859444472c3fc5": "미니 모드 탭", + "d73799a1a5dcdf8e": "창", + "ba6e9ca3c387a18a": "사용량", + "cfeadf6c739273b9": "업데이트", + "15cd4faf32acd232": "확장", + "342704a7a178e7fb": "풀 리퀘스트 페이지 필터와 일치하는 풀 리퀘스트가 없습니다.", + "478e85d1f1cc8d2d": "사용량을 확인할 수 없음", + "2385e81b6c12dcb9": "창 불러오는 중", + "2735332f75a23d00": "포커스됨", + "4dc8634c75ecf2b9": "저장 안 됨", + "e99bc76101a1d90c": "저장됨", + "737c1e72eafe8151": "열려 있는 다른 창이 없습니다.", + "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..bca8c42d6b6c7 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1970,6 +1970,12 @@ "9c6962c66efa5668": "Mudar aparência", "074c1660aac1c7cf": "Alternar editor de temas", "02c340f8d0bb7649": "Atual", + "9268423936e5989f": "Nova janela", + "a2f254e4f19e2fe4": "Abrir janela: {name}", + "188538ba87e9652e": "Não foi possível abrir a janela", + "92c1c0f097a72cca": "Sair do modo mini", + "320cc15e79d58d96": "Entrar no modo mini", + "e380fd3d2c06377c": "Não foi possível alterar o modo mini", "b8ec049821ce511c": "Permissões: {label}", "f0d4573b2e03e2a7": "Permissões", "38695f22426981d6": "Pré-visualizar {path}", @@ -11677,6 +11683,36 @@ ], "625f25278bc683ba": "Ambiente escolhido (indisponível)", "e69e34d4f44d4136": "Integrado", + "839ddd6e58f3d585": "Janelas", + "52131da2b0adefe9": "Várias janelas", + "c01fda7b8376b13d": "Não foi possível alterar a opção de várias janelas", + "3caa89d3bd6855e6": "Não foi possível salvar esta janela", + "267c6c89c7c660bf": "Salvar esta janela", + "84dcab349acc5493": "Nome da janela", + "431911fee26dc1a1": "Cor do projeto", + "4b91dc8c5794c2be": "Igual à janela principal", + "e0dd6f7c7f0ff443": "Excluir a janela salva \"{name}\"?\nSe estiver aberta, ela continuará aberta como uma janela não salva.", + "89935e0fe713b694": "Não foi possível excluir a janela salva", + "ea344357d4e940cc": "Tema de {name}", + "45502d1da6eb4a22": "Não foi possível alterar o tema da janela", + "1aec90409a876b7a": "Mostrar", + "d6535a1b0a6be500": "Abrir", + "3e827ce1777a2c26": "Não foi possível salvar a janela", + "61113c0adb210c5b": "Nome da nova janela", + "c07399a76925488b": "Nova janela salva", + "30f801cb98794666": "Tema da nova janela", + "bd9cc67de51c6bad": "Projetos da nova janela", + "158b4c6263400d75": "Não foi possível renomear a janela", + "2166524596f06e50": "Nome de {name}", + "20fa0d173479f038": "Adicionar janela salva", + "6fdff5142be87c75": "Abra mais janelas que compartilham as conexões deste app. Ao desativar, as janelas abertas continuam abertas.", + "fa5a272ce126e94f": "Mantenha o filtro de projetos e o tema desta janela para reabri-la depois.", + "80170559eb36e39b": "(janela principal)", + "e9b167119ae9c73a": "Mantém as conexões e os rascunhos que todas as janelas compartilham.", + "20529ca475e73f99": "Tema", + "b16163a63f671aec": "Excluir janela salva", + "f9bac4a057bed34d": "Abra depois por aqui, pela paleta de comandos ou pelo menu Janela.", + "3a16e63273d7d383": "Projetos", "ae0b91ed52736998": "Usa o commit mais recente do branch remoto rastreado pelo branch base, mesmo que o nome seja diferente. Caso contrário, usa o branch de mesmo nome no origin. Usa seu branch local se esse branch remoto não existir.", "81f82840d9589bc9": "Redefinir \"Novos worktrees começam a partir do remoto\" para o padrão", "f68e05c50f67ab91": "Iniciar novos worktrees do remoto por padrão", @@ -11906,6 +11942,7 @@ "2bb905a7e7cddff7": "perguntar antes thread seção de fixadas", "53390c9ebb75f5d3": "perguntar antes thread segundo clique ação inline", "a26bd55959bfa3d3": "perguntar antes thread histórico do chat", + "e4fed2a24eb4dbcd": "várias janelas janela salva perfil tema modo mini nova janela", "de504407a9dfe3bd": "confirmação app desktop sair imediato manter pressionado clique duplo pressionar duas vezes", "a8a6da6439b8333e": "títulos gerados de threads controle de versão conteúdo provedor padrão", "0c5fc3b5e41e1956": "títulos gerados de threads prompt estilo personalizado nomenclatura renomear gerar novamente", @@ -12667,6 +12704,25 @@ "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.", + "0abe9c295ac554fe": "Não foi possível fechar a janela", + "87b07debb269d8b7": "Salvar esta janela?", + "b0efb26131c569e7": "Uma janela salva mantém o filtro de projetos e o tema. Reabra-a pela paleta de comandos ou pelas Configurações.", + "a708d8d44263e84d": "Não salvar", + "d346177041591bb6": "Não foi possível sair do modo mini", + "834e138d2b26cd6b": "Não foi possível focar a janela", + "fe859444472c3fc5": "Abas do modo mini", + "d73799a1a5dcdf8e": "Janelas", + "ba6e9ca3c387a18a": "Uso", + "cfeadf6c739273b9": "Atualização", + "15cd4faf32acd232": "Expandir", + "342704a7a178e7fb": "Nenhum pull request corresponde ao filtro da página Pull requests.", + "478e85d1f1cc8d2d": "Uso indisponível", + "2385e81b6c12dcb9": "Carregando janelas", + "2735332f75a23d00": "Em foco", + "4dc8634c75ecf2b9": "Não salva", + "e99bc76101a1d90c": "Salva", + "737c1e72eafe8151": "Nenhuma outra janela está aberta.", + "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..332c2a2a50516 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1970,6 +1970,12 @@ "9c6962c66efa5668": "Изменить оформление", "074c1660aac1c7cf": "Показать/скрыть редактор темы", "02c340f8d0bb7649": "Текущая", + "9268423936e5989f": "Новое окно", + "a2f254e4f19e2fe4": "Открыть окно: {name}", + "188538ba87e9652e": "Не удалось открыть окно", + "92c1c0f097a72cca": "Выйти из мини-режима", + "320cc15e79d58d96": "Включить мини-режим", + "e380fd3d2c06377c": "Не удалось переключить мини-режим", "b8ec049821ce511c": "Разрешения: {label}", "f0d4573b2e03e2a7": "Разрешения", "38695f22426981d6": "Предпросмотр {path}", @@ -11678,6 +11684,36 @@ ], "625f25278bc683ba": "Выбранное окружение (недоступно)", "e69e34d4f44d4136": "Встроенные", + "839ddd6e58f3d585": "Окна", + "52131da2b0adefe9": "Несколько окон", + "c01fda7b8376b13d": "Не удалось изменить режим нескольких окон", + "3caa89d3bd6855e6": "Не удалось сохранить это окно", + "267c6c89c7c660bf": "Сохранить это окно", + "84dcab349acc5493": "Название окна", + "431911fee26dc1a1": "Цвет проекта", + "4b91dc8c5794c2be": "Как в главном окне", + "e0dd6f7c7f0ff443": "Удалить сохранённое окно «{name}»?\nЕсли оно открыто, оно останется открытым как несохранённое окно.", + "89935e0fe713b694": "Не удалось удалить сохранённое окно", + "ea344357d4e940cc": "Тема окна {name}", + "45502d1da6eb4a22": "Не удалось изменить тему окна", + "1aec90409a876b7a": "Показать", + "d6535a1b0a6be500": "Открыть", + "3e827ce1777a2c26": "Не удалось сохранить окно", + "61113c0adb210c5b": "Название нового окна", + "c07399a76925488b": "Новое сохранённое окно", + "30f801cb98794666": "Тема нового окна", + "bd9cc67de51c6bad": "Проекты нового окна", + "158b4c6263400d75": "Не удалось переименовать окно", + "2166524596f06e50": "Название окна {name}", + "20fa0d173479f038": "Добавить сохранённое окно", + "6fdff5142be87c75": "Открывайте дополнительные окна с общими подключениями этого приложения. Если выключить, открытые окна останутся открытыми.", + "fa5a272ce126e94f": "Сохраните фильтр проектов и тему этого окна, чтобы открыть его позже.", + "80170559eb36e39b": "(главное окно)", + "e9b167119ae9c73a": "Хранит подключения и черновики, общие для всех окон.", + "20529ca475e73f99": "Тема", + "b16163a63f671aec": "Удалить сохранённое окно", + "f9bac4a057bed34d": "Откройте его позже здесь, из палитры команд или меню «Окно».", + "3a16e63273d7d383": "Проекты", "ae0b91ed52736998": "Использует последний коммит удалённой ветки, которую отслеживает базовая ветка, даже если её имя отличается. Иначе использует одноимённую ветку на origin. Если удалённой ветки нет, используется локальная.", "81f82840d9589bc9": "Сбросить «Начинать с удалённой ветки» к значению по умолчанию", "f68e05c50f67ab91": "По умолчанию начинать новые рабочие деревья с удалённой ветки", @@ -11907,6 +11943,7 @@ "2bb905a7e7cddff7": "спрашивать перед тред закреплённые раздел", "53390c9ebb75f5d3": "спрашивать перед тред повторное нажатие кнопка в строке", "a26bd55959bfa3d3": "спрашивать перед тред история чата", + "e4fed2a24eb4dbcd": "несколько окон сохранённое окно профиль тема мини-режим новое окно", "de504407a9dfe3bd": "подтверждение десктоп приложение выход одно нажатие удержание двойное нажатие нажать дважды", "a8a6da6439b8333e": "генерируемые заголовки тредов контроль версий содержимое провайдер по умолчанию", "0c5fc3b5e41e1956": "генерируемые заголовки тредов промпт свой стиль именование переименовать сгенерировать заново", @@ -12668,6 +12705,25 @@ "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", "d7ffde2874d60d4f": "Введите токен сопряжения, чтобы продолжить.", "5d18537f82794deb": "Локальное окружение отключено.", + "0abe9c295ac554fe": "Не удалось закрыть окно", + "87b07debb269d8b7": "Сохранить это окно?", + "b0efb26131c569e7": "Сохранённое окно сохраняет фильтр проектов и тему. Откройте его снова из палитры команд или настроек.", + "a708d8d44263e84d": "Не сохранять", + "d346177041591bb6": "Не удалось выйти из мини-режима", + "834e138d2b26cd6b": "Не удалось переключиться на окно", + "fe859444472c3fc5": "Вкладки мини-режима", + "d73799a1a5dcdf8e": "Окна", + "ba6e9ca3c387a18a": "Использование", + "cfeadf6c739273b9": "Обновление", + "15cd4faf32acd232": "Развернуть", + "342704a7a178e7fb": "Нет пул-реквестов, подходящих под фильтр страницы пул-реквестов.", + "478e85d1f1cc8d2d": "Данные об использовании недоступны", + "2385e81b6c12dcb9": "Загрузка окон", + "2735332f75a23d00": "Активно", + "4dc8634c75ecf2b9": "Не сохранено", + "e99bc76101a1d90c": "Сохранено", + "737c1e72eafe8151": "Других открытых окон нет.", + "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..948e84005d646 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1970,6 +1970,12 @@ "9c6962c66efa5668": "Ändra utseende", "074c1660aac1c7cf": "Växla temaredigerare", "02c340f8d0bb7649": "Aktuellt", + "9268423936e5989f": "Nytt fönster", + "a2f254e4f19e2fe4": "Öppna fönster: {name}", + "188538ba87e9652e": "Kunde inte öppna fönstret", + "92c1c0f097a72cca": "Avsluta miniläge", + "320cc15e79d58d96": "Starta miniläge", + "e380fd3d2c06377c": "Kunde inte ändra miniläget", "b8ec049821ce511c": "Behörigheter: {label}", "f0d4573b2e03e2a7": "Behörigheter", "38695f22426981d6": "Förhandsvisa {path}", @@ -11685,6 +11691,36 @@ ], "625f25278bc683ba": "Vald miljö (inte tillgänglig)", "e69e34d4f44d4136": "Inbyggd", + "839ddd6e58f3d585": "Fönster", + "52131da2b0adefe9": "Flera fönster", + "c01fda7b8376b13d": "Kunde inte ändra inställningen för flera fönster", + "3caa89d3bd6855e6": "Kunde inte spara det här fönstret", + "267c6c89c7c660bf": "Spara det här fönstret", + "84dcab349acc5493": "Fönsternamn", + "431911fee26dc1a1": "Projektfärg", + "4b91dc8c5794c2be": "Samma som huvudfönstret", + "e0dd6f7c7f0ff443": "Ta bort det sparade fönstret ”{name}”?\nOm det är öppet förblir det öppet som ett osparat fönster.", + "89935e0fe713b694": "Kunde inte ta bort det sparade fönstret", + "ea344357d4e940cc": "Tema för {name}", + "45502d1da6eb4a22": "Kunde inte ändra fönstrets tema", + "1aec90409a876b7a": "Visa", + "d6535a1b0a6be500": "Öppna", + "3e827ce1777a2c26": "Kunde inte spara fönstret", + "61113c0adb210c5b": "Namn på det nya fönstret", + "c07399a76925488b": "Nytt sparat fönster", + "30f801cb98794666": "Tema för det nya fönstret", + "bd9cc67de51c6bad": "Projekt för det nya fönstret", + "158b4c6263400d75": "Kunde inte byta namn på fönstret", + "2166524596f06e50": "Namn på {name}", + "20fa0d173479f038": "Lägg till sparat fönster", + "6fdff5142be87c75": "Öppna fler fönster som delar appens anslutningar. Om du stänger av det förblir öppna fönster öppna.", + "fa5a272ce126e94f": "Behåll fönstrets projektfilter och tema så att du kan öppna det igen senare.", + "80170559eb36e39b": "(huvudfönster)", + "e9b167119ae9c73a": "Håller anslutningarna och utkasten som alla fönster delar.", + "20529ca475e73f99": "Tema", + "b16163a63f671aec": "Ta bort sparat fönster", + "f9bac4a057bed34d": "Öppna det senare här, från kommandopaletten eller Fönster-menyn.", + "3a16e63273d7d383": "Projekt", "ae0b91ed52736998": "Använder den senaste commiten i basgrenens spårade fjärrgren, även om namnet skiljer sig. Annars används grenen med samma namn på origin. Använder din lokala gren om fjärrgrenen saknas.", "81f82840d9589bc9": "Återställ nya worktrees startar från fjärr till standard", "f68e05c50f67ab91": "Starta nya worktrees från fjärrgrenen som standard", @@ -11914,6 +11950,7 @@ "2bb905a7e7cddff7": "fråga före tråd fästa avsnitt", "53390c9ebb75f5d3": "fråga före tråd andra klick inline-åtgärd", "a26bd55959bfa3d3": "fråga före tråd chatthistorik", + "e4fed2a24eb4dbcd": "flera fönster sparat fönster profil tema miniläge nytt fönster", "de504407a9dfe3bd": "bekräftelse skrivbordsapp avsluta direkt håll dubbelklicka tryck två gånger", "a8a6da6439b8333e": "genererade trådtitlar versionshantering innehåll standardleverantör", "0c5fc3b5e41e1956": "genererade trådtitlar prompt anpassad stil namngivning byt namn generera om", @@ -12675,6 +12712,25 @@ "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.", + "0abe9c295ac554fe": "Kunde inte stänga fönstret", + "87b07debb269d8b7": "Spara det här fönstret?", + "b0efb26131c569e7": "Ett sparat fönster behåller sitt projektfilter och tema. Öppna det igen från kommandopaletten eller Inställningar.", + "a708d8d44263e84d": "Spara inte", + "d346177041591bb6": "Kunde inte lämna miniläget", + "834e138d2b26cd6b": "Kunde inte fokusera fönstret", + "fe859444472c3fc5": "Flikar i miniläge", + "d73799a1a5dcdf8e": "Fönster", + "ba6e9ca3c387a18a": "Användning", + "cfeadf6c739273b9": "Uppdatering", + "15cd4faf32acd232": "Expandera", + "342704a7a178e7fb": "Inga pull requests matchar filtret på sidan Pull requests.", + "478e85d1f1cc8d2d": "Användning är inte tillgänglig", + "2385e81b6c12dcb9": "Läser in fönster", + "2735332f75a23d00": "I fokus", + "4dc8634c75ecf2b9": "Osparat", + "e99bc76101a1d90c": "Sparat", + "737c1e72eafe8151": "Inga andra fönster är öppna.", + "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..fc8db40876fc4 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1971,6 +1971,12 @@ "9c6962c66efa5668": "切换外观", "074c1660aac1c7cf": "开关主题编辑器", "02c340f8d0bb7649": "当前", + "9268423936e5989f": "新建窗口", + "a2f254e4f19e2fe4": "打开窗口:{name}", + "188538ba87e9652e": "无法打开窗口", + "92c1c0f097a72cca": "退出迷你模式", + "320cc15e79d58d96": "进入迷你模式", + "e380fd3d2c06377c": "无法切换迷你模式", "b8ec049821ce511c": "权限:{label}", "f0d4573b2e03e2a7": "权限", "38695f22426981d6": "预览 {path}", @@ -11702,6 +11708,36 @@ ], "625f25278bc683ba": "已选择的环境(不可用)", "e69e34d4f44d4136": "内置", + "839ddd6e58f3d585": "窗口", + "52131da2b0adefe9": "多窗口", + "c01fda7b8376b13d": "无法更改多窗口设置", + "3caa89d3bd6855e6": "无法保存此窗口", + "267c6c89c7c660bf": "保存此窗口", + "84dcab349acc5493": "窗口名称", + "431911fee26dc1a1": "项目颜色", + "4b91dc8c5794c2be": "跟随主窗口", + "e0dd6f7c7f0ff443": "删除已保存的窗口“{name}”?\n如果它已打开,它会作为未保存的窗口保持打开。", + "89935e0fe713b694": "无法删除已保存的窗口", + "ea344357d4e940cc": "{name} 的主题", + "45502d1da6eb4a22": "无法更改窗口主题", + "1aec90409a876b7a": "切换到", + "d6535a1b0a6be500": "打开", + "3e827ce1777a2c26": "无法保存窗口", + "61113c0adb210c5b": "新窗口的名称", + "c07399a76925488b": "新的已保存窗口", + "30f801cb98794666": "新窗口的主题", + "bd9cc67de51c6bad": "新窗口的项目", + "158b4c6263400d75": "无法重命名窗口", + "2166524596f06e50": "{name} 的名称", + "20fa0d173479f038": "添加已保存窗口", + "6fdff5142be87c75": "打开更多共享此应用连接的窗口。关闭此选项后,已打开的窗口仍保持打开。", + "fa5a272ce126e94f": "保留此窗口的项目筛选和主题,以便稍后重新打开。", + "80170559eb36e39b": "(主窗口)", + "e9b167119ae9c73a": "保存所有窗口共享的连接和草稿。", + "20529ca475e73f99": "主题", + "b16163a63f671aec": "删除已保存的窗口", + "f9bac4a057bed34d": "稍后可在此处、命令面板或“窗口”菜单中打开。", + "3a16e63273d7d383": "项目", "ae0b91ed52736998": "使用基准分支所跟踪的远程分支的最新提交,即使名称不同。未跟踪远程分支时,使用 origin 上的同名分支。远程分支不存在时,使用本地分支。", "81f82840d9589bc9": "重置新工作树从远程开始为默认值", "f68e05c50f67ab91": "默认从远程分支创建新工作树", @@ -11931,6 +11967,7 @@ "2bb905a7e7cddff7": "询问 之前 会话 置顶 分区", "53390c9ebb75f5d3": "询问 之前 会话 再次点击 行内 操作", "a26bd55959bfa3d3": "询问 之前 会话 聊天记录", + "e4fed2a24eb4dbcd": "多窗口 已保存窗口 配置 主题 迷你模式 新建窗口", "de504407a9dfe3bd": "确认 桌面应用 退出 直接 长按 双击 按两次", "a8a6da6439b8333e": "生成 会话标题 版本控制 内容 默认 提供方", "0c5fc3b5e41e1956": "生成 会话标题 提示词 自定义 风格 命名 重命名 重新生成", @@ -12686,6 +12723,25 @@ "0e4b49c8203aae81": "引导完成后等待登录状态超时。", "d7ffde2874d60d4f": "请输入配对 token 以继续。", "5d18537f82794deb": "本地环境已停用。", + "0abe9c295ac554fe": "无法关闭窗口", + "87b07debb269d8b7": "保存此窗口?", + "b0efb26131c569e7": "已保存的窗口会保留其项目筛选和主题。可从命令面板或设置中重新打开。", + "a708d8d44263e84d": "不保存", + "d346177041591bb6": "无法退出迷你模式", + "834e138d2b26cd6b": "无法切换到该窗口", + "fe859444472c3fc5": "迷你模式标签页", + "d73799a1a5dcdf8e": "窗口", + "ba6e9ca3c387a18a": "用量", + "cfeadf6c739273b9": "更新", + "15cd4faf32acd232": "展开", + "342704a7a178e7fb": "没有符合 PR 页面筛选条件的 PR。", + "478e85d1f1cc8d2d": "用量不可用", + "2385e81b6c12dcb9": "正在加载窗口", + "2735332f75a23d00": "当前窗口", + "4dc8634c75ecf2b9": "未保存", + "e99bc76101a1d90c": "已保存", + "737c1e72eafe8151": "没有其他打开的窗口。", + "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/DesktopWindowsHost.tsx b/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx new file mode 100644 index 0000000000000..0faecd33f9fa8 --- /dev/null +++ b/apps/web/src/multiWindow/ui/DesktopWindowsHost.tsx @@ -0,0 +1,124 @@ +import type { + DesktopWindowCloseDecision, + DesktopWindowCloseRequest, + DesktopWindowsBridge, +} from "@t3tools/contracts"; +import { T, useGT } from "gt-react"; +import { useEffect, useRef, useState } from "react"; + +import { Button } from "../../components/ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../../components/ui/dialog"; +import { Input } from "../../components/ui/input"; +import { desktopWindowsBridge } from "../windowContext"; +import { notifyWindowActionFailure } from "./windowActions"; +import { normalizeWindowProfileName, WINDOW_PROFILE_NAME_MAX_LENGTH } from "./windowProfiles.logic"; + +/** The save-on-close prompt, once per desktop window. */ +export function DesktopWindowsHost() { + const [bridge] = useState(desktopWindowsBridge); + return bridge === null ? null : ; +} + +function DesktopWindowsHostContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const gt = useGT(); + const [request, setRequest] = useState(null); + const [name, setName] = useState(""); + const pendingRequestIdRef = useRef(null); + const inputRef = useRef(null); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the desktop shell's close requests + useEffect( + () => + bridge.onCloseRequest((next) => { + const previous = pendingRequestIdRef.current; + // A newer request supersedes one still on screen; the shell waits on every request. + if (previous !== null && previous !== next.requestId) { + void bridge.resolveCloseRequest(previous, { action: "cancel" }).catch(() => {}); + } + pendingRequestIdRef.current = next.requestId; + setRequest(next); + setName(next.suggestedName); + }), + [bridge], + ); + + const resolve = (decision: DesktopWindowCloseDecision) => { + if (request === null) return; + pendingRequestIdRef.current = null; + setRequest(null); + bridge.resolveCloseRequest(request.requestId, decision).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't close the window"), cause); + }); + }; + const savedName = normalizeWindowProfileName(name); + // Without a usable name, Save leaves the prompt open. + const save = () => { + if (savedName !== null) resolve({ action: "save", name: savedName }); + }; + + return ( + { + if (!open) resolve({ action: "cancel" }); + }} + > + + + + Save this window? + + + + A saved window keeps its project filter and theme. Reopen it from the command palette + or Settings. + + + + + setName(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + event.preventDefault(); + save(); + }} + /> + + + + + + + + + ); +} diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx new file mode 100644 index 0000000000000..96186000d0fda --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.browser.test.tsx @@ -0,0 +1,245 @@ +import "../../index.css"; + +import type { DesktopOpenWindow, DesktopUpdateState } from "@t3tools/contracts"; +import type { LimitPresentations } from "@t3tools/shared/usageLimits"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { APP_DISPLAY_NAME } from "../../branding"; +import { + CLAUDE, + CLAUDE_UNREADABLE, + CODEX, + FIXTURE_NOW, + openWindow, + presentations, + projectsFor, + PULL_REQUESTS, + UPDATE_AVAILABLE, +} from "./mini.test-fixtures"; +import { MiniPanel } from "./MiniMainWindow"; +import { MiniPullRequestList } from "./MiniPullRequests"; +import { MiniUpdate } from "./MiniUpdate"; +import { MiniUsageSection } from "./MiniUsage"; +import { MiniWindows } from "./MiniWindows"; + +const mocks = vi.hoisted(() => ({ update: null as DesktopUpdateState | null })); +vi.mock("../../state/desktopUpdate", async (importOriginal) => ({ + ...(await importOriginal()), + useDesktopUpdateState: () => mocks.update, +})); + +const WINDOWS = [ + openWindow(2, "Client work", "Rate limit review - Client work", { + projectScopeKeys: ["Northwind"], + }), + openWindow(3, "Window 3", "Filter envelope - Window 3", { profileId: null, focused: true }), + openWindow(4, "Idle", `${APP_DISPLAY_NAME} - Idle`), +]; + +const makeActions = () => ({ + search: vi.fn(), + expand: vi.fn(), + newWindow: vi.fn(), + focusWindow: vi.fn(), + openPullRequest: vi.fn(), +}); + +interface PanelOptions { + readonly usage?: LimitPresentations; + readonly windows?: readonly DesktopOpenWindow[] | null; + readonly multiWindowEnabled?: boolean; + readonly pullRequestsSupported?: boolean; +} + +function Panel({ + usage = presentations([CLAUDE, CODEX]), + windows = WINDOWS, + multiWindowEnabled = true, + pullRequestsSupported = true, + actions, +}: PanelOptions & { readonly actions: ReturnType }) { + return ( + + ), + pullRequests: ( + + ), + usage: , + update: , + }} + /> + ); +} + +async function renderPanel(options: PanelOptions = {}) { + await page.viewport(320, 184); + const actions = makeActions(); + const screen = await render(); + const openTab = (name: string) => screen.getByRole("button", { name, exact: true }).click(); + return { screen, actions, openTab }; +} + +const TAB_REGIONS = ["Windows", "Pull requests", "Usage", "Update"]; + +describe("MiniPanel", () => { + it("opens on Usage and shows one tab's content at a time", async () => { + mocks.update = UPDATE_AVAILABLE; + const { screen, openTab } = await renderPanel(); + await using _screen = screen; + + await expect.element(screen.getByText("62%")).toBeVisible(); + expect(document.documentElement.scrollWidth).toBe(320); + for (const tab of ["Windows", "Pull requests", "Update", "Usage"]) { + await openTab(tab); + await expect + .element(screen.getByRole("button", { name: tab, exact: true })) + .toHaveAttribute("aria-current", "page"); + await expect.element(screen.getByRole("region", { name: tab })).toBeVisible(); + for (const other of TAB_REGIONS) { + if (other !== tab) expect(screen.getByRole("region", { name: other }).query()).toBeNull(); + } + } + }); + + it("puts the tabs at the left of the top bar and Search, New Window and Expand at its right", async () => { + const { screen, actions } = await renderPanel(); + await using _screen = screen; + + const left = (name: string) => + screen.getByRole("button", { name, exact: true }).element().getBoundingClientRect(); + expect(left("Windows").left).toBeLessThan(left("Update").left); + expect(left("Update").right).toBeLessThan(left("Search").left); + expect(left("Search").right).toBeLessThan(left("New Window").left); + expect(left("New Window").right).toBeLessThan(left("Expand").left); + // Flush with the panel's right edge, inside its content inset. + expect(320 - left("Expand").right).toBeLessThanOrEqual(12); + for (const [name, action] of [ + ["Search", actions.search], + ["New Window", actions.newWindow], + ["Expand", actions.expand], + ] as const) { + const button = screen.getByRole("button", { name }); + await expect.element(button).toHaveTextContent(""); + await button.click(); + expect(action).toHaveBeenCalledOnce(); + } + }); + + it("shows Claude's and OpenAI's limits together at the panel's default size", async () => { + const { screen } = await renderPanel(); + await using _screen = screen; + + await expect.element(screen.getByText("Claude · Max")).toBeInViewport(); + await expect.element(screen.getByText("Codex · ChatGPT Pro 100 Subscription")).toBeInViewport(); + for (const percent of ["62%", "41%", "6%", "78%"]) { + await expect.element(screen.getByText(percent, { exact: true })).toBeInViewport(); + } + const viewport = screen.container.querySelector("[data-slot=scroll-area-viewport]")!; + expect(viewport.scrollHeight).toBe(viewport.clientHeight); + }); + + it("hides New Window while multiple windows are off, and PRs where no server supports them", async () => { + const { screen } = await renderPanel({ + multiWindowEnabled: false, + pullRequestsSupported: false, + }); + await using _screen = screen; + await expect.element(screen.getByRole("button", { name: "Expand" })).toBeVisible(); + expect(screen.getByRole("button", { name: "New Window" }).query()).toBeNull(); + expect(screen.getByRole("button", { name: "Pull requests" }).query()).toBeNull(); + }); + + it("lists windows as cards: project filter and state, then name, then what the window shows", async () => { + const { screen, actions, openTab } = await renderPanel(); + await using _screen = screen; + await openTab("Windows"); + + const saved = screen.getByRole("button", { name: /Client work/ }); + await expect.element(saved).toHaveTextContent("NWNorthwindSavedClient workRate limit review"); + const focused = screen.getByRole("button", { name: /Window 3/ }); + await expect.element(focused).toHaveTextContent("All projectsFocusedWindow 3Filter envelope"); + await expect.element(focused).toHaveAttribute("aria-current", "true"); + // A window with no thread open is titled with the app's name, which says nothing. + await expect + .element(screen.getByRole("button", { name: /Idle/ })) + .toHaveTextContent("All projectsSavedIdle"); + await saved.click(); + expect(actions.focusWindow).toHaveBeenCalledWith(2); + }); + + it("keeps both bars on screen and scrolls only the tab when its list is long", async () => { + const { screen, openTab } = await renderPanel({ + windows: Array.from({ length: 14 }, (_, index) => + openWindow( + 10 + index, + `Northwind storefront and checkout redesign ${index + 1} (Q4 holiday freeze)`, + "Investigate why the dungeon lighting pass flickers on integrated GPUs", + { projectScopeKeys: ["Northwind", "Dungeon", "Synth"] }, + ), + ), + }); + await using _screen = screen; + await openTab("Windows"); + + for (const name of ["Search", "Expand", "New Window", "Windows", "Update"]) { + await expect.element(screen.getByRole("button", { name, exact: true })).toBeInViewport(); + } + await expect.element(screen.getByRole("button", { name: /redesign 1 / })).toBeInViewport(); + await expect.element(screen.getByRole("button", { name: /redesign 14 / })).not.toBeInViewport(); + expect(document.documentElement.scrollWidth).toBe(320); + expect(document.documentElement.scrollHeight).toBe(184); + const viewport = screen.container.querySelector("[data-slot=scroll-area-viewport]")!; + expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight); + expect(viewport.scrollWidth).toBe(viewport.clientWidth); + }); + + it("says when Usage has no limits, and why", async () => { + const { screen } = await renderPanel({ usage: presentations([CLAUDE_UNREADABLE]) }); + await using _screen = screen; + await expect.element(screen.getByText("Usage unavailable")).toBeVisible(); + await expect + .element(screen.getByText("Claude: Could not read limits. Sign in again.")) + .toBeVisible(); + }); + + it("PRs opens a pull request on its host", async () => { + const { screen, actions, openTab } = await renderPanel(); + await using _screen = screen; + await openTab("Pull requests"); + + await expect.element(screen.getByLabelText("Some checks were not successful")).toBeVisible(); + await screen.getByRole("button", { name: /Rate limit the checkout webhook/ }).click(); + expect(actions.openPullRequest).toHaveBeenCalledWith(PULL_REQUESTS[0]!.url); + }); + + it("Update names the running version and where its update stands", async () => { + mocks.update = UPDATE_AVAILABLE; + const { screen, openTab } = await renderPanel(); + await using _screen = screen; + await openTab("Update"); + + const update = screen.getByRole("region", { name: "Update" }); + await expect.element(update.getByText(/0\.0\.50$/)).toBeVisible(); + await expect + .element(update.getByRole("status")) + .toHaveTextContent("Update 0.0.51 ready to download"); + }); +}); diff --git a/apps/web/src/multiWindow/ui/MiniMainWindow.tsx b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx new file mode 100644 index 0000000000000..860e723e2abca --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniMainWindow.tsx @@ -0,0 +1,181 @@ +import { useRouter } from "@tanstack/react-router"; +import type { DesktopWindowsBridge } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { + AppWindowIcon, + ChartNoAxesColumnIcon, + CircleArrowUpIcon, + LayersIcon, + Maximize2Icon, + SearchIcon, +} from "lucide-react"; +import { type ReactNode, useEffect, useState } from "react"; + +import { openCommandPalette } from "../../commandPaletteBus"; +import { CommandPalette } from "../../components/CommandPalette"; +import { resolveDesktopUpdateButtonAction } from "../../components/desktopUpdate.logic"; +import { PullRequestGlyph } from "../../components/pullRequest/pullRequestIcons"; +import { SidebarHeaderIconButton } from "../../components/sidebar/SidebarThreadHeader"; +import { ScrollArea } from "../../components/ui/scroll-area"; +import { SidebarProvider } from "../../components/ui/sidebar"; +import { useDesktopUpdateState } from "../../state/desktopUpdate"; +import { usePullRequestsSupported } from "../../state/environments"; +import { desktopWindowsBridge } from "../windowContext"; +import { useDesktopWindowsState } from "../windowsState"; +import { MiniPullRequests } from "./MiniPullRequests"; +import { MiniUpdate } from "./MiniUpdate"; +import { MiniUsage } from "./MiniUsage"; +import { MiniWindows } from "./MiniWindows"; +import { useProjectScopeGroups } from "./useProjectScopeGroups"; +import { notifyWindowActionFailure, openNewDesktopWindow } from "./windowActions"; + +type MiniTab = "windows" | "pullRequests" | "usage" | "update"; + +/** The main window's compact stand-in for the app shell while Mini Mode is on. */ +export function MiniMainWindow() { + const [bridge] = useState(desktopWindowsBridge); + return bridge === null ? null : ; +} + +function MiniMainWindowContent({ bridge }: { readonly bridge: DesktopWindowsBridge }) { + const gt = useGT(); + const router = useRouter(); + const windowsState = useDesktopWindowsState(); + const updateState = useDesktopUpdateState(); + const pullRequestsSupported = usePullRequestsSupported(); + const { groupsForKeys } = useProjectScopeGroups(); + const multiWindowEnabled = windowsState?.multiWindowEnabled !== false; + + const expand = () => { + bridge.setMiniMode(false).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't leave Mini Mode"), cause); + }); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- follows the router: the panel shows no pages, so going to one (a search result, Settings) needs the full window + useEffect( + () => + router.subscribe("onBeforeNavigate", ({ pathChanged }) => { + if (pathChanged) void bridge.setMiniMode(false); + }), + [bridge, router], + ); + + return ( + + openCommandPalette()} + onExpand={expand} + // Off in Settings, the main process refuses new windows, so don't offer one. + onNewWindow={multiWindowEnabled ? () => openNewDesktopWindow(bridge) : undefined} + tabs={{ + windows: ( + !window.isMain) ?? null} + projectsFor={groupsForKeys} + onFocusWindow={(windowId) => { + bridge.focus(windowId).catch((cause: unknown) => { + notifyWindowActionFailure(gt("Couldn't focus the window"), cause); + }); + }} + /> + ), + pullRequests: , + usage: , + update: , + }} + /> + + ); +} + +/** One top bar, tabs on the left and actions on the right, over one tab's content. */ +export function MiniPanel({ + pullRequestsSupported, + updateAvailable, + onSearch, + onExpand, + onNewWindow, + tabs, +}: { + readonly pullRequestsSupported: boolean; + readonly updateAvailable: boolean; + readonly onSearch: () => void; + readonly onExpand: () => void; + /** Omitted while multiple windows are turned off. */ + readonly onNewWindow?: (() => void) | undefined; + /** Only the showing tab's content mounts. */ + readonly tabs: Readonly>; +}) { + const gt = useGT(); + const [tab, setTab] = useState("usage"); + const tabItem = (id: MiniTab, label: string, icon: ReactNode) => ( + setTab(id)} + > + {icon} + + ); + return ( + +
+
+ + + + + + {onNewWindow === undefined ? null : ( + + + + )} + + + +
+
+ + {tabs[tab]} + +
+
+
+ ); +} diff --git a/apps/web/src/multiWindow/ui/MiniPullRequests.tsx b/apps/web/src/multiWindow/ui/MiniPullRequests.tsx new file mode 100644 index 0000000000000..f320ebc49304b --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniPullRequests.tsx @@ -0,0 +1,123 @@ +import { T, useGT, useMessages } from "gt-react"; +import { useState } from "react"; + +import type { EnvironmentPullRequestEntry } from "../../components/pullRequest/pullRequestList.logic"; +import { readPullRequestListPreferences } from "../../components/pullRequest/pullRequestListPreferences"; +import { + PULL_REQUEST_ROW_CLASS, + PULL_REQUEST_ROW_NUMBER_CLASS, + PullRequestRowGlyph, + PullRequestRowLines, +} from "../../components/pullRequest/PullRequestListRow"; +import { + PullRequestReviewDecisionGlyph, + pullRequestChecksStatePresentation, +} from "../../components/pullRequest/pullRequestPresentation"; +import { Skeleton } from "../../components/ui/skeleton"; +import { cn } from "../../lib/utils"; +import { ensureLocalApi } from "../../localApi"; +import { useEnvironments } from "../../state/environments"; +import { usePullRequestList } from "../../state/pullRequests"; + +const MINI_PULL_REQUEST_LIMIT = 20; + +/** The PRs tab: the list the Pull requests page would open with, read while the tab is showing. */ +export function MiniPullRequests() { + const { environments } = useEnvironments(); + const [{ state, involvement }] = useState(readPullRequestListPreferences); + const list = usePullRequestList( + environments + .filter((environment) => environment.serverConfig !== null) + .map(({ environmentId }) => ({ + environmentId, + input: { state, involvement, limit: MINI_PULL_REQUEST_LIMIT }, + })), + ); + return ( + void ensureLocalApi().shell.openExternal(url)} + /> + ); +} + +export function MiniPullRequestList({ + entries, + error, + onOpen, +}: { + /** Null until a connected environment answers. */ + readonly entries: readonly EnvironmentPullRequestEntry[] | null; + readonly error: string | null; + readonly onOpen: (url: string) => void; +}) { + const gt = useGT(); + const messages = useMessages(); + return ( +
+ {entries === null ? ( +
+ + +
+ ) : entries.length === 0 ? ( +

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

+ ) : ( +
    + {entries.map((entry) => { + const checks = + entry.checksState === undefined + ? null + : pullRequestChecksStatePresentation(entry.checksState, messages); + return ( +
  • + +
  • + ); + })} +
+ )} +
+ ); +} diff --git a/apps/web/src/multiWindow/ui/MiniUpdate.tsx b/apps/web/src/multiWindow/ui/MiniUpdate.tsx new file mode 100644 index 0000000000000..8f014419526ce --- /dev/null +++ b/apps/web/src/multiWindow/ui/MiniUpdate.tsx @@ -0,0 +1,51 @@ +import { managedUpdatesDenial } from "@t3tools/client-runtime/contract-labels"; +import { useGT, useMessages } from "gt-react"; + +import { APP_DISPLAY_NAME } from "../../branding"; +import { + getDesktopUpdateButtonTooltip, + getDesktopUpdateDisabledReason, +} from "../../components/desktopUpdate.logic"; +import { SidebarProviderUpdatePill } from "../../components/sidebar/SidebarProviderUpdatePill"; +import { + SidebarUpdateArchitectureWarning, + SidebarUpdatePill, +} from "../../components/sidebar/SidebarUpdatePill"; +import { SidebarMenu } from "../../components/ui/sidebar"; +import { useDesktopUpdateState } from "../../state/desktopUpdate"; +import { usePrimaryManagedPolicy } from "../../state/managedPolicy"; + +/** The Update tab: the running version, where its update stands, and the sidebar's own update controls. */ +export function MiniUpdate() { + const gt = useGT(); + const messages = useMessages(); + const state = useDesktopUpdateState(); + const disabledReason = getDesktopUpdateDisabledReason( + state, + managedUpdatesDenial(usePrimaryManagedPolicy(), messages), + messages, + ); + return ( +
+
+
+

+ {APP_DISPLAY_NAME} {state?.currentVersion} +

+

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

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

+ Usage unavailable +

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

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

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

+ {notice} +

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

+ No other windows are open. +

+ ) : ( +
    + {windows.map((window) => ( + onFocusWindow(window.windowId)} + /> + ))} +
+ )} +
+ ); +} + +function MiniWindowCard({ + window, + projects, + onFocus, +}: { + readonly window: DesktopOpenWindow; + readonly projects: readonly MiniWindowProject[]; + readonly onFocus: () => void; +}) { + const gt = useGT(); + // The desktop shell appends the window's name to its title, and the card already leads with it. + // What is left names the open thread, or only the app when the window has none open. + const nameSuffix = ` - ${window.name}`; + const shown = window.title.endsWith(nameSuffix) + ? window.title.slice(0, -nameSuffix.length) + : window.title; + const title = shown === APP_DISPLAY_NAME ? "" : shown; + return ( +
  • + +
  • + ); +} diff --git a/apps/web/src/multiWindow/ui/mini.test-fixtures.ts b/apps/web/src/multiWindow/ui/mini.test-fixtures.ts new file mode 100644 index 0000000000000..e596f84dba57c --- /dev/null +++ b/apps/web/src/multiWindow/ui/mini.test-fixtures.ts @@ -0,0 +1,210 @@ +import { + type DesktopOpenWindow, + type DesktopUpdateState, + EnvironmentId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, + type ServerProviderUsageLimits, + type ServerProviderUsageWindow, + SourceControlProviderKind, +} from "@t3tools/contracts"; +import type { LimitPresentations } from "@t3tools/shared/usageLimits"; + +import type { EnvironmentPullRequestEntry } from "../../components/pullRequest/pullRequestList.logic"; +import type { MiniWindowProject } from "./MiniWindows"; + +export const FIXTURE_NOW = Date.parse("2026-10-25T16:00:00.000Z"); +const HOUR = 3_600_000; + +const iso = (offsetMs: number) => new Date(FIXTURE_NOW + offsetMs).toISOString(); + +function usageWindow( + id: string, + kind: ServerProviderUsageWindow["kind"], + label: string, + usedPercent: number, + resetsInHours: number, + durationHours: number, +): ServerProviderUsageWindow { + return { + id, + kind, + label, + usedPercent, + resetsAt: iso(resetsInHours * HOUR), + windowDurationMins: durationHours * 60, + }; +} + +function provider( + driver: string, + usageLimits: Partial, + options: { readonly plan?: string; readonly name?: string } = {}, +): ServerProvider { + return { + instanceId: ProviderInstanceId.make(options.name ? `${driver}_${options.name}` : driver), + driver: ProviderDriverKind.make(driver), + ...(options.name ? { displayName: options.name } : {}), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated", ...(options.plan ? { label: options.plan } : {}) }, + checkedAt: iso(-4 * 60_000), + models: [], + slashCommands: [], + skills: [], + usageLimits: { checkedAt: iso(-4 * 60_000), windows: [], ...usageLimits }, + }; +} + +export function presentations(providers: readonly ServerProvider[]): LimitPresentations { + return new Map([ + [ + EnvironmentId.make("desk"), + { entry: { target: { label: "Desk" } }, serverConfig: { providers } }, + ], + ]); +} + +export const CLAUDE = provider( + "claudeAgent", + { + windows: [ + usageWindow("five_hour", "session", "Session", 38, 2.25, 5), + usageWindow("seven_day", "weekly", "Weekly", 59, 76, 168), + ], + }, + { plan: "Max" }, +); + +export const CODEX = provider( + "codex", + { + windows: [ + usageWindow("primary", "session", "Session", 94, 0.7, 5), + usageWindow("secondary", "weekly", "Weekly", 22, 120, 168), + ], + }, + { plan: "ChatGPT Pro 100 Subscription" }, +); + +export const CLAUDE_UNREADABLE = provider( + "claudeAgent", + { unavailable: { reason: "probeFailed", message: "Could not read limits. Sign in again." } }, + { name: "Claude" }, +); + +export function openWindow( + windowId: number, + name: string, + title: string, + overrides: Partial = {}, +): DesktopOpenWindow { + return { + windowId, + isMain: false, + profileId: name, + name, + title, + focused: false, + projectScopeKeys: [], + ...overrides, + }; +} + +function windowProject( + displayName: string, + text: string, + color: "orange" | "pink" | "sky", +): MiniWindowProject { + return { + projectKey: displayName, + displayName, + environmentId: EnvironmentId.make("desk"), + workspaceRoot: `/work/${displayName}`, + title: displayName, + faviconPath: null, + projectIcon: { kind: "monogram", text, color }, + }; +} + +const WINDOW_PROJECTS = [ + windowProject("Northwind", "NW", "orange"), + windowProject("Dungeon", "DG", "pink"), + windowProject("Synth", "SY", "sky"), +]; + +export const projectsFor = (keys: readonly string[]) => + WINDOW_PROJECTS.filter((project) => keys.includes(project.projectKey)); + +function pullRequest( + number: number, + title: string, + overrides: Partial = {}, +): EnvironmentPullRequestEntry { + return { + environmentId: EnvironmentId.make("desk"), + provider: SourceControlProviderKind.make("github"), + host: "github.com", + projectId: ProjectId.make("northwind"), + projectTitle: "Northwind", + repository: "acme/northwind", + number, + title, + url: `https://github.com/acme/northwind/pull/${number}`, + author: null, + headBranch: `feature-${number}`, + baseBranch: "main", + state: "open", + isDraft: false, + mergeability: "mergeable", + additions: 0, + deletions: 0, + createdAt: iso(-30 * HOUR), + updatedAt: iso(-2 * HOUR), + viewerReviewRequested: false, + labels: [], + ...overrides, + }; +} + +export const PULL_REQUESTS = [ + pullRequest(482, "Rate limit the checkout webhook", { + checksState: "passing", + reviewDecision: "approved", + }), + pullRequest(479, "Dungeon lighting: fix flicker on integrated GPUs", { + repository: "acme/dungeon", + checksState: "failing", + reviewDecision: "changes-requested", + updatedAt: iso(-5 * HOUR), + }), + pullRequest(31, "Filter envelope presets", { + repository: "acme/synth", + isDraft: true, + checksState: "pending", + updatedAt: iso(-26 * HOUR), + }), +]; + +export const UPDATE_AVAILABLE: DesktopUpdateState = { + enabled: true, + status: "available", + channel: "latest", + currentVersion: "0.0.50", + hostArch: "x64", + appArch: "x64", + runningUnderArm64Translation: false, + availableVersion: "0.0.51", + downloadedVersion: null, + releaseNotes: [], + omittedReleaseCount: 0, + downloadPercent: null, + checkedAt: null, + message: null, + errorContext: null, + canRetry: false, +}; diff --git a/apps/web/src/multiWindow/ui/useProjectScopeGroups.ts b/apps/web/src/multiWindow/ui/useProjectScopeGroups.ts new file mode 100644 index 0000000000000..ac47979e45ca7 --- /dev/null +++ b/apps/web/src/multiWindow/ui/useProjectScopeGroups.ts @@ -0,0 +1,34 @@ +import { + pickableProjectGroups, + selectProjectGroupingSettings, +} from "@t3tools/client-runtime/state/project-grouping"; + +import { useClientSettings } from "../../hooks/useSettings"; +import { + buildSidebarProjectSnapshots, + resolveSidebarProjectScopeKeys, + type SidebarProjectSnapshot, +} from "../../sidebarProjectGrouping"; +import { usePrimaryEnvironmentId } from "../../state/environments"; +import { useProjects } from "../../state/entities"; + +/** The project groups a window's project filter picks from, grouped and ordered as the sidebar's. */ +export function useProjectScopeGroups() { + const projects = useProjects(); + const settings = useClientSettings(selectProjectGroupingSettings); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const groups = pickableProjectGroups( + buildSidebarProjectSnapshots({ + projects, + groupScratchProjects: true, + settings, + primaryEnvironmentId, + resolveEnvironmentLabel: () => null, + }), + ); + const groupsForKeys = (keys: readonly string[]): SidebarProjectSnapshot[] => + resolveSidebarProjectScopeKeys({ groups, keys, settings }).flatMap( + (key) => groups.find((group) => group.projectKey === key) ?? [], + ); + return { groups, groupsForKeys }; +} diff --git a/apps/web/src/multiWindow/ui/useProjectTintColors.ts b/apps/web/src/multiWindow/ui/useProjectTintColors.ts new file mode 100644 index 0000000000000..2ab4cfeddf361 --- /dev/null +++ b/apps/web/src/multiWindow/ui/useProjectTintColors.ts @@ -0,0 +1,37 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { ProjectFaviconTarget } from "@t3tools/client-runtime/project-favicon-cache"; +import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon"; +import { Atom } from "effect/reactivity"; + +import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; +import { projectFaviconUrlAtom } from "../../state/assets"; +import { projectTintColors } from "./windowTint.logic"; + +// Keyed by the JSON of the projects' icon targets, so one atom reads every project's icon. +const projectsShowImageAtom = Atom.family((key: string) => + Atom.make((get) => + (JSON.parse(key) as ProjectFaviconTarget[]).map((target) => { + // As `ProjectFavicon` decides: a fallback URL draws the monogram, not an image. + const src = get(projectFaviconUrlAtom(target)); + return src !== null && !isProjectFaviconFallbackUrl(src); + }), + ), +); + +/** The distinct colours the projects' icons show, in order; emoji and image icons show none. */ +export function useProjectTintColors(projects: readonly SidebarProjectSnapshot[]): string[] { + // Only a project without an icon override can show an image. + const automatic = projects.filter((project) => project.projectIcon == null); + const showsImage = useAtomValue( + projectsShowImageAtom( + JSON.stringify( + automatic.map((project): ProjectFaviconTarget => ({ + environmentId: project.environmentId, + cwd: project.workspaceRoot, + faviconPath: project.faviconPath ?? null, + })), + ), + ), + ); + return projectTintColors(projects, (project) => showsImage[automatic.indexOf(project)] === true); +} diff --git a/apps/web/src/multiWindow/ui/windowActions.ts b/apps/web/src/multiWindow/ui/windowActions.ts new file mode 100644 index 0000000000000..df94d5e21c9e7 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowActions.ts @@ -0,0 +1,47 @@ +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 { useUiStateStore } from "../../uiStateStore"; +import { desktopWindowsBridge } from "../windowContext"; +import { readDesktopWindowsState } from "../windowsState"; + +export function notifyWindowActionFailure(title: string, cause: unknown): void { + console.error(title, cause); + toastManager.add({ + type: "error", + title, + description: cause instanceof Error ? cause.message : undefined, + }); +} + +/** Opens an unsaved window that starts with this window's project filter. */ +export function openNewDesktopWindow(bridge: DesktopWindowsBridge): void { + const projectScopeKeys = useUiStateStore.getState().sidebarProjectScopeKeys; + bridge.openNew({ projectScopeKeys }).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) => { + // Off, the chord is free for whatever else is bound to it. + if (readDesktopWindowsState()?.multiWindowEnabled === false) return false; + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) openNewDesktopWindow(bridge); + }, + }), + registerMenuAction("new-window", () => openNewDesktopWindow(bridge)), + ]; + return () => { + for (const dispose of disposers) dispose(); + }; +} diff --git a/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts b/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts new file mode 100644 index 0000000000000..29bd1252a36db --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowProfiles.logic.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { normalizeWindowProfileName } from "./windowProfiles.logic"; + +describe("normalizeWindowProfileName", () => { + it.each([ + [" Work ", "Work"], + [" ", null], + ["x".repeat(80), "x".repeat(80)], + ["x".repeat(81), null], + ])("normalizes %j", (name, expected) => { + expect(normalizeWindowProfileName(name)).toBe(expected); + }); +}); diff --git a/apps/web/src/multiWindow/ui/windowProfiles.logic.ts b/apps/web/src/multiWindow/ui/windowProfiles.logic.ts new file mode 100644 index 0000000000000..ba24ca2655f91 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowProfiles.logic.ts @@ -0,0 +1,8 @@ +export const WINDOW_PROFILE_NAME_MAX_LENGTH = 80; + +/** The trimmed name, or null when the desktop shell would reject it. */ +export function normalizeWindowProfileName(name: string): string | null { + const trimmed = name.trim(); + if (trimmed.length === 0 || trimmed.length > WINDOW_PROFILE_NAME_MAX_LENGTH) return null; + return trimmed; +} diff --git a/apps/web/src/multiWindow/ui/windowTheme.ts b/apps/web/src/multiWindow/ui/windowTheme.ts new file mode 100644 index 0000000000000..e12b59ea3b3b1 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowTheme.ts @@ -0,0 +1,41 @@ +import { setWindowThemeOverride } from "../../hooks/useTheme"; +import { desktopWindowsBridge, readDesktopWindowContext } from "../windowContext"; +import { + readDesktopWindowsState, + resolveWindowThemeOverride, + selectCurrentWindowProfile, + subscribeDesktopWindowsState, +} from "../windowsState"; + +let installed = false; + +/** Applies a secondary window's profile theme in place of the shared one, live. */ +export function installDesktopWindowTheme(): void { + const bridge = desktopWindowsBridge(); + const context = readDesktopWindowContext(); + if (installed || bridge === null || context === null || context.isMain) return; + installed = true; + const sync = () => { + const windowsState = readDesktopWindowsState(); + const theme = resolveWindowThemeOverride(windowsState, context); + const profileId = + windowsState === null + ? context.profileId + : (selectCurrentWindowProfile(windowsState, context)?.id ?? null); + if (theme === null || profileId === null) { + setWindowThemeOverride(null); + return; + } + setWindowThemeOverride({ + theme, + save: (next) => { + bridge.updateProfile({ profileId, theme: next }).catch((cause: unknown) => { + console.error("Failed to save the window theme.", cause); + sync(); + }); + }, + }); + }; + sync(); + subscribeDesktopWindowsState(sync); +} diff --git a/apps/web/src/multiWindow/ui/windowTint.logic.test.ts b/apps/web/src/multiWindow/ui/windowTint.logic.test.ts new file mode 100644 index 0000000000000..6b32fff31de59 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowTint.logic.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { projectIconSwatch } from "../../projectIconColors"; +import { deriveProjectIdentity } from "../../projectIdentity"; +import { + projectIconTintColor, + projectTintColors, + type WindowTintProject, +} from "./windowTint.logic"; + +const monogram = (title: string, color: "blue" | "rose" | "green"): WindowTintProject => ({ + title, + projectIcon: { kind: "monogram", text: title.slice(0, 2), color }, +}); +const lucide = (title: string, color: "amber"): WindowTintProject => ({ + title, + projectIcon: { kind: "lucide", name: "folder", color }, +}); +const emoji: WindowTintProject = { title: "party", projectIcon: { kind: "emoji", emoji: "🎉" } }; +const automatic = (title: string): WindowTintProject => ({ title, projectIcon: null }); + +describe("projectIconTintColor", () => { + it("uses the icon's colour, the name's monogram colour without one, and none for an emoji", () => { + expect(projectIconTintColor(monogram("api", "rose"), false)).toBe("rose"); + expect(projectIconTintColor(lucide("api", "amber"), false)).toBe("amber"); + expect(projectIconTintColor(automatic("storefront"), false)).toBe( + deriveProjectIdentity("storefront").color, + ); + expect(projectIconTintColor(emoji, false)).toBeNull(); + }); + + it("has no colour for a project whose icon is an image", () => { + expect(projectIconTintColor(automatic("storefront"), true)).toBeNull(); + // An override replaces the image, so its colour shows. + expect(projectIconTintColor(monogram("api", "rose"), true)).toBe("rose"); + }); +}); + +describe("projectTintColors", () => { + it("lists each colour once, in project order, skipping emoji and image icons", () => { + const image = automatic("brand-site"); + expect( + projectTintColors( + [monogram("api", "rose"), emoji, image, monogram("web", "green"), monogram("docs", "rose")], + (project) => project === image, + ), + ).toEqual([projectIconSwatch("rose"), projectIconSwatch("green")]); + }); + + it("is empty when no project shows a colour", () => { + const image = automatic("brand-site"); + expect(projectTintColors([emoji, image], (project) => project === image)).toEqual([]); + }); +}); diff --git a/apps/web/src/multiWindow/ui/windowTint.logic.ts b/apps/web/src/multiWindow/ui/windowTint.logic.ts new file mode 100644 index 0000000000000..33c2902dc1c57 --- /dev/null +++ b/apps/web/src/multiWindow/ui/windowTint.logic.ts @@ -0,0 +1,32 @@ +import type { ProjectIconColor, ProjectIconOverride } from "@t3tools/contracts"; + +import { projectIconSwatch } from "../../projectIconColors"; +import { deriveProjectIdentity } from "../../projectIdentity"; + +export interface WindowTintProject { + readonly title: string; + readonly projectIcon?: ProjectIconOverride | null | undefined; +} + +/** The colour the project's icon shows; an emoji or an image shows none. */ +export function projectIconTintColor( + project: WindowTintProject, + showsImage: boolean, +): ProjectIconColor | null { + const icon = project.projectIcon; + // Without an override the icon is the project's image, or else the name's monogram in this colour. + if (icon == null) return showsImage ? null : deriveProjectIdentity(project.title).color; + return icon.kind === "emoji" ? null : icon.color; +} + +/** Each distinct colour the projects' icons show, as a CSS colour, in project order. */ +export function projectTintColors( + projects: readonly TProject[], + showsImage: (project: TProject) => boolean, +): string[] { + return [ + ...new Set( + projects.flatMap((project) => projectIconTintColor(project, showsImage(project)) ?? []), + ), + ].map(projectIconSwatch); +} diff --git a/apps/web/src/multiWindow/windowContext.ts b/apps/web/src/multiWindow/windowContext.ts new file mode 100644 index 0000000000000..0be4435ac6582 --- /dev/null +++ b/apps/web/src/multiWindow/windowContext.ts @@ -0,0 +1,19 @@ +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) cachedContext = desktopWindowsBridge()?.getContext() ?? 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.test.ts b/apps/web/src/multiWindow/windowsState.test.ts new file mode 100644 index 0000000000000..9e139bf53676d --- /dev/null +++ b/apps/web/src/multiWindow/windowsState.test.ts @@ -0,0 +1,104 @@ +import type { + DesktopWindowContext, + DesktopWindowProfile, + DesktopWindowsState, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { openWindow } from "./ui/mini.test-fixtures"; +import { + isMiniMainWindow, + resolveWindowThemeOverride, + selectCurrentWindowProfile, +} from "./windowsState"; + +const mainProfile: DesktopWindowProfile = { + id: "main", + name: "Main", + projectScopeKeys: [], + theme: null, + isDefault: true, +}; +const workProfile: DesktopWindowProfile = { + id: "work", + name: "Work", + projectScopeKeys: ["project:a"], + theme: "dracula", + isDefault: false, +}; + +const unsavedWindow = openWindow(2, "Window 2", "", { profileId: null, focused: true }); + +function context(overrides: Partial = {}): DesktopWindowContext { + return { + windowId: 2, + isMain: false, + profileId: null, + projectScopeKeys: [], + theme: null, + ...overrides, + }; +} + +function windowsState(overrides: Partial = {}): DesktopWindowsState { + return { + profiles: [mainProfile, workProfile], + windows: [ + openWindow(1, "Main", "", { isMain: true, profileId: "main" }), + openWindow(2, "Work", "", { profileId: "work", focused: true }), + ], + miniMode: false, + multiWindowEnabled: true, + ...overrides, + }; +} + +describe("selectCurrentWindowProfile", () => { + it("follows the live window entry, not the profile the window opened with", () => { + // Opened unsaved, then saved as "work". + expect(selectCurrentWindowProfile(windowsState(), context({ profileId: null }))).toBe( + workProfile, + ); + const deleted = windowsState({ windows: [unsavedWindow] }); + expect(selectCurrentWindowProfile(deleted, context({ profileId: "work" }))).toBeNull(); + }); + + it("falls back to the open-time profile until the window appears in state", () => { + expect( + selectCurrentWindowProfile(windowsState({ windows: [] }), context({ profileId: "work" })), + ).toBe(workProfile); + }); +}); + +describe("resolveWindowThemeOverride", () => { + it.each([ + ["no desktop context", null, windowsState(), null], + ["the main window", context({ windowId: 1, isMain: true, theme: "x" }), windowsState(), null], + ["state not loaded yet", context({ theme: "nord" }), null, "nord"], + ["a profile with a theme", context(), windowsState(), "dracula"], + [ + "a profile that follows the main window", + context(), + windowsState({ profiles: [mainProfile, { ...workProfile, theme: null }] }), + null, + ], + [ + "an unsaved window", + context({ theme: "nord" }), + windowsState({ windows: [unsavedWindow] }), + null, + ], + ] as const)("resolves %s", (_label, windowContext, state, expected) => { + expect(resolveWindowThemeOverride(state, windowContext)).toBe(expected); + }); +}); + +describe("isMiniMainWindow", () => { + it("applies Mini Mode to the main window only", () => { + const mini = windowsState({ miniMode: true }); + expect(isMiniMainWindow(mini, context({ windowId: 1, isMain: true }))).toBe(true); + expect(isMiniMainWindow(mini, context())).toBe(false); + expect(isMiniMainWindow(windowsState(), context({ windowId: 1, isMain: true }))).toBe(false); + expect(isMiniMainWindow(null, context({ windowId: 1, isMain: true }))).toBe(false); + }); +}); diff --git a/apps/web/src/multiWindow/windowsState.ts b/apps/web/src/multiWindow/windowsState.ts new file mode 100644 index 0000000000000..a92fdb1cdf786 --- /dev/null +++ b/apps/web/src/multiWindow/windowsState.ts @@ -0,0 +1,105 @@ +import type { + DesktopOpenWindow, + DesktopWindowContext, + DesktopWindowProfile, + DesktopWindowsState, +} from "@t3tools/contracts"; +import { useSyncExternalStore } from "react"; + +import { desktopWindowsBridge, readDesktopWindowContext } 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); + }; +} + +/** Null outside a desktop shell with multi-window support, and until the first state arrives. */ +export function useDesktopWindowsState(): DesktopWindowsState | null { + return useSyncExternalStore(subscribeDesktopWindowsState, readDesktopWindowsState, () => null); +} + +export function selectCurrentWindow( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): DesktopOpenWindow | null { + if (windowsState === null || context === null) return null; + return windowsState.windows.find((window) => window.windowId === context.windowId) ?? null; +} + +/** The window's live profile: saving or deleting it changes the profile after open. */ +export function selectCurrentWindowProfile( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): DesktopWindowProfile | null { + if (windowsState === null || context === null) return null; + const window = selectCurrentWindow(windowsState, context); + const profileId = window === null ? context.profileId : window.profileId; + if (profileId === null) return null; + return windowsState.profiles.find((profile) => profile.id === profileId) ?? null; +} + +/** + * The theme preference id this window uses instead of the shared one, or null to follow it. + * Before the first state arrives, the preload's open-time theme avoids a flash. + */ +export function resolveWindowThemeOverride( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): string | null { + if (context === null || context.isMain) return null; + if (windowsState === null) return context.theme; + return selectCurrentWindowProfile(windowsState, context)?.theme ?? null; +} + +export function isMiniMainWindow( + windowsState: DesktopWindowsState | null, + context: DesktopWindowContext | null, +): boolean { + return context?.isMain === true && windowsState?.miniMode === true; +} + +const readIsMiniMainWindow = () => + isMiniMainWindow(readDesktopWindowsState(), readDesktopWindowContext()); + +/** Re-renders only when mini mode flips, not for every focus change in the windows state. */ +export function useIsMiniMainWindow(): boolean { + return useSyncExternalStore(subscribeDesktopWindowsState, readIsMiniMainWindow, () => false); +} diff --git a/apps/web/src/projectIconColors.ts b/apps/web/src/projectIconColors.ts index 0f4161a6b86ba..8a4c3a18fbeb5 100644 --- a/apps/web/src/projectIconColors.ts +++ b/apps/web/src/projectIconColors.ts @@ -124,3 +124,8 @@ const PROJECT_ICON_COLOR_CLASSES = Object.fromEntries( export function projectIconColorClassName(color: ProjectIconColor): string { return PROJECT_ICON_COLOR_CLASSES[color]; } + +/** The swatch class's colour as a CSS value, for code that computes with it. */ +export function projectIconSwatch(color: ProjectIconColor): string { + return `var(--color-${color}-500)`; +} diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 3cbef77306c8e..61d4ae8f7200f 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -61,6 +61,14 @@ import { readProject } from "../state/entities"; import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot"; import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; +import { DesktopWindowsHost } from "../multiWindow/ui/DesktopWindowsHost"; +import { MiniMainWindow } from "../multiWindow/ui/MiniMainWindow"; +import { installDesktopWindowTheme } from "../multiWindow/ui/windowTheme"; +import { useIsMiniMainWindow } from "../multiWindow/windowsState"; +import { isSecondaryDesktopWindow } from "../multiWindow/windowContext"; + +// Before the first render, so a window with its own theme never paints the shared one. +installDesktopWindowTheme(); export const Route = createRootRoute({ beforeLoad: async ({ location }) => { @@ -143,6 +151,7 @@ function RootRouteView() { + ); @@ -160,6 +169,8 @@ function RootRouteBranch() { const hostedPromptLinkLanding = useHostedPromptLinkLanding( authGateState.status === "hosted-static", ); + const miniMainWindow = useIsMiniMainWindow(); + const secondaryWindow = isSecondaryDesktopWindow(); if (pathname === GUEST_PAGE_PATH) return ; @@ -186,13 +197,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} @@ -208,7 +220,9 @@ function RootRouteBranch() { {import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null} ); - const appShell = ( + const appShell = miniMainWindow ? ( + + ) : ( {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */} diff --git a/apps/web/src/uiStateStore.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..c405b17a87779 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 { desktopWindowsBridge, 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 lives in its window profile, never in 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,16 @@ interface UiStateStore extends UiState { ) => void; } +function readInitialState(): UiState { + const state = readPersistedState(); + persistedBaseline = state; + return windowContext !== null && !windowContext.isMain + ? { ...state, sidebarProjectScopeKeys: [...windowContext.projectScopeKeys] } + : state; +} + export const useUiStateStore = create((set) => ({ - ...readPersistedState(), + ...readInitialState(), markThreadVisited: (threadId, visitedAt) => set((state) => markThreadVisited(state, threadId, visitedAt)), markThreadUnread: (threadId, latestTurnCompletedAt) => @@ -460,6 +560,26 @@ 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 (!windowContext.isMain) { + const bridge = desktopWindowsBridge(); + useUiStateStore.subscribe((state, previous) => { + if (state.sidebarProjectScopeKeys === previous.sidebarProjectScopeKeys) return; + void bridge?.setProjectScopeKeys(state.sidebarProjectScopeKeys).catch(() => undefined); + }); + } +} + if (typeof window !== "undefined" && typeof window.addEventListener === "function") { 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..7cb05d4799b51 --- /dev/null +++ b/docs/user/multiple-windows.md @@ -0,0 +1,51 @@ +# Multiple windows + +The desktop app can open more than one window. Each window has its own sidebar project filter and +can use its own theme, so you can keep one window per project or task side by side. All windows +share the same environments, threads, and settings. The web app and mobile app use a single window. + +## Open a window + +Choose **New Window** in the command palette or the app menu, or press **Cmd+Option+Shift+N** on +macOS or **Ctrl+Alt+Shift+N** on Windows and Linux. The new window starts with the current window's +project filter. Change the shortcut under **Settings → Keybindings** (`window.new`). + +Closing the main window while others are open hides it instead, since the other windows connect +through it. On Windows and Linux it closes once the last other window does. + +To keep to one window, turn off **Multiple windows** under **Settings → General → Windows**. New +Window, its shortcut, and opening saved windows are then unavailable; windows already open stay open +until you close them. + +## Save a window + +When you close a window you have not saved, T3 Code asks whether to save it. Enter a name and choose +**Save** to keep its project filter and theme, **Don't Save** to close it without keeping anything, +or **Cancel** (or Escape) to keep it open. + +Reopen a saved window with **Open window: _name_** in the command palette, or from +**Settings → General → Windows**. If the window is already open, it comes to the front instead. + +## Manage saved windows + +**Settings → General → Windows** lists the main window with your saved windows below it. Rename a +window by editing its name in place, pick its theme, open or focus it, or delete it. **Add saved +window** creates one without opening it. Deleting a saved window that is open leaves it open as an +unsaved window. A window you have not saved yet can be saved from the same section. + +A window with a project filter uses **Project colour** by default: it keeps the main window's +theme, and its projects' icon colours mark its entry in the list. Projects whose icon is an image or +an emoji add no colour. Pick a theme for a saved window to use that theme +instead. Changing the theme from inside a window with its own theme changes only that window. +Light, dark, and system appearance stay shared by every window. + +## Mini Mode + +Choose **Enter Mini Mode** in the main window's command palette to turn the main window into a +small panel; drag its edge for more room. **Expand** returns to the full app, as does opening a +search result. On macOS the panel has no close, minimise or zoom buttons. + +The tabs along the panel's top show your other open windows, the list your Pull requests page opens +with, each account's usage limits, and whether an update is ready. Search, New Window and Expand sit +at the right. It opens on **Usage**, which shows each account's limits as small bars with the percent +left, and rereads them when the tab opens if they are more than five minutes old. 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..b491a24f5dbe3 --- /dev/null +++ b/packages/client-runtime/src/connection/hub.ts @@ -0,0 +1,190 @@ +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")(() => + Effect.succeed("unchecked" as const), + ), + checkHost: Effect.fn("HubConnectionDriver.checkHost")(() => + 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 supervisor: EnvironmentSupervisor.EnvironmentSupervisor["Service"]; + } + | { 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, + supervisor, + }); + } + 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, supervisor } = 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. + 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..6d17f44972383 --- /dev/null +++ b/packages/client-runtime/src/rpc/relay.ts @@ -0,0 +1,338 @@ +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"; +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; +} + +/** 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. +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 = yield* makeInbox(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 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 = yield* makeInbox(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..be8d02c1d104e 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,497 @@ 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, + options: RpcSession.RpcSessionOptions = { 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); + 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 { factory, 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, hub, socket } = yield* connectHubAndWindows(0, {}); + 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, hub } = yield* connectHubAndWindows(0); + 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..56f84272cef28 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,45 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( Effect.ignore, Effect.forkScoped, ); + const session = yield* finishSession({ + connection, + protocolContext, + via, + inboundFrames: Effect.sync(() => inboundFrames), + mapRpcError, + }); + 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: { + 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; + }) { + 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 +601,58 @@ 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)), } 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 })), + }), + ), + }); + }); + + 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..50185cf74d750 --- /dev/null +++ b/packages/contracts/src/desktopWindows.ts @@ -0,0 +1,151 @@ +import * as Schema from "effect/Schema"; + +/** The main window's profile. It always exists and cannot be deleted. */ +export const DEFAULT_DESKTOP_WINDOW_PROFILE_ID = "main"; + +export const DesktopWindowProfileIdSchema = Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(64), +); + +export const DesktopWindowProfileNameSchema = Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(80), +); + +export const DesktopWindowProjectScopeKeysSchema = Schema.Array( + Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)), +).check(Schema.isMaxLength(1000)); + +/** A theme preference id, or null for the main window's theme tinted with the filtered projects' icon colours. */ +export const DesktopWindowProfileThemeSchema = Schema.NullOr( + Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)), +); + +export const DesktopWindowProfileSchema = Schema.Struct({ + id: DesktopWindowProfileIdSchema, + name: DesktopWindowProfileNameSchema, + /** Unused for the default profile: the main window keeps its filter in its own UI state. */ + projectScopeKeys: DesktopWindowProjectScopeKeysSchema, + theme: DesktopWindowProfileThemeSchema, + isDefault: Schema.Boolean, +}); +export type DesktopWindowProfile = typeof DesktopWindowProfileSchema.Type; + +export const DesktopOpenWindowSchema = Schema.Struct({ + /** Electron's BrowserWindow id. */ + windowId: Schema.Int, + isMain: Schema.Boolean, + /** Null while a secondary window is unsaved. */ + profileId: Schema.NullOr(DesktopWindowProfileIdSchema), + /** The profile name, or a generated "Window N" label for an unsaved window. */ + name: Schema.String, + title: Schema.String, + focused: Schema.Boolean, + /** The window's current project filter; empty shows every project. */ + projectScopeKeys: DesktopWindowProjectScopeKeysSchema, +}); +export type DesktopOpenWindow = typeof DesktopOpenWindowSchema.Type; + +export const DesktopWindowsStateSchema = Schema.Struct({ + profiles: Schema.Array(DesktopWindowProfileSchema), + windows: Schema.Array(DesktopOpenWindowSchema), + miniMode: Schema.Boolean, + /** Off: no new secondary windows open; windows already open stay open. */ + multiWindowEnabled: Schema.Boolean, +}); +export type DesktopWindowsState = typeof DesktopWindowsStateSchema.Type; + +/** 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, + /** The profile the window opened with; null for an unsaved secondary window. */ + profileId: Schema.NullOr(Schema.String), + /** The profile's project filter at open time (secondary windows only). */ + projectScopeKeys: Schema.Array(Schema.String), + /** The profile's theme override at open time; null follows the default profile. */ + theme: Schema.NullOr(Schema.String), +}); +export type DesktopWindowContext = typeof DesktopWindowContextSchema.Type; + +export const DesktopOpenWindowInputSchema = Schema.Struct({ + /** Seeds an unsaved window's project filter, such as the opener's current filter. */ + projectScopeKeys: Schema.optionalKey(DesktopWindowProjectScopeKeysSchema), +}); +export type DesktopOpenWindowInput = typeof DesktopOpenWindowInputSchema.Type; + +export const DesktopCreateWindowProfileInputSchema = Schema.Struct({ + name: DesktopWindowProfileNameSchema, + projectScopeKeys: DesktopWindowProjectScopeKeysSchema, + theme: DesktopWindowProfileThemeSchema, +}); +export type DesktopCreateWindowProfileInput = typeof DesktopCreateWindowProfileInputSchema.Type; + +export const DesktopUpdateWindowProfileInputSchema = Schema.Struct({ + profileId: DesktopWindowProfileIdSchema, + name: Schema.optionalKey(DesktopWindowProfileNameSchema), + theme: Schema.optionalKey(DesktopWindowProfileThemeSchema), +}); +export type DesktopUpdateWindowProfileInput = typeof DesktopUpdateWindowProfileInputSchema.Type; + +export const DesktopWindowCloseRequestSchema = Schema.Struct({ + requestId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64)), + suggestedName: Schema.String, +}); +export type DesktopWindowCloseRequest = typeof DesktopWindowCloseRequestSchema.Type; + +export const DesktopWindowCloseDecisionSchema = Schema.Union([ + Schema.Struct({ action: Schema.Literal("save"), name: DesktopWindowProfileNameSchema }), + Schema.Struct({ action: Schema.Literal("discard") }), + Schema.Struct({ action: Schema.Literal("cancel") }), +]); +export type DesktopWindowCloseDecision = typeof DesktopWindowCloseDecisionSchema.Type; + +export const DesktopResolveWindowCloseInputSchema = Schema.Struct({ + requestId: DesktopWindowCloseRequestSchema.fields.requestId, + decision: DesktopWindowCloseDecisionSchema, +}); + +/** + * `window.postMessage` payload the preload uses to hand a hub link port to the page, + * since a MessagePort cannot cross the context bridge. The port is `event.ports[0]`. + */ +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: (input?: DesktopOpenWindowInput) => Promise; + /** Focuses the profile's window when it is open, otherwise opens it. */ + openProfile: (profileId: string) => Promise; + focus: (windowId: number) => Promise; + /** Saves a profile without opening its window. */ + createProfile: (input: DesktopCreateWindowProfileInput) => Promise; + /** Saves the calling window as a new profile. */ + saveAsProfile: (name: string) => Promise; + updateProfile: (input: DesktopUpdateWindowProfileInput) => Promise; + /** An open window of a deleted profile stays open, unsaved. The default profile cannot be deleted. */ + deleteProfile: (profileId: string) => Promise; + /** The calling secondary window's filter; saved to its profile, or held for save-on-close. */ + setProjectScopeKeys: (projectScopeKeys: readonly string[]) => Promise; + /** Asks the calling window whether to save itself before it closes. */ + onCloseRequest: (listener: (request: DesktopWindowCloseRequest) => void) => () => void; + resolveCloseRequest: (requestId: string, decision: DesktopWindowCloseDecision) => Promise; + setMiniMode: (enabled: boolean) => Promise; + setMultiWindowEnabled: (enabled: boolean) => Promise; + /** Main window only: its renderer serves secondary windows' environment connections. */ + registerHub: () => void; + /** Secondary windows only: asks for a port to the hub, delivered as a `DesktopHubLinkMessage`. */ + 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" },