From e5a9fe0724b790aa79417497a4473f49b900e588 Mon Sep 17 00:00:00 2001 From: Dan Shapiro <3732858+danshapiro@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:43:42 -0800 Subject: [PATCH 01/28] docs: add implementation plan for windows-single-notification --- .../2026-11-26-windows-single-notification.md | 1307 +++++++++++++++++ 1 file changed, 1307 insertions(+) create mode 100644 docs/plans/2026-11-26-windows-single-notification.md diff --git a/docs/plans/2026-11-26-windows-single-notification.md b/docs/plans/2026-11-26-windows-single-notification.md new file mode 100644 index 0000000000000..7e97e9e8a895a --- /dev/null +++ b/docs/plans/2026-11-26-windows-single-notification.md @@ -0,0 +1,1307 @@ +# Windows Single-Notification Background Banner Implementation Plan + +> **For agentic workers:** Execute this plan task by task with a fresh +> implementer and a specification-plus-quality review after every task. Track +> progress with the checkbox steps below. + +## User Request + +### Requested result + +Implement single-notification Windows background banner behavior in T3 Code: while T3 is not focused on Windows, maintain one Windows notification for the latest thread alert where each new alert replaces the previous notification and points to the thread that triggered it; clicking the notification or its action button opens that thread and clears the notification; the notification's action button reflects visiting/opening the thread ("Open thread") rather than dismissing it; bringing T3 to the foreground clears the notification without changing the currently viewed thread; and closing the notification (×) dismisses it without opening or switching threads. + +### Explicit constraints + +- Keep the existing foreground in-app popup behavior (bypassing Windows notifications when T3 is focused) unchanged. +- Scope the behavior changes to Windows background notification banners (notifications shown when T3 is not focused). +- Use `gpt-6.1-sol` (Sol 6.1) for Fresh Eyes code review. + +### Accepted tradeoffs and residuals + +- Earlier background Windows alerts are replaced when a newer alert arrives; the sidebar remains where all threads needing attention are viewed. + +**Goal:** When T3 Code is unfocused on Windows, display at most one background Windows notification for the latest thread alert with an `"Open thread"` action button, replacing prior banners on each new alert, opening that thread and clearing the banner on body or button click, clearing without changing threads on foreground focus, and dismissing without navigating when closed via `×`. + +**Architecture:** Add a minimal, schema-validated `DesktopBridge` IPC contract (`showThreadNotification`, `dismissThreadNotification`, `onThreadNotificationActivate`) implemented by a scoped Electron main-process installer (`apps/desktop/src/ipc/methods/threadNotification.ts`) using `Electron.Notification` on `win32` with a fixed short Windows tag (`"t3-thread-alert"`), `"Open thread"` action button (localized label supplied by `apps/web`'s existing `m(msg("Open thread"))` translation), `silent: true`, and lifecycle hooks for focus, quit, and disposal. In `apps/web`, route Windows desktop background alerts through this bridge while preserving unread alerted thread counts for the taskbar badge, fall back to a single-tag Web `Notification` without `requireInteraction` for standalone Windows browsers, and leave foreground in-app toasts plus macOS and Linux background notification behavior unchanged. + +**Tech Stack:** TypeScript, Effect 4 (`effect/Effect`, `effect/Schema`, `effect/Option`), Electron `44.10.1` (`Notification`, `BrowserWindow`, `ipcMain`, `ipcRenderer`, `contextBridge`), React / TanStack Router (`apps/web`), Vitest via Vite+ (`vp test run`), `effect-tsgo`, `oxlint`, `oxfmt`, `knip`. + +## Global Constraints + +- Work only inside `/home/dan/code/t3-worktrees/t3code/t3-0dffd761-e03f8e37d646a042` on branch `t3/preload-finished-threads`. +- Prefix shell verification commands with `export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH"` so Node 26 (`v26.13.0`) and `vp` (`v1.4.0`) resolve cleanly. +- Keep foreground in-app popup behavior (bypassing Windows notifications when T3 is focused) and all macOS/Linux background notification behavior unchanged. +- Reuse `apps/web`'s existing `m(msg("Open thread"))` translation (already translated in all 10 locales) instead of introducing duplicate desktop i18n keys. +- Follow `AGENTS.md` and `docs/internals/testing.md`: + - Never run repo-wide `vp check`, `vp run -r test`, or `vp run -r typecheck`; use focused `vp test run`, package `typecheck`, `node apps/desktop/scripts/verify-preload-bundle.mjs`, and `vp run check:changed`. + - Use `Effect.fn("...")` for reusable Effect functions; keep comments minimal (<= 4 lines, constraints/invariants only); satisfy `t3code/no-low-value-comments`, `t3code/require-disposable-render`, `knip`, and `oxfmt`. + - Keep `apps/desktop/src/preload.ts` sandbox-safe (only `electron`, `./ipc/channels.ts`, and type imports; no Effect or Node imports). + - Keep Windows notification `id` / `tag` at most 16 characters (`"t3-thread-alert"`, 15 chars) because Windows drops overly long tags. + - Keep `DesktopBridge` additions optional (`?:`) so existing partial test stubs stay valid while `apps/desktop/src/preload.ts` implements all three methods. + - Use structured logging (`Effect.logWarning`) on desktop notification failures. +- **Standalone Windows browser surface boundary:** Standard Web `new Notification()` outside a Service Worker throws `TypeError` if `actions` is passed, and `apps/web` has no Service Worker. On standalone Windows browsers (`!window.desktopBridge`), remove `requireInteraction: true` (eliminating Chromium's injected `"Close"` button), enforce single-notification replacement with tag `"t3-thread-alert"`, clear on body click / `window` `focus` / `visibilitychange`, and handle `×` close without navigating. Full `"Open thread"` button support is delivered via the Electron Windows main-process `Notification` path. + +## File Responsibilities + +- `packages/contracts/src/ipc.ts`: Define `DesktopThreadNotificationSchema`, `DesktopThreadNotification`, `DesktopThreadNotificationResultSchema`, `DesktopThreadNotificationResult`, `DesktopThreadNotificationActivation`, and optional `DesktopBridge` methods `showThreadNotification`, `dismissThreadNotification`, and `onThreadNotificationActivate`. +- `packages/contracts/src/ipc.test.ts`: Unit-test `DesktopThreadNotificationSchema` and `DesktopThreadNotificationResultSchema` validation boundaries (valid payloads, empty body allowed, max-length rejection, blank title/actionLabel rejection). +- `apps/desktop/src/ipc/channels.ts`: Define `SHOW_THREAD_NOTIFICATION_CHANNEL`, `DISMISS_THREAD_NOTIFICATION_CHANNEL`, and `THREAD_NOTIFICATION_ACTIVATE_CHANNEL`. +- `apps/desktop/src/preload.ts`: Expose `showThreadNotification`, `dismissThreadNotification`, and `onThreadNotificationActivate` (with runtime payload guard on activation events) on `desktopBridge`. +- `apps/desktop/src/ipc/methods/threadNotification.ts`: Scoped Electron main-process installer `installThreadNotification()` managing the single `win32` `Electron.Notification` instance, replacement, `"Open thread"` button + body click activation (send IPC then reveal window), `browser-window-focus` / `before-quit` / finalizer dismissal, `userCanceled` vs `timedOut` close semantics, and stale-token deduplication. +- `apps/desktop/src/ipc/DesktopIpcHandlers.ts`: Register `yield* installThreadNotification()` alongside `installNotificationBadge()`. +- `apps/desktop/src/ipc/methods/threadNotification.test.ts`: Unit-test every main-process behavior (schema rejection, non-win32/unsupported/focused suppression, replacement and stale-event suppression, click/action activation and deduplication, focus-before-click race, `userCanceled` vs `timedOut` Action Center retention, explicit dismiss, quit/finalizer cleanup). +- `apps/web/src/threadNotifications.ts`: Export `WINDOWS_THREAD_NOTIFICATION_TAG = "t3-thread-alert"` and `isWindowsNotificationClient(platform?: string): boolean` reading `window.desktopBridge?.getClientPlatform() ?? navigator.platform`. +- `apps/web/src/components/ThreadNotificationCoordinator.logic.ts`: Add pure helpers `buildDesktopThreadNotification` (safe title/body/actionLabel normalization and truncation within IPC schema bounds) and `createWindowsThreadNotificationTracker` (single active notification target + distinct unread alerted thread keys for taskbar badge count + hide/remove-environment/clear transitions). +- `apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts`: Unit-test `buildDesktopThreadNotification` and `createWindowsThreadNotificationTracker`. +- `apps/web/src/components/ThreadNotificationCoordinator.tsx`: Wire Windows Electron bridge path (`showThreadNotification`, `dismissThreadNotification`, `onThreadNotificationActivate`), Windows standalone browser single-tag fallback (without `requireInteraction`, with `"close"` listener), `visibilitychange` foreground clear, async generation guards, and preserve foreground in-app toasts and non-Windows macOS/Linux behavior. +- `apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts`: Extend real-browser coordinator tests to verify Windows Electron single-notification lifecycle, Windows browser fallback lifecycle, foreground in-app popup preservation, and non-Windows preservation. + +--- + +### Task 1: Shared contracts, desktop IPC channels, and preload bridge + +**Files:** + +- Modify: `packages/contracts/src/ipc.ts:5` and `packages/contracts/src/ipc.ts:1085-1105` +- Create: `packages/contracts/src/ipc.test.ts` +- Modify: `apps/desktop/src/ipc/channels.ts:1-6` +- Modify: `apps/desktop/src/preload.ts:120-130` + +**Interfaces:** + +- Consumes: `EnvironmentId`, `ThreadId`, `TrimmedNonEmptyString` from `packages/contracts/src/baseSchemas.ts`; `DesktopBridge` in `packages/contracts/src/ipc.ts`; `IpcChannels` in `apps/desktop/src/ipc/channels.ts`. +- Produces: + - `DesktopThreadNotificationSchema` & `DesktopThreadNotification` (`{ environmentId: EnvironmentId; threadId: ThreadId; title: string; body: string; actionLabel: string }`) + - `DesktopThreadNotificationResultSchema` & `DesktopThreadNotificationResult` (`"shown" | "suppressed" | "unsupported"`) + - `DesktopThreadNotificationActivation` (`{ environmentId: EnvironmentId; threadId: ThreadId }`) + - `SHOW_THREAD_NOTIFICATION_CHANNEL = "desktop:show-thread-notification"` + - `DISMISS_THREAD_NOTIFICATION_CHANNEL = "desktop:dismiss-thread-notification"` + - `THREAD_NOTIFICATION_ACTIVATE_CHANNEL = "desktop:thread-notification-activate"` + - Optional `DesktopBridge` methods `showThreadNotification`, `dismissThreadNotification`, `onThreadNotificationActivate` implemented in `apps/desktop/src/preload.ts`. + +- [ ] **Step 1: Write the failing behavioral test** + +Create `packages/contracts/src/ipc.test.ts`: + +```ts +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { DesktopThreadNotificationResultSchema, DesktopThreadNotificationSchema } from "./ipc.ts"; + +describe("DesktopThreadNotificationSchema", () => { + const decode = Schema.decodeUnknownSync(DesktopThreadNotificationSchema); + const decodeResult = Schema.decodeUnknownSync(DesktopThreadNotificationResultSchema); + + it("accepts valid thread notifications including an empty body and trims title and actionLabel", () => { + expect( + decode({ + environmentId: "env-1", + threadId: "thread-1", + title: " Thread completed ", + body: "", + actionLabel: " Open thread ", + }), + ).toEqual({ + environmentId: "env-1", + threadId: "thread-1", + title: "Thread completed", + body: "", + actionLabel: "Open thread", + }); + + expect(decodeResult("shown")).toBe("shown"); + expect(decodeResult("suppressed")).toBe("suppressed"); + expect(decodeResult("unsupported")).toBe("unsupported"); + }); + + it("rejects blank or overlong fields and unknown results", () => { + const valid = { + environmentId: "env-1", + threadId: "thread-1", + title: "Thread completed", + body: "Fix build", + actionLabel: "Open thread", + }; + + for (const invalid of [ + { ...valid, environmentId: "" }, + { ...valid, threadId: " " }, + { ...valid, title: " " }, + { ...valid, title: "a".repeat(257) }, + { ...valid, body: "b".repeat(513) }, + { ...valid, actionLabel: "" }, + { ...valid, actionLabel: "c".repeat(65) }, + ]) { + expect(() => decode(invalid)).toThrow(); + } + + expect(() => decodeResult("dismissed")).toThrow(); + }); +}); +``` + +- [ ] **Step 2: Run the test and verify the intended failure** + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run packages/contracts/src/ipc.test.ts +``` + +Expected: FAIL because `DesktopThreadNotificationSchema` and `DesktopThreadNotificationResultSchema` are not yet exported from `packages/contracts/src/ipc.ts`. + +- [ ] **Step 3: Add the minimal production implementation** + +1. In `packages/contracts/src/ipc.ts`: + - Update line 5 import to include `ThreadId`: + ```ts + import { EnvironmentId, PortSchema, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + ``` + - Directly above `export interface DesktopBridge` (around line 1087), add: + ```ts + export const DesktopThreadNotificationSchema = Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + title: TrimmedNonEmptyString.check(Schema.isMaxLength(256)), + body: Schema.String.check(Schema.isMaxLength(512)), + actionLabel: TrimmedNonEmptyString.check(Schema.isMaxLength(64)), + }); + export type DesktopThreadNotification = typeof DesktopThreadNotificationSchema.Type; + + export const DesktopThreadNotificationResultSchema = Schema.Literals([ + "shown", + "suppressed", + "unsupported", + ]); + export type DesktopThreadNotificationResult = + typeof DesktopThreadNotificationResultSchema.Type; + + export interface DesktopThreadNotificationActivation { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + } + ``` + - Inside `DesktopBridge` right after `onNotificationBadgeClear` (around line 1096), add: + ```ts + showThreadNotification?: ( + notification: DesktopThreadNotification, + ) => Promise; + dismissThreadNotification?: () => Promise; + onThreadNotificationActivate?: ( + listener: (target: DesktopThreadNotificationActivation) => void, + ) => () => void; + ``` + +2. In `apps/desktop/src/ipc/channels.ts` directly after `SET_NOTIFICATION_BADGE_CHANNEL`: + + ```ts + 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"; + ``` + +3. In `apps/desktop/src/preload.ts` directly after `onNotificationBadgeClear` (around line 127): + ```ts + showThreadNotification: (notification) => + ipcRenderer.invoke(IpcChannels.SHOW_THREAD_NOTIFICATION_CHANNEL, notification), + dismissThreadNotification: () => + ipcRenderer.invoke(IpcChannels.DISMISS_THREAD_NOTIFICATION_CHANNEL), + onThreadNotificationActivate: (listener) => { + const handler = (_event: Electron.IpcRendererEvent, target: unknown) => { + if ( + typeof target !== "object" || + target === null || + typeof (target as { environmentId?: unknown }).environmentId !== "string" || + typeof (target as { threadId?: unknown }).threadId !== "string" + ) { + return; + } + listener(target as Parameters[0]); + }; + ipcRenderer.on(IpcChannels.THREAD_NOTIFICATION_ACTIVATE_CHANNEL, handler); + return () => + ipcRenderer.removeListener(IpcChannels.THREAD_NOTIFICATION_ACTIVATE_CHANNEL, handler); + }, + ``` + +- [ ] **Step 4: Run the focused test** + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run packages/contracts/src/ipc.test.ts +``` + +Expected: PASS (2 tests passed). + +- [ ] **Step 5: Refactor while green** + +Review `packages/contracts/src/ipc.ts` and `apps/desktop/src/preload.ts` for type safety (`satisfies DesktopBridge` with no `any`) and minimal diff; no extra abstraction is needed. + +- [ ] **Step 6: Run impacted-test verification** + +Impacted surfaces: `@t3tools/contracts` schema tests and typecheck, `@t3tools/desktop` preload bundle verification and typecheck (because `DesktopBridge`, `channels.ts`, and `preload.ts` changed). + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run packages/contracts/src/ipc.test.ts apps/desktop/scripts/verify-preload-bundle.test.mjs && vp run --filter @t3tools/contracts typecheck && vp run --filter @t3tools/desktop build && node apps/desktop/scripts/verify-preload-bundle.mjs && vp run --filter @t3tools/desktop typecheck +``` + +Expected: PASS (all tests, typechecks, desktop bundle build, and preload bundle verification exit 0). + +- [ ] **Step 7: Commit the task** + +```bash +git add packages/contracts/src/ipc.ts packages/contracts/src/ipc.test.ts apps/desktop/src/ipc/channels.ts apps/desktop/src/preload.ts +git commit -m "feat(contracts,desktop): add Windows thread notification IPC bridge" +``` + +--- + +### Task 2: Electron main-process single Windows thread notification installer + +**Files:** + +- Create: `apps/desktop/src/ipc/methods/threadNotification.ts` +- Modify: `apps/desktop/src/ipc/DesktopIpcHandlers.ts:6` and `apps/desktop/src/ipc/DesktopIpcHandlers.ts:91-96` +- Create: `apps/desktop/src/ipc/methods/threadNotification.test.ts` + +**Interfaces:** + +- Consumes: `DesktopThreadNotificationSchema`, `DesktopThreadNotificationResultSchema`, `DesktopThreadNotificationActivation` from `@t3tools/contracts`; `DesktopIpc.DesktopIpc`, `DesktopIpc.makeIpcMethod` from `../DesktopIpc.ts`; `ElectronApp.ElectronApp` from `../../electron/ElectronApp.ts`; `ElectronWindow.ElectronWindow` from `../../electron/ElectronWindow.ts`; `HostProcess.Platform` from `@t3tools/shared/HostProcess`; channels from `../channels.ts`. +- Produces: `WINDOWS_THREAD_NOTIFICATION_ID = "t3-thread-alert"` and `installThreadNotification` registered in `installDesktopIpcHandlers()`. + +- [ ] **Step 1: Write the failing behavioral test** + +Create `apps/desktop/src/ipc/methods/threadNotification.test.ts`: + +```ts +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { beforeEach, expect, vi } from "vite-plus/test"; +import { it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +interface FakeNotification { + readonly options: Electron.NotificationConstructorOptions; + readonly show: ReturnType; + readonly close: ReturnType; + readonly listeners: Map void>; + emit: (event: string, ...args: unknown[]) => void; +} + +const native = vi.hoisted(() => ({ + isSupported: vi.fn(() => true), + notifications: [] as FakeNotification[], + showError: null as Error | null, + getFocusedWindow: vi.fn(() => null as object | null), + mainWindowDestroyed: false, + mainWindowSend: vi.fn(), + reveal: vi.fn(() => Effect.void), + appListeners: new Map void>(), +})); + +vi.mock("electron", () => ({ + app: { + on: (event: string, listener: () => void) => native.appListeners.set(event, listener), + removeListener: (event: string) => native.appListeners.delete(event), + }, + BrowserWindow: { + getFocusedWindow: native.getFocusedWindow, + }, + Notification: class MockNotification { + static isSupported = native.isSupported; + readonly show = vi.fn(() => { + if (native.showError) throw native.showError; + }); + readonly close = vi.fn(); + readonly listeners = new Map void>(); + constructor(readonly options: Electron.NotificationConstructorOptions) { + native.notifications.push(this); + } + on(event: string, listener: (...args: unknown[]) => void) { + this.listeners.set(event, listener); + return this; + } + emit(event: string, ...args: unknown[]) { + this.listeners.get(event)?.(...args); + } + }, +})); + +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 { installThreadNotification, WINDOWS_THREAD_NOTIFICATION_ID } from "./threadNotification.ts"; + +const alertA = { + environmentId: "env-1", + threadId: "thread-1", + title: "Thread completed", + body: "First thread", + actionLabel: "Open thread", +}; + +const alertB = { + environmentId: "env-2", + threadId: "thread-2", + title: "Approval needed", + body: "Second thread", + actionLabel: "Open thread", +}; + +function electronWindowLayer() { + const mainWindow = { + isDestroyed: () => native.mainWindowDestroyed, + webContents: { send: native.mainWindowSend }, + } as unknown as Electron.BrowserWindow; + return Layer.mock(ElectronWindow.ElectronWindow, { + main: Effect.sync(() => (native.mainWindowDestroyed ? Option.none() : Option.some(mainWindow))), + reveal: (window) => native.reveal(window), + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + native.isSupported.mockReturnValue(true); + native.notifications.length = 0; + native.showError = null; + native.getFocusedWindow.mockReturnValue(null); + native.mainWindowDestroyed = false; + native.reveal.mockImplementation(() => Effect.void); + native.appListeners.clear(); +}); + +it.effect( + "replaces the single Windows notification, activates on click/action, and clears on focus, close, dismiss, and quit", + () => + Effect.gen(function* () { + const handlers = new Map(); + const event = { sender: { id: 1 } }; + + yield* Effect.scoped( + Effect.gen(function* () { + yield* installThreadNotification(); + const show = handlers.get(SHOW_THREAD_NOTIFICATION_CHANNEL)!; + const dismiss = handlers.get(DISMISS_THREAD_NOTIFICATION_CHANNEL)!; + + // Invalid payload is rejected by schema. + yield* Effect.promise(() => + expect(show(event, { ...alertA, title: " " })).rejects.toBeDefined(), + ); + expect(native.notifications).toHaveLength(0); + + // First alert creates a silent Windows toast with fixed id and "Open thread" button. + const firstResult = yield* Effect.promise(() => Promise.resolve(show(event, alertA))); + expect(firstResult).toBe("shown"); + expect(native.notifications).toHaveLength(1); + const first = native.notifications[0]!; + expect(first.options).toMatchObject({ + id: WINDOWS_THREAD_NOTIFICATION_ID, + title: "Thread completed", + body: "First thread", + silent: true, + timeoutType: "default", + actions: [{ type: "button", text: "Open thread" }], + }); + expect(first.show).toHaveBeenCalledTimes(1); + + // Second alert replaces the first; stale events from the first are ignored. + const secondResult = yield* Effect.promise(() => Promise.resolve(show(event, alertB))); + expect(secondResult).toBe("shown"); + expect(native.notifications).toHaveLength(2); + const second = native.notifications[1]!; + expect(first.close).toHaveBeenCalledTimes(1); + expect(second.options.id).toBe(WINDOWS_THREAD_NOTIFICATION_ID); + + first.emit("click", {}); + first.emit("action", { actionIndex: 0, selectionIndex: -1 }, 0); + first.emit("close", { reason: "userCanceled" }); + expect(native.mainWindowSend).not.toHaveBeenCalled(); + + // Clicking the "Open thread" action button opens the latest thread, reveals window, and closes once. + second.emit("action", { actionIndex: 0, selectionIndex: -1 }, 0); + second.emit("click", {}); + yield* Effect.promise(() => Promise.resolve()); + expect(second.close).toHaveBeenCalledTimes(1); + expect(native.mainWindowSend).toHaveBeenCalledTimes(1); + expect(native.mainWindowSend).toHaveBeenCalledWith(THREAD_NOTIFICATION_ACTIVATE_CHANNEL, { + environmentId: "env-2", + threadId: "thread-2", + }); + expect(native.reveal).toHaveBeenCalledTimes(1); + + // Body click also activates even if browser-window-focus arrived first. + yield* Effect.promise(() => Promise.resolve(show(event, alertA))); + const third = native.notifications[2]!; + native.appListeners.get("browser-window-focus")!(); + expect(third.close).toHaveBeenCalledTimes(1); + expect(native.mainWindowSend).toHaveBeenCalledTimes(1); + third.emit("click", {}); + yield* Effect.promise(() => Promise.resolve()); + expect(native.mainWindowSend).toHaveBeenCalledTimes(2); + expect(native.mainWindowSend).toHaveBeenLastCalledWith( + THREAD_NOTIFICATION_ACTIVATE_CHANNEL, + { environmentId: "env-1", threadId: "thread-1" }, + ); + + // Closing via X (userCanceled) clears without activating; subsequent focus does not re-close. + yield* Effect.promise(() => Promise.resolve(show(event, alertA))); + const fourth = native.notifications[3]!; + fourth.emit("close", { reason: "userCanceled" }); + native.appListeners.get("browser-window-focus")!(); + expect(fourth.close).not.toHaveBeenCalled(); + expect(native.mainWindowSend).toHaveBeenCalledTimes(2); + + // Timing out into Action Center retains the handle so focus still clears it from Action Center. + yield* Effect.promise(() => Promise.resolve(show(event, alertB))); + const fifth = native.notifications[4]!; + fifth.emit("close", { reason: "timedOut" }); + native.appListeners.get("browser-window-focus")!(); + expect(fifth.close).toHaveBeenCalledTimes(1); + expect(native.mainWindowSend).toHaveBeenCalledTimes(2); + + // Explicit dismiss IPC closes the active banner without activating. + yield* Effect.promise(() => Promise.resolve(show(event, alertA))); + const sixth = native.notifications[5]!; + yield* Effect.promise(() => Promise.resolve(dismiss(event, undefined))); + expect(sixth.close).toHaveBeenCalledTimes(1); + expect(native.mainWindowSend).toHaveBeenCalledTimes(2); + + // Focused window suppresses showing a new banner and clears any active one. + yield* Effect.promise(() => Promise.resolve(show(event, alertA))); + const seventh = native.notifications[6]!; + native.getFocusedWindow.mockReturnValue({}); + const suppressed = yield* Effect.promise(() => Promise.resolve(show(event, alertB))); + expect(suppressed).toBe("suppressed"); + expect(seventh.close).toHaveBeenCalledTimes(1); + expect(native.notifications).toHaveLength(7); + + // Quit clears any remaining active notification. + native.getFocusedWindow.mockReturnValue(null); + yield* Effect.promise(() => Promise.resolve(show(event, alertA))); + const eighth = native.notifications[7]!; + native.appListeners.get("before-quit")!(); + expect(eighth.close).toHaveBeenCalledTimes(1); + + // Scope disposal clears any remaining active notification. + yield* Effect.promise(() => Promise.resolve(show(event, alertB))); + }), + ).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provide([ + ElectronApp.layer, + electronWindowLayer(), + DesktopIpc.layerTest({ + handle: (channel, handler) => { + handlers.set(channel, handler); + }, + removeHandler: (channel) => { + handlers.delete(channel); + }, + on: vi.fn(), + removeAllListeners: vi.fn(), + }), + ]), + ); + + expect(native.notifications[8]!.close).toHaveBeenCalledTimes(1); + expect(native.appListeners.size).toBe(0); + expect(handlers.size).toBe(0); + }), +); + +it.effect( + "returns unsupported on non-Windows platforms or when Electron Notification is unavailable", + () => + Effect.gen(function* () { + const handlers = new Map(); + const event = { sender: { id: 1 } }; + + for (const [platform, supported] of [ + ["darwin", true], + ["linux", true], + ["win32", false], + ] as const) { + native.isSupported.mockReturnValue(supported); + yield* Effect.scoped( + Effect.gen(function* () { + yield* installThreadNotification(); + const show = handlers.get(SHOW_THREAD_NOTIFICATION_CHANNEL)!; + const result = yield* Effect.promise(() => Promise.resolve(show(event, alertA))); + expect(result).toBe("unsupported"); + }), + ).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provide([ + ElectronApp.layer, + electronWindowLayer(), + DesktopIpc.layerTest({ + handle: (channel, handler) => { + handlers.set(channel, handler); + }, + removeHandler: (channel) => { + handlers.delete(channel); + }, + on: vi.fn(), + removeAllListeners: vi.fn(), + }), + ]), + ); + } + + expect(native.notifications).toHaveLength(0); + }), +); +``` + +- [ ] **Step 2: Run the test and verify the intended failure** + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run apps/desktop/src/ipc/methods/threadNotification.test.ts +``` + +Expected: FAIL because `./threadNotification.ts` does not exist yet. + +- [ ] **Step 3: Add the minimal production implementation** + +1. Create `apps/desktop/src/ipc/methods/threadNotification.ts`: + +```ts +import * as Electron from "electron"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { + DesktopThreadNotificationResultSchema, + DesktopThreadNotificationSchema, + type DesktopThreadNotificationActivation, + type DesktopThreadNotificationResult, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +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"; + +// Windows drops toasts with tags longer than 16 characters. +export const WINDOWS_THREAD_NOTIFICATION_ID = "t3-thread-alert"; + +interface ActiveThreadNotification { + readonly token: number; + readonly notification: Electron.Notification; + superseded: boolean; +} + +function closeNotificationSafely(notification: Electron.Notification): void { + try { + notification.close(); + } catch (error) { + Effect.runSync(Effect.logWarning("Could not close thread notification", error)); + } +} + +export const installThreadNotification = Effect.fn("desktop.ipc.installThreadNotification")( + function* () { + const ipc = yield* DesktopIpc.DesktopIpc; + const app = yield* ElectronApp.ElectronApp; + const electronWindow = yield* ElectronWindow.ElectronWindow; + const platform = yield* HostProcess.Platform; + + let nextToken = 0; + let active: ActiveThreadNotification | null = null; + + const dismissActive = (supersede = false): void => { + const current = active; + if (current === null) return; + active = null; + if (supersede) current.superseded = true; + closeNotificationSafely(current.notification); + }; + + const activateTarget = (target: DesktopThreadNotificationActivation): void => { + void Effect.runPromise( + Effect.gen(function* () { + const window = yield* electronWindow.main; + if (Option.isNone(window) || window.value.isDestroyed()) return; + // Send before best-effort reveal; another process may refuse to yield foreground focus. + window.value.webContents.send(THREAD_NOTIFICATION_ACTIVATE_CHANNEL, target); + yield* electronWindow.reveal(window.value).pipe(Effect.ignoreCause); + }), + ); + }; + + yield* ipc.handle( + DesktopIpc.makeIpcMethod({ + channel: SHOW_THREAD_NOTIFICATION_CHANNEL, + payload: DesktopThreadNotificationSchema, + result: DesktopThreadNotificationResultSchema, + handler: (payload): Effect.Effect => + Effect.sync(() => { + if (platform !== "win32" || !Electron.Notification.isSupported()) { + return "unsupported"; + } + if (Electron.BrowserWindow.getFocusedWindow()) { + dismissActive(true); + return "suppressed"; + } + dismissActive(true); + const token = ++nextToken; + try { + const notification = new Electron.Notification({ + id: WINDOWS_THREAD_NOTIFICATION_ID, + title: payload.title, + body: payload.body, + silent: true, + timeoutType: "default", + actions: [{ type: "button", text: payload.actionLabel }], + }); + const entry: ActiveThreadNotification = { + token, + notification, + superseded: false, + }; + let activated = false; + const onActivate = () => { + if (entry.superseded || activated) return; + activated = true; + if (active?.token === token) { + active = null; + } + closeNotificationSafely(notification); + activateTarget({ + environmentId: payload.environmentId, + threadId: payload.threadId, + }); + }; + notification.on("click", onActivate); + notification.on("action", onActivate); + notification.on("close", (details) => { + // Keep active on timeout so foregrounding still removes the entry from Action Center. + if (details.reason === "timedOut") return; + if (active?.token === token) { + active = null; + } + }); + notification.on("failed", (_event, error) => { + Effect.runSync(Effect.logWarning("Windows thread notification failed", { error })); + if (active?.token === token) { + active = null; + } + }); + active = entry; + notification.show(); + return "shown"; + } catch (error) { + if (active?.token === token) { + active = null; + } + Effect.runSync( + Effect.logWarning("Could not show Windows thread notification", error), + ); + return "unsupported"; + } + }), + }), + ); + + yield* ipc.handle( + DesktopIpc.makeIpcMethod({ + channel: DISMISS_THREAD_NOTIFICATION_CHANNEL, + payload: Schema.Undefined, + result: Schema.Void, + handler: () => Effect.sync(() => dismissActive(true)), + }), + ); + + // Do not supersede on focus so an in-flight toast click that triggered focus still navigates. + yield* app.on("browser-window-focus", () => dismissActive(false)); + yield* app.on("before-quit", () => dismissActive(true)); + yield* Effect.addFinalizer(() => Effect.sync(() => dismissActive(true))); + }, +); +``` + +2. In `apps/desktop/src/ipc/DesktopIpcHandlers.ts`: + - Import `installThreadNotification` right after `installNotificationBadge` (line 6): + ```ts + import { installThreadNotification } from "./methods/threadNotification.ts"; + ``` + - Call `yield* installThreadNotification();` right after `yield* installNotificationBadge();` (line 93). + +- [ ] **Step 4: Run the focused test** + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run apps/desktop/src/ipc/methods/threadNotification.test.ts +``` + +Expected: PASS (2 tests passed). + +- [ ] **Step 5: Refactor while green** + +Check `apps/desktop/src/ipc/methods/threadNotification.ts` for any subtle race on `dismissActive` + `show()`, structured logging clarity, and lint/comment rules (<= 4 lines per comment, no unused variables). Re-run the focused test if changed. + +- [ ] **Step 6: Run impacted-test verification** + +Impacted surfaces: desktop IPC tests (`threadNotification.test.ts`, `notificationBadge.test.ts`, `DesktopIpc.test.ts`), `DesktopApp.test.ts` (verifies `DesktopApp.program` Effect service requirements still align), and `@t3tools/desktop` typecheck. + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run apps/desktop/src/ipc/methods/threadNotification.test.ts apps/desktop/src/ipc/methods/notificationBadge.test.ts apps/desktop/src/ipc/DesktopIpc.test.ts apps/desktop/src/app/DesktopApp.test.ts && vp run --filter @t3tools/desktop typecheck +``` + +Expected: PASS. + +- [ ] **Step 7: Commit the task** + +```bash +git add apps/desktop/src/ipc/methods/threadNotification.ts apps/desktop/src/ipc/methods/threadNotification.test.ts apps/desktop/src/ipc/DesktopIpcHandlers.ts +git commit -m "feat(desktop): manage single Windows background thread notification" +``` + +--- + +### Task 3: Web notification coordinator integration (Windows Electron + standalone browser fallback) + +**Files:** + +- Modify: `apps/web/src/threadNotifications.ts:24-40` +- Modify: `apps/web/src/components/ThreadNotificationCoordinator.logic.ts:1-133` +- Modify: `apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts` +- Modify: `apps/web/src/components/ThreadNotificationCoordinator.tsx:20-135, 200-235, 375-425` +- Modify: `apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts` + +**Interfaces:** + +- Consumes: `DesktopBridge` optional methods (`showThreadNotification`, `dismissThreadNotification`, `onThreadNotificationActivate`), `DesktopThreadNotification`, `DesktopThreadNotificationActivation` from `@t3tools/contracts`; `isWindowsPlatform` from `apps/web/src/lib/utils.ts`; `m(msg("Open thread"))` from `apps/web/src/i18n/messages`. +- Produces: + - `WINDOWS_THREAD_NOTIFICATION_TAG = "t3-thread-alert"` and `isWindowsNotificationClient(platform?: string): boolean` in `apps/web/src/threadNotifications.ts` + - `buildDesktopThreadNotification(...)` and `createWindowsThreadNotificationTracker()` in `apps/web/src/components/ThreadNotificationCoordinator.logic.ts` + - Updated `startThreadNotifications` in `apps/web/src/components/ThreadNotificationCoordinator.tsx` handling Windows single-notification replacement, `"Open thread"` desktop activation, focus/visibility clear without navigating, `×` close without navigating, hidden/removed thread pruning, and accurate taskbar badge counts while keeping foreground in-app toasts and non-Windows behavior unchanged. + +- [ ] **Step 1: Write the failing behavioral tests** + +1. Extend `apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts` with unit tests for `buildDesktopThreadNotification` and `createWindowsThreadNotificationTracker`: + +```ts +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + buildDesktopThreadNotification, + createWindowsThreadNotificationTracker, +} from "./ThreadNotificationCoordinator.logic"; + +describe("Windows single-notification helpers", () => { + it("normalizes and bounds desktop notification fields to IPC limits", () => { + expect( + buildDesktopThreadNotification({ + environmentId: EnvironmentId.make("env-1"), + threadId: ThreadId.make("thread-1"), + title: " " + "T".repeat(300), + body: "B".repeat(600), + actionLabel: "Open thread", + }), + ).toEqual({ + environmentId: "env-1", + threadId: "thread-1", + title: "T".repeat(256), + body: "B".repeat(512), + actionLabel: "Open thread", + }); + }); + + it("tracks one latest notification target while counting distinct unread alerted threads", () => { + const tracker = createWindowsThreadNotificationTracker(); + const a = { environmentId: EnvironmentId.make("env-1"), threadId: ThreadId.make("t-1") }; + const b = { environmentId: EnvironmentId.make("env-2"), threadId: ThreadId.make("t-2") }; + + expect(tracker.record(a)).toBe(1); + expect(tracker.current()).toEqual(a); + + expect(tracker.record(b)).toBe(2); + expect(tracker.current()).toEqual(b); + + // Re-alerting an already unread thread replaces the target without inflating the count. + expect(tracker.record(a)).toBe(2); + expect(tracker.current()).toEqual(a); + + // Pruning the currently shown thread dismisses the single banner without resurrecting older ones. + const pruneCurrent = tracker.prune((target) => target.threadId === a.threadId); + expect(pruneCurrent).toEqual({ count: 1, dismissBanner: true, changed: true }); + expect(tracker.current()).toBeNull(); + + // Clearing resets both banner target and badge count. + expect(tracker.clear()).toBe(true); + expect(tracker.count()).toBe(0); + expect(tracker.clear()).toBe(false); + }); +}); +``` + +2. Extend `apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts` by adding a Windows `desktopBridge` / `navigator.platform` helper option to `setup()` and adding two focused browser integration tests covering the Windows Electron bridge path and the Windows standalone browser fallback: + +```ts +it("uses a single Windows desktop notification with Open thread action, clears on focus, and keeps foreground toasts", async () => { + await using app = setup({ platform: "win32", desktopNotifications: true }); + app.start(); + + // Completion and input alerts both route to desktopBridge with localized "Open thread" label. + state.shells.set( + "one", + shell({ + id: "t-1", + title: "First", + latestTurn: { turnId: "r-1", state: "completed", completedAt: "2026-09-13T07:00:05.000Z" }, + }), + ); + await vi.waitFor(() => expect(app.desktop.showThreadNotification).toHaveBeenCalledTimes(1)); + expect(TestNotification.sent).toHaveLength(0); + expect(app.desktop.showThreadNotification).toHaveBeenLastCalledWith({ + environmentId: "one", + threadId: "t-1", + title: "Thread completed", + body: "First", + actionLabel: "Open thread", + }); + expect(state.badge).toHaveBeenLastCalledWith(1); + + // Second alert replaces the single latest notification while badge tracks distinct unread threads. + state.shells.set("two", shell({ id: "t-2", title: "Second", hasPendingApprovals: true })); + await vi.waitFor(() => expect(app.desktop.showThreadNotification).toHaveBeenCalledTimes(2)); + expect(app.desktop.showThreadNotification).toHaveBeenLastCalledWith({ + environmentId: "two", + threadId: "t-2", + title: "Approval needed", + body: "Second", + actionLabel: "Open thread", + }); + expect(state.badge).toHaveBeenLastCalledWith(2); + + // Clicking the banner / "Open thread" button activates the latest thread and clears badge. + app.desktop.emitActivate({ + environmentId: EnvironmentId.make("two"), + threadId: ThreadId.make("t-2"), + }); + expect(state.navigate).toHaveBeenCalledWith({ + to: "/$environmentId/$threadId", + params: { environmentId: "two", threadId: "t-2" }, + }); + expect(state.badge).toHaveBeenLastCalledWith(0); + + // Bringing T3 to foreground clears notification and badge without navigating. + state.navigate.mockClear(); + app.desktop.dismissThreadNotification.mockClear(); + state.shells.set("one", shell({ id: "t-1", title: "First", hasPendingUserInput: true })); + await vi.waitFor(() => expect(state.badge).toHaveBeenLastCalledWith(1)); + window.dispatchEvent(new Event("focus")); + expect(app.desktop.dismissThreadNotification).toHaveBeenCalled(); + expect(state.badge).toHaveBeenLastCalledWith(0); + expect(state.navigate).not.toHaveBeenCalled(); + + // Removing the environment of the active alert dismisses the banner. + app.desktop.dismissThreadNotification.mockClear(); + state.shells.set("two", shell({ id: "t-2", title: "Second", hasPendingUserInput: true })); + await vi.waitFor(() => expect(state.badge).toHaveBeenLastCalledWith(1)); + app.setEnvironmentIds(["one"]); + expect(app.desktop.dismissThreadNotification).toHaveBeenCalled(); + expect(state.badge).toHaveBeenLastCalledWith(0); + + // Foreground in-app popup behavior remains unchanged when T3 is focused. + focused = true; + state.inApp = true; + app.desktop.showThreadNotification.mockClear(); + state.shells.set("one", shell({ id: "t-3", title: "Foreground", hasPendingApprovals: true })); + expect(state.toast).toHaveBeenCalledTimes(1); + expect(app.desktop.showThreadNotification).not.toHaveBeenCalled(); +}); + +it("uses a single shared Web Notification without requireInteraction in Windows browsers and clears on close or visibility", async () => { + await using app = setup({ platform: "Win32", desktopNotifications: false }); + app.start(); + + state.shells.set( + "one", + shell({ + id: "t-1", + title: "First", + latestTurn: { turnId: "r-1", state: "completed", completedAt: "2026-09-13T07:00:05.000Z" }, + }), + ); + expect(TestNotification.sent).toHaveLength(1); + const first = TestNotification.sent[0]!; + expect(first.options).toMatchObject({ + body: "First", + tag: "t3-thread-alert", + silent: true, + requireInteraction: false, + }); + + state.shells.set("two", shell({ id: "t-2", title: "Second", hasPendingApprovals: true })); + expect(TestNotification.sent).toHaveLength(2); + const second = TestNotification.sent[1]!; + expect(first.close).toHaveBeenCalledTimes(1); + expect(second.options.tag).toBe("t3-thread-alert"); + expect(state.badge).toHaveBeenLastCalledWith(2); + + // Closing via X dismisses without navigating. + second.dispatchEvent(new Event("close")); + expect(state.navigate).not.toHaveBeenCalled(); + + // Clicking the latest banner closes, clears badge, focuses, and opens the thread. + state.shells.set("one", shell({ id: "t-3", title: "Third", hasPendingUserInput: true })); + const third = TestNotification.sent[2]!; + third.dispatchEvent(new Event("click")); + expect(third.close).toHaveBeenCalledTimes(1); + expect(state.badge).toHaveBeenLastCalledWith(0); + expect(state.navigate).toHaveBeenCalledWith({ + to: "/$environmentId/$threadId", + params: { environmentId: "one", threadId: "t-3" }, + }); + + // Returning to a visible focused tab clears the active banner without navigating. + state.navigate.mockClear(); + state.shells.set("two", shell({ id: "t-4", title: "Fourth", hasPendingApprovals: true })); + const fourth = TestNotification.sent[3]!; + focused = true; + visibility = "visible"; + document.dispatchEvent(new Event("visibilitychange")); + expect(fourth.close).toHaveBeenCalledTimes(1); + expect(state.badge).toHaveBeenLastCalledWith(0); + expect(state.navigate).not.toHaveBeenCalled(); +}); +``` + +- [ ] **Step 2: Run the tests and verify the intended failure** + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +``` + +Expected: FAIL because `buildDesktopThreadNotification`, `createWindowsThreadNotificationTracker`, and Windows Electron/browser single-notification routing are not yet implemented. + +- [ ] **Step 3: Add the minimal production implementation** + +1. In `apps/web/src/threadNotifications.ts`, import `isWindowsPlatform` from `./lib/utils` and export: + +```ts +// Windows drops toast notifications with tags longer than 16 characters. +export const WINDOWS_THREAD_NOTIFICATION_TAG = "t3-thread-alert"; + +export function isWindowsNotificationClient(platform?: string): boolean { + const resolved = + platform ?? + window.desktopBridge?.getClientPlatform() ?? + (typeof navigator !== "undefined" ? navigator.platform : ""); + return isWindowsPlatform(resolved); +} +``` + +2. In `apps/web/src/components/ThreadNotificationCoordinator.logic.ts`, import `threadKey` from `@t3tools/client-runtime/state/entities` and `type DesktopThreadNotification, type DesktopThreadNotificationActivation` from `@t3tools/contracts`, then add: + +```ts +const MAX_NOTIFICATION_TITLE_LENGTH = 256; +const MAX_NOTIFICATION_BODY_LENGTH = 512; +const MAX_NOTIFICATION_ACTION_LABEL_LENGTH = 64; + +export function buildDesktopThreadNotification( + input: DesktopThreadNotification, +): DesktopThreadNotification { + return { + environmentId: input.environmentId, + threadId: input.threadId, + title: input.title.trim().slice(0, MAX_NOTIFICATION_TITLE_LENGTH), + body: input.body.slice(0, MAX_NOTIFICATION_BODY_LENGTH), + actionLabel: input.actionLabel.trim().slice(0, MAX_NOTIFICATION_ACTION_LABEL_LENGTH), + }; +} + +export function createWindowsThreadNotificationTracker() { + let activeTarget: DesktopThreadNotificationActivation | null = null; + const unread = new Map(); + + const sameTarget = ( + left: DesktopThreadNotificationActivation | null, + right: DesktopThreadNotificationActivation, + ) => + left !== null && left.environmentId === right.environmentId && left.threadId === right.threadId; + + return { + record( + target: DesktopThreadNotificationActivation, + options?: { readonly updateBanner?: boolean }, + ): number { + unread.set(threadKey(target), target); + if (options?.updateBanner !== false) { + activeTarget = target; + } + return unread.size; + }, + current(): DesktopThreadNotificationActivation | null { + return activeTarget; + }, + count(): number { + return unread.size; + }, + dismissBannerIfCurrent(target: DesktopThreadNotificationActivation): boolean { + if (!sameTarget(activeTarget, target)) return false; + activeTarget = null; + return true; + }, + prune(shouldRemove: (target: DesktopThreadNotificationActivation) => boolean): { + readonly count: number; + readonly dismissBanner: boolean; + readonly changed: boolean; + } { + const previousCount = unread.size; + for (const [key, target] of unread) { + if (shouldRemove(target)) unread.delete(key); + } + const dismissBanner = activeTarget !== null && shouldRemove(activeTarget); + if (dismissBanner) activeTarget = null; + return { + count: unread.size, + dismissBanner, + changed: dismissBanner || unread.size !== previousCount, + }; + }, + clear(): boolean { + const hadState = activeTarget !== null || unread.size > 0; + activeTarget = null; + unread.clear(); + return hadState; + }, + }; +} +``` + +3. In `apps/web/src/components/ThreadNotificationCoordinator.tsx`: + - Keep foreground in-app toasts (lines 164–204) and foreground OS suppression (`document.visibilityState === "visible" && document.hasFocus()`) completely unchanged. + - Replace `isWindowsPlatform` import with `isWindowsNotificationClient` and `WINDOWS_THREAD_NOTIFICATION_TAG` from `../threadNotifications`, and import `buildDesktopThreadNotification`, `createWindowsThreadNotificationTracker` from `./ThreadNotificationCoordinator.logic` and `type DesktopThreadNotificationActivation` from `@t3tools/contracts`. + - Maintain single-Windows-notification state beside `pending`: + +```ts +const windowsTracker = createWindowsThreadNotificationTracker(); +let activeWindowsWebNotification: { + readonly notification: Notification; + readonly target: DesktopThreadNotificationActivation; +} | null = null; +let windowsShowGeneration = 0; +let windowsClearGeneration = 0; + +const syncBadge = () => { + setNotificationBadge(pending.size + windowsTracker.count()); +}; + +const dismissWindowsDesktopBanner = () => { + if (!isWindowsNotificationClient()) return; + void window.desktopBridge?.dismissThreadNotification?.().catch(() => undefined); +}; + +const closeWindowsWebBanner = () => { + if (activeWindowsWebNotification === null) return; + const current = activeWindowsWebNotification; + activeWindowsWebNotification = null; + current.notification.close(); +}; + +const pruneWindowsPending = (shouldRemove: (key: string) => boolean) => { + const result = windowsTracker.prune((target) => shouldRemove(threadKey(target))); + if (result.dismissBanner) { + closeWindowsWebBanner(); + dismissWindowsDesktopBanner(); + } + if (result.changed) syncBadge(); +}; + +const clearPending = () => { + for (const { notification } of pending.values()) notification.close(); + pending.clear(); + windowsShowGeneration += 1; + windowsClearGeneration += 1; + closeWindowsWebBanner(); + windowsTracker.clear(); + dismissWindowsDesktopBanner(); + setNotificationBadge(0); +}; +``` + +- In `closeHiddenPending` and `pruneRemovedEnvironments`, call `pruneWindowsPending(shouldClose)` and `pruneWindowsPending((key) => !activeIds.has(parseThreadKey(key).environmentId))`, respectively, and use `syncBadge()` instead of `setNotificationBadge(pending.size)`. +- In `present()`, replace lines 212–232 with: + +```ts +const target: DesktopThreadNotificationActivation = { + environmentId, + threadId: thread.id, +}; +const isWindows = isWindowsNotificationClient(); +const showDesktopNotification = isWindows + ? window.desktopBridge?.showThreadNotification + : undefined; +if (showDesktopNotification) { + const payload = buildDesktopThreadNotification({ + ...target, + title, + body: thread.title, + actionLabel: m(msg("Open thread")), + }); + const showGeneration = ++windowsShowGeneration; + const clearGeneration = windowsClearGeneration; + void showDesktopNotification(payload) + .then((result) => { + if (result === "suppressed") { + clearPending(); + return; + } + if (result !== "shown" || clearGeneration !== windowsClearGeneration) return; + const key = threadKey(target); + const hidden = registry.get(environmentThreadShells.hiddenThreadKeysAtom); + const activeEnvironments = new Set(registry.get(environmentSummaries.environmentIdsAtom)); + if (hidden.has(key) || !activeEnvironments.has(environmentId)) { + if (showGeneration === windowsShowGeneration) dismissWindowsDesktopBanner(); + return; + } + windowsTracker.record(target, { updateBanner: showGeneration === windowsShowGeneration }); + syncBadge(); + }) + .catch(() => undefined); + return; +} +try { + if (isWindows) { + closeWindowsWebBanner(); + const notification = new Notification(title, { + body: thread.title, + tag: WINDOWS_THREAD_NOTIFICATION_TAG, + silent: true, + requireInteraction: false, + }); + activeWindowsWebNotification = { notification, target }; + windowsTracker.record(target); + syncBadge(); + notification.addEventListener("click", () => { + clearPending(); + window.focus(); + void window.desktopBridge?.revealWindow().catch(() => undefined); + void router.navigate({ + to: "/$environmentId/$threadId", + params: target, + }); + }); + notification.addEventListener("close", () => { + if (activeWindowsWebNotification?.notification === notification) { + activeWindowsWebNotification = null; + windowsTracker.dismissBannerIfCurrent(target); + } + }); + return; + } + const notification = new Notification(title, { + body: thread.title, + tag: threadNotificationTag(environmentId, thread.id), + silent: true, + requireInteraction: false, + }); + trackNotification(environmentId, thread.id, notification); + notification.addEventListener("click", () => { + notification.close(); + window.focus(); + void window.desktopBridge?.revealWindow().catch(() => undefined); + void router.navigate({ + to: "/$environmentId/$threadId", + params: target, + }); + }); +} catch { + // Some browsers expose Notification but reject desktop presentation. +} +``` + +- In `applyMode()` when `hasDesktopNotifications(nextMode)`, add `visibilitychange` and `onThreadNotificationActivate`: + +```ts +if (hasDesktopNotifications(nextMode)) { + const onVisibilityChange = () => { + if (document.visibilityState === "visible" && document.hasFocus()) { + clearPending(); + } + }; + const unsubscribeBadgeClear = window.desktopBridge?.onNotificationBadgeClear(clearPending); + const unsubscribeActivate = window.desktopBridge?.onThreadNotificationActivate?.((target) => { + clearPending(); + void router.navigate({ + to: "/$environmentId/$threadId", + params: target, + }); + }); + window.addEventListener("focus", clearPending); + document.addEventListener("visibilitychange", onVisibilityChange); + stops.push(() => { + unsubscribeBadgeClear?.(); + unsubscribeActivate?.(); + window.removeEventListener("focus", clearPending); + document.removeEventListener("visibilitychange", onVisibilityChange); + clearPending(); + }); +} +``` + +- [ ] **Step 4: Run the focused tests** + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts apps/web/src/threadNotifications.test.ts +``` + +Expected: PASS (all unit and browser tests pass). + +- [ ] **Step 5: Refactor while green** + +Audit `ThreadNotificationCoordinator.tsx` for cleanliness, ensure no unnecessary re-renders or React hook issues (it is a plain TS module, not a component), verify all comments follow `t3code/no-low-value-comments`, and re-run focused tests if refactored. + +- [ ] **Step 6: Run impacted-test verification** + +Impacted surfaces: all notification tests across `packages/contracts`, `apps/desktop`, and `apps/web`, preload bundle check, `vp run i18n:check`, and `vp run check:changed` against `f0a2aa10f5165413e863db9f1502dc4bb6fa42e8`. + +Run: + +```bash +export PATH="/usr/local/bin:$PWD/node_modules/.bin:$PATH" +vp test run packages/contracts/src/ipc.test.ts apps/desktop/src/ipc/methods/threadNotification.test.ts apps/desktop/src/ipc/methods/notificationBadge.test.ts apps/web/src/threadNotifications.test.ts apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts && vp run --filter @t3tools/desktop build && node apps/desktop/scripts/verify-preload-bundle.mjs && vp run i18n:check && vp run check:changed f0a2aa10f5165413e863db9f1502dc4bb6fa42e8 +``` + +Expected: PASS (every check, typecheck, lint, format, knip, i18n, preload check, and test exits 0). + +- [ ] **Step 7: Commit the task** + +```bash +git add apps/web/src/threadNotifications.ts apps/web/src/components/ThreadNotificationCoordinator.logic.ts apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts apps/web/src/components/ThreadNotificationCoordinator.tsx apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +git commit -m "feat(web): use single Windows background thread notification" +``` From 0bec2c59206f841d00ae850b1031af1056c34cc3 Mon Sep 17 00:00:00 2001 From: Dan Shapiro <3732858+danshapiro@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:16:19 -0800 Subject: [PATCH 02/28] docs: update plan from load-bearing validation --- .../2026-11-26-windows-single-notification.md | 1223 ++--------------- 1 file changed, 145 insertions(+), 1078 deletions(-) diff --git a/docs/plans/2026-11-26-windows-single-notification.md b/docs/plans/2026-11-26-windows-single-notification.md index 7e97e9e8a895a..b826153057ab3 100644 --- a/docs/plans/2026-11-26-windows-single-notification.md +++ b/docs/plans/2026-11-26-windows-single-notification.md @@ -20,11 +20,11 @@ Implement single-notification Windows background banner behavior in T3 Code: whi - Earlier background Windows alerts are replaced when a newer alert arrives; the sidebar remains where all threads needing attention are viewed. -**Goal:** When T3 Code is unfocused on Windows, display at most one background Windows notification for the latest thread alert with an `"Open thread"` action button, replacing prior banners on each new alert, opening that thread and clearing the banner on body or button click, clearing without changing threads on foreground focus, and dismissing without navigating when closed via `×`. +**Goal:** When T3 Code is unfocused on Windows, display at most one background Windows notification for the latest thread alert with an `"Open thread"` action button, replacing prior banners on each new alert, opening that thread and bringing T3 to the foreground on body or button click, clearing without changing threads on foreground focus, and dismissing without navigating when closed via `×`. -**Architecture:** Add a minimal, schema-validated `DesktopBridge` IPC contract (`showThreadNotification`, `dismissThreadNotification`, `onThreadNotificationActivate`) implemented by a scoped Electron main-process installer (`apps/desktop/src/ipc/methods/threadNotification.ts`) using `Electron.Notification` on `win32` with a fixed short Windows tag (`"t3-thread-alert"`), `"Open thread"` action button (localized label supplied by `apps/web`'s existing `m(msg("Open thread"))` translation), `silent: true`, and lifecycle hooks for focus, quit, and disposal. In `apps/web`, route Windows desktop background alerts through this bridge while preserving unread alerted thread counts for the taskbar badge, fall back to a single-tag Web `Notification` without `requireInteraction` for standalone Windows browsers, and leave foreground in-app toasts plus macOS and Linux background notification behavior unchanged. +**Architecture:** Add a minimal, schema-validated `DesktopBridge` IPC contract (`showThreadNotification`, `dismissThreadNotification`, `onThreadNotificationActivate`) implemented by a scoped Electron main-process installer (`apps/desktop/src/ipc/methods/threadNotification.ts`) on `win32`. To work reliably with Electron `44.10.1`'s WinRT/COM notification stack (validated in Stage 2: `/home/dan/code/t3code/.worktrees/.the-usual-logs/windows-single-notification/load-bearing-ledger.md`), the installer sets a deterministic `app.setToastActivatorCLSID(...)` per AUMID, warms `Electron.Notification.isSupported()` at install, assigns each alert a short unique `id` (`t3a-`, <= 16 chars) while closing the previous instance to maintain a single notification without Electron's reused-`id` pointer-shadowing bug, renders custom XML-escaped `toastXml` (``, `