diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index e11e946dd41ba..772379b964374 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -73,7 +73,9 @@ function layerElectronWindow(destroyAll: Effect.Effect = Effect.void) { create: () => Effect.die("unexpected window creation"), main: Effect.die("unexpected main window read"), currentMainOrFirst: Effect.die("unexpected current window read"), - focusedMainOrFirst: Effect.die("unexpected focused window read"), + apps: Effect.succeed([]), + focusedApp: Effect.succeedNone, + registerApp: () => Effect.void, setMain: () => Effect.void, clearMain: () => Effect.void, prepareReveal: () => Effect.succeed(false), @@ -90,7 +92,7 @@ function layerDesktopWindow( readonly flushMainWindowBounds?: Effect.Effect; } = {}, ) { - return Layer.succeed(DesktopWindow.DesktopWindow, { + return Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected window creation"), ensureMain: Effect.die("unexpected window creation"), revealOrCreateMain: Effect.die("unexpected window creation"), @@ -103,7 +105,6 @@ function layerDesktopWindow( prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.void, dispatchSnapShotEvent: () => Effect.void, - zoomMain: () => Effect.void, runMainContentsCommand: () => Effect.void, syncAppearance: Effect.void, }); diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 005a1cde1224a..1be204cb02354 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -203,7 +203,7 @@ function layerPool( showErrorBox: () => Effect.void, } satisfies ElectronDialog.ElectronDialog["Service"]), ElectronApp.layer, - Layer.succeed(DesktopWindow.DesktopWindow, { + Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected window create"), ensureMain: Effect.die("unexpected window ensure"), revealOrCreateMain: Effect.die("unexpected window reveal"), @@ -216,11 +216,10 @@ function layerPool( prepareCaptureReveal: Effect.void, dispatchMenuAction: () => Effect.die("unexpected menu action"), dispatchSnapShotEvent: () => Effect.void, - zoomMain: () => Effect.die("unexpected zoom"), runMainContentsCommand: options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")), syncAppearance: Effect.void, - } satisfies DesktopWindow.DesktopWindow["Service"]), + }), ), ), ); diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts index b5f89969e66c7..098e9191328f2 100644 --- a/apps/desktop/src/electron/ElectronWindow.ts +++ b/apps/desktop/src/electron/ElectronWindow.ts @@ -117,7 +117,11 @@ export class ElectronWindow extends Context.Service< ) => Effect.Effect; readonly main: Effect.Effect>; readonly currentMainOrFirst: Effect.Effect>; - readonly focusedMainOrFirst: Effect.Effect>; + /** Windows that load the app renderer: the main window first, then secondary windows. */ + readonly apps: Effect.Effect>; + /** The focused app window, else the main window; never a popup or auxiliary window. */ + readonly focusedApp: Effect.Effect>; + readonly registerApp: (window: Electron.BrowserWindow) => Effect.Effect; readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect; readonly clearMain: (window: Option.Option) => Effect.Effect; readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect; @@ -148,6 +152,7 @@ export const make = Effect.gen(function* () { yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close())); const mainWindowRef = yield* Ref.make>(Option.none()); const auxiliaryWindows = new WeakSet(); + const appWindows = new Set(); const titleBarOverlayWindows = new WeakSet(); const listWindows = Effect.try({ @@ -198,9 +203,22 @@ export const make = Effect.gen(function* () { return first; }); - const focusedMainOrFirst = Effect.gen(function* () { + const liveApps = Effect.gen(function* () { + const main = yield* liveMain; + const apps: Electron.BrowserWindow[] = Option.isSome(main) ? [main.value] : []; + for (const window of appWindows) { + if (yield* isWindowDestroyed(window)) { + appWindows.delete(window); + } else if (!apps.includes(window)) { + apps.push(window); + } + } + return apps; + }); + + const focusedApp = Effect.gen(function* () { const focused = yield* Effect.try({ - try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null), + try: () => Electron.BrowserWindow.getFocusedWindow(), catch: (cause) => new ElectronWindowOperationError({ operation: "get-focused-window", @@ -210,10 +228,9 @@ export const make = Effect.gen(function* () { cause, }), }).pipe(Effect.orDie); - if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) { - return focused; - } - return yield* currentMainOrFirst; + const apps = yield* liveApps; + if (focused !== null && apps.includes(focused)) return Option.some(focused); + return yield* liveMain; }); return ElectronWindow.of({ @@ -255,9 +272,15 @@ export const make = Effect.gen(function* () { }), main: liveMain, currentMainOrFirst, - focusedMainOrFirst, + apps: liveApps, + focusedApp, + registerApp: Effect.fn("ElectronWindow.registerApp")(function (window) { + return Effect.sync(() => void appWindows.add(window)); + }), setMain: Effect.fn("ElectronWindow.setMain")(function (window) { - return Ref.set(mainWindowRef, Option.some(window)); + return Ref.set(mainWindowRef, Option.some(window)).pipe( + Effect.andThen(Effect.sync(() => void appWindows.add(window))), + ); }), clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) { return Ref.update(mainWindowRef, (current) => { diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json index 8e39e7585f60d..94d156f928ed0 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "Verkleinern", "50fe114d093a5bc7": "Vollbildmodus ein/aus", "d8c6d6d9845353da": "Fenster", + "c015841b7b2523c6": "Neues Fenster", + "9f6a942f2b085033": "T3_BOT öffnen", "f184aa190588625e": "Minimieren", "c20a9deaed71bd1c": "Zoomen", "d207ba3a23f94223": "Alle nach vorne bringen", diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 9a07ef060cbc9..a3de7422cbccb 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "Zoom Out", "50fe114d093a5bc7": "Toggle Full Screen", "d8c6d6d9845353da": "Window", + "c015841b7b2523c6": "New Window", + "9f6a942f2b085033": "Open T3_BOT", "f184aa190588625e": "Minimize", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Bring All to Front", diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index f891e9eaf850b..73ca5f1d286d6 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "Alejar", "50fe114d093a5bc7": "Activar/desactivar pantalla completa", "d8c6d6d9845353da": "Ventana", + "c015841b7b2523c6": "Nueva ventana", + "9f6a942f2b085033": "Abrir T3_BOT", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Traer todo al frente", diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 0bb5a47518581..3733416eeb06b 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "Zoom arrière", "50fe114d093a5bc7": "Activer/désactiver le plein écran", "d8c6d6d9845353da": "Fenêtre", + "c015841b7b2523c6": "Nouvelle fenêtre", + "9f6a942f2b085033": "Ouvrir T3_BOT", "f184aa190588625e": "Réduire", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Tout ramener au premier plan", diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index df89efe466261..146c805a9db26 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "縮小", "50fe114d093a5bc7": "フルスクリーンに切り替え", "d8c6d6d9845353da": "ウインドウ", + "c015841b7b2523c6": "新規ウインドウ", + "9f6a942f2b085033": "T3_BOT を開く", "f184aa190588625e": "しまう", "c20a9deaed71bd1c": "拡大/縮小", "d207ba3a23f94223": "すべてを手前に移動", diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index 566724b9b91c1..675bd218b439f 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "축소", "50fe114d093a5bc7": "전체 화면 전환", "d8c6d6d9845353da": "윈도우", + "c015841b7b2523c6": "새 윈도우", + "9f6a942f2b085033": "T3_BOT 열기", "f184aa190588625e": "최소화", "c20a9deaed71bd1c": "확대/축소", "d207ba3a23f94223": "모두 앞으로 가져오기", diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 67f4eefd1c9ec..6c32b7717ff53 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "Diminuir zoom", "50fe114d093a5bc7": "Alternar tela cheia", "d8c6d6d9845353da": "Janela", + "c015841b7b2523c6": "Nova janela", + "9f6a942f2b085033": "Abrir T3_BOT", "f184aa190588625e": "Minimizar", "c20a9deaed71bd1c": "Zoom", "d207ba3a23f94223": "Trazer tudo para a frente", diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index 46364dfabe488..fd0aa70c3d6c2 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "Уменьшить", "50fe114d093a5bc7": "Полноэкранный режим", "d8c6d6d9845353da": "Окно", + "c015841b7b2523c6": "Новое окно", + "9f6a942f2b085033": "Открыть T3_BOT", "f184aa190588625e": "Свернуть", "c20a9deaed71bd1c": "Масштаб", "d207ba3a23f94223": "Все окна на передний план", diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index 67bcaf6a380aa..2dff7cae897de 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "Zooma ut", "50fe114d093a5bc7": "Växla helskärm", "d8c6d6d9845353da": "Fönster", + "c015841b7b2523c6": "Nytt fönster", + "9f6a942f2b085033": "Öppna T3_BOT", "f184aa190588625e": "Minimera", "c20a9deaed71bd1c": "Zooma", "d207ba3a23f94223": "Lägg alla överst", diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index 72122de01df62..0e32481098d4f 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -114,6 +114,8 @@ "df6ed2014f1737a8": "缩小", "50fe114d093a5bc7": "切换全屏", "d8c6d6d9845353da": "窗口", + "c015841b7b2523c6": "新建窗口", + "9f6a942f2b085033": "打开 T3_BOT", "f184aa190588625e": "最小化", "c20a9deaed71bd1c": "缩放", "d207ba3a23f94223": "前置全部窗口", diff --git a/apps/desktop/src/ipc/DesktopIpc.test.ts b/apps/desktop/src/ipc/DesktopIpc.test.ts index 1973ab49cefeb..36defff9eb9ea 100644 --- a/apps/desktop/src/ipc/DesktopIpc.test.ts +++ b/apps/desktop/src/ipc/DesktopIpc.test.ts @@ -9,9 +9,12 @@ vi.mock("electron", () => ({})); import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as DesktopIpc from "./DesktopIpc.ts"; -it.effect("answers only the main window's top frame", () => +it.effect("answers only app windows' top frames and tells handlers which window sent", () => Effect.gen(function* () { const mainFrame = {}; + const secondaryFrame = {}; + const mainWindow = { id: 10, webContents: { id: 1, mainFrame } }; + const secondaryWindow = { id: 11, webContents: { id: 3, mainFrame: secondaryFrame } }; const invoke = new Map(); const sync = new Map(); const ipc = yield* DesktopIpc.DesktopIpc.pipe( @@ -24,9 +27,11 @@ it.effect("answers only the main window's top frame", () => }).pipe( Layer.provide( Layer.mock(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ - webContents: { id: 1, mainFrame }, - } as unknown as Electron.BrowserWindow), + main: Effect.succeedSome(mainWindow as unknown as Electron.BrowserWindow), + apps: Effect.succeed([ + mainWindow, + secondaryWindow, + ] as unknown as ReadonlyArray), }), ), ), @@ -37,13 +42,21 @@ it.effect("answers only the main window's top frame", () => channel: "token", payload: Schema.Void, result: Schema.String, - handler: () => Effect.succeed("secret"), + handler: () => + Effect.map( + DesktopIpc.DesktopIpcSender, + ({ window, isMain }) => `secret-${window.id}${isMain ? "-main" : ""}`, + ), }), ); - yield* ipc.handleSync({ channel: "token-sync", handler: () => Effect.succeed("secret") }); + yield* ipc.handleSync({ + channel: "token-sync", + handler: () => Effect.map(DesktopIpc.DesktopIpcSender, ({ window }) => `secret-${window.id}`), + }); const senders = { app: { sender: { id: 1 }, senderFrame: mainFrame }, + secondary: { sender: { id: 3 }, senderFrame: secondaryFrame }, appSubframe: { sender: { id: 1 }, senderFrame: {} }, previewGuest: { sender: { id: 2 }, senderFrame: {} }, }; @@ -59,7 +72,8 @@ it.effect("answers only the main window's top frame", () => ]; } assert.deepEqual(results, { - app: ["secret", "secret"], + app: ["secret-10-main", "secret-10"], + secondary: ["secret-11", "secret-11"], appSubframe: ["rejected", undefined], previewGuest: ["rejected", undefined], }); diff --git a/apps/desktop/src/ipc/DesktopIpc.ts b/apps/desktop/src/ipc/DesktopIpc.ts index 69d4f70c15a0e..16a5e01bae121 100644 --- a/apps/desktop/src/ipc/DesktopIpc.ts +++ b/apps/desktop/src/ipc/DesktopIpc.ts @@ -5,6 +5,8 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import type * as Electron from "electron"; + import * as ElectronWindow from "../electron/ElectronWindow.ts"; export interface DesktopIpcInvokeEvent { @@ -16,7 +18,16 @@ export interface DesktopIpcSyncEvent extends DesktopIpcInvokeEvent { returnValue: unknown; } -export type DesktopIpcSenderGuard = (event: DesktopIpcInvokeEvent) => Effect.Effect; +/** The app window that sent the IPC call being handled. */ +export class DesktopIpcSender extends Context.Service< + DesktopIpcSender, + { readonly window: Electron.BrowserWindow; readonly isMain: boolean } +>()("@t3tools/desktop/ipc/DesktopIpc/DesktopIpcSender") {} + +/** Resolves the app window whose top frame sent the event; none rejects the call. */ +export type DesktopIpcSenderGuard = ( + event: DesktopIpcInvokeEvent, +) => Effect.Effect>; export type DesktopIpcHandleListener = ( event: DesktopIpcInvokeEvent, @@ -83,15 +94,17 @@ export interface DesktopSyncIpcMethod { readonly handler: () => Effect.Effect; } +type HandlerServices = Exclude; + export class DesktopIpc extends Context.Service< DesktopIpc, { readonly handle: ( input: DesktopIpcMethod, - ) => Effect.Effect; + ) => Effect.Effect | Scope.Scope>; readonly handleSync: ( input: DesktopSyncIpcMethod, - ) => Effect.Effect; + ) => Effect.Effect | Scope.Scope>; } >()("@t3tools/desktop/ipc/DesktopIpc") {} @@ -106,7 +119,7 @@ export const make = ( handler, }: DesktopIpcMethod) { yield* Effect.annotateCurrentSpan({ channel }); - const context = yield* Effect.context(); + const context = yield* Effect.context>(); const runPromise = Effect.runPromiseWith(context); yield* Effect.acquireRelease( @@ -117,10 +130,13 @@ export const make = ( runPromise( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); - if (!(yield* isTrustedSender(event))) { + const sender = yield* isTrustedSender(event); + if (Option.isNone(sender)) { return yield* new DesktopIpcUntrustedSenderError({ channel }); } - return yield* handler(raw, event); + return yield* handler(raw, event).pipe( + Effect.provideService(DesktopIpcSender, sender.value), + ); }).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")), ), ); @@ -142,7 +158,7 @@ export const make = ( handler, }: DesktopSyncIpcMethod) { yield* Effect.annotateCurrentSpan({ channel }); - const context = yield* Effect.context(); + const context = yield* Effect.context>(); const runSync = Effect.runSyncWith(context); yield* Effect.acquireRelease( @@ -154,11 +170,14 @@ export const make = ( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); // Throwing here would surface as an uncaught main-process exception. - if (!(yield* isTrustedSender(event))) { + const sender = yield* isTrustedSender(event); + if (Option.isNone(sender)) { yield* Effect.logWarning("Rejected sync IPC from an untrusted sender."); return undefined; } - return yield* handler(); + return yield* handler().pipe( + Effect.provideService(DesktopIpcSender, sender.value), + ); }).pipe( Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync"), @@ -184,22 +203,30 @@ export const layer = (ipcMain: DesktopIpcMain) => DesktopIpc, Effect.gen(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; + // Only an app window's top frame is trusted, never a preview guest or subframe. return make(ipcMain, (event) => - Effect.map( - electronWindow.main, - (main) => - Option.isSome(main) && - main.value.webContents.id === event.sender.id && - main.value.webContents.mainFrame === event.senderFrame, - ), + Effect.gen(function* () { + const main = yield* electronWindow.main; + const window = (yield* electronWindow.apps).find( + (candidate) => + candidate.webContents.id === event.sender.id && + candidate.webContents.mainFrame === event.senderFrame, + ); + return window === undefined + ? Option.none() + : Option.some({ window, isMain: Option.contains(main, window) }); + }), ); }), ); -export const layerTest = (ipcMain: DesktopIpcMain) => +export const layerTest = ( + ipcMain: DesktopIpcMain, + sender: DesktopIpcSender["Service"] = { window: {} as Electron.BrowserWindow, isMain: true }, +) => Layer.succeed( DesktopIpc, - make(ipcMain, () => Effect.succeed(true)), + make(ipcMain, () => Effect.succeedSome(sender)), ); export interface DesktopIpcMethodRegistration< diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index c88ddd0827df0..099ae312c7c12 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -79,6 +79,7 @@ import { setSnapShotShortcutSuppressed, } from "./methods/snapShot.ts"; import * as PreviewIpc from "./methods/preview.ts"; +import * as WindowsIpc from "./methods/windows.ts"; import * as AppActivationIpc from "./methods/appActivation.ts"; import * as WebLinksIpc from "./methods/webLinks.ts"; import { @@ -189,6 +190,13 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" Effect.Services> >(previewMethod); } + yield* ipc.handleSync(WindowsIpc.getContext); + for (const windowsMethod of WindowsIpc.methods) { + yield* ipc.handle< + Effect.Error>, + Effect.Services> + >(windowsMethod); + } yield* ipc.handle(PreviewIpc.listBrowserImportSources); yield* ipc.handle(PreviewIpc.importBrowserCookies); }); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 71d272333fdc7..b9452236fa1f4 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -154,3 +154,18 @@ 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_BOT_OPEN_CHANNEL = "desktop:windows-bot-open"; +export const WINDOWS_BOT_SET_SIZE_CHANNEL = "desktop:windows-bot-set-size"; +export const WINDOWS_BOT_SET_PINNED_CHANNEL = "desktop:windows-bot-set-pinned"; +export const WINDOWS_REGISTER_HUB_CHANNEL = "desktop:windows-register-hub"; +export const WINDOWS_REQUEST_HUB_LINK_CHANNEL = "desktop:windows-request-hub-link"; +export const WINDOWS_HUB_LINK_CHANNEL = "desktop:windows-hub-link"; +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..d5e491710dd25 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -142,9 +142,8 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL, result: Schema.Boolean, handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.currentMainOrFirst; - return Option.isSome(window) && window.value.isFullScreen(); + const { window } = yield* DesktopIpc.DesktopIpcSender; + return !window.isDestroyed() && window.isFullScreen(); }), }); @@ -237,7 +236,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const environment = yield* DesktopEnvironment.DesktopEnvironment; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; @@ -268,7 +267,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ ) : environment.resolvePickFolderDefaultPath(options); const selectedPath = yield* dialog.pickFolder({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath, }); if (Option.isNone(selectedPath)) { @@ -306,13 +305,13 @@ export const pickProjectFavicon = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; if (!(yield* appSettings.get).localEnvironmentEnabled) { return null; } const paths = yield* dialog.pickFiles({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath: Option.fromNullishOr(initialPath), multiple: false, filters: [ @@ -342,14 +341,13 @@ export const showContextMenu = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.String), handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) { const electronMenu = yield* ElectronMenu.ElectronMenu; - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.focusedMainOrFirst; - if (Option.isNone(window)) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return null; } const selectedItemId = yield* electronMenu.showContextMenu({ - window: window.value, + window, items: input.items, position: Option.fromNullishOr(input.position), source: Option.fromNullishOr(input.source), @@ -381,17 +379,12 @@ export const readMedia = DesktopIpc.makeIpcMethod({ channel: IpcChannels.READ_MEDIA_CHANNEL, payload: Schema.String, result: Schema.NullOr(DesktopMediaReadSchema), - handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) { - const window = yield* (yield* ElectronWindow.ElectronWindow).main; - if ( - event === undefined || - Option.isNone(window) || - window.value.webContents.id !== event.sender.id || - !/^https?:$/.test(URL.parse(url)?.protocol ?? "") - ) { + handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed() || !/^https?:$/.test(URL.parse(url)?.protocol ?? "")) { return null; } - const session = window.value.webContents.session; + const session = window.webContents.session; return yield* Effect.tryPromise({ try: async () => { // Like an , send the session's cookies. @@ -463,22 +456,16 @@ export const pasteAsText = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PASTE_AS_TEXT_CHANNEL, payload: Schema.Undefined, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(window) || - window.value.isDestroyed() || - window.value.webContents.id !== event.sender.id - ) { + handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return; } const focused = Electron.webContents.getFocusedWebContents(); if ( focused && !focused.isDestroyed() && - Electron.BrowserWindow.fromWebContents(focused) === window.value + Electron.BrowserWindow.fromWebContents(focused) === window ) { focused.paste(); } @@ -489,17 +476,10 @@ export const revealWindow = DesktopIpc.makeIpcMethod({ channel: IpcChannels.REVEAL_WINDOW_CHANNEL, payload: Schema.Undefined, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) { + handler: Effect.fn("desktop.ipc.window.revealWindow")(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(window) || - window.value.webContents.id !== event.sender.id - ) { - return; - } - yield* electronWindow.reveal(window.value); + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* electronWindow.reveal(window); }), }); @@ -521,24 +501,17 @@ const htmlFullscreenState = (window: Electron.BrowserWindow) => { return state; }; -// The main window keeps HTML fullscreen inside itself so preview guests stay in their webview, +// App windows keep HTML fullscreen inside themselves so preview guests stay in their webview, // so the app's own fullscreen elements, such as chat videos, take the screen here. export const syncHtmlFullscreen = DesktopIpc.makeIpcMethod({ channel: IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL, payload: Schema.Boolean, result: Schema.Void, - handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen, event) { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const main = yield* electronWindow.main; - if ( - event === undefined || - Option.isNone(main) || - main.value.isDestroyed() || - main.value.webContents.id !== event.sender.id - ) { + handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + if (window.isDestroyed()) { return; } - const window = main.value; const state = htmlFullscreenState(window); if (fullscreen) { // macOS reports fullscreen until its exit animation ends, and Electron queues the re-entry. @@ -561,7 +534,7 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({ result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)), handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () { const dialog = yield* ElectronDialog.ElectronDialog; - const electronWindow = yield* ElectronWindow.ElectronWindow; + const { window } = yield* DesktopIpc.DesktopIpcSender; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions"); @@ -569,7 +542,7 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({ .exists(extensionsDir) .pipe(Effect.orElseSucceed(() => false)); const paths = yield* dialog.pickFiles({ - owner: yield* electronWindow.focusedMainOrFirst, + owner: Option.some(window), defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(), filters: [{ name: "JSON", extensions: ["json"] }], multiple: true, diff --git a/apps/desktop/src/ipc/methods/windows.ts b/apps/desktop/src/ipc/methods/windows.ts new file mode 100644 index 0000000000000..a22643583f383 --- /dev/null +++ b/apps/desktop/src/ipc/methods/windows.ts @@ -0,0 +1,99 @@ +import { + DesktopBotWindowSizeSchema, + DesktopWindowContextSchema, + DesktopWindowsStateSchema, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as DesktopWindow from "../../window/DesktopWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; + +export const getContext = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.WINDOWS_GET_CONTEXT_CHANNEL, + result: Schema.NullOr(DesktopWindowContextSchema), + handler: Effect.fn("desktop.ipc.windows.getContext")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + const desktopWindow = yield* DesktopWindow.DesktopWindow; + return Option.getOrNull(yield* desktopWindow.windowContext(window)); + }), +}); + +const getState = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_GET_STATE_CHANNEL, + payload: Schema.Void, + result: DesktopWindowsStateSchema, + handler: Effect.fn("desktop.ipc.windows.getState")(function* () { + return yield* (yield* DesktopWindow.DesktopWindow).windowsState; + }), +}); + +const openNew = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_OPEN_NEW_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openNew")(function* () { + yield* (yield* DesktopWindow.DesktopWindow).openNewWindow; + }), +}); + +const registerHub = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.registerHub")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).registerHub(window); + }), +}); + +const requestHubLink = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_REQUEST_HUB_LINK_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.requestHubLink")(function* () { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).requestHubLink(window); + }), +}); + +const openBot = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_BOT_OPEN_CHANNEL, + payload: Schema.Void, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.openBot")(function* () { + yield* (yield* DesktopWindow.DesktopWindow).openBot; + }), +}); + +const setBotSize = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_BOT_SET_SIZE_CHANNEL, + payload: DesktopBotWindowSizeSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setBotSize")(function* (size) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setBotSize(window, size); + }), +}); + +const setBotPinned = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.WINDOWS_BOT_SET_PINNED_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.windows.setBotPinned")(function* (pinned) { + const { window } = yield* DesktopIpc.DesktopIpcSender; + yield* (yield* DesktopWindow.DesktopWindow).setBotPinned(window, pinned); + }), +}); + +export const methods = [ + getState, + openNew, + registerHub, + requestHubLink, + openBot, + setBotSize, + setBotPinned, +] as const; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ac52fbc73d868..5aa154191ad98 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -1,5 +1,7 @@ import type { + DESKTOP_HUB_LINK_MESSAGE_TYPE, DesktopBridge, + DesktopHubLinkMessage, DesktopPreviewAnnotationVoiceEvent, DesktopPreviewFindResultEvent, DesktopPreviewOpenLinkEvent, @@ -7,6 +9,9 @@ import type { DesktopPreviewRecordingInputEvent, DesktopPreviewTabState, DesktopSnapShotEvent, + DesktopWindowContext, + DesktopWindowsBridge, + DesktopWindowsState, } from "@t3tools/contracts"; import { exposeClerkBridge } from "@clerk/electron/preload"; import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron"; @@ -87,6 +92,69 @@ if (!primaryPasteEnabled) { ); } +// Typed against the contract's constant so they cannot drift; importing it would bundle contracts. +const HUB_LINK_MESSAGE_TYPE: typeof DESKTOP_HUB_LINK_MESSAGE_TYPE = "t3code:desktop-hub-link"; + +const windowContext = ((): DesktopWindowContext => { + try { + const result: unknown = ipcRenderer.sendSync(IpcChannels.WINDOWS_GET_CONTEXT_CHANNEL); + if (typeof result === "object" && result !== null) return result as DesktopWindowContext; + } catch {} + return { windowId: -1, isMain: true }; +})(); + +// A MessagePort cannot cross the context bridge, so the page receives it as a window message. +ipcRenderer.on(IpcChannels.WINDOWS_HUB_LINK_CHANNEL, (event, message: unknown) => { + const peerWindowId = + typeof message === "object" && message !== null && "peerWindowId" in message + ? message.peerWindowId + : undefined; + if (typeof peerWindowId !== "number" || event.ports.length === 0) return; + window.postMessage( + { type: HUB_LINK_MESSAGE_TYPE, peerWindowId } satisfies DesktopHubLinkMessage, + "*", + event.ports, + ); +}); + +const subscribe = + (channel: string, decode: (value: unknown) => A | undefined) => + (listener: (value: A) => void) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, value: unknown) => { + const decoded = decode(value); + if (decoded !== undefined) listener(decoded); + }; + ipcRenderer.on(channel, wrappedListener); + return () => { + ipcRenderer.removeListener(channel, wrappedListener); + }; + }; + +const windows: DesktopWindowsBridge = { + getContext: () => windowContext, + getState: () => ipcRenderer.invoke(IpcChannels.WINDOWS_GET_STATE_CHANNEL), + onState: subscribe(IpcChannels.WINDOWS_STATE_CHANNEL, (state) => + typeof state === "object" && state !== null ? (state as DesktopWindowsState) : undefined, + ), + openNew: () => ipcRenderer.invoke(IpcChannels.WINDOWS_OPEN_NEW_CHANNEL), + registerHub: () => { + void ipcRenderer.invoke(IpcChannels.WINDOWS_REGISTER_HUB_CHANNEL).catch(() => undefined); + }, + requestHubLink: () => { + void ipcRenderer.invoke(IpcChannels.WINDOWS_REQUEST_HUB_LINK_CHANNEL).catch(() => undefined); + }, + onHubPeerGone: subscribe(IpcChannels.WINDOWS_HUB_PEER_GONE_CHANNEL, (windowId) => + typeof windowId === "number" ? windowId : undefined, + ), + onHubReset: (listener) => + subscribe(IpcChannels.WINDOWS_HUB_RESET_CHANNEL, () => true)(() => listener()), + bot: { + open: () => ipcRenderer.invoke(IpcChannels.WINDOWS_BOT_OPEN_CHANNEL), + setSize: (size) => ipcRenderer.invoke(IpcChannels.WINDOWS_BOT_SET_SIZE_CHANNEL, size), + setPinned: (pinned) => ipcRenderer.invoke(IpcChannels.WINDOWS_BOT_SET_PINNED_CHANNEL, pinned), + }, +}; + function unwrapEnsureSshEnvironmentResult(result: unknown) { if ( typeof result === "object" && @@ -164,6 +232,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 +640,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..3129752a0ed8a 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -13,6 +13,20 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopAppSettings from "./DesktopAppSettings.ts"; const DesktopSettingsPatch = Schema.Struct({ + botWindow: Schema.optionalKey( + Schema.Struct({ + bounds: Schema.optionalKey( + Schema.Struct({ + x: Schema.Number, + y: Schema.Number, + width: Schema.Number, + height: Schema.Number, + }), + ), + size: Schema.optionalKey(Schema.Literals(["narrow", "medium"])), + pinned: Schema.optionalKey(Schema.Boolean), + }), + ), linuxPasswordStore: Schema.optionalKey( Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]), ), @@ -223,6 +237,7 @@ describe("DesktopSettings", () => { ); assert.deepEqual(yield* settings.load, { + botWindow: { bounds: null, size: "narrow", pinned: false }, linuxPasswordStore: "auto", localEnvironmentEnabled: true, mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 }, @@ -295,11 +310,16 @@ describe("DesktopSettings", () => { yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 400, height: 360 }, true); yield* settings.setServerExposureMode("network-accessible"); + // Narrower than any main window may be. + yield* settings.updateBotWindow({ bounds: { x: 1500, y: 60, width: 380, height: 720 } }); + yield* settings.updateBotWindow({ pinned: true }); + assert.isFalse((yield* settings.updateBotWindow({ pinned: true })).changed); const persisted = yield* decodeDesktopSettingsPatch( yield* fileSystem.readFileString(environment.desktopSettingsPath), ); assert.deepEqual(persisted, { + botWindow: { bounds: { x: 1500, y: 60, width: 380, height: 720 }, pinned: true }, mainWindowBounds: { x: -1200, y: 40, width: 400, height: 360 }, mainWindowMaximized: true, serverExposureMode: "network-accessible", @@ -311,6 +331,11 @@ describe("DesktopSettings", () => { }).pipe(Effect.provide(DesktopAppSettings.layer)); assert.deepEqual(restored.mainWindowBounds, persisted.mainWindowBounds); assert.isTrue(restored.mainWindowMaximized); + assert.deepEqual(restored.botWindow, { + bounds: { x: 1500, y: 60, width: 380, height: 720 }, + size: "narrow", + pinned: true, + }); }), ), ); @@ -376,6 +401,7 @@ describe("DesktopSettings", () => { }); assert.deepEqual(yield* settings.load, { + botWindow: { bounds: null, size: "narrow", pinned: false }, linuxPasswordStore: "auto", localEnvironmentEnabled: true, mainWindowBounds: null, @@ -405,6 +431,7 @@ describe("DesktopSettings", () => { }); assert.deepEqual(yield* settings.load, { + botWindow: { bounds: null, size: "narrow", pinned: false }, linuxPasswordStore: "auto", localEnvironmentEnabled: true, mainWindowBounds: null, diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index e81da70660648..a5e592f3adb37 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -1,6 +1,8 @@ import { + DesktopBotWindowSizeSchema, DesktopServerExposureModeSchema, DesktopUpdateChannelSchema, + type DesktopBotWindowSize, type DesktopServerExposureMode, type DesktopUpdateChannel, } from "@t3tools/contracts"; @@ -27,7 +29,14 @@ import { import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; import { isValidDistroName } from "../wsl/wslPathParsing.ts"; +export interface DesktopBotWindowSettings { + readonly bounds: DesktopBotWindowBounds | null; + readonly size: DesktopBotWindowSize; + readonly pinned: boolean; +} + export interface DesktopSettings { + readonly botWindow: DesktopBotWindowSettings; readonly localEnvironmentEnabled: boolean; readonly linuxPasswordStore: LinuxPasswordStorePreference; readonly mainWindowBounds: DesktopWindowBounds | null; @@ -68,7 +77,29 @@ export const DEFAULT_MAIN_WINDOW_SIZE = { height: 780, } as const; +export const MIN_BOT_WINDOW_SIZE = { + width: 320, + height: 420, +} as const; +export const BOT_WINDOW_SIZES = { + narrow: { width: 380, height: 720 }, + medium: { width: 900, height: 760 }, +} as const satisfies Record; +export const DesktopBotWindowBoundsSchema = Schema.Struct({ + x: Schema.Int, + y: Schema.Int, + width: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_BOT_WINDOW_SIZE.width)), + height: Schema.Int.check(Schema.isGreaterThanOrEqualTo(MIN_BOT_WINDOW_SIZE.height)), +}); +export type DesktopBotWindowBounds = typeof DesktopBotWindowBoundsSchema.Type; +const DEFAULT_BOT_WINDOW_SETTINGS: DesktopBotWindowSettings = { + bounds: null, + size: "narrow", + pinned: false, +}; + export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { + botWindow: DEFAULT_BOT_WINDOW_SETTINGS, localEnvironmentEnabled: true, linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE, mainWindowBounds: null, @@ -95,7 +126,14 @@ const DesktopWindowBoundsDocument = Schema.Struct({ const optionalReadableKey = (schema: S) => Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone))); +const DesktopBotWindowDocument = Schema.Struct({ + bounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), + size: optionalReadableKey(DesktopBotWindowSizeSchema), + pinned: optionalReadableKey(Schema.Boolean), +}); + const DesktopSettingsDocument = Schema.Struct({ + botWindow: optionalReadableKey(DesktopBotWindowDocument), localEnvironmentEnabled: optionalReadableKey(Schema.Boolean), linuxPasswordStore: optionalReadableKey(Schema.Unknown), mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), @@ -119,6 +157,8 @@ const decodeDesktopSettingsJson = Schema.decodeEffect(DesktopSettingsJson); const encodeDesktopSettingsJson = Schema.encodeEffect(DesktopSettingsJson); const decodeDesktopWindowBounds = Schema.decodeUnknownOption(DesktopWindowBoundsSchema); const desktopWindowBoundsEquivalence = Schema.toEquivalence(DesktopWindowBoundsSchema); +const decodeDesktopBotWindowBounds = Schema.decodeUnknownOption(DesktopBotWindowBoundsSchema); +const desktopBotWindowBoundsEquivalence = Schema.toEquivalence(DesktopBotWindowBoundsSchema); const settingsChange = (settings: DesktopSettings, changed: boolean): DesktopSettingsChange => ({ settings, @@ -160,6 +200,9 @@ export class DesktopAppSettings extends Context.Service< bounds: DesktopWindowBounds, isMaximized: boolean, ) => Effect.Effect; + readonly updateBotWindow: ( + update: Partial, + ) => Effect.Effect; readonly setServerExposureMode: ( mode: DesktopServerExposureMode, ) => Effect.Effect; @@ -208,6 +251,10 @@ export function normalizeMainWindowBounds(value: unknown): DesktopWindowBounds | return Option.getOrNull(decodeDesktopWindowBounds(value)); } +export function normalizeBotWindowBounds(value: unknown): DesktopBotWindowBounds | null { + return Option.getOrNull(decodeDesktopBotWindowBounds(value)); +} + function normalizeDesktopSettingsDocument( parsed: DesktopSettingsDocument, appVersion: string, @@ -225,6 +272,11 @@ function normalizeDesktopSettingsDocument( (parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl"); return { + botWindow: { + bounds: normalizeBotWindowBounds(parsed.botWindow?.bounds), + size: parsed.botWindow?.size ?? DEFAULT_BOT_WINDOW_SETTINGS.size, + pinned: parsed.botWindow?.pinned === true, + }, localEnvironmentEnabled: parsed.localEnvironmentEnabled !== false, linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore), mainWindowBounds, @@ -249,6 +301,16 @@ function toDesktopSettingsDocument( ): DesktopSettingsDocument { const document: Mutable = {}; + const { botWindow } = settings; + const botWindowDocument = { + ...(botWindow.bounds === null ? {} : { bounds: botWindow.bounds }), + ...(botWindow.size === DEFAULT_BOT_WINDOW_SETTINGS.size ? {} : { size: botWindow.size }), + ...(botWindow.pinned ? { pinned: true } : {}), + }; + if (Object.keys(botWindowDocument).length > 0) { + document.botWindow = botWindowDocument; + } + if (settings.localEnvironmentEnabled !== defaults.localEnvironmentEnabled) { document.localEnvironmentEnabled = settings.localEnvironmentEnabled; } @@ -318,6 +380,22 @@ function setMainWindowBounds( }; } +function updateBotWindow( + settings: DesktopSettings, + update: Partial, +): DesktopSettings { + const current = settings.botWindow; + const next = { ...current, ...update }; + const boundsUnchanged = + next.bounds === current.bounds || + (next.bounds !== null && + current.bounds !== null && + desktopBotWindowBoundsEquivalence(next.bounds, current.bounds)); + return boundsUnchanged && next.size === current.size && next.pinned === current.pinned + ? settings + : { ...settings, botWindow: next }; +} + function setTailscaleServe( settings: DesktopSettings, input: { readonly enabled: boolean; readonly port: Option.Option }, @@ -562,6 +640,9 @@ export const make = Effect.gen(function* () { return yield* persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)); }, ), + updateBotWindow: Effect.fn("desktop.settings.updateBotWindow")(function* (patch) { + return yield* persist((settings) => updateBotWindow(settings, patch)); + }), setServerExposureMode: Effect.fn("desktop.settings.setServerExposureMode")(function* (mode) { yield* Effect.annotateCurrentSpan({ mode }); @@ -635,6 +716,9 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET return update((settings) => setMainWindowBounds(settings, bounds, isMaximized)); }, ), + updateBotWindow: Effect.fn("DesktopAppSettings.updateBotWindow")(function (patch) { + return update((settings) => updateBotWindow(settings, patch)); + }), setServerExposureMode: Effect.fn("DesktopAppSettings.setServerExposureMode")( function (mode) { return update((settings) => setServerExposureMode(settings, mode)); diff --git a/apps/desktop/src/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..9c2b8e0d15cd6 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), @@ -216,6 +218,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { get: Effect.sync(() => testSettings), load: Effect.sync(() => testSettings), setMainWindowBounds: () => Effect.die("unexpected main window bounds update"), + updateBotWindow: () => Effect.die("unexpected bot window update"), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: (channel) => diff --git a/apps/desktop/src/window/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..df488889b5b20 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -92,7 +92,7 @@ const layerDesktopUpdates = ({ checkResult }: MenuServices) => } satisfies DesktopUpdates.DesktopUpdates["Service"]); const layerDesktopWindow = (selectedAction: Deferred.Deferred) => - Layer.succeed(DesktopWindow.DesktopWindow, { + Layer.mock(DesktopWindow.DesktopWindow)({ createMain: Effect.die("unexpected createMain"), ensureMain: Effect.die("unexpected ensureMain"), revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"), @@ -105,12 +105,13 @@ const layerDesktopWindow = (selectedAction: Deferred.Deferred) => prepareCaptureReveal: Effect.void, dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid), dispatchSnapShotEvent: () => Effect.void, - zoomMain: (direction) => + zoomFocused: (direction) => Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid), - runMainContentsCommand: (command) => + runFocusedContentsCommand: (command) => Deferred.succeed(selectedAction, `main-${command}`).pipe(Effect.asVoid), syncAppearance: Effect.void, - } satisfies DesktopWindow.DesktopWindow["Service"]); + openBot: Deferred.succeed(selectedAction, "open-bot").pipe(Effect.asVoid), + }); const layerElectronMenu = ( applicationMenuTemplate: Deferred.Deferred, @@ -347,6 +348,33 @@ describe("DesktopApplicationMenu", () => { assert.equal(yield* Deferred.await(selectedAction), "main-reload"); }), ); + it.effect.each([ + { index: 0, label: "New Window", accelerator: "CmdOrCtrl+Alt+Shift+N", action: "new-window" }, + { index: 1, label: "Open T3_BOT", accelerator: "CmdOrCtrl+Alt+Shift+B", action: "open-bot" }, + ])("leads the Window menu with $label and leaves its chord to the renderer", (expected) => + Effect.gen(function* () { + const selectedAction = yield* Deferred.make(); + const applicationMenuTemplate = + yield* Deferred.make(); + yield* configureMenu(selectedAction, applicationMenuTemplate); + + const windowMenu = (yield* Deferred.await(applicationMenuTemplate)).find( + (item) => item.role === "windowMenu", + ); + if (!Array.isArray(windowMenu?.submenu)) { + throw new Error("Expected the Window menu submenu to be an array."); + } + const item = windowMenu.submenu[expected.index]; + assert.deepEqual( + { label: item?.label, accelerator: item?.accelerator }, + { label: expected.label, accelerator: expected.accelerator }, + ); + assert.equal(item?.registerAccelerator, false); + item?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + assert.equal(yield* Deferred.await(selectedAction), expected.action); + }), + ); + 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..689d74d0bef4f 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -55,18 +55,18 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function }); }); -const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* ( +const zoomFocusedWindow = Effect.fn("desktop.menu.zoomFocusedWindow")(function* ( direction: DesktopWindow.MainWindowZoomDirection, ): Effect.fn.Return { const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.zoomMain(direction); + yield* desktopWindow.zoomFocused(direction); }); -const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")(function* ( +const runFocusedContentsCommand = Effect.fn("desktop.menu.runFocusedContentsCommand")(function* ( command: DesktopWindow.MainWindowContentsCommand, ): Effect.fn.Return { const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.runMainContentsCommand(command); + yield* desktopWindow.runFocusedContentsCommand(command); }); const trackLabel = (channel: DesktopUpdateChannel) => @@ -74,6 +74,10 @@ const trackLabel = (channel: DesktopUpdateChannel) => ? m(msg("Nightly", { $context: "release track" })) : m(msg("Stable", { $context: "release track" })); +const openBotWindow = Effect.gen(function* () { + yield* (yield* DesktopWindow.DesktopWindow).openBot; +}).pipe(Effect.withSpan("desktop.menu.openBotWindow")); + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -224,10 +228,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 +400,21 @@ export const make = Effect.gen(function* () { role: "windowMenu", label: m(msg("Window", { $context: "menu bar title" })), submenu: [ + { + label: m(msg("New Window", { $context: "Window menu item" })), + // The renderer's window.new keybinding owns the chord. + accelerator: "CmdOrCtrl+Alt+Shift+N", + registerAccelerator: false, + click: () => runMenuEffect("new-window", dispatchMenuAction("new-window")), + }, + { + label: m(msg("Open T3_BOT", { $context: "Window menu item" })), + // The renderer's bot.open keybinding owns the chord. + accelerator: "CmdOrCtrl+Alt+Shift+B", + registerAccelerator: false, + click: () => runMenuEffect("open-bot", openBotWindow), + }, + { type: "separator" }, { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) }, { role: "zoom", diff --git a/apps/desktop/src/window/DesktopHubLinks.test.ts b/apps/desktop/src/window/DesktopHubLinks.test.ts new file mode 100644 index 0000000000000..af4d8ce49dd3f --- /dev/null +++ b/apps/desktop/src/window/DesktopHubLinks.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; + +const setup = () => { + let channels = 0; + const deliveries: Array<{ to: number; port: string; peerWindowId: number }> = []; + const broker = new HubLinkBroker(() => { + channels += 1; + return { port1: `hub-end-${channels}`, port2: `window-end-${channels}` }; + }); + const peer = (windowId: number): HubLinkPeer => ({ + windowId, + deliver: (port, peerWindowId) => deliveries.push({ to: windowId, port, peerWindowId }), + }); + return { broker, deliveries, peer }; +}; + +describe("HubLinkBroker", () => { + it("holds requests until the hub registers, once per window", () => { + const { broker, deliveries, peer } = setup(); + broker.request(peer(2)); + broker.request(peer(2)); + broker.request(peer(3)); + expect(deliveries).toEqual([]); + + broker.registerHub(peer(1)); + expect(deliveries).toEqual([ + { to: 1, port: "hub-end-1", peerWindowId: 2 }, + { to: 2, port: "window-end-1", peerWindowId: 1 }, + { to: 1, port: "hub-end-2", peerWindowId: 3 }, + { to: 3, port: "window-end-2", peerWindowId: 1 }, + ]); + }); + + it("links at once while the hub is ready and makes windows relink after it resets", () => { + const { broker, deliveries, peer } = setup(); + broker.registerHub(peer(1)); + broker.request(peer(2)); + expect(deliveries).toHaveLength(2); + + expect(broker.resetHub()).toBe(true); + expect(broker.resetHub()).toBe(false); + expect(broker.peerGone(2)).toBe(false); + broker.request(peer(2)); + expect(deliveries).toHaveLength(2); + + broker.registerHub(peer(1)); + expect(deliveries.slice(2)).toEqual([ + { to: 1, port: "hub-end-2", peerWindowId: 2 }, + { to: 2, port: "window-end-2", peerWindowId: 1 }, + ]); + }); + + it("tells the hub about a gone window only when it held links to it", () => { + const { broker, deliveries, peer } = setup(); + broker.request(peer(4)); + expect(broker.peerGone(4)).toBe(false); + broker.registerHub(peer(1)); + expect(deliveries).toEqual([]); + + broker.request(peer(2)); + expect(broker.peerGone(2)).toBe(true); + expect(broker.peerGone(2)).toBe(false); + }); +}); diff --git a/apps/desktop/src/window/DesktopHubLinks.ts b/apps/desktop/src/window/DesktopHubLinks.ts new file mode 100644 index 0000000000000..e0e91197c0411 --- /dev/null +++ b/apps/desktop/src/window/DesktopHubLinks.ts @@ -0,0 +1,55 @@ +export interface HubLinkPeer { + readonly windowId: number; + readonly deliver: (port: Port, peerWindowId: number) => void; +} + +/** + * Pairs secondary windows with the main window's renderer, which owns every environment + * connection. Requests made before the hub registers wait for it. + */ +export class HubLinkBroker { + private hub: HubLinkPeer | null = null; + private readonly pending = new Map>(); + private readonly linked = new Set(); + private readonly createChannel: () => { port1: Port; port2: Port }; + + constructor(createChannel: () => { port1: Port; port2: Port }) { + this.createChannel = createChannel; + } + + registerHub(hub: HubLinkPeer): void { + this.hub = hub; + const waiting = [...this.pending.values()]; + this.pending.clear(); + for (const peer of waiting) this.link(hub, peer); + } + + /** Returns whether the hub had been serving; its secondary windows must then relink. */ + resetHub(): boolean { + if (this.hub === null) return false; + this.hub = null; + this.linked.clear(); + return true; + } + + request(peer: HubLinkPeer): void { + if (this.hub === null) { + this.pending.set(peer.windowId, peer); + return; + } + this.link(this.hub, peer); + } + + /** Returns whether the hub held links to the peer and must drop them. */ + peerGone(windowId: number): boolean { + this.pending.delete(windowId); + return this.linked.delete(windowId) && this.hub !== null; + } + + private link(hub: HubLinkPeer, peer: HubLinkPeer): void { + const { port1, port2 } = this.createChannel(); + hub.deliver(port1, peer.windowId); + peer.deliver(port2, hub.windowId); + this.linked.add(peer.windowId); + } +} diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index e4e426b1975ae..5f4e9512e0f25 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -29,6 +29,7 @@ vi.mock("electron", async (importOriginal) => ({ getAllDisplays: vi.fn(() => [ { bounds: { x: 0, y: 0, width: 1920, height: 1080 }, + workArea: { x: 0, y: 25, width: 1920, height: 1055 }, }, ]), }, @@ -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 })), @@ -131,7 +136,9 @@ function makeFakeBrowserWindow() { }), restore: vi.fn(), setBackgroundColor: vi.fn(), + setAlwaysOnTop: vi.fn(), setAutoHideCursor: vi.fn(), + setBounds: vi.fn(), setFullScreen: vi.fn(), setOpacity: vi.fn(), setTitle: vi.fn(), @@ -161,12 +168,16 @@ function makeFakeBrowserWindow() { setZoomLevel: webContents.setZoomLevel, setWindowButtonPosition: window.setWindowButtonPosition, setBackgroundThrottling: webContents.setBackgroundThrottling, + setAlwaysOnTop: window.setAlwaysOnTop, setAutoHideCursor: window.setAutoHideCursor, + setBounds: window.setBounds, setFullScreen: window.setFullScreen, setOpacity: window.setOpacity, webContentsListeners, webContentsOnce: webContents.once, windowListeners, + close: window.close, + hide: window.hide, }; } @@ -241,6 +252,7 @@ function layerTest(input: { readonly desktopSettings?: DesktopAppSettings.DesktopSettings; readonly mainWindowBoundsUpdates?: DesktopAppSettings.DesktopWindowBounds[]; readonly mainWindowMaximizedUpdates?: boolean[]; + readonly botWindowUpdates?: Partial[]; readonly beforeMainWindowBoundsUpdate?: ( bounds: DesktopAppSettings.DesktopWindowBounds, ) => Effect.Effect; @@ -252,6 +264,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; @@ -286,6 +300,15 @@ function layerTest(input: { } return { settings: desktopSettings, changed }; }), + updateBotWindow: (patch) => + Effect.sync(() => { + input.botWindowUpdates?.push(patch); + desktopSettings = { + ...desktopSettings, + botWindow: { ...desktopSettings.botWindow, ...patch }, + }; + return { settings: desktopSettings, changed: true }; + }), setServerExposureMode: () => Effect.die("unexpected server exposure update"), setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"), setUpdateChannel: () => Effect.die("unexpected update channel change"), @@ -304,16 +327,20 @@ function layerTest(input: { }).pipe( Effect.andThen(Ref.update(input.createCount, (count) => count + 1)), Effect.andThen(input.onWindowCreate ?? Effect.void), - Effect.as(input.window), + Effect.map(() => input.createdWindows?.shift() ?? input.window), ), main: Ref.get(input.mainWindow), currentMainOrFirst: Ref.get(input.mainWindow).pipe( Effect.map(Option.orElse(() => Option.fromNullishOr(input.fallbackWindow ?? null))), ), - focusedMainOrFirst: - input.focusedWindow === undefined - ? Ref.get(input.mainWindow) - : Effect.succeedSome(input.focusedWindow), + apps: Effect.map(Ref.get(input.mainWindow), Option.toArray), + // Popups and auxiliary windows are never app windows, so focus falls back to main. + focusedApp: Effect.map(Ref.get(input.mainWindow), (main) => + input.focusedWindow !== undefined && Option.contains(main, input.focusedWindow) + ? Option.some(input.focusedWindow) + : main, + ), + registerApp: () => Effect.void, setMain: (window) => Ref.set(input.mainWindow, Option.some(window)), clearMain: () => Ref.set(input.mainWindow, Option.none()), prepareReveal: () => Effect.succeed(false), @@ -374,6 +401,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 +471,9 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n }), main: Ref.get(mainWindow), currentMainOrFirst, - focusedMainOrFirst: currentMainOrFirst, + apps: Effect.map(Ref.get(mainWindow), Option.toArray), + focusedApp: Ref.get(mainWindow), + registerApp: () => Effect.void, setMain: (window) => Ref.set(mainWindow, Option.some(window)), clearMain: () => Ref.set(mainWindow, Option.none()), prepareReveal: () => Effect.succeed(false), @@ -807,10 +837,10 @@ describe("DesktopWindow", () => { const desktopWindow = yield* DesktopWindow.DesktopWindow; yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - yield* desktopWindow.zoomMain("out"); - yield* desktopWindow.zoomMain("out"); - yield* desktopWindow.zoomMain("in"); - yield* desktopWindow.zoomMain("reset"); + yield* desktopWindow.zoomFocused("out"); + yield* desktopWindow.zoomFocused("out"); + yield* desktopWindow.zoomFocused("in"); + yield* desktopWindow.zoomFocused("reset"); assert.deepEqual( fakeWindow.setZoomLevel.mock.calls.map(([level]) => level), @@ -1470,6 +1500,113 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens a secondary window, keeping the main window hidden while it serves it", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const secondary = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, secondary.window], + createCount, + mainWindow, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* windows.openNewWindow; + assert.equal(yield* Ref.get(createCount), 2); + assert.deepEqual(Option.getOrThrow(yield* windows.windowContext(secondary.window)), { + windowId: secondary.window.id, + isMain: false, + }); + assert.deepEqual((yield* windows.windowsState).windows, [ + { windowId: main.window.id, isMain: true }, + { windowId: secondary.window.id, isMain: false }, + ]); + + const preventMainClose = vi.fn(); + main.windowListeners.get("close")?.({ preventDefault: preventMainClose }); + assert.equal(preventMainClose.mock.calls.length, 1); + assert.equal(main.hide.mock.calls.length, 1); + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect("opens one bot window at /bot that resizes, pins, and keeps its placement", () => + Effect.gen(function* () { + const main = makeFakeBrowserWindow(); + const bot = makeFakeBrowserWindow(); + const savedBounds = { x: 1500, y: 60, width: 380, height: 720 }; + bot.getBounds.mockReturnValue(savedBounds); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = []; + const botWindowUpdates: Partial[] = []; + const revealed: Electron.BrowserWindow[] = []; + const layer = layerTest({ + window: main.window, + createdWindows: [main.window, bot.window], + createCount, + mainWindow, + createdWindowOptions, + botWindowUpdates, + onReveal: (window) => revealed.push(window), + desktopSettings: { + ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, + botWindow: { bounds: savedBounds, size: "narrow", pinned: true }, + }, + }); + + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* windows.openBot; + yield* windows.openBot; + assert.equal(yield* Ref.get(createCount), 2); + assert.deepEqual(revealed, [bot.window]); + assert.deepEqual(bot.loadURL.mock.calls, [["t3code-dev://app/#/bot"]]); + assert.deepInclude(createdWindowOptions[1], { + ...savedBounds, + minWidth: DesktopAppSettings.MIN_BOT_WINDOW_SIZE.width, + maximizable: false, + titleBarStyle: "hiddenInset", + }); + assert.deepEqual(bot.setAlwaysOnTop.mock.calls, [[true, "floating"]]); + // Not the main window: the main window hides instead of closing while the bot needs it. + assert.deepEqual((yield* windows.windowsState).windows, [ + { windowId: main.window.id, isMain: true }, + { windowId: bot.window.id, isMain: false }, + ]); + + yield* windows.setBotSize(bot.window, "medium"); + // Grown in place, then pulled left onto the display's work area. + assert.deepEqual(bot.setBounds.mock.calls, [[{ x: 1020, y: 60, width: 900, height: 760 }]]); + yield* windows.setBotPinned(bot.window, false); + assert.deepEqual(bot.setAlwaysOnTop.mock.calls.at(-1), [false]); + yield* windows.setBotPinned(main.window, true); + yield* windows.setBotSize(main.window, "narrow"); + assert.equal(main.setAlwaysOnTop.mock.calls.length + main.setBounds.mock.calls.length, 0); + assert.deepEqual(Option.getOrThrow(yield* windows.windowContext(bot.window)), { + windowId: bot.window.id, + isMain: false, + bot: { size: "medium", pinned: false }, + }); + + bot.getBounds.mockReturnValue({ x: 1020, y: 60, width: 900, height: 760 }); + bot.windowListeners.get("move")?.(); + yield* TestClock.adjust(500); + assert.deepEqual(botWindowUpdates, [ + { size: "medium" }, + { pinned: false }, + { bounds: { x: 1020, y: 60, width: 900, height: 760 } }, + ]); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("persists the current main window bounds before the window closes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index c99fbb52c49e2..31e9fc796df63 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -11,7 +11,14 @@ 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 DesktopBotWindowSize, + type DesktopBotWindowState, + type DesktopSnapShotEvent, + type DesktopWindowContext, + type DesktopWindowsState, + DEFAULT_CLIENT_SETTINGS, +} from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; import * as DesktopClerk from "../app/DesktopClerk.ts"; @@ -31,6 +38,10 @@ import { TRACKPAD_SCROLL_BEGIN_CHANNEL, TRACKPAD_SCROLL_END_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL, + WINDOWS_HUB_LINK_CHANNEL, + WINDOWS_HUB_PEER_GONE_CHANNEL, + WINDOWS_HUB_RESET_CHANNEL, + WINDOWS_STATE_CHANNEL, } from "../ipc/channels.ts"; import { PASSKEY_BRIDGE_ARGUMENT, @@ -46,6 +57,9 @@ import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts" import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; +import { setUnthrottledHold } from "./BackgroundThrottling.ts"; +import { HubLinkBroker, type HubLinkPeer } from "./DesktopHubLinks.ts"; +import { cascadeWindowBounds, resizeWithinDisplay } from "./DesktopWindowProfiles.ts"; const TITLEBAR_HEIGHT = 40; @@ -96,6 +110,7 @@ const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500; const RENDERER_RECOVERY_MAX_ATTEMPTS = 3; const RENDERER_RECOVERY_WINDOW_MS = 60_000; const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([-2, -7, -9, -102, -105, -106, -118]); +const HUB_UNTHROTTLED_REASON = "hub-serving-windows"; type WindowTitleBarOptions = Pick< Electron.BrowserWindowConstructorOptions, @@ -143,10 +158,27 @@ export class DesktopWindow extends Context.Service< readonly dispatchSnapShotEvent: ( event: DesktopSnapShotEvent, ) => Effect.Effect; - // Electron zoom roles target focused guests; zoomMain must always target the app. - readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect; + // Electron zoom roles target focused guests; this must always target an app window. + readonly zoomFocused: (direction: MainWindowZoomDirection) => Effect.Effect; readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; + readonly runFocusedContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; readonly syncAppearance: Effect.Effect; + readonly windowsState: Effect.Effect; + readonly windowContext: ( + window: Electron.BrowserWindow, + ) => Effect.Effect>; + readonly openNewWindow: Effect.Effect; + /** Opens the single bot window, or brings it forward. */ + readonly openBot: Effect.Effect; + /** No-ops unless `window` is the bot window. */ + readonly setBotSize: ( + window: Electron.BrowserWindow, + size: DesktopBotWindowSize, + ) => Effect.Effect; + /** No-ops unless `window` is the bot window. */ + readonly setBotPinned: (window: Electron.BrowserWindow, pinned: boolean) => Effect.Effect; + readonly registerHub: (window: Electron.BrowserWindow) => Effect.Effect; + readonly requestHubLink: (window: Electron.BrowserWindow) => Effect.Effect; } >()("@t3tools/desktop/window/DesktopWindow") {} @@ -239,6 +271,14 @@ function readDisplayBoundsOrEmpty(): readonly DisplayBounds[] { } } +function readDisplayWorkAreasOrEmpty(): readonly DisplayBounds[] { + try { + return Electron.screen.getAllDisplays().map((display) => display.workArea); + } catch { + return []; + } +} + function windowBoundsEqual( left: DesktopAppSettings.DesktopWindowBounds, right: DesktopAppSettings.DesktopWindowBounds, @@ -251,17 +291,20 @@ function windowBoundsEqual( ); } +type WindowSize = { readonly width: number; readonly height: number }; + export function resolveInitialMainWindowBounds( persistedBounds: DesktopAppSettings.DesktopWindowBounds | null, displays: readonly DisplayBounds[], -): DesktopAppSettings.DesktopWindowBounds | typeof DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE { + defaultSize: WindowSize = DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, +): DesktopAppSettings.DesktopWindowBounds | WindowSize { if ( persistedBounds !== null && displays.some((display) => windowFitsWithinDisplay(persistedBounds, display)) ) { return persistedBounds; } - return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE; + return defaultSize; } function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string { @@ -381,6 +424,22 @@ function bindFirstRevealTrigger( } } +type AppWindowSpec = + | { readonly role: "main" } + | { readonly role: "secondary"; readonly anchorBounds: DisplayBounds | null } + | { readonly role: "bot" }; + +interface AppWindowEntry { + readonly window: Electron.BrowserWindow; + readonly windowId: number; + readonly isMain: boolean; + readonly isBot: boolean; + rendererLive: boolean; + hubUnthrottled: boolean; +} + +const serializeWindowsState = (state: DesktopWindowsState) => JSON.stringify(state); + /** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -404,13 +463,41 @@ export const make = Effect.gen(function* () { const context = yield* Effect.context(); const runFork = Effect.runForkWith(context); const runPromise = Effect.runPromiseWith(context); + const runSync = Effect.runSyncWith(context); const mainWindowMutex = yield* Semaphore.make(1); + const botWindowMutex = yield* Semaphore.make(1); + // The bot window's renderer reads this at load; settings may refuse writes. + let botState: DesktopBotWindowState = { + size: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.botWindow.size, + pinned: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.botWindow.pinned, + }; const pendingMainReveals = new WeakMap>(); const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) => Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), ); let flushMainWindowBounds: Effect.Effect = Effect.void; let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; + const entries = new Map(); + // macOS: float above other apps' windows, as the preview picture-in-picture window does. + const applyBotPinned = (window: Electron.BrowserWindow, pinned: boolean) => { + if (!pinned) window.setAlwaysOnTop(false); + else window.setAlwaysOnTop(true, environment.platform === "darwin" ? "floating" : "normal"); + }; + let lastBroadcastState = ""; + const hubLinks = new HubLinkBroker( + () => new Electron.MessageChannelMain(), + ); + + const liveEntries = () => [...entries.values()].filter((entry) => !entry.window.isDestroyed()); + const mainEntry = () => liveEntries().find((entry) => entry.isMain); + const secondaryEntries = () => liveEntries().filter((entry) => !entry.isMain); + const botEntry = () => liveEntries().find((entry) => entry.isBot); + const entryOf = (window: Electron.BrowserWindow) => { + const entry = entries.get(window.id); + return entry !== undefined && entry.window === window && !window.isDestroyed() + ? entry + : undefined; + }; const dismissConnectingSplash = Effect.gen(function* () { const splash = yield* Ref.getAndSet(splashWindowRef, Option.none()); @@ -444,18 +531,60 @@ export const make = Effect.gen(function* () { yield* previewManager.reapplyZoom(); }); - const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return< - Option.Option, - DesktopWindowError - > { - if (yield* Ref.get(desktopState.quitting)) return Option.none(); - yield* previewManager.getBrowserSession(); - const applicationUrl = getDesktopUrl(environment.isDevelopment); - const iconPaths = yield* assets.iconPaths; - const iconOption = getIconOption(iconPaths, environment.platform); - const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; - const persistedSettings = yield* desktopSettings.get; - const persistedBounds = persistedSettings.mainWindowBounds; + const computeWindowsState = Effect.sync((): DesktopWindowsState => ({ + windows: liveEntries() + .sort((left, right) => Number(right.isMain) - Number(left.isMain)) + .map(({ windowId, isMain }) => ({ windowId, isMain })), + })); + + // The hub must keep serving secondary windows while it is hidden or minimized. + const syncHubThrottling = () => { + const main = mainEntry(); + if (main === undefined) return; + const held = secondaryEntries().length > 0; + if (held === main.hubUnthrottled) return; + main.hubUnthrottled = held; + setUnthrottledHold(main.window, HUB_UNTHROTTLED_REASON, held); + }; + + // Throttling and every renderer's list of open windows follow from the open windows. + const syncWindows = Effect.fn("desktop.window.syncWindows")(function* () { + syncHubThrottling(); + const state = yield* computeWindowsState; + const serialized = serializeWindowsState(state); + if (serialized === lastBroadcastState) return; + lastBroadcastState = serialized; + for (const entry of liveEntries()) { + if (entry.rendererLive) entry.window.webContents.send(WINDOWS_STATE_CHANNEL, state); + } + }); + const requestSync = () => { + runFork(syncWindows()); + }; + + const notifyHubReset = () => { + if (!hubLinks.resetHub()) return; + for (const entry of secondaryEntries()) { + if (entry.rendererLive) entry.window.webContents.send(WINDOWS_HUB_RESET_CHANNEL); + } + }; + const notifyHubPeerGone = (windowId: number) => { + if (!hubLinks.peerGone(windowId)) return; + const main = mainEntry(); + if (main !== undefined) main.window.webContents.send(WINDOWS_HUB_PEER_GONE_CHANNEL, windowId); + }; + const hubPeer = (entry: AppWindowEntry): HubLinkPeer => ({ + windowId: entry.windowId, + deliver: (port, peerWindowId) => { + if (entry.window.isDestroyed()) { + port.close(); + return; + } + entry.window.webContents.postMessage(WINDOWS_HUB_LINK_CHANNEL, { peerWindowId }, [port]); + }, + }); + + const readDisplayBounds = Effect.gen(function* () { const displayBoundsResult = yield* Effect.sync(() => { try { return { @@ -466,22 +595,64 @@ 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"; + const isBot = spec.role === "bot"; + yield* previewManager.getBrowserSession(); + const applicationUrl = getDesktopUrl(environment.isDevelopment); + const iconPaths = yield* assets.iconPaths; + const iconOption = getIconOption(iconPaths, environment.platform); + const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; + const persistedSettings = yield* desktopSettings.get; + // Only the main and bot windows keep their placement. + const persistedBounds = isMain + ? persistedSettings.mainWindowBounds + : isBot + ? persistedSettings.botWindow.bounds + : null; + const displayBounds = yield* readDisplayBounds; + const restorableBounds = resolveInitialMainWindowBounds( + persistedBounds, + displayBounds, + isBot + ? DesktopAppSettings.BOT_WINDOW_SIZES[persistedSettings.botWindow.size] + : DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, + ); + const restoredPersistedBounds = + persistedBounds !== null && restorableBounds === persistedBounds; + if (persistedBounds !== null && !restoredPersistedBounds) { + yield* logWindowWarning("saved window bounds could not be restored; using defaults", { + role: spec.role, + }); } + const initialBounds = + spec.role === "secondary" + ? cascadeWindowBounds({ + anchor: spec.anchorBounds, + size: DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, + displays: displayBounds, + }) + : restorableBounds; if (yield* Ref.get(desktopState.quitting)) return Option.none(); + const minimumSize = isBot + ? DesktopAppSettings.MIN_BOT_WINDOW_SIZE + : DesktopAppSettings.MIN_MAIN_WINDOW_SIZE; const window = yield* electronWindow.create({ ...initialBounds, - minWidth: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width, - minHeight: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height, + minWidth: minimumSize.width, + minHeight: minimumSize.height, + // The bot window stays compact; its sizes are presets. + ...(isBot ? { maximizable: false, fullscreenable: false } : {}), show: false, autoHideMenuBar: true, ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}), @@ -507,11 +678,27 @@ export const make = Effect.gen(function* () { return Option.none(); } - pendingMainReveals.set(window, Effect.void); + if (isMain) pendingMainReveals.set(window, Effect.void); + if (isBot) { + botState = { + size: persistedSettings.botWindow.size, + pinned: persistedSettings.botWindow.pinned, + }; + if (botState.pinned) applyBotPinned(window, true); + } + setUnthrottledHold(window, "first-reveal", true); yield* rendererHistory.register(window.webContents, { surface: "main" }); if (environment.platform === "darwin") { window.setAutoHideCursor(false); } + const entry: AppWindowEntry = { + window, + windowId: window.id, + isMain, + isBot, + rendererLive: false, + hubUnthrottled: false, + }; let boundsPersistFiber: Fiber.Fiber | undefined; let pendingBoundsPersistFiber: Fiber.Fiber | undefined; let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds; @@ -537,7 +724,10 @@ export const make = Effect.gen(function* () { readDisplayBoundsOrEmpty(), ) : window.getBounds(); - const persistableBounds = DesktopAppSettings.normalizeMainWindowBounds({ + const normalizeBounds = isBot + ? DesktopAppSettings.normalizeBotWindowBounds + : DesktopAppSettings.normalizeMainWindowBounds; + const persistableBounds = normalizeBounds({ x: Math.round(bounds.x), y: Math.round(bounds.y), width: Math.round(bounds.width), @@ -550,9 +740,9 @@ export const make = Effect.gen(function* () { const fallbackWindowBounds = boundsPersistenceEnabled ? null : (readPersistableState()?.bounds ?? null); - const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; + const fallbackWindowMaximized = isMain && persistedSettings.mainWindowMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { - if (!boundsPersistenceEnabled) { + if ((!isMain && !isBot) || !boundsPersistenceEnabled) { return pendingBoundsPersistFiber; } const state = readPersistableState(); @@ -560,10 +750,14 @@ export const make = Effect.gen(function* () { return pendingBoundsPersistFiber; } pendingBoundsPersistFiber = runFork( - desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe( + (isBot + ? desktopSettings.updateBotWindow({ bounds: state.bounds }) + : desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized) + ).pipe( Effect.asVoid, Effect.catch((error) => - logWindowWarning("failed to persist main window bounds", { + logWindowWarning("failed to persist window bounds", { + role: spec.role, message: error.message, }), ), @@ -615,9 +809,13 @@ export const make = Effect.gen(function* () { fiber === undefined ? Effect.void : Fiber.join(fiber).pipe(Effect.asVoid), ), ); - flushMainWindowBounds = flushBoundsPersist; + if (isMain) flushMainWindowBounds = flushBoundsPersist; - yield* previewManager.setMainWindow(window); + if (isMain) { + yield* previewManager.setMainWindow(window); + } else { + yield* previewManager.registerSecondaryWindow(window); + } if (yield* Ref.get(desktopState.quitting)) { yield* electronWindow.destroyAll; return Option.none(); @@ -794,6 +992,16 @@ export const make = Effect.gen(function* () { void runPromise(electronShell.openExternal(url)); } }); + // A new document drops the old renderer's hub links. + const rendererGone = () => { + entry.rendererLive = false; + if (isMain) notifyHubReset(); + else notifyHubPeerGone(entry.windowId); + }; + window.webContents.on("did-start-navigation", (event) => { + if (event.isMainFrame && !event.isSameDocument) rendererGone(); + }); + window.webContents.on("destroyed", rendererGone); const quitShortcutHandler = makeQuitShortcutHandler({ platform: environment.platform, @@ -860,7 +1068,13 @@ export const make = Effect.gen(function* () { window.on("move", scheduleBoundsPersist); window.on("maximize", scheduleBoundsPersist); window.on("unmaximize", scheduleBoundsPersist); - window.on("close", () => { + window.on("close", (event) => { + // Hidden, the main window keeps serving the secondary windows' connections. + if (isMain && secondaryEntries().length > 0 && !runSync(Ref.get(desktopState.quitting))) { + event.preventDefault(); + window.hide(); + return; + } runFork(flushBoundsPersist); }); @@ -891,11 +1105,13 @@ export const make = Effect.gen(function* () { developmentLoadRetryFiber = undefined; runFork(Fiber.interrupt(retryFiber)); }; + // Electron renderers use hash history, so a route is the URL fragment. + const windowUrl = isBot ? `${applicationUrl}#/bot` : applicationUrl; const loadApplication = () => { if (window.isDestroyed()) { return; } - void window.loadURL(applicationUrl).catch(() => undefined); + void window.loadURL(windowUrl).catch(() => undefined); }; const scheduleDevelopmentLoadRetry = () => { if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) { @@ -936,6 +1152,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 +1175,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 +1186,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 +1215,8 @@ export const make = Effect.gen(function* () { RENDERER_RECOVERY_RELOAD_DELAY_MS, oldestAttempt + RENDERER_RECOVERY_WINDOW_MS - now, ); - yield* logWindowWarning("main window render process gone", { + yield* logWindowWarning("app window render process gone", { + role: spec.role, reason: details.reason, exitCode: details.exitCode, recovering: shouldRecover, @@ -1026,53 +1250,69 @@ export const make = Effect.gen(function* () { return; firstRevealComplete = true; pendingMainReveals.delete(window); - window.webContents.setBackgroundThrottling(true); - if (persistedSettings.mainWindowMaximized) window.maximize(); + setUnthrottledHold(window, "first-reveal", false); + if (isMain && persistedSettings.mainWindowMaximized) window.maximize(); yield* electronWindow.reveal(window); - yield* dismissConnectingSplash; + if (isMain) yield* dismissConnectingSplash; }); - pendingMainReveals.set(window, revealWhenReady); + if (isMain) pendingMainReveals.set(window, revealWhenReady); bindFirstRevealTrigger(revealSubscribers, () => { rendererReady = true; void runPromise(revealWhenReady); }); - // Desktop IPC only answers the main window, so register it before its renderer can call in. - yield* electronWindow.setMain(window); - remoteRequestHeaderOwner = window; - const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( - window.webContents.session, - { - desktopOrigin: getDesktopOrigin(environment.isDevelopment), - mainWebContentsId: window.webContents.id, - clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, - devServerOrigin: Option.getOrUndefined( - Option.map(environment.devServerUrl, (url) => url.origin), - ), - isDevelopment: environment.isDevelopment, - }, - ); + entries.set(window.id, entry); + // Desktop IPC only answers app windows, so register this one before its renderer can call in. + let detachRemoteRequestHeaders = () => {}; + if (isMain) { + yield* electronWindow.setMain(window); + // App windows share one session, whose single header listener follows the main window. + remoteRequestHeaderOwner = window; + detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( + window.webContents.session, + { + desktopOrigin: getDesktopOrigin(environment.isDevelopment), + mainWebContentsId: window.webContents.id, + clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, + devServerOrigin: Option.getOrUndefined( + Option.map(environment.devServerUrl, (url) => url.origin), + ), + isDevelopment: environment.isDevelopment, + }, + ); + } else { + yield* electronWindow.registerApp(window); + } + yield* syncWindows(); loadApplication(); - if (environment.isDevelopment) { + if (isMain && environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); } window.on("closed", () => { - if (!backendHasStarted) mainClosedDuringStartup = true; + if (entries.get(window.id) === entry) entries.delete(window.id); clearDevelopmentLoadRetry(); clearBoundsPersist(); if (remoteRequestHeaderOwner === window) { remoteRequestHeaderOwner = null; detachRemoteRequestHeaders(); } - void runPromise(electronWindow.clearMain(Option.some(window))); + if (isMain) { + if (!backendHasStarted) mainClosedDuringStartup = true; + notifyHubReset(); + void runPromise(electronWindow.clearMain(Option.some(window))); + } else { + notifyHubPeerGone(entry.windowId); + runFork(handleSecondaryClosed); + } + requestSync(); }); return Option.some(window); }); const createMain = Effect.gen(function* () { - const window = yield* createWindow(); + const window = yield* buildAppWindow({ role: "main" }); if (Option.isSome(window)) { mainClosedDuringStartup = false; yield* logWindowInfo("main window created"); @@ -1101,6 +1341,47 @@ export const make = Effect.gen(function* () { return window; }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain")); + const openSecondary = Effect.gen(function* () { + // Secondary windows reach environments through the main window's renderer. + if (Option.isNone(yield* ensureMain)) return; + const anchor = yield* electronWindow.focusedApp; + yield* buildAppWindow({ + role: "secondary", + anchorBounds: + Option.isSome(anchor) && !anchor.value.isDestroyed() ? anchor.value.getBounds() : null, + }); + }).pipe(Effect.withSpan("desktop.window.openSecondary")); + + const openBot = Effect.gen(function* () { + const existing = botEntry(); + if (existing !== undefined) { + yield* electronWindow.reveal(existing.window); + return; + } + // Like menu actions, wait for the backend rather than strand a new main window on auth. + if (Option.isNone(yield* electronWindow.main) && (yield* waitingForBackend)) return; + // The bot window reaches environments through the main window's renderer. + if (Option.isNone(yield* ensureMain)) return; + yield* buildAppWindow({ role: "bot" }); + }).pipe(botWindowMutex.withPermits(1), Effect.withSpan("desktop.window.openBot")); + + const persistBotWindow = (patch: Partial) => + desktopSettings.updateBotWindow(patch).pipe( + Effect.asVoid, + Effect.catch((error) => + logWindowWarning("failed to persist bot window settings", { message: error.message }), + ), + ); + + const handleSecondaryClosed = Effect.gen(function* () { + if (yield* Ref.get(desktopState.quitting)) return; + const main = mainEntry(); + if (secondaryEntries().length > 0 || main === undefined || main.window.isVisible()) return; + // The hidden main window kept the app alive for its secondary windows; without them, quit + // as closing the last window always has. macOS apps outlive their windows. + if (environment.platform !== "darwin") main.window.close(); + }).pipe(Effect.withSpan("desktop.window.handleSecondaryClosed")); + const waitingForBackend = Effect.gen(function* () { if (yield* Ref.get(backendReadyRef)) return false; return (yield* desktopSettings.get).localEnvironmentEnabled; @@ -1166,14 +1447,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 +1473,35 @@ export const make = Effect.gen(function* () { : send; if (targetWindow.webContents.isLoadingMainFrame()) { targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch)); - return; + return window; } yield* dispatch; + return window; }); + // A capture finishes in the window it started in, even if focus moved meanwhile. + const captureWindows = new Map(); + + const runContentsCommand = ( + window: Electron.BrowserWindow, + command: MainWindowContentsCommand, + ) => { + if (window.isDestroyed()) return; + const webContents = window.webContents; + if (command === "reload") webContents.reload(); + else if (command === "forceReload") webContents.reloadIgnoringCache(); + else webContents.toggleDevTools(); + }; return DesktopWindow.of({ createMain: createMain.pipe(Effect.flatMap(requireWindow)), ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)), revealOrCreateMain, prepareCaptureReveal: Effect.gen(function* () { - const existingWindow = yield* currentMainWindow; + // The capture lands in the focused app window, so that is the one to bring forward. + const focusedWindow = yield* electronWindow.focusedApp; + const existingWindow = Option.isSome(focusedWindow) + ? focusedWindow + : yield* currentMainWindow; if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) { yield* electronWindow.prepareReveal(existingWindow.value); } @@ -1243,13 +1550,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 +1577,70 @@ export const make = Effect.gen(function* () { }), runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) { yield* Effect.annotateCurrentSpan({ command }); - // A focused OAuth popup must not receive the app's Reload command. const window = yield* electronWindow.main; - if (Option.isNone(window) || window.value.isDestroyed()) return; - const webContents = window.value.webContents; - if (command === "reload") webContents.reload(); - else if (command === "forceReload") webContents.reloadIgnoringCache(); - else webContents.toggleDevTools(); + if (Option.isSome(window)) runContentsCommand(window.value, command); }), + runFocusedContentsCommand: Effect.fn("desktop.window.runFocusedContentsCommand")( + function* (command) { + yield* Effect.annotateCurrentSpan({ command }); + // A focused OAuth popup must not receive the app's Reload command. + const window = yield* electronWindow.focusedApp; + if (Option.isSome(window)) runContentsCommand(window.value, command); + }, + ), syncAppearance: Effect.gen(function* () { const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; yield* electronWindow.syncAllAppearance((window, { titleBarOverlay }) => syncWindowAppearance(window, titleBarOverlay, shouldUseDarkColors, environment.platform), ); }).pipe(Effect.withSpan("desktop.window.syncAppearance")), + windowsState: computeWindowsState, + windowContext: Effect.fn("desktop.window.windowContext")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + if (entry === undefined) return Option.none(); + return Option.some({ + windowId: entry.windowId, + isMain: entry.isMain, + ...(entry.isBot ? { bot: botState } : {}), + }); + }); + }), + openNewWindow: openSecondary, + openBot, + setBotSize: Effect.fn("desktop.window.setBotSize")(function* (window, size) { + yield* Effect.annotateCurrentSpan({ size }); + if (entryOf(window)?.isBot !== true) return; + botState = { ...botState, size }; + if (window.isMinimized()) window.restore(); + window.setBounds( + resizeWithinDisplay({ + bounds: window.getBounds(), + size: DesktopAppSettings.BOT_WINDOW_SIZES[size], + displays: readDisplayWorkAreasOrEmpty(), + }), + ); + yield* persistBotWindow({ size }); + }), + setBotPinned: Effect.fn("desktop.window.setBotPinned")(function* (window, pinned) { + yield* Effect.annotateCurrentSpan({ pinned }); + if (entryOf(window)?.isBot !== true) return; + botState = { ...botState, pinned }; + applyBotPinned(window, pinned); + yield* persistBotWindow({ pinned }); + }), + registerHub: Effect.fn("desktop.window.registerHub")(function (window) { + return Effect.sync(() => { + const entry = entryOf(window); + 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..b86557b60ca72 --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { cascadeWindowBounds, resizeWithinDisplay } from "./DesktopWindowProfiles.ts"; + +describe("cascadeWindowBounds", () => { + const display = { x: 0, y: 0, width: 1920, height: 1080 }; + + it("offsets from the opener and wraps back inside its display", () => { + const size = { width: 1100, height: 780 }; + expect( + cascadeWindowBounds({ + anchor: { x: 100, y: 100, width: 1100, height: 780 }, + size, + displays: [display], + }), + ).toEqual({ x: 128, y: 128, width: 1100, height: 780 }); + expect( + cascadeWindowBounds({ + anchor: { x: 900, y: 290, width: 1100, height: 780 }, + size, + displays: [display], + }), + ).toEqual({ x: 28, y: 28, width: 1100, height: 780 }); + expect(cascadeWindowBounds({ anchor: null, size, displays: [display] })).toEqual(size); + }); +}); + +describe("resizeWithinDisplay", () => { + const left = { x: 0, y: 25, width: 1920, height: 1055 }; + const right = { x: 1920, y: 0, width: 1280, height: 800 }; + + it("keeps the origin when the new size fits, and pulls the window back onto its display", () => { + const medium = { width: 900, height: 760 }; + expect( + resizeWithinDisplay({ + bounds: { x: 200, y: 100, width: 380, height: 720 }, + size: medium, + displays: [left, right], + }), + ).toEqual({ x: 200, y: 100, ...medium }); + // A narrow window at the right edge of the second display grows to the left. + expect( + resizeWithinDisplay({ + bounds: { x: 2800, y: 40, width: 380, height: 720 }, + size: medium, + displays: [left, right], + }), + ).toEqual({ x: 2300, y: 40, ...medium }); + // Larger than the display: as large as it allows. + expect( + resizeWithinDisplay({ + bounds: { x: 2000, y: 0, width: 380, height: 720 }, + size: { width: 900, height: 1000 }, + displays: [left, right], + }), + ).toEqual({ x: 2000, y: 0, width: 900, height: 800 }); + }); +}); diff --git a/apps/desktop/src/window/DesktopWindowProfiles.ts b/apps/desktop/src/window/DesktopWindowProfiles.ts new file mode 100644 index 0000000000000..652d9eefe51ef --- /dev/null +++ b/apps/desktop/src/window/DesktopWindowProfiles.ts @@ -0,0 +1,70 @@ +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, + }; +} + +/** Resizes a window in place, moving it only as far as it takes to stay on its display. */ +export function resizeWithinDisplay(input: { + readonly bounds: Rectangle; + readonly size: { readonly width: number; readonly height: number }; + readonly displays: readonly Rectangle[]; +}): Rectangle { + const { bounds } = input; + const centerX = bounds.x + bounds.width / 2; + const centerY = bounds.y + bounds.height / 2; + const display = + input.displays.find( + (candidate) => + centerX >= candidate.x && + centerY >= candidate.y && + centerX < candidate.x + candidate.width && + centerY < candidate.y + candidate.height, + ) ?? input.displays[0]; + if (display === undefined) return { x: bounds.x, y: bounds.y, ...input.size }; + const width = Math.min(input.size.width, display.width); + const height = Math.min(input.size.height, display.height); + const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max); + return { + x: Math.round(clamp(bounds.x, display.x, display.x + display.width - width)), + y: Math.round(clamp(bounds.y, display.y, display.y + display.height - height)), + width, + height, + }; +} diff --git a/apps/mobile/src/components/ComposerContextSheet.tsx b/apps/mobile/src/components/ComposerContextSheet.tsx index 19aeeed4bfbe1..79a1933914a87 100644 --- a/apps/mobile/src/components/ComposerContextSheet.tsx +++ b/apps/mobile/src/components/ComposerContextSheet.tsx @@ -392,6 +392,15 @@ export function ComposerContextSheet(props: { {record.kind === "environment" ? ( ) : null} + {record.kind === "bot" ? ( + + ) : null} {record.kind === "skill" ? ( handleSelectDetail({ name: "Thread", params }); - const projects = useProjects(); + const projects = useVisibleProjects(); const compactAndroidSettings = Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView; // Reads the open page when pressed, so the layout context doesn't change on every navigation. diff --git a/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts b/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts index b1e80081d8a4a..f6d96b705de82 100644 --- a/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts +++ b/apps/mobile/src/features/prompt-links/newTaskPromptLink.ts @@ -402,7 +402,7 @@ function resolveLink(linkSearch: string) { const activityOf = (project: EnvironmentProject) => lastActivity.get(`${project.environmentId}:${project.id}`) ?? ""; const projects = findPromptLinkProjects( - [...appAtomRegistry.get(environmentProjects.projectsAtom)].sort((left, right) => + [...appAtomRegistry.get(environmentProjects.visibleProjectsAtom)].sort((left, right) => activityOf(right).localeCompare(activityOf(left)), ), repository, diff --git a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx index f07ffea096ec8..034cc2a41a9d9 100644 --- a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx +++ b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx @@ -1,8 +1,10 @@ import { msg, T, useGT, useMessages } from "gt-react-native"; import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { LegendList } from "@legendapp/list/react-native"; +import { useAtomValue } from "@effect/atom-react"; import { useNavigation } from "@react-navigation/native"; import { scheduledTaskWorktreeBaseRef } from "@t3tools/client-runtime/scheduled-task-worktree"; +import { threadKey } from "@t3tools/client-runtime/state/entities"; import { isListedThreadLineage } from "@t3tools/contracts"; import * as Haptics from "expo-haptics"; import { useMemo, useState } from "react"; @@ -14,11 +16,8 @@ import { SelectionRow } from "../../components/ui/SelectionRow"; import { useSearchToolbarInset } from "../../components/ui/useBarInset"; import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; -import { - useEnvironmentServerConfig, - useProjects, - useVisibleThreadShells, -} from "../../state/entities"; +import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities"; +import { environmentThreadShells } from "../../state/threads"; import { useDebouncedValue, usePaginatedBranches, useThreadSearch } from "../../state/queries"; import { BranchPickerScreen } from "../threads/NewTaskContextPickerScreens"; import { ThreadSettingsPickerScreen } from "../threads/ThreadSettingsSheet"; @@ -204,7 +203,12 @@ export function ScheduledTaskThreadPickerRouteScreen() { const projectId = editor?.draft.projectId ?? null; const threadId = editor?.draft.threadId ?? null; const currentLabel = useScheduledTaskDestinationLabel(environmentId, threadId); - const shells = useVisibleThreadShells(); + // Unlike other lists, bot threads stay pickable: a bot's tasks post to its own conversations. + const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + const shells = useThreadShells().filter( + (shell) => + !hiddenKeys.has(threadKey({ environmentId: shell.environmentId, threadId: shell.id })), + ); const [query, setQuery] = useState(""); const search = { value: query, diff --git a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx index bf34ff7777262..cb236a8c0571c 100644 --- a/apps/mobile/src/features/threads/ComposerCommandPopover.tsx +++ b/apps/mobile/src/features/threads/ComposerCommandPopover.tsx @@ -1,3 +1,4 @@ +import type { ComposerBotItem } from "@t3tools/client-runtime/composerThreadItems"; import { resolveProviderSkillSourceKind, type ProviderSkillSourceKind, @@ -56,6 +57,7 @@ export type ComposerCommandItem = readonly label: string; readonly description: string; } + | ComposerBotItem | { readonly id: string; readonly type: "slash-command"; @@ -136,6 +138,8 @@ function itemIcon(item: ComposerCommandItem): AppSymbolName | null { return "text.bubble"; case "environment": return ENVIRONMENT_MACHINE_SYMBOLS[item.machine]; + case "bot": + return "person.crop.circle"; } } diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index c6fa629d18b43..0385fb492c906 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -65,7 +65,7 @@ import { updateComposerDraftSettings, scheduleUnusedComposerAttachmentCleanup, } from "../../state/use-composer-drafts"; -import { useEnvironmentServerConfig, useProjects } from "../../state/entities"; +import { useEnvironmentServerConfig, useVisibleProjects } from "../../state/entities"; import { useProjectClone } from "../../state/projectClones"; import { projectEnvironment } from "../../state/projects"; import { sourceControlEnvironment } from "../../state/sourceControl"; @@ -166,7 +166,7 @@ export function NewTaskDraftScreen(props: { const gt = useGT(); const m = useMessages(); const [creationMetadata] = useState(makeTurnCommandMetadata); - const projects = useProjects(); + const projects = useVisibleProjects(); const flow = useNewTaskFlow(); const navigation = useNavigation(); const isFocused = useIsFocused(); diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index b2ebef9a42523..162620900355a 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -51,7 +51,7 @@ import { useComposerDraftResetGeneration, } from "../../state/use-composer-drafts"; import type { ComposerDocumentAttachment } from "../../lib/composerContext"; -import { useProject, useVisibleThreadShells } from "../../state/entities"; +import { useProject, useProjects, useVisibleThreadShells } from "../../state/entities"; import { useMentionableEnvironments } from "../../state/environments"; import { useLinkedEnvironments } from "../../state/peerLinks"; import { useEnvironmentScopeDenied } from "../../state/session"; @@ -430,6 +430,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps environments: offersLinkedEnvironments(props.serverConfig) ? mentionableEnvironments : NO_MACHINES, + projects: useProjects(), + bots: props.serverConfig?.settings.bots, linkedEnvironments: useLinkedEnvironments(props.environmentId), currentThreadId: props.selectedThread.id, projectCwd: props.projectCwd, diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 005a6fb8f30c1..9b0c4d40bce2c 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -274,6 +274,7 @@ import { } from "./pending-thread-feed"; import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size"; +import { foldThreadFeedSections, threadFeedSectionFolds } from "./threadFeedSections"; import { htmlRenderFrameHeight } from "@t3tools/shared/htmlRender"; import { htmlRenderRowHeight, ThreadHtmlRender } from "./HtmlRenderWebView"; import { ThreadMcpApp } from "./McpAppWebView"; @@ -3037,28 +3038,41 @@ function useThreadFeedPresentation( const [feedCache] = useState(createThreadFeedCache); const messages = useMessages(); const locale = useLocale(); + const [sectionFoldRows] = useState( + () => new Map>(), + ); return appendPendingThreadMessages( - deriveThreadFeedPresentation( + foldThreadFeedSections( + deriveThreadFeedPresentation( + props.feed, + props.latestRun, + expandedTurnIds, + new Set( + Object.entries(expandedWorkGroups) + .filter(([, expanded]) => expanded) + .map(([groupId]) => groupId), + ), + props.activeWorkStartedAt, + props.runlessWorkActive ?? false, + feedCache, + { toolCallVisibility: props.toolCallVisibility ?? "showAll", revealedMessageId }, + messages, + locale, + ), props.feed, - props.latestRun, + threadFeedSectionFolds(props.feed, threadFeedIsWorking(props)), expandedTurnIds, - new Set( - Object.entries(expandedWorkGroups) - .filter(([, expanded]) => expanded) - .map(([groupId]) => groupId), - ), - props.activeWorkStartedAt, - props.runlessWorkActive ?? false, - feedCache, - { toolCallVisibility: props.toolCallVisibility ?? "showAll", revealedMessageId }, - messages, - locale, + sectionFoldRows, ), props.feed, props.queuedMessages, ); } +function threadFeedIsWorking(props: Pick) { + return props.activeWorkStartedAt !== null && props.latestRun?.status !== "preparing"; +} + type DisclosureLayout = { /** Each row's top relative to the anchor row's top, before the toggle. */ positions: ReadonlyMap; @@ -3921,6 +3935,18 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { expandedTurnIds: new Set(current.expandedTurnIds).add(jumpRunId), })); } + const jumpSection = + jumpReady && !presentedFeed.some((entry) => entry.id === jumpToMessageId) + ? threadFeedSectionFolds(props.feed, threadFeedIsWorking(props)).get(jumpToMessageId) + : undefined; + if (jumpSection && expandedTurnIds.has(jumpSection.key) === jumpSection.expandedByDefault) { + setInteractionState((current) => { + const next = new Set(current.expandedTurnIds); + if (jumpSection.expandedByDefault) next.delete(jumpSection.key); + else next.add(jumpSection.key); + return { ...current, expandedTurnIds: next }; + }); + } const setupAnchorIndex = presentedFeed.findIndex( (entry) => entry.type === "message" && entry.message.role === "user", ); diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 681f5d3c6fa0a..dcc66407c906b 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -25,7 +25,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities"; -import { useProjects } from "../../state/entities"; +import { useVisibleProjects } from "../../state/entities"; import { steadyNavigationThreadShellsAtom } from "../../state/threads"; import { useThreadSearch } from "../../state/queries"; import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences"; @@ -129,7 +129,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { const insets = useSafeAreaInsets(); const { fabClearance, fabSize } = useAndroidControlSizing(); - const projects = useProjects(); + const projects = useVisibleProjects(); const threads = useAtomValue(steadyNavigationThreadShellsAtom); const selectedThreadKey = useSidebarRowThreadKey(props.selectedThreadKey); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 8f509de9e674a..fc7194059bcc0 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -102,7 +102,7 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE, threadErrorText, } from "@t3tools/client-runtime/state/threads"; -import { useProjects } from "../../state/entities"; +import { useVisibleProjects } from "../../state/entities"; import { projectThreadContentPresentation, threadSyncStatusLabel, @@ -215,7 +215,7 @@ function ThreadUnavailableScreen(props: { /** A thread that can't load opens a new task in its environment instead of a dead end. */ function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) { const navigation = useNavigation(); - const projects = useProjects(); + const projects = useVisibleProjects(); const openDraft = useEffectEvent(() => { const project = projects.find((candidate) => candidate.environmentId === props.environmentId); navigation.dispatch( diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx index cf7b35b05f45a..ddc35a5f80d93 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx @@ -45,7 +45,7 @@ vi.mock("../../state/atom-registry", () => ({ }, })); vi.mock("../../state/entities", () => ({ - useProjects: mocks.projects, + useVisibleProjects: mocks.projects, useThreadShells: () => [], useEnvironmentServerConfig: () => mocks.serverConfig() ?? null, useServerConfigs: () => new Map(), diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 33fbbd7e02b7f..d361f3c3caa4a 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -26,7 +26,7 @@ import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triag import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; -import { useProjects, useServerConfigs, useThreadShells } from "../../state/entities"; +import { useServerConfigs, useThreadShells, useVisibleProjects } from "../../state/entities"; import type { TurnCommandMetadata } from "../../lib/commandMetadata"; import type { DraftComposerAttachment } from "../../lib/composerImages"; import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; @@ -243,7 +243,7 @@ export function NewTaskFlowProvider( routeDraftId?: string; }>, ) { - const projects = useProjects(); + const projects = useVisibleProjects(); const messages = useMessages(); const threads = useThreadShells(); const { savedConnectionsById } = useSavedRemoteConnections(); diff --git a/apps/mobile/src/features/threads/threadFeedSections.test.ts b/apps/mobile/src/features/threads/threadFeedSections.test.ts new file mode 100644 index 0000000000000..7b14ddc4b6d7d --- /dev/null +++ b/apps/mobile/src/features/threads/threadFeedSections.test.ts @@ -0,0 +1,90 @@ +import { MessageId, RunId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { ThreadFeedEntry } from "../../lib/threadActivity"; +import { foldThreadFeedSections, threadFeedSectionFolds } from "./threadFeedSections"; + +const at = "2026-01-01T11:18:04.000Z"; +const message = (id: string, role: "user" | "assistant", text = id): ThreadFeedEntry => ({ + type: "message", + id, + createdAt: at, + message: { + id: MessageId.make(id), + role, + text, + attachments: [], + runId: null, + streaming: false, + visibility: "local", + sourceThreadId: ThreadId.make("thread"), + createdAt: at, + updatedAt: at, + }, +}); +const runFold = (id: string): ThreadFeedEntry => ({ + type: "run-fold", + id: `run-fold:${id}`, + createdAt: at, + runId: RunId.make(id), + label: "Worked for 3s", + expanded: false, +}); +const thinking: ThreadFeedEntry = { + type: "thinking", + id: "live-activity-row", + createdAt: at, + runId: null, +}; + +describe("foldThreadFeedSections", () => { + const exchange = [ + message("before", "user"), + message("ask", "user"), + message("relay", "assistant", '\nAll green.'), + message("reply", "user"), + message("done", "assistant", "Done.\n"), + ]; + const feed = [...exchange, message("after", "user")]; + // The presentation adds rows of its own between the feed's entries. + const presented = (entries: ReadonlyArray) => [ + ...entries.slice(0, 4), + runFold("r2"), + ...entries.slice(4), + thinking, + ]; + const expandedSection = ["ask", "relay", "reply", "run-fold:r2", "done"]; + + it.each<[string, ReadonlyArray, boolean, ReadonlyArray, string[]]>([ + [ + "folds a closed section with the rows derived inside it", + feed, + false, + [], + ["before", "run-fold:section:relay", "after", "live-activity-row"], + ], + [ + "opens a closed section from the expanded set", + feed, + false, + ["section:relay"], + ["before", "run-fold:section:relay", ...expandedSection, "after", "live-activity-row"], + ], + [ + "keeps a section open while the turn that ends it runs", + exchange, + true, + [], + ["before", "run-fold:section-open:relay", ...expandedSection, "live-activity-row"], + ], + ])("%s", (_name, entries, isWorking, expanded, expected) => { + const folded = foldThreadFeedSections( + presented(entries), + entries, + threadFeedSectionFolds(entries, isWorking), + new Set(expanded.map((id) => RunId.make(id))), + new Map(), + ); + expect(folded.map((row) => row.id)).toEqual(expected); + }); +}); diff --git a/apps/mobile/src/features/threads/threadFeedSections.ts b/apps/mobile/src/features/threads/threadFeedSections.ts new file mode 100644 index 0000000000000..e7645f477cf06 --- /dev/null +++ b/apps/mobile/src/features/threads/threadFeedSections.ts @@ -0,0 +1,134 @@ +import { RunId } from "@t3tools/contracts"; +import { + deriveBotSectionSpans, + formatBotSectionLabel, + parseBotSectionMarkers, + type BotSectionMessageMarkers, +} from "@t3tools/shared/botSections"; + +import type { ThreadFeedEntry } from "../../lib/threadActivity"; + +type ThreadFeedMessage = Extract["message"]; +type RunFoldRow = Extract; + +export interface ThreadFeedSectionFold { + /** Toggled-from-default key in the expanded run set; open and closed sections use separate keys. */ + readonly key: RunId; + readonly label: string; + readonly createdAt: string; + readonly expandedByDefault: boolean; +} + +const markersByMessage = new WeakMap(); + +function entryMarkers(entry: ThreadFeedEntry): BotSectionMessageMarkers | null { + if (entry.type !== "message" || entry.message.role !== "assistant") return null; + let markers = markersByMessage.get(entry.message); + if (markers === undefined) { + markers = parseBotSectionMarkers(entry.message.text); + markersByMessage.set(entry.message, markers); + } + return markers; +} + +function startsTurn(entry: ThreadFeedEntry): boolean { + if (entry.type === "message") { + return ( + entry.message.role === "user" && + entry.message.inputIntent !== "steer" && + entry.message.inputIntent !== "promoted_queued_to_steer" + ); + } + return ( + entry.type === "activity-group" && + entry.activities.some((activity) => activity.projectedItem.item.type === "notification") + ); +} + +/** Bot section folds by member entry id, from the unfiltered feed so zen cannot drop a marker. */ +export function threadFeedSectionFolds( + feed: ReadonlyArray, + isWorking: boolean, +): ReadonlyMap { + const byEntryId = new Map(); + const spans = deriveBotSectionSpans(feed, { markers: entryMarkers, startsTurn }); + if (spans.length === 0) return byEntryId; + const activeTurnStart = isWorking ? feed.findLastIndex(startsTurn) : feed.length; + for (const span of spans) { + // A section ended inside the running turn stays open until that turn settles. + const open = !span.closed || span.endIndex >= activeTurnStart; + const startEntry = feed[span.startIndex]!; + const fold: ThreadFeedSectionFold = { + key: RunId.make(`${open ? "section-open" : "section"}:${feed[span.markerIndex]!.id}`), + label: formatBotSectionLabel(span.marker, startEntry.createdAt), + createdAt: startEntry.createdAt, + expandedByDefault: open, + }; + for (let index = span.startIndex; index <= span.endIndex; index += 1) { + byEntryId.set(feed[index]!.id, fold); + } + } + return byEntryId; +} + +export function threadFeedSectionExpanded( + fold: ThreadFeedSectionFold, + expandedRunIds: ReadonlySet, +): boolean { + return fold.expandedByDefault !== expandedRunIds.has(fold.key); +} + +/** + * Folds presented rows under their section's run-fold row. Rows the + * presentation derived (folds, toggles, split groups) belong to the entry + * row above them; the live thinking row always stays visible. + */ +export function foldThreadFeedSections( + rows: ReadonlyArray, + feed: ReadonlyArray, + folds: ReadonlyMap, + expandedRunIds: ReadonlySet, + foldRows: Map, +): ReadonlyArray { + if (folds.size === 0) return rows; + const feedIds = new Set(feed.map((entry) => entry.id)); + const emitted = new Set(); + const result: ThreadFeedEntry[] = []; + let current: ThreadFeedSectionFold | undefined; + for (const row of rows) { + if (row.type === "thinking") { + result.push(row); + continue; + } + if (folds.has(row.id)) current = folds.get(row.id); + else if (feedIds.has(row.id)) current = undefined; + if (current === undefined) { + result.push(row); + continue; + } + const expanded = threadFeedSectionExpanded(current, expandedRunIds); + if (!emitted.has(current.key)) { + emitted.add(current.key); + let foldRow = foldRows.get(current.key); + if ( + foldRow === undefined || + foldRow.label !== current.label || + foldRow.createdAt !== current.createdAt || + foldRow.expanded !== expanded + ) { + foldRow = { + type: "run-fold", + id: `run-fold:${current.key}`, + createdAt: current.createdAt, + runId: current.key, + label: current.label, + expanded, + }; + foldRows.set(current.key, foldRow); + } + result.push(foldRow); + } + if (expanded) result.push(row); + } + return result; +} diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts index b5b6ce681c018..c8befd7004bfa 100644 --- a/apps/mobile/src/features/threads/use-composer-command-menu.ts +++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts @@ -1,6 +1,7 @@ import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests"; import * as Dialog from "../../components/ui/Dialog"; import type { + BotSettings, EnvironmentId, ProjectId, ServerProvider, @@ -9,16 +10,22 @@ import type { } from "@t3tools/contracts"; import { type ComposerEnvironmentCandidate, + matchComposerBotItems, matchComposerEnvironmentItems, matchComposerThreadItems, } from "@t3tools/client-runtime/composerThreadItems"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/models"; const EMPTY_THREAD_SHELLS: ReadonlyArray = []; const EMPTY_ENVIRONMENTS: ReadonlyArray = []; +const EMPTY_PROJECTS: ReadonlyArray = []; const NO_LINKED_ENVIRONMENTS: ReadonlyMap = new Map(); import { COMPOSER_CONTEXT_MAX_RECORDS } from "@t3tools/contracts"; import { + botContextRecord, formatComposerContextReference, threadContextRecord, } from "@t3tools/shared/composerContextReferences"; @@ -254,6 +261,8 @@ export function useComposerCommandMenu({ environmentId, threadShells = EMPTY_THREAD_SHELLS, environments = EMPTY_ENVIRONMENTS, + projects = EMPTY_PROJECTS, + bots = null, linkedEnvironments = NO_LINKED_ENVIRONMENTS, currentThreadId = null, projectCwd, @@ -278,6 +287,9 @@ export function useComposerCommandMenu({ readonly environmentId: EnvironmentId | null; readonly threadShells?: ReadonlyArray; readonly environments?: ReadonlyArray; + /** Projects and the `bots` setting of `environmentId`, whose T3_BOTs the picker offers. */ + readonly projects?: ReadonlyArray; + readonly bots?: Readonly> | null; /** The machines `environmentId` links to, by name, whose threads the picker also offers. */ readonly linkedEnvironments?: ReadonlyMap; readonly currentThreadId?: ThreadId | null; @@ -537,11 +549,15 @@ export function useComposerCommandMenu({ messages, ) : []; + const botItems = environmentId + ? matchComposerBotItems({ projects, bots, environmentId, query: trigger.query }) + : []; const modelItems = modelOptions && modelProviders ? buildComposerModelItems(modelOptions, trigger.query, modelProviders) : []; return [ + ...botItems, ...threadItems, ...environmentItems, ...modelItems, @@ -564,9 +580,12 @@ export function useComposerCommandMenu({ const onSelect = (item: ComposerCommandItem) => { if (!trigger) return; - if (item.type === "environment") { + if (item.type === "environment" || item.type === "bot") { if (!ownerKey || trigger.kind !== "path") return; - const record = environmentComposerContext(item.environmentId, item.label); + const record = + item.type === "bot" + ? botContextRecord(item, item.label) + : environmentComposerContext(item.environmentId, item.label); const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? []; const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId); if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) { diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 1116dd8895c6e..4c1c216969f52 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "Thread", "c6196d99000642b4": "Thread öffnen", "c3f083943d8c530e": "Rechner", + "503be8043f6ac9de": "Beim Senden wird diese Nachricht an die Hauptunterhaltung von {name} zugestellt.", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Beschreibung", "9ff9f24d1568fbaf": "Für diesen Skill ist keine Beschreibung verfügbar.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index d9c7d08df765b..b7b13cd1275b3 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "Thread", "c6196d99000642b4": "Open thread", "c3f083943d8c530e": "Machine", + "503be8043f6ac9de": "Sending delivers this message to {name}''s main conversation.", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Description", "9ff9f24d1568fbaf": "No description is available for this skill.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 8ceac2b26a722..14134ea82f8e1 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "Hilo", "c6196d99000642b4": "Abrir hilo", "c3f083943d8c530e": "Máquina", + "503be8043f6ac9de": "Al enviar, este mensaje se entrega a la conversación principal de {name}.", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Descripción", "9ff9f24d1568fbaf": "No hay descripción disponible para esta skill.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index a6904b69d7f73..2ec5970d50741 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "Fil", "c6196d99000642b4": "Ouvrir le fil", "c3f083943d8c530e": "Machine", + "503be8043f6ac9de": "À l’envoi, ce message est remis à la conversation principale de {name}.", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Description", "9ff9f24d1568fbaf": "Aucune description n’est disponible pour ce skill.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 3ce3515fae73b..cc428bd2a900c 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "スレッド", "c6196d99000642b4": "スレッドを開く", "c3f083943d8c530e": "マシン", + "503be8043f6ac9de": "送信すると、このメッセージは {name} のメイン会話に届きます。", "5d0f9cf6550667af": "スキル", "c0d3dd0975eb2f22": "説明", "9ff9f24d1568fbaf": "このスキルには説明がありません。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 484ab67231b2e..3be6f85902657 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "스레드", "c6196d99000642b4": "스레드 열기", "c3f083943d8c530e": "머신", + "503be8043f6ac9de": "보내면 이 메시지가 {name}의 기본 대화로 전달됩니다.", "5d0f9cf6550667af": "스킬", "c0d3dd0975eb2f22": "설명", "9ff9f24d1568fbaf": "이 스킬에 대한 설명이 없습니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 4959be9c365b1..73cae7a3ea979 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "Thread", "c6196d99000642b4": "Abrir thread", "c3f083943d8c530e": "Máquina", + "503be8043f6ac9de": "Ao enviar, esta mensagem é entregue à conversa principal de {name}.", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Descrição", "9ff9f24d1568fbaf": "Não há descrição disponível para esta skill.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 7987d3d16485a..917dbba2ff090 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "Тред", "c6196d99000642b4": "Открыть тред", "c3f083943d8c530e": "Машина", + "503be8043f6ac9de": "При отправке это сообщение будет доставлено в основной разговор {name}.", "5d0f9cf6550667af": "Навык", "c0d3dd0975eb2f22": "Описание", "9ff9f24d1568fbaf": "У этого навыка нет описания.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 38f2f3c80172c..570c13d2336ab 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "Tråd", "c6196d99000642b4": "Öppna tråd", "c3f083943d8c530e": "Dator", + "503be8043f6ac9de": "När du skickar levereras meddelandet till huvudkonversationen för {name}.", "5d0f9cf6550667af": "Färdighet", "c0d3dd0975eb2f22": "Beskrivning", "9ff9f24d1568fbaf": "Ingen beskrivning finns för den här färdigheten.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index e673d0e56ba1b..4420eb73fd82e 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1418,6 +1418,7 @@ "e05357a50398306a": "会话", "c6196d99000642b4": "打开会话", "c3f083943d8c530e": "机器", + "503be8043f6ac9de": "发送后,这条消息会送到 {name} 的主对话。", "5d0f9cf6550667af": "技能", "c0d3dd0975eb2f22": "描述", "9ff9f24d1568fbaf": "这个技能没有描述。", diff --git a/apps/mobile/src/lib/composerChipPresentation.test.ts b/apps/mobile/src/lib/composerChipPresentation.test.ts index 21474f6de7e96..61ebd5a54a12d 100644 --- a/apps/mobile/src/lib/composerChipPresentation.test.ts +++ b/apps/mobile/src/lib/composerChipPresentation.test.ts @@ -23,6 +23,7 @@ const CHIP_ACCENTS = [ "skill", "thread", "environment", + "bot", ].map((kind) => contextChipPresentation(kind)), ...[ { state: "open", isDraft: false }, diff --git a/apps/mobile/src/lib/composerChipPresentation.ts b/apps/mobile/src/lib/composerChipPresentation.ts index 6f2113dc564c5..51f5a6525907d 100644 --- a/apps/mobile/src/lib/composerChipPresentation.ts +++ b/apps/mobile/src/lib/composerChipPresentation.ts @@ -46,6 +46,8 @@ const CONTEXT_CHIP_PRESENTATIONS = { }, // A machine: the record carries only its identity, so every machine wears one glyph. environment: { accent: "#3f9a4f", icon: "server" }, + // A tagged T3_BOT. Its server delivers the message, so the chip only names it. + bot: { accent: "#cb6440", icon: "bot" }, // An earlier response the message replies to. Mobile shows it as a plain labelled chip. response: { accent: "#7f8793", icon: null }, } as const satisfies Record; diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts index cecb7fa84a446..67d527a09753b 100644 --- a/apps/mobile/src/state/entities.ts +++ b/apps/mobile/src/state/entities.ts @@ -197,11 +197,16 @@ export function useProjects(): ReadonlyArray { return useAtomValue(environmentProjects.projectsAtom); } +/** Projects without T3_BOT projects, for lists and pickers. */ +export function useVisibleProjects(): ReadonlyArray { + return useAtomValue(environmentProjects.visibleProjectsAtom); +} + export function useThreadShells(): ReadonlyArray { return useAtomValue(environmentThreadShells.threadShellsAtom); } -/** Thread shells minus those the tag filter hides, for lists that show threads to the user. */ +/** Thread shells minus tag-hidden and T3_BOT threads, for lists that show threads to the user. */ export function useVisibleThreadShells(): ReadonlyArray { return useAtomValue(environmentThreadShells.visibleThreadShellsAtom); } diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index bf2013aef5398..c3796bcd76052 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -46,6 +46,7 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: threadEnvironment.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + botProjectIdsAtom: serverEnvironment.botProjectIdsAtom, }); const steadyShells = createSteadyShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, @@ -63,6 +64,7 @@ export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtom catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: steadyShells.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + botProjectIdsAtom: serverEnvironment.botProjectIdsAtom, }).navigationThreadShellsAtom; export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom, diff --git a/apps/server/scripts/dev-replay-agent.ts b/apps/server/scripts/dev-replay-agent.ts index 2aa50e353f57a..c28036f26d871 100644 --- a/apps/server/scripts/dev-replay-agent.ts +++ b/apps/server/scripts/dev-replay-agent.ts @@ -69,6 +69,11 @@ export const SCENARIOS = [ name: "Command output", file: "./dev-replay/command_output_transcript.ndjson", }, + { + id: "bot-sections", + name: "T3_BOT sections", + file: "./dev-replay/bot_sections_transcript.ndjson", + }, ] as const; // Session setup and vendor state stay out: they would replace the replay agent's own models. diff --git a/apps/server/scripts/dev-replay/bot_sections_transcript.ndjson b/apps/server/scripts/dev-replay/bot_sections_transcript.ndjson new file mode 100644 index 0000000000000..53f9f9fe185ce --- /dev/null +++ b/apps/server/scripts/dev-replay/bot_sections_transcript.ndjson @@ -0,0 +1,13 @@ +{"type": "transcript_start", "provider": "acpRegistry", "protocol": "acp.ndjson-jsonrpc", "version": "1", "scenario": "dev_replay_bot_sections", "metadata": {"generatedBy": "hand-written for the dev replay agent"}} +{"type": "expect_outbound", "frame": {"kind": "request", "method": "session/prompt", "params": ""}} +{"type": "emit_inbound", "frame": {"kind": "notification", "method": "session/update", "params": {"sessionId": "dev-replay-session", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Launched a worker in Ryder App and linked it here. Watching it."}}}}} +{"type": "emit_inbound", "frame": {"kind": "response", "method": "session/prompt", "result": {"stopReason": "end_turn"}}} +{"type": "expect_outbound", "frame": {"kind": "request", "method": "session/prompt", "params": ""}} +{"type": "emit_inbound", "frame": {"kind": "notification", "method": "session/update", "params": {"sessionId": "dev-replay-session", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "\n**Ryder App › Fix Vivaldi embed origin:** running, 3 of 4 functions verified.\n\n**PR #214:** checks failed on lint; I sent the fix back to its thread.\n\nAnything you want me to change?"}}}}} +{"type": "emit_inbound", "frame": {"kind": "response", "method": "session/prompt", "result": {"stopReason": "end_turn"}}} +{"type": "expect_outbound", "frame": {"kind": "request", "method": "session/prompt", "params": ""}} +{"type": "emit_inbound", "frame": {"kind": "notification", "method": "session/update", "params": {"sessionId": "dev-replay-session", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Done. I will merge #214 when checks are green and ping your phone.\n\n"}}}}} +{"type": "emit_inbound", "frame": {"kind": "response", "method": "session/prompt", "result": {"stopReason": "end_turn"}}} +{"type": "expect_outbound", "frame": {"kind": "request", "method": "session/prompt", "params": ""}} +{"type": "emit_inbound", "frame": {"kind": "notification", "method": "session/update", "params": {"sessionId": "dev-replay-session", "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Noted. Nothing else is waiting on you."}}}}} +{"type": "emit_inbound", "frame": {"kind": "response", "method": "session/prompt", "result": {"stopReason": "end_turn"}}} diff --git a/apps/server/src/bot/BotMentionDelivery.test.ts b/apps/server/src/bot/BotMentionDelivery.test.ts new file mode 100644 index 0000000000000..5cb71e4c4d18c --- /dev/null +++ b/apps/server/src/bot/BotMentionDelivery.test.ts @@ -0,0 +1,355 @@ +import { + type BotSettings, + CommandId, + type ComposerContextRecord, + EnvironmentId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { + botContextRecord, + formatComposerContextReference, + threadContextRecord, +} from "@t3tools/shared/composerContextReferences"; +import { assert, it } from "@effect/vitest"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as TestClock from "effect/testing/TestClock"; + +import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as GitWorkflow from "../git/GitWorkflowService.ts"; +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts"; +import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; +import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts"; +import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as TerminalManager from "../terminal/Manager.ts"; +import * as TextGeneration from "../textGeneration/TextGeneration.ts"; +import * as TaskFolders from "../workspace/TaskFolders.ts"; +import * as BotMentionDelivery from "./BotMentionDelivery.ts"; + +const environmentId = EnvironmentId.make("environment:bot-mentions"); +const sourceProjectId = ProjectId.make("project:source"); +const botProjectId = ProjectId.make("project:atlas"); +const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.1-codex" }; +const botModelSelection = { ...modelSelection, model: "gpt-5.1-codex-mini" }; + +const projectRecord = (id: ProjectId, title: string, defaultModel: typeof modelSelection) => + ({ + id, + title, + workspaceRoot: `/projects/${title.toLowerCase()}`, + repositoryIdentity: null, + faviconPath: null, + defaultModelSelection: defaultModel, + defaultThreadEnvMode: null, + scripts: [], + pinnedAt: null, + archivedAt: null, + createdAt: "2026-11-20T00:00:00.000Z", + updatedAt: "2026-11-20T00:00:00.000Z", + deletedAt: null, + }) as const; +const projects = [ + projectRecord(sourceProjectId, "Source", modelSelection), + projectRecord(botProjectId, "Atlas", botModelSelection), +]; + +const adapter = { + instanceId: modelSelection.instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("provider execution is disabled in bot mention tests"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; + +function makeLayer(bots: Record = { [botProjectId]: {} }) { + const layerDatabase = SqlitePersistence.layerMemory; + const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( + { name: "bot-mentions" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ); + const layerSettings = ServerSettings.layerTest({ bots }); + const layerReceipts = CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase)); + const layerThreads = ThreadManagement.layer.pipe( + Layer.provide(Layer.mergeAll(layerOrchestrator, layerSettings, layerReceipts)), + ); + const layerProjects = Layer.mock(ProjectService.ProjectService)({ + getById: (id) => Effect.succeed(Option.fromNullishOr(projects.find((p) => p.id === id))), + }); + const layerLaunch = ThreadLaunch.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerThreads, + layerReceipts, + layerOrchestrator, + layerSettings, + layerProjects, + IdAllocator.layer, + WorktreeSetupTracker.layer, + ProviderRegistryMock.layer(), + Layer.mock(TerminalManager.TerminalManager)({ close: () => Effect.void }), + Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({ get: () => Effect.succeed(null) }), + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: () => Effect.succeed(false), + }), + Layer.mock(GitWorkflow.GitWorkflowService)({ currentBranch: () => Effect.succeed(null) }), + Layer.mock(TextGeneration.TextGeneration)({}), + Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, { + runForThread: () => Effect.succeed({ status: "no-script" as const }), + }), + Layer.mock(TaskFolders.TaskFolders)({ plan: () => Effect.succeed(null) }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + folderForThread: () => Effect.succeedNone, + }), + ), + ), + ); + const layerDelivery = BotMentionDelivery.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerLaunch, + layerThreads, + layerSettings, + layerProjects, + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getEnvironmentId: Effect.succeed(environmentId), + }), + ), + ), + ); + return Layer.mergeAll( + layerDelivery, + layerLaunch, + layerThreads, + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ); +} + +const atlas = botContextRecord({ environmentId, projectId: botProjectId }, "Atlas"); + +/** A source thread whose first message tags the given records; returns that message's id. */ +const tagFromSourceThread = Effect.fn("test.tagFromSourceThread")(function* ( + records: ReadonlyArray = [atlas], + text = `${records.map((record) => formatComposerContextReference(record)).join(" ")} check the deploy`, +) { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threadId = ThreadId.make("thread:source"); + const messageId = MessageId.make("message:source"); + yield* launches.launch({ + commandId: CommandId.make("command:source"), + threadId, + projectId: sourceProjectId, + title: "Fix login", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + initialMessage: { messageId, text, attachments: [], context: { version: 1, records } }, + createdBy: "user", + creationSource: "web", + }); + return { threadId, messageId }; +}); + +const launchBotThread = Effect.fn("test.launchBotThread")(function* (id: string) { + const launches = yield* ThreadLaunch.ThreadLaunchService; + yield* TestClock.adjust("1 second"); + return (yield* launches.launch({ + commandId: CommandId.make(`command:${id}`), + threadId: ThreadId.make(id), + projectId: botProjectId, + title: id, + modelSelection: botModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + createdBy: "user", + creationSource: "web", + })).threadId; +}); + +const userMessages = Effect.fn("test.userMessages")(function* (threadId: ThreadId) { + const threads = yield* ThreadManagement.ThreadManagementService; + const { messages } = yield* threads.getThreadRecords(threadId, ["messages"]); + return messages.filter((message) => message.role === "user").map((message) => message.text); +}); + +const expectedText = [ + "Tagged from Fix login ():", + "", + "@Atlas check the deploy", +].join("\n"); + +it.effect("enqueues one delivery per tagged bot after the message commits", () => + Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + const scout = botContextRecord( + { environmentId, projectId: ProjectId.make("project:scout") }, + "Scout", + ); + const text = [atlas, scout, atlas].map((bot) => formatComposerContextReference(bot)).join(" "); + const { threadId, messageId } = yield* tagFromSourceThread([atlas, scout], text); + // A retry of the accepted command replays its receipt. + yield* tagFromSourceThread([atlas, scout], text); + const deliveries = (yield* outbox.listByCommandId(CommandId.make("command:source"))) + .filter((effect) => effect.request.type === "bot-mention.deliver") + .map((effect) => ({ threadId: effect.threadId, request: effect.request })); + assert.deepStrictEqual(deliveries, [ + { + threadId, + request: { type: "bot-mention.deliver", messageId, projectId: botProjectId }, + }, + { + threadId, + request: { type: "bot-mention.deliver", messageId, projectId: scout.projectId }, + }, + ]); + }).pipe(Effect.provide(makeLayer())), +); + +it.effect("enqueues nothing for a message without bot tags", () => + Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + const thread = threadContextRecord( + { environmentId, threadId: ThreadId.make("thread:other") }, + "Other", + ); + yield* tagFromSourceThread([thread]); + // A record the text no longer references tags nobody. + yield* tagFromSourceThread([atlas], "plain text"); + const types = (yield* outbox.listByCommandId(CommandId.make("command:source"))).map( + (effect) => effect.request.type, + ); + assert.notInclude(types, "bot-mention.deliver"); + }).pipe(Effect.provide(makeLayer())), +); + +it.effect("delivers to the main thread once, however often the effect runs", () => + Effect.gen(function* () { + const delivery = yield* BotMentionDelivery.BotMentionDelivery; + const main = yield* launchBotThread("thread:atlas-main"); + const recent = yield* launchBotThread("thread:atlas-recent"); + const source = yield* tagFromSourceThread(); + const input = { sourceThreadId: source.threadId, messageId: source.messageId }; + + const first = yield* delivery.deliver({ ...input, projectId: botProjectId }); + assert.deepStrictEqual(first, { status: "delivered", threadId: main, target: "main" }); + // A replay after a restart, or a retry after the send committed, sends nothing new. + yield* delivery.deliver({ ...input, projectId: botProjectId }); + assert.deepStrictEqual(yield* userMessages(main), [expectedText]); + assert.deepStrictEqual(yield* userMessages(recent), []); + }).pipe( + Effect.provide( + makeLayer({ [botProjectId]: { mainThreadId: ThreadId.make("thread:atlas-main") } }), + ), + ), +); + +it.effect("falls back to the most recent thread when the main thread is archived", () => + Effect.gen(function* () { + const delivery = yield* BotMentionDelivery.BotMentionDelivery; + const threads = yield* ThreadManagement.ThreadManagementService; + const older = yield* launchBotThread("thread:atlas-older"); + const main = yield* launchBotThread("thread:atlas-main"); + const recent = yield* launchBotThread("thread:atlas-recent"); + yield* threads.dispatch({ + type: "thread.archive", + commandId: CommandId.make("command:archive-main"), + threadId: main, + }); + const source = yield* tagFromSourceThread(); + + const result = yield* delivery.deliver({ + sourceThreadId: source.threadId, + messageId: source.messageId, + projectId: botProjectId, + }); + assert.deepStrictEqual(result, { status: "delivered", threadId: recent, target: "recent" }); + assert.deepStrictEqual(yield* userMessages(recent), [expectedText]); + assert.deepStrictEqual(yield* userMessages(older), []); + }).pipe( + Effect.provide( + makeLayer({ [botProjectId]: { mainThreadId: ThreadId.make("thread:atlas-main") } }), + ), + ), +); + +it.effect("starts a Main thread on the bot's default model when it has none, once", () => + Effect.gen(function* () { + const delivery = yield* BotMentionDelivery.BotMentionDelivery; + const threads = yield* ThreadManagement.ThreadManagementService; + const source = yield* tagFromSourceThread(); + const input = { + sourceThreadId: source.threadId, + messageId: source.messageId, + projectId: botProjectId, + }; + + const first = yield* delivery.deliver(input); + assert.equal(first.status, "delivered"); + if (first.status !== "delivered") return; + assert.equal(first.target, "new"); + // The Main thread now exists, so a retry that picked a target again would also send to it. + const retry = yield* delivery.deliver(input); + assert.deepStrictEqual(retry, first); + + const botThreads = yield* threads.listProjectThreads({ + projectId: botProjectId, + includeSubagents: false, + }); + assert.deepStrictEqual( + botThreads.map((thread) => thread.title), + [BotMentionDelivery.NEW_BOT_THREAD_TITLE], + ); + const shell = yield* threads.getThreadShell(first.threadId); + assert.deepStrictEqual(shell?.modelSelection, botModelSelection); + assert.deepStrictEqual(yield* userMessages(first.threadId), [expectedText]); + }).pipe(Effect.provide(makeLayer())), +); + +it.effect("delivers nothing to a project that is not a bot, or a bot on another environment", () => + Effect.gen(function* () { + const delivery = yield* BotMentionDelivery.BotMentionDelivery; + const threads = yield* ThreadManagement.ThreadManagementService; + const elsewhere = botContextRecord( + { environmentId: EnvironmentId.make("environment:other"), projectId: botProjectId }, + "Atlas", + ); + const source = yield* tagFromSourceThread([elsewhere]); + const input = { sourceThreadId: source.threadId, messageId: source.messageId }; + + assert.deepStrictEqual(yield* delivery.deliver({ ...input, projectId: botProjectId }), { + status: "skipped", + reason: "other-environment", + }); + assert.deepStrictEqual(yield* delivery.deliver({ ...input, projectId: sourceProjectId }), { + status: "skipped", + reason: "not-a-bot", + }); + assert.deepStrictEqual( + yield* threads.listProjectThreads({ projectId: botProjectId, includeSubagents: false }), + [], + ); + }).pipe(Effect.provide(makeLayer())), +); diff --git a/apps/server/src/bot/BotMentionDelivery.ts b/apps/server/src/bot/BotMentionDelivery.ts new file mode 100644 index 0000000000000..853762bb34170 --- /dev/null +++ b/apps/server/src/bot/BotMentionDelivery.ts @@ -0,0 +1,221 @@ +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + MessageId, + type ProjectId, + type ThreadId, +} from "@t3tools/contracts"; +import { + composerContextPlainText, + referencedBotMentions, +} from "@t3tools/shared/composerContextReferences"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { formatThreadLink } from "@t3tools/shared/threadLinks"; +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 * as Semaphore from "effect/Semaphore"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ServerSettings from "../serverSettings.ts"; + +export class BotMentionDeliveryError extends Schema.TaggedError()( + "BotMentionDeliveryError", + { + stage: Schema.Literals(["read-settings", "read-source", "read-bot", "send", "launch"]), + projectId: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Delivering a T3_BOT mention to ${this.projectId} failed at ${this.stage}.`; + } +} + +export interface BotMentionDeliveryInput { + readonly sourceThreadId: ThreadId; + readonly messageId: MessageId; + readonly projectId: ProjectId; +} + +export type BotMentionDeliveryResult = + | { + readonly status: "delivered"; + readonly threadId: ThreadId; + readonly target: "main" | "recent" | "new"; + } + | { readonly status: "already-delivered" } + | { + readonly status: "skipped"; + readonly reason: "not-a-bot" | "source-missing" | "other-environment" | "self"; + }; + +/** The title of the conversation a bot with no threads gets for its first mention. */ +export const NEW_BOT_THREAD_TITLE = "Main"; + +/** + * Runs `bot-mention.deliver` effects. Production provides it beside thread launch, which the + * effect executor cannot depend on; elsewhere a mention is dropped. + */ +export class BotMentionDelivery extends Context.Reference<{ + readonly deliver: ( + input: BotMentionDeliveryInput, + ) => Effect.Effect; +}>("t3/bot/BotMentionDelivery", { + defaultValue: () => ({ + deliver: () => Effect.succeed({ status: "skipped", reason: "not-a-bot" } as const), + }), +}) {} + +/** The message a bot receives: where it was tagged, then what the user wrote. */ +function botMentionMessageText(input: { + readonly sourceTitle: string; + readonly sourceLink: string; + readonly text: string; +}): string { + return `Tagged from ${input.sourceTitle} (${input.sourceLink}):\n\n${input.text}`; +} + +const make = Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const environment = yield* ServerEnvironment.ServerEnvironment; + const projects = yield* ProjectService.ProjectService; + const threads = yield* ThreadManagement.ThreadManagementService; + const launches = yield* ThreadLaunch.ThreadLaunchService; + // Two mentions of a bot without threads must not each start a "Main". + const lock = yield* Semaphore.make(1); + + const fail = + (stage: BotMentionDeliveryError["stage"], projectId: ProjectId) => (cause: unknown) => + new BotMentionDeliveryError({ stage, projectId, cause }); + + const selectTarget = Effect.fn("BotMentionDelivery.selectTarget")(function* ( + projectId: ProjectId, + mainThreadId: ThreadId | null, + ) { + if (mainThreadId !== null) { + const main = yield* threads.getThreadShell(mainThreadId); + if (main !== null && main.projectId === projectId && main.archivedAt === null) { + return { threadId: main.id, target: "main" as const }; + } + } + const [recent] = yield* threads.listProjectThreads({ projectId, includeSubagents: false }); + return recent === undefined ? null : { threadId: recent.id, target: "recent" as const }; + }); + + // Runs only inside `deliver`, whose span covers it. + const deliverUnlocked = Effect.fnUntraced(function* (input: BotMentionDeliveryInput) { + const { projectId } = input; + const current = yield* settings.getSettings.pipe( + Effect.mapError(fail("read-settings", projectId)), + ); + const bot = current.bots[projectId]; + if (bot === undefined) return { status: "skipped", reason: "not-a-bot" } as const; + + const source = yield* threads + .getThreadShell(input.sourceThreadId) + .pipe(Effect.mapError(fail("read-source", projectId))); + if (source === null) return { status: "skipped", reason: "source-missing" } as const; + if (source.projectId === projectId) return { status: "skipped", reason: "self" } as const; + const message = (yield* threads + .getMessagesById(input.sourceThreadId, [input.messageId]) + .pipe(Effect.mapError(fail("read-source", projectId)))).get(input.messageId); + if (message === undefined) return { status: "skipped", reason: "source-missing" } as const; + const environmentId = yield* environment.getEnvironmentId; + const records = message.context?.records ?? []; + const tagged = referencedBotMentions(message.text, records).some( + (record) => record.projectId === projectId && record.environmentId === environmentId, + ); + if (!tagged) return { status: "skipped", reason: "other-environment" } as const; + + const project = yield* projects + .getById(projectId) + .pipe(Effect.mapError(fail("read-bot", projectId))); + if (Option.isNone(project) || project.value.archivedAt !== null) { + return { status: "skipped", reason: "not-a-bot" } as const; + } + + const key = `${input.messageId}:${projectId}`; + const sendCommandId = CommandId.make(`bot-mention:send:${key}`); + const launchCommandId = CommandId.make(`bot-mention:launch:${key}`); + const messageId = MessageId.make(`bot-mention:${key}`); + const text = botMentionMessageText({ + sourceTitle: source.title, + sourceLink: formatThreadLink({ environmentId, threadId: source.id }), + text: composerContextPlainText(message.text, records), + }); + // Sent by T3 Code for the user, as other server-sent messages are. + const provenance = { createdBy: "agent", creationSource: "server" } as const; + + const projectSettings = resolveProjectSettings(current, projectId, project.value).settings; + const launch = launches + .launch({ + commandId: launchCommandId, + projectId, + title: NEW_BOT_THREAD_TITLE, + modelSelection: projectSettings.defaultModelSelection ?? source.modelSelection, + runtimeMode: projectSettings.defaultRuntimeMode, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + workspaceStrategy: { type: "root" }, + initialMessage: { messageId, text, attachments: [] }, + ...provenance, + }) + .pipe( + Effect.map((launched) => ({ + status: "delivered" as const, + threadId: launched.threadId, + target: "new" as const, + })), + Effect.mapError(fail("launch", projectId)), + ); + + // Command receipts make a retry replay the first attempt. A retry must not pick a new + // target either: a launched "Main" would otherwise also get a send. + if (yield* threads.hasReceipt(launchCommandId)) return yield* launch; + if (yield* threads.hasReceipt(sendCommandId)) return { status: "already-delivered" } as const; + + const target = yield* selectTarget(projectId, bot.mainThreadId ?? null).pipe( + Effect.mapError(fail("read-bot", projectId)), + ); + if (target === null) return yield* launch; + yield* threads + .sendToThread({ + projectId, + commandId: sendCommandId, + threadId: target.threadId, + messageId, + text, + attachments: [], + mode: "queue", + ...provenance, + }) + .pipe(Effect.mapError(fail("send", projectId))); + return { status: "delivered", ...target } as const; + }); + + const deliver = Effect.fn("BotMentionDelivery.deliver")(function* ( + input: BotMentionDeliveryInput, + ) { + yield* Effect.annotateCurrentSpan({ + "bot_mention.project_id": input.projectId, + "bot_mention.source_thread_id": input.sourceThreadId, + }); + const result = yield* lock.withPermits(1)(deliverUnlocked(input)); + if (result.status === "skipped") { + yield* Effect.logInfo("T3_BOT mention not delivered", { + projectId: input.projectId, + reason: result.reason, + }); + } + return result; + }); + + return { deliver }; +}); + +export const layer = Layer.effect(BotMentionDelivery, make); diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index b495293bc2228..8720e1a91727d 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -6,6 +6,7 @@ import { ModelSelection, NodeId, NonNegativeInt, + ProjectId, ProviderSessionId, RunAttemptId, ProviderApprovalDecision, @@ -138,6 +139,12 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ type: Schema.Literal("delegated-tasks.stop"), reason: Schema.optional(Schema.String), }), + /** Delivers a user message that tags a T3_BOT to that bot's main conversation. */ + Schema.Struct({ + type: Schema.Literal("bot-mention.deliver"), + messageId: MessageId, + projectId: ProjectId, + }), ]); export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type; @@ -152,6 +159,7 @@ export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [ "attachment.cleanup", "thread-title.generate", "delegated-tasks.stop", + "bot-mention.deliver", ] as const satisfies ReadonlyArray; export const PROCESS_BOUND_EFFECT_TYPES = [ @@ -164,6 +172,12 @@ export const PROCESS_BOUND_EFFECT_TYPES = [ "runtime-request.respond", ] as const satisfies ReadonlyArray; +/** Each runs in its own lane per thread, so a long provider start does not hold it back. */ +const SIDE_LANE_EFFECT_TYPES = [ + "thread-title.generate", + "bot-mention.deliver", +] as const satisfies ReadonlyArray; + export const OrchestrationEffectStatusV2 = Schema.Literals([ "pending", "running", @@ -370,13 +384,13 @@ export const layer: Layer.Layer = La ) AND ( ( - candidate.effect_type = 'thread-title.generate' - AND active.effect_type = 'thread-title.generate' + candidate.effect_type IN ${sql.in(SIDE_LANE_EFFECT_TYPES)} + AND active.effect_type = candidate.effect_type ) OR ( - candidate.effect_type != 'thread-title.generate' - AND active.effect_type != 'thread-title.generate' + candidate.effect_type NOT IN ${sql.in(SIDE_LANE_EFFECT_TYPES)} + AND active.effect_type NOT IN ${sql.in(SIDE_LANE_EFFECT_TYPES)} ) ) ) diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 6c805cfc4592f..b02706fc652e3 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -31,6 +31,7 @@ import * as RuntimeRequestService from "./RuntimeRequestService.ts"; import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as BotMentionDelivery from "../bot/BotMentionDelivery.ts"; import { continueRestartedRun } from "./RestartContinuation.ts"; const isProviderTurnControlError = Schema.is(ProviderTurnControlService.ProviderTurnControlError); @@ -107,6 +108,7 @@ export const layerExecutor: Layer.Layer< Effect.gen(function* () { const runFinalization = yield* RunFinalizationService.RunFinalizationService; const resourceCleanup = yield* ResourceCleanupService.ResourceCleanupService; + const botMentions = yield* BotMentionDelivery.BotMentionDelivery; const checkpointRollback = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const providerTurnControl = yield* ProviderTurnControlService.ProviderTurnControlServiceV2; @@ -696,6 +698,24 @@ export const layerExecutor: Layer.Layer< }), ), ); + case "bot-mention.deliver": + return botMentions + .deliver({ + sourceThreadId: effect.threadId, + messageId: effect.request.messageId, + projectId: effect.request.projectId, + }) + .pipe( + Effect.asVoid, + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); case "delegated-tasks.stop": return threads .stopDelegatedTasks({ diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 5e208fc7fd658..299fc1f93aed1 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -2767,7 +2767,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { }), ); - it.effect("runs title generation beside critical work while serializing each lane", () => + it.effect("runs title generation and bot mentions beside critical work, each in its lane", () => Effect.gen(function* () { const outbox = yield* EffectOutbox.EffectOutboxV2; const commandId = CommandId.make("command:foundation-title-effect-lane"); @@ -2776,6 +2776,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { const providerEffectId = "effect:foundation-title-effect-lane:b-provider"; const nextTitleEffectId = "effect:foundation-title-effect-lane:c-title"; const nextCriticalEffectId = "effect:foundation-title-effect-lane:d-critical"; + const botEffectId = "effect:foundation-title-effect-lane:e-bot"; yield* outbox.enqueue([ { id: titleEffectId, @@ -2810,6 +2811,16 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { threadId, request: { type: "terminal.cleanup" }, }, + { + id: botEffectId, + commandId, + threadId, + request: { + type: "bot-mention.deliver", + messageId: MessageId.make("message:foundation-title-effect-lane"), + projectId: ProjectId.make("project:foundation-title-effect-lane:bot"), + }, + }, ]); const title = yield* outbox.claimNext({ @@ -2826,6 +2837,14 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { if (Option.isNone(provider)) return; assert.equal(provider.value.id, providerEffectId); + const bot = yield* outbox.claimNext({ + workerId: "bot-lane-worker", + }); + assert.isTrue(Option.isSome(bot)); + if (Option.isNone(bot)) return; + assert.equal(bot.value.id, botEffectId); + yield* outbox.succeed({ effectId: bot.value.id, workerId: "bot-lane-worker" }); + assert.isTrue( Option.isNone( yield* outbox.claimNext({ diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b95f618d8c1df..0be6b8ba6fce3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -167,6 +167,7 @@ import { type GuestShareCommand, } from "./GuestShareDecider.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; +import { botMentionDeliveryEffects } from "./botMentionEffects.ts"; import { withCommandMetrics } from "../observability/Metrics.ts"; import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -16284,9 +16285,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio default: return yield* dispatchUnsupported(command); } + const decidedEvents = yield* Ref.get(events); return { - events: yield* Ref.get(events), - effects: yield* Ref.get(effects), + events: decidedEvents, + effects: [ + ...(yield* Ref.get(effects)), + ...botMentionDeliveryEffects(command.commandId, decidedEvents), + ], ...(cancelUnsettledEffects === undefined ? {} : { cancelUnsettledEffects }), ...(updateDelegatedCompletionOnlyRunId === undefined ? {} diff --git a/apps/server/src/orchestration-v2/botMentionEffects.ts b/apps/server/src/orchestration-v2/botMentionEffects.ts new file mode 100644 index 0000000000000..7ac9ee03f96f8 --- /dev/null +++ b/apps/server/src/orchestration-v2/botMentionEffects.ts @@ -0,0 +1,30 @@ +import type { CommandId, OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import { referencedBotMentions } from "@t3tools/shared/composerContextReferences"; + +import type { PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; + +/** + * One delivery per user message and tagged bot. Its id makes a command retry, or a later update + * of the same message, enqueue nothing new. + */ +export function botMentionDeliveryEffects( + commandId: CommandId, + events: ReadonlyArray, +): PendingOrchestrationEffectV2[] { + const effects = new Map(); + for (const event of events) { + if (event.type !== "message.updated") continue; + const message = event.payload; + if (message.role !== "user" || message.context === undefined) continue; + for (const bot of referencedBotMentions(message.text, message.context.records)) { + const id = `effect:bot-mention.deliver:${message.id}:${bot.projectId}`; + effects.set(id, { + id, + commandId, + threadId: message.threadId, + request: { type: "bot-mention.deliver", messageId: message.id, projectId: bot.projectId }, + }); + } + } + return [...effects.values()]; +} diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index c4eed74b274cf..27b5a7d7936b4 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -53,6 +53,7 @@ import { layerThreadWorktreeRestore } from "../workspace/restoreMissingWorktree. import * as RunExecutionService from "./RunExecutionService.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; import * as ResourceCleanupService from "./ResourceCleanupService.ts"; +import * as BotMentionDelivery from "../bot/BotMentionDelivery.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; import * as RuntimeRequestService from "./RuntimeRequestService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; @@ -460,6 +461,11 @@ export const layerProduction = Layer.mergeAll( EffectOutbox.layerPruneWorker.pipe(Layer.provide(EffectOutbox.layer)), ).pipe( Layer.provide(ResourceCleanupService.layer.pipe(Layer.provide(layerScheduledTaskProvided))), + Layer.provide( + BotMentionDelivery.layer.pipe( + Layer.provide(Layer.merge(layerThreadLaunchProvided, layerThreadManagementProvided)), + ), + ), Layer.provideMerge(layerProjectService), Layer.provide(Scheduler.layer), Layer.provideMerge(layerEventInfrastructure), 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/BotContextChip.tsx b/apps/web/src/components/BotContextChip.tsx new file mode 100644 index 0000000000000..2fd9ebb7adba1 --- /dev/null +++ b/apps/web/src/components/BotContextChip.tsx @@ -0,0 +1,77 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import type { BotContextRecord, EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { BotIcon as BotGlyph, CheckIcon } from "lucide-react"; + +import { cn } from "~/lib/utils"; +import { useProject } from "~/state/entities"; +import { serverEnvironment } from "~/state/server"; +import { BotIcon } from "./bot/BotIcon"; +import { ContextChip, ContextChipLabel } from "./ContextChip"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; + +/** A bot's own icon, or a generic one while its project is unknown here. */ +export function BotMentionIcon(props: { + environmentId: EnvironmentId; + projectId: ProjectId; + className?: string; +}) { + const project = useProject(scopeProjectRef(props.environmentId, props.projectId)); + return project ? ( + + ) : ( +