Skip to content

Commit e95355d

Browse files
donjor-agent[bot]rsi-pr-agent
authored andcommitted
feat(desktop): window requests target the sender or the most recent window
## What Changed Every "main" window lookup in main now resolves by one rule. | Request | Target | | --- | --- | | From a renderer (IPC) | The sender window | | App-wide (menu, dock, `t3 app`, capture) | Most recently focused app window | Only windows that main registered can be targets, so the splash, DevTools, and popups never are. The upstream fallback runs only while no window is registered yet. | File | Change | | --- | --- | | `WindowTargets.fork.ts` (new) | `IpcRequester` reference; `DesktopIpc` provides the sender around every invoke and sync handler | | `WindowRegistry.fork.ts` | Focus recency per `WindowId`, dropped on close; `requestTarget` is the sender if registered, else the most recent window; `windowsByRecency` lists windows newest first | | `ElectronWindow.ts` | `main`, `currentMainOrFirst`, `focusedMainOrFirst` return `requestTarget` first | | `DesktopWindow.ts` | `activate` and `prepareCaptureReveal` use the capture's pinned window while a capture is acquiring, else the target; hub creation stays hub-only | | `SnapShotTarget.fork.ts` (new) | A capture pins its window on `requested`; later events, the reveal, the post-capture activation, and the Linux destination window follow the pin. The pin is released on `ready`, `failed`, or when the capture fiber ends, interruption included | | `DesktopAppActivationRenderers.fork.ts` (new) | Readiness per sender window; a request walks the ready windows in focus-recency order; an unregistered sender is ignored and never clears readiness; losing a window fails only the request it was handling | ### Audit | Consumer | Resolves to | | --- | --- | | `ElectronWindow.main`, `currentMainOrFirst`, `focusedMainOrFirst` | Sender, else most recent (hooked once here) | | `getWindowFullscreenState` (sync IPC) | Sender | | `pickFolder`, `pickProjectFavicon`, `pickThemeFiles` owner | Sender | | `showContextMenu` | Sender | | `pasteAsText` main check | Sender: project windows can now paste as text | | `ensureTrustedSnapShotSender` | Sender; the registered-window fallback is now redundant but kept | | `DesktopSshPasswordPrompts.request` | Requester inside IPC, else most recent | | `DesktopAppActivation.setRendererReady` | Per registered sender; an unregistered sender is ignored | | `DesktopWindow.activate` (dock, `t3 app`) | Most recent | | `DesktopWindow.activate` (post-capture) | Window pinned at `requested` | | `prepareCaptureReveal` | Window pinned at `requested` | | `dispatchMenuAction`, `zoomMain` | Most recent | | `dispatchSnapShotEvent` | Window pinned at `requested` | | `DesktopSnapShot` `destinationWindow` | Window pinned at `requested` | | `openSystemSettings`, snapshot permission and setup owners | Kept: on macOS the focused window is the sender | | `notificationBadge` | Kept: app-wide badge | | `sendAll`, `destroyAll`, `syncAllAppearance` | Kept: broadcast | | Preview `setMainWindow` owner | Kept: `"app"` owner from #1341 | | `mainWindowBounds`, `flushMainWindowBounds` | Kept: hub bounds, #1345 | | `ensureMain`, `createMain`, `revealOrCreateMain`, `createMainIfBackendReady`, `showConnectingSplash` | Kept: hub creation, #1343 | ## Why Upstream binds IPC answers, dialogs, captures, and activation to the single hub window. | Flow | Before, with project windows | | --- | --- | | Dialog from a project window | Parented to the hub | | Fullscreen state | Read from the hub | | One window's cleanup | Cleared `t3 app` activation for all | Closes #1342 ### Close conditions - [x] Audit: every `main`-style consumer resolved - [x] Fullscreen: targets the sender - [x] Async: dialog, capture return to requester - [x] Activation: readiness is per sender - [x] Close one: others keep activation - [x] Exclusions: no splash, DevTools, or popup | Condition | Evidence in `apps/desktop/src/electron/WindowTargets.fork.test.ts` | | --- | --- | | Audit | Audit table above; "an IPC request resolves every main-style lookup to the sending window" | | Fullscreen | "fullscreen state is read from the sender, not the hub", through `DesktopIpc.handleSync` | | Async | "a dialog opened from a window is owned by that window while another has focus"; "every event of one capture reaches the window its request pinned"; "the capture reveals and activates the window it pinned"; "an interrupted capture releases its pinned window" | | Activation | "a request goes to the most recently focused ready window"; "with the focused window not ready, a request walks focus recency"; "a renderer main did not register cannot clear the app windows" | | Close one | "closing one ready window leaves the others activated"; "losing the window handling a request fails only that request" | | Exclusions | "an app-wide request resolves to the most recently focused app window only": a focused unregistered window and an unregistered sender both resolve to the last app window | ### Live checks (host, not run here) | Check | Steps and expectation | | --- | --- | | Fullscreen | Fullscreen a project window and reload it; its chrome reads fullscreen and the hub's does not | | Dialog | Focus the hub, then pick a folder from a project window; the sheet parents to the project window | | Capture | Snap shot with a project window last focused; the animation and result land there | | Activation | Open the hub and a project, close the project, run `t3 app`; the request still completes | | Exclusions | Focus detached DevTools, then use a menu action; it reaches the last app window | ### Swap proof Temporary reverts at `f38334a280`, not committed: | Reverted | `WindowTargets.fork.test.ts` | | --- | --- | | `ElectronWindow.ts` and `DesktopIpc.ts` hooks | 6 of 8 fail | | `setRendererReady` hook | 3 of 8 fail (every activation case) | ### Checks ```text vp test run <12 desktop files> → exit 0 (12 files, 156 tests) vp run fork:ci → exit 0 (scripts: 59 files, 648 tests) vpr typecheck → exit 0 vp run knip:check → exit 0 ``` **Note:** `activate` now reveals the most recent window, not the hub, which also affects the dock behaviour in #1343. ## UI Changes None: this changes which window main targets and adds no UI. ## Checklist - [x] Small and focused - [x] Explains what and why - [x] Screenshots: n/a, no UI change - [x] Video: n/a, no motion Model and harness: Claude Opus 5.5, Claude Code in T3 Code. ## Fork trailers Squashes: - c3c9d16 feat(desktop): window requests target the sender or the most recent window - 14073c5 fixup! feat(desktop): window requests target the sender or the most recent window - c74e5dc feat(desktop): window requests target the sender or the most recent window - faa53bd refactor(multi-window): createWindow seams become marked insertions (#1811) (#1811) Fork-Domain: multi-window Fork-Tier: core
1 parent 2e5c1a7 commit e95355d

14 files changed

Lines changed: 736 additions & 11 deletions

‎apps/desktop/src/app/DesktopAppActivation.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
2727
import { DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL } from "../ipc/channels.ts";
2828
import * as DesktopWindow from "../window/DesktopWindow.ts";
2929
import { DesktopAppActivationBroker } from "./DesktopAppActivationBroker.ts";
30+
import { makeActivationRenderers } from "./DesktopAppActivationRenderers.fork.ts"; // fork-hook: multi-window/window-targets-activation-import
3031
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
3132
import { makeComponentLogger } from "./DesktopObservability.ts";
3233

@@ -320,6 +321,7 @@ export const make = Effect.gen(function* () {
320321
},
321322
});
322323

324+
const forkRenderers = makeActivationRenderers({ broker, electronWindow }); // fork-hook: multi-window/window-targets-activation
323325
const clearRegisteredRenderer = () => {
324326
detachRendererListeners?.();
325327
detachRendererListeners = null;
@@ -352,6 +354,7 @@ export const make = Effect.gen(function* () {
352354
),
353355
).pipe(Effect.asVoid),
354356
setRendererReady: Effect.fn("DesktopAppActivation.setRendererReady")(function* (ready) {
357+
if (yield* forkRenderers.setReady(ready)) return; // fork-hook: multi-window/window-targets-activation-ready
355358
if (!ready) {
356359
clearRegisteredRenderer();
357360
return;
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import type { DesktopAppActivationRequest } from "@t3tools/contracts";
2+
import * as Effect from "effect/Effect";
3+
import * as Option from "effect/Option";
4+
import type * as Electron from "electron";
5+
6+
import type * as ElectronWindow from "../electron/ElectronWindow.ts";
7+
import { IpcRequester } from "../electron/WindowTargets.fork.ts";
8+
import { DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL } from "../ipc/channels.ts";
9+
import type { DesktopAppActivationBroker } from "./DesktopAppActivationBroker.ts";
10+
11+
interface ReadyRenderer {
12+
readonly webContents: Electron.WebContents;
13+
readonly detach: () => void;
14+
}
15+
16+
/**
17+
* Tracks activation readiness per app window, so closing one never clears the
18+
* others. Requests go to the most recently focused ready window, one at a time;
19+
* losing a window fails only the request it was handling.
20+
*/
21+
export function makeActivationRenderers(input: {
22+
readonly broker: DesktopAppActivationBroker;
23+
readonly electronWindow: ElectronWindow.ElectronWindow["Service"];
24+
}) {
25+
const ready = new Map<number, ReadyRenderer>();
26+
let inFlight: number | null = null;
27+
28+
const pick = (): ReadyRenderer | undefined => {
29+
for (const window of Effect.runSync(input.electronWindow.windowsByRecency)) {
30+
const renderer = ready.get(window.webContents.id);
31+
if (renderer !== undefined) return renderer;
32+
}
33+
// A ready window main has since unregistered, such as one whose close was vetoed.
34+
return ready.values().next().value;
35+
};
36+
37+
const send = (request: DesktopAppActivationRequest) => {
38+
const renderer = pick();
39+
if (renderer === undefined) throw new Error("No ready desktop renderer.");
40+
inFlight = renderer.webContents.id;
41+
renderer.webContents.send(DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL, request);
42+
};
43+
44+
const remove = (id: number) => {
45+
const renderer = ready.get(id);
46+
if (renderer === undefined) return;
47+
renderer.detach();
48+
ready.delete(id);
49+
// A broker clear fails whatever request is dispatched. Only do that when
50+
// the window that went away was the one handling it, or none remain.
51+
if (inFlight !== id && ready.size > 0) return;
52+
inFlight = null;
53+
input.broker.clearRenderer();
54+
if (ready.size > 0) input.broker.registerRenderer(send);
55+
};
56+
57+
const add = (webContents: Electron.WebContents) => {
58+
const id = webContents.id;
59+
if (!ready.has(id)) {
60+
const onUnavailable = () => remove(id);
61+
const onNavigation = (
62+
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
63+
) => {
64+
if (event.isMainFrame && !event.isSameDocument) remove(id);
65+
};
66+
webContents.on("did-start-navigation", onNavigation);
67+
webContents.once("destroyed", onUnavailable);
68+
ready.set(id, {
69+
webContents,
70+
detach: () => {
71+
webContents.removeListener("did-start-navigation", onNavigation);
72+
webContents.removeListener("destroyed", onUnavailable);
73+
},
74+
});
75+
}
76+
input.broker.registerRenderer(send);
77+
};
78+
79+
return {
80+
/**
81+
* Records readiness for the requesting window. Returns false only when
82+
* there is no IPC requester, leaving the caller's single-renderer path in
83+
* charge; a renderer main did not register is ignored, so it can never
84+
* clear the app windows' readiness.
85+
*/
86+
setReady: Effect.fn("DesktopAppActivationRenderers.setReady")(function* (isReady: boolean) {
87+
const requester = yield* IpcRequester;
88+
if (Option.isNone(requester)) return false;
89+
const sender = yield* input.electronWindow.currentMainOrFirst;
90+
if (Option.isNone(sender)) return true;
91+
const webContents = sender.value.webContents;
92+
if (webContents.id !== requester.value) return true;
93+
if (!isReady) remove(webContents.id);
94+
else if (!webContents.isDestroyed()) add(webContents);
95+
return true;
96+
}),
97+
};
98+
}

‎apps/desktop/src/app/DesktopLifecycle.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ function layerElectronWindow(destroyAll: Effect.Effect<void> = Effect.void) {
7373
close: () => Effect.void,
7474
windowIdFor: () => Effect.succeed(Option.none()), // fork-hook: multi-window/window-id-for
7575
listWindows: Effect.succeed([]), // fork-hook: multi-window/window-id-list
76+
windowsByRecency: Effect.succeed([]), // fork-hook: multi-window/window-targets-by-recency
7677
currentMainOrFirst: Effect.die("unexpected current window read"),
7778
focusedMainOrFirst: Effect.die("unexpected focused window read"),
7879
setMain: () => Effect.void,

‎apps/desktop/src/electron/ElectronWindow.fork.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boo
4242
id: input.id,
4343
isDestroyed: vi.fn(() => input.destroyed),
4444
once: vi.fn((event: string, listener: () => void) => listeners.set(event, listener)),
45+
on: vi.fn((event: string, listener: () => void) => listeners.set(event, listener)),
4546
close: vi.fn(() => listeners.get("closed")?.()),
4647
__emit: (event: string) => listeners.get(event)?.(),
4748
} as unknown as Electron.BrowserWindow & {

‎apps/desktop/src/electron/ElectronWindow.ts‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import * as Semaphore from "effect/Semaphore"; // fork-hook: multi-window/regist
1515

1616
import * as Electron from "electron";
1717

18-
import { HUB_WINDOW_IDENTITY, type WindowIdentity } from "../window/WindowIdentity.ts"; // fork-hook: multi-window/window-identity-import
1918
import * as WindowRegistry from "./WindowRegistry.fork.ts"; // fork-hook: multi-window/window-registry-import
2019
import {
2120
activateWindowsForeground,
@@ -118,15 +117,13 @@ export class ElectronWindow extends Context.Service<
118117
behavior?: { readonly auxiliary?: boolean },
119118
) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
120119
readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
121-
readonly get: (
122-
identity: WindowIdentity,
123-
) => Effect.Effect<Option.Option<Electron.BrowserWindow>>;
120+
readonly get: WindowRegistry.WindowRegistryService["get"]; // fork-hook: multi-window/window-registry-get
124121
readonly getById: WindowRegistry.WindowRegistryService["getById"]; // fork-hook: multi-window/window-id-get-by-id
125122
readonly getOrCreate: WindowRegistry.WindowRegistryService["getOrCreate"]; // fork-hook: multi-window/window-id-get-or-create
126123
readonly close: (identity: WindowIdentity) => Effect.Effect<void>;
127124
readonly windowIdFor: WindowRegistry.WindowRegistryService["windowIdFor"]; // fork-hook: multi-window/window-id-for
128-
/** Every live registered window, in registration order. */
129125
readonly listWindows: WindowRegistry.WindowRegistryService["listWindows"]; // fork-hook: multi-window/window-id-list
126+
readonly windowsByRecency: WindowRegistry.WindowRegistryService["windowsByRecency"]; // fork-hook: multi-window/window-targets-by-recency
130127
readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
131128
readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
132129
readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
@@ -157,7 +154,12 @@ export const make = Effect.gen(function* () {
157154
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
158155
const auxiliaryWindows = new WeakSet<Electron.BrowserWindow>();
159156
const registry = WindowRegistry.makeWindowRegistry(); // fork-hook: multi-window/window-registry
160-
const registrySemaphore = yield* Semaphore.make(1);
157+
const registrySemaphore = yield* Semaphore.make(1); // fork-hook: multi-window/registry-semaphore
158+
const registryService = WindowRegistry.makeWindowRegistryService(
159+
registry,
160+
registrySemaphore,
161+
mainWindowRef,
162+
); // fork-hook: multi-window/window-targets-registry-service
161163

162164
const listWindows = Effect.try({
163165
try: () => Electron.BrowserWindow.getAllWindows(),
@@ -184,10 +186,9 @@ export const make = Effect.gen(function* () {
184186
}),
185187
}).pipe(Effect.orDie);
186188

187-
const getLiveWindow = (identity: WindowIdentity) => Effect.sync(() => registry.get(identity)); // fork-hook: multi-window/window-registry-get
188-
189189
const liveMain = Effect.gen(function* () {
190-
}
190+
const forkTarget = yield* registryService.requestTarget; // fork-hook: multi-window/window-targets-main
191+
if (Option.isSome(forkTarget)) return forkTarget; // fork-hook: multi-window/window-targets-main-return
191192
const main = yield* Ref.get(mainWindowRef);
192193
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
193194
return Option.none<Electron.BrowserWindow>();
@@ -211,6 +212,8 @@ export const make = Effect.gen(function* () {
211212
});
212213

213214
const focusedMainOrFirst = Effect.gen(function* () {
215+
const forkTarget = yield* registryService.requestTarget; // fork-hook: multi-window/window-targets-focused
216+
if (Option.isSome(forkTarget)) return forkTarget; // fork-hook: multi-window/window-targets-focused-return
214217
const focused = yield* Effect.try({
215218
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
216219
catch: (cause) =>
@@ -263,8 +266,7 @@ export const make = Effect.gen(function* () {
263266
});
264267
}),
265268
main: liveMain,
266-
get: getLiveWindow,
267-
...WindowRegistry.makeWindowRegistryService(registry, registrySemaphore, mainWindowRef), // fork-hook: multi-window/window-registry-service
269+
...registryService, // fork-hook: multi-window/window-registry-service
268270
currentMainOrFirst,
269271
focusedMainOrFirst,
270272
setMain: Effect.fn("ElectronWindow.setMain")(function (window) {

0 commit comments

Comments
 (0)