diff --git a/apps/desktop/src/electron/ElectronWindow.test.ts b/apps/desktop/src/electron/ElectronWindow.test.ts index eac944722e73b..90da2950b5533 100644 --- a/apps/desktop/src/electron/ElectronWindow.test.ts +++ b/apps/desktop/src/electron/ElectronWindow.test.ts @@ -148,6 +148,67 @@ describe("ElectronWindow", () => { }).pipe(Effect.provide(layerTestFor("win32"))), ); + it.effect("forces Windows foreground activation when requested without prior prepareReveal", () => + Effect.gen(function* () { + const expectedTarget = { + windowId: 41, + processId: process.pid, + title: "T3 Code (Dev)", + bounds: { x: 200, y: 100, width: 2_400, height: 1_600 }, + contentBounds: { x: 216, y: 100, width: 2_368, height: 1_584 }, + }; + + // Direct forced reveal without prepareReveal uses Windows foreground activation. + yield* Effect.gen(function* () { + const window = makeWindowsRevealWindow(); + const electronWindow = yield* ElectronWindow.ElectronWindow; + yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow, { + forceWindowsForeground: true, + }); + + assert.lengthOf(appFocusMock.mock.calls, 1); + assert.lengthOf(window.show.mock.calls, 1); + assert.lengthOf(window.moveTop.mock.calls, 1); + assert.lengthOf(window.focus.mock.calls, 1); + assert.lengthOf(activateWindowsForegroundMock.mock.calls, 1); + assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 0); + }).pipe(Effect.provide(layerTestFor("win32"))); + + // Shell-hosted foreground lazily starts the UIA worker without prior prepareReveal. + shellHostedForegroundMock.mockResolvedValueOnce(true); + yield* Effect.gen(function* () { + const window = makeWindowsRevealWindow(); + const electronWindow = yield* ElectronWindow.ElectronWindow; + yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow, { + forceWindowsForeground: true, + }); + + assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 1); + assert.deepEqual(windowsForegroundFocusMock.mock.calls[0]?.[0], expectedTarget); + assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2); + }).pipe(Effect.provide(layerTestFor("win32"))); + + // Failed foreground activation lazily starts the UIA worker and retries activation. + startWindowsForegroundFocusThreadMock.mockClear(); + windowsForegroundFocusMock.mockClear(); + activateWindowsForegroundMock.mockClear(); + activateWindowsForegroundMock.mockRejectedValueOnce( + new Error("Windows initially refused foreground activation"), + ); + yield* Effect.gen(function* () { + const window = makeWindowsRevealWindow(); + const electronWindow = yield* ElectronWindow.ElectronWindow; + yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow, { + forceWindowsForeground: true, + }); + + assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 1); + assert.deepEqual(windowsForegroundFocusMock.mock.calls[0]?.[0], expectedTarget); + assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2); + }).pipe(Effect.provide(layerTestFor("win32"))); + }), + ); + it.effect("reports which windows were created with a title bar overlay", () => Effect.gen(function* () { const framed = { isDestroyed: () => false }; diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts index b5f89969e66c7..4f42c717cbc66 100644 --- a/apps/desktop/src/electron/ElectronWindow.ts +++ b/apps/desktop/src/electron/ElectronWindow.ts @@ -121,7 +121,10 @@ export class ElectronWindow extends Context.Service< readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect; readonly clearMain: (window: Option.Option) => Effect.Effect; readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect; - readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect; + readonly reveal: ( + window: Electron.BrowserWindow, + options?: { readonly forceWindowsForeground?: boolean }, + ) => Effect.Effect; readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect; readonly destroyAll: Effect.Effect; readonly syncAllAppearance: ( @@ -281,30 +284,32 @@ export const make = Effect.gen(function* () { .catch(() => false); }); }), - reveal: Effect.fn("ElectronWindow.reveal")(function (window) { + reveal: Effect.fn("ElectronWindow.reveal")(function (window, options) { return Effect.tryPromise({ try: async () => { if (window.isDestroyed()) { return; } - const captureReveal = platform === "win32" && captureRevealWindows.delete(window.id); + const forceWindowsForeground = + platform === "win32" && + (captureRevealWindows.delete(window.id) || options?.forceWindowsForeground === true); const shellHostedForeground = - captureReveal && (await isWindowsShellHostedForeground().catch(() => false)); + forceWindowsForeground && (await isWindowsShellHostedForeground().catch(() => false)); if (window.isMinimized()) { window.restore(); } - if (captureReveal) { + if (forceWindowsForeground) { Electron.app.focus(); } - if (captureReveal || !window.isVisible()) { + if (forceWindowsForeground || !window.isVisible()) { window.show(); } - if (captureReveal) { + if (forceWindowsForeground) { window.moveTop(); } @@ -314,10 +319,10 @@ export const make = Effect.gen(function* () { window.focus(); - if (captureReveal) { + if (forceWindowsForeground) { if (shellHostedForeground) { - await windowsForegroundFocus - ?.focus(windowsForegroundFocusTarget(window)) + await ensureWindowsForegroundFocus() + .focus(windowsForegroundFocusTarget(window)) .catch(() => false); } try { @@ -325,8 +330,8 @@ export const make = Effect.gen(function* () { } catch { const needsFocus = !(await isWindowsBrowserWindowForeground(window)); if (needsFocus && !window.isDestroyed()) { - await windowsForegroundFocus - ?.focus(windowsForegroundFocusTarget(window)) + await ensureWindowsForegroundFocus() + .focus(windowsForegroundFocusTarget(window)) .catch(() => false); } if (!window.isDestroyed()) { diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 0326af51dbad2..3be9d73045154 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -9,6 +9,7 @@ import { } from "./methods/appleSpeech.ts"; import * as DesktopIpc from "./DesktopIpc.ts"; import { installNotificationBadge } from "./methods/notificationBadge.ts"; +import { installThreadNotification } from "./methods/threadNotification.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; import { getConnectionCatalog, setConnectionCatalog } from "./methods/connectionCatalog.ts"; import { @@ -98,6 +99,7 @@ import { export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () { const ipc = yield* DesktopIpc.DesktopIpc; yield* installNotificationBadge(); + yield* installThreadNotification(); yield* PreviewIpc.installPreviewEventForwarding(); yield* ipc.handle(AppActivationIpc.setReady); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index c2e053b972a12..5d7fc218c4ad4 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -1,6 +1,9 @@ export const PICK_FOLDER_CHANNEL = "desktop:pick-folder"; export const TO_LOCAL_BACKEND_PATH_CHANNEL = "desktop:to-local-backend-path"; export const SET_NOTIFICATION_BADGE_CHANNEL = "desktop:set-notification-badge"; +export const SHOW_THREAD_NOTIFICATION_CHANNEL = "desktop:show-thread-notification"; +export const DISMISS_THREAD_NOTIFICATION_CHANNEL = "desktop:dismiss-thread-notification"; +export const THREAD_NOTIFICATION_ACTIVATE_CHANNEL = "desktop:thread-notification-activate"; export const PICK_PROJECT_FAVICON_CHANNEL = "desktop:pick-project-favicon"; export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files"; export const SET_THEME_CHANNEL = "desktop:set-theme"; diff --git a/apps/desktop/src/ipc/methods/threadNotification.test.ts b/apps/desktop/src/ipc/methods/threadNotification.test.ts new file mode 100644 index 0000000000000..4527572bd2399 --- /dev/null +++ b/apps/desktop/src/ipc/methods/threadNotification.test.ts @@ -0,0 +1,1060 @@ +import { assert, describe, it } from "@effect/vitest"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import type * as Electron from "electron"; +import { beforeEach, expect, vi } from "vite-plus/test"; + +interface MockNotificationInstance { + readonly options: Electron.NotificationConstructorOptions; + readonly show: ReturnType; + readonly close: ReturnType; + readonly on: (event: string, listener: (...args: ReadonlyArray) => void) => this; + readonly emit: (event: string, ...args: ReadonlyArray) => void; +} + +const native = vi.hoisted(() => { + const callLog: Array = []; + const notifications: Array = []; + const appListeners = new Map) => void>(); + let activationHandler: ((details: Electron.ActivationArguments) => void) | null = null; + let constructError: Error | null = null; + let showError: Error | null = null; + + const setToastActivatorCLSID = vi.fn((_clsid: string) => { + callLog.push("setToastActivatorCLSID"); + }); + const isSupported = vi.fn(() => { + callLog.push("Notification.isSupported"); + return true; + }); + const handleActivation = vi.fn((callback: (details: Electron.ActivationArguments) => void) => { + callLog.push("Notification.handleActivation"); + activationHandler = callback; + }); + const getFocusedWindow = vi.fn(() => null as object | null); + + class MockNotification implements MockNotificationInstance { + readonly options: Electron.NotificationConstructorOptions; + readonly show: ReturnType; + readonly close: ReturnType; + private readonly listeners = new Map< + string, + Array<(...args: ReadonlyArray) => void> + >(); + + constructor(options: Electron.NotificationConstructorOptions = {}) { + if (constructError) { + const error = constructError; + constructError = null; + throw error; + } + this.options = options; + this.show = vi.fn(() => { + if (showError) { + const error = showError; + showError = null; + throw error; + } + }); + this.close = vi.fn(); + notifications.push(this); + } + + on(event: string, listener: (...args: ReadonlyArray) => void): this { + const existing = this.listeners.get(event) ?? []; + existing.push(listener); + this.listeners.set(event, existing); + return this; + } + + emit(event: string, ...args: ReadonlyArray): void { + const listeners = this.listeners.get(event); + if (listeners === undefined) { + return; + } + for (const listener of listeners.slice()) { + listener(...args); + } + } + + static isSupported = isSupported; + static handleActivation = handleActivation; + } + + return { + callLog, + notifications, + appListeners, + setToastActivatorCLSID, + isSupported, + handleActivation, + getFocusedWindow, + MockNotification, + getActivationHandler: () => activationHandler, + resetActivationHandler: () => { + activationHandler = null; + }, + setConstructError: (error: Error | null) => { + constructError = error; + }, + setShowError: (error: Error | null) => { + showError = error; + }, + }; +}); + +vi.mock("electron", () => ({ + app: { + setToastActivatorCLSID: native.setToastActivatorCLSID, + on: (event: string, listener: (...args: ReadonlyArray) => void) => { + native.appListeners.set(event, listener); + }, + removeListener: (event: string) => { + native.appListeners.delete(event); + }, + }, + BrowserWindow: { + getFocusedWindow: native.getFocusedWindow, + }, + Notification: native.MockNotification, +})); + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronApp from "../../electron/ElectronApp.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; +import { + DISMISS_THREAD_NOTIFICATION_CHANNEL, + SHOW_THREAD_NOTIFICATION_CHANNEL, + THREAD_NOTIFICATION_ACTIVATE_CHANNEL, +} from "../channels.ts"; +import { + buildWindowsThreadToastXml, + installThreadNotification, + parseWindowsThreadNotificationTag, +} from "./threadNotification.ts"; + +interface RecordedSpawn { + readonly command: string; + readonly args: ReadonlyArray; + readonly env: Readonly> | undefined; + readonly extendEnv: boolean | undefined; + readonly stdin: unknown; + readonly stdout: unknown; + readonly stderr: unknown; +} + +interface RecordedReveal { + readonly window: Electron.BrowserWindow; + readonly options: { readonly forceWindowsForeground?: boolean } | undefined; +} + +const sampleAlert = ( + overrides?: Partial<{ + environmentId: EnvironmentId; + threadId: ThreadId; + title: string; + body: string; + actionLabel: string; + }>, +) => ({ + environmentId: overrides?.environmentId ?? EnvironmentId.make("env-1"), + threadId: overrides?.threadId ?? ThreadId.make("thread-1"), + title: overrides?.title ?? "Fix Windows notifications", + body: overrides?.body ?? "Turn completed with summary.", + actionLabel: overrides?.actionLabel ?? "Open thread", +}); + +const ipcEvent = { sender: { id: 1 } }; + +const makeHarness = Effect.fnUntraced(function* (options?: { + readonly platform?: NodeJS.Platform; + readonly appUserModelId?: string; + readonly isDevelopment?: boolean; + readonly hostEnv?: NodeJS.ProcessEnv; + readonly spawnExitCode?: Effect.Effect; + readonly spawnError?: unknown; +}) { + const handlers = new Map(); + const spawns = yield* Queue.unbounded(); + const reveals = yield* Queue.unbounded(); + const spawnedCommands: Array = []; + const finalizedSpawns: Array = []; + const callOrder: Array = []; + const sendMock = vi.fn((channel: string, payload: unknown) => { + callOrder.push(`send:${channel}`); + return payload; + }); + const mainWindow = { + id: 1, + isDestroyed: vi.fn(() => false), + webContents: { id: 1, send: sendMock }, + } as unknown as Electron.BrowserWindow; + + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const standard = command as unknown as { + readonly command: string; + readonly args: ReadonlyArray; + readonly options: { + readonly env?: Record; + readonly extendEnv?: boolean; + readonly stdin?: unknown; + readonly stdout?: unknown; + readonly stderr?: unknown; + }; + }; + const recorded: RecordedSpawn = { + command: standard.command, + args: standard.args, + env: standard.options.env, + extendEnv: standard.options.extendEnv, + stdin: standard.options.stdin, + stdout: standard.options.stdout, + stderr: standard.options.stderr, + }; + spawnedCommands.push(recorded); + yield* Queue.offer(spawns, recorded); + if (options?.spawnError !== undefined) { + return yield* Effect.fail(options.spawnError as never); + } + yield* Effect.addFinalizer(() => + Effect.sync(() => { + finalizedSpawns.push(recorded); + }), + ); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(42), + exitCode: options?.spawnExitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(0)), + exitStatus: Effect.never, + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + }), + ); + + const revealMock = vi.fn( + ( + window: Electron.BrowserWindow, + revealOptions?: { readonly forceWindowsForeground?: boolean }, + ) => + Effect.gen(function* () { + callOrder.push("reveal"); + yield* Queue.offer(reveals, { window, options: revealOptions }); + }), + ); + + const layer = Layer.mergeAll( + ElectronApp.layer, + DesktopIpc.layerTest({ + handle: (channel, handler) => { + handlers.set(channel, handler); + }, + removeHandler: (channel) => { + handlers.delete(channel); + }, + on: vi.fn(), + removeAllListeners: vi.fn(), + }), + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + appUserModelId: options?.appUserModelId ?? "com.t3tools.t3code", + isDevelopment: options?.isDevelopment ?? false, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Layer.mock(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome(mainWindow), + reveal: revealMock, + }), + Layer.succeed(HostProcess.Platform, options?.platform ?? "win32"), + Layer.succeed(HostProcess.Environment, options?.hostEnv ?? { SystemRoot: "C:\\Windows" }), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const invokeShow = (payload: unknown) => { + const handler = handlers.get(SHOW_THREAD_NOTIFICATION_CHANNEL); + assert.isDefined(handler); + return Promise.resolve(handler(ipcEvent, payload)); + }; + + const invokeDismiss = (payload?: unknown) => { + const handler = handlers.get(DISMISS_THREAD_NOTIFICATION_CHANNEL); + assert.isDefined(handler); + return Promise.resolve(handler(ipcEvent, payload)); + }; + + return { + layer, + handlers, + spawns, + reveals, + spawnedCommands, + finalizedSpawns, + callOrder, + sendMock, + revealMock, + mainWindow, + invokeShow, + invokeDismiss, + }; +}); + +beforeEach(() => { + vi.clearAllMocks(); + native.callLog.length = 0; + native.notifications.length = 0; + native.appListeners.clear(); + native.resetActivationHandler(); + native.setConstructError(null); + native.setShowError(null); + native.isSupported.mockImplementation(() => { + native.callLog.push("Notification.isSupported"); + return true; + }); + native.getFocusedWindow.mockReturnValue(null); +}); + +describe("buildWindowsThreadToastXml", () => { + it("escapes XML entities, strips invalid XML 1.0 control chars, and omits empty/control-only body", () => { + const xml = buildWindowsThreadToastXml({ + id: "t3a-1", + title: `A & "C" 'D'\u0000\u0008\u000B\u000C\u001F\uFFFE\uFFFF\t\n\r`, + body: `Line 1 & 'quote' "double"\u0007`, + actionLabel: `Open & "thread"`, + }); + + expect(xml).toContain( + ``, + ); + expect(xml).toContain(`A & <B> "C" 'D'\t\n\r`); + expect(xml).toContain( + `Line 1 <tag> & 'quote' "double"`, + ); + expect(xml).toContain(`