From 2669a8beb0adeaa80d2de238086610d906c242c4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 22 Oct 2026 11:56:54 +0000 Subject: [PATCH 01/14] test(desktop): reproduce #12689 topology polling blocking on sendSync These tests reproduce #12689: every topology poll calls the sendSync-backed bridge reads for bootstraps and local-environment enabled, so a busy main process freezes the renderer while typing. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preload.test.ts | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 apps/desktop/src/preload.test.ts diff --git a/apps/desktop/src/preload.test.ts b/apps/desktop/src/preload.test.ts new file mode 100644 index 000000000000..2c4bcbb91e0c --- /dev/null +++ b/apps/desktop/src/preload.test.ts @@ -0,0 +1,50 @@ +import type { DesktopBridge } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import * as IpcChannels from "./ipc/channels.ts"; + +const { exposed, sendSync } = vi.hoisted(() => ({ + exposed: new Map(), + sendSync: vi.fn((channel: string): unknown => + channel === "desktop:get-local-environment-enabled" ? true : [], + ), +})); + +vi.mock("electron", () => ({ + contextBridge: { + exposeInMainWorld: (key: string, api: unknown) => exposed.set(key, api), + }, + ipcRenderer: { + sendSync, + invoke: vi.fn(async (channel: string) => + channel === IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL ? true : [], + ), + on: vi.fn(), + removeListener: vi.fn(), + }, + webFrame: { getZoomFactor: () => 1 }, + webUtils: { getPathForFile: () => "" }, +})); +vi.mock("@clerk/electron/preload", () => ({ exposeClerkBridge: vi.fn() })); + +it("polling topology reads do not block the renderer on synchronous IPC each time", async () => { + vi.stubGlobal("window", { localStorage: { getItem: () => null, setItem: () => {} } }); + await import("./preload.ts"); + const bridge = exposed.get("desktopBridge") as DesktopBridge; + sendSync.mockClear(); + + // The renderer's platform poll reads these every few seconds; ipcRenderer.sendSync + // freezes the renderer for as long as the main process takes to answer. + for (let poll = 0; poll < 5; poll += 1) { + bridge.getLocalEnvironmentBootstraps(); + bridge.getLocalEnvironmentEnabled?.(); + } + + const syncCalls = (channel: string) => + sendSync.mock.calls.filter(([called]) => called === channel).length; + // Each read may block once at startup; later polls must not. + expect + .soft(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)) + .toBeLessThanOrEqual(1); + expect.soft(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL)).toBeLessThanOrEqual(1); +}); From 0427a89a55ffeeb4bf5e2620d75bd23c13a351a3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 22 Oct 2026 12:03:36 +0000 Subject: [PATCH 02/14] fix(desktop): stop blocking the renderer during topology polling Every 3 s topology poll and every composer render called sendSync for the local-environment bootstraps and enabled flag, so a busy main process froze the renderer while typing (#12689). The preload now reads each value synchronously once for the first paint and caches it. The enabled flag only changes through a setter that relaunches the app, so the startup value stays correct. Bootstraps are refreshed by a new async bridge method over ipcRenderer.invoke on the same channel; the platform poll awaits it before reading the primary and secondary topology, so a WSL/secondary backend appearing, disappearing or changing still reaches the UI within one poll. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 2 + apps/desktop/src/ipc/methods/window.ts | 105 ++++++++++--------- apps/desktop/src/preload.test.ts | 22 ++++ apps/desktop/src/preload.ts | 30 ++++-- apps/web/src/connection/desktopLocal.test.ts | 30 ++++++ apps/web/src/connection/desktopLocal.ts | 64 ++++++----- apps/web/src/connection/platform.ts | 5 +- packages/contracts/src/ipc.ts | 2 + 8 files changed, 179 insertions(+), 81 deletions(-) diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 2d67aa56e6cc..ade54964ce09 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -40,6 +40,7 @@ import { import { getAppBranding, getLocalEnvironmentBootstraps, + getLocalEnvironmentBootstrapsAsync, getLocalEnvironmentBearerToken, getRelayTelemetryEnabled, getSystemLocale, @@ -100,6 +101,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handleSync(getSystemLocale); yield* ipc.handleSync(getWindowFullscreenState); yield* ipc.handleSync(getLocalEnvironmentBootstraps); + yield* ipc.handle(getLocalEnvironmentBootstrapsAsync); yield* ipc.handleSync(getLocalEnvironmentEnabled); yield* ipc.handle(setLocalEnvironmentEnabled); yield* ipc.handle(getLocalEnvironmentBearerToken); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 9066cf6f1a67..59c6acd0d2cb 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -99,57 +99,68 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({ }), }); -export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({ - channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL, - result: Schema.Array(DesktopEnvironmentBootstrapSchema), - handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () { - const pool = yield* DesktopBackendPool.DesktopBackendPool; - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const instances = yield* pool.list; - const bootstraps: DesktopEnvironmentBootstrap[] = []; - for (const instance of instances) { - const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID; - const config = yield* instance.currentConfig; - const snapshot = yield* instance.snapshot; - if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) { - const fatalPreflight = - Option.isSome(config) && - Option.isSome(config.value.preflightFailure) && - config.value.preflightFailure.value.fatal; - const stoppedPreflight = - Option.isSome(config) && - Option.isSome(config.value.preflightFailure) && - (!snapshot.desiredRunning || !snapshot.restartScheduled); - if (isPrimary || fatalPreflight || stoppedPreflight) continue; - bootstraps.push({ - id: instance.id, - label: yield* instance.label, - runningDistro: null, - httpBaseUrl: null, - wsBaseUrl: null, - }); - continue; - } - const { bootstrap, httpBaseUrl } = config.value; - const runningDistro = config.value.runningDistro ?? null; +const readLocalEnvironmentBootstrapSnapshot = Effect.fn( + "desktop.ipc.window.getLocalEnvironmentBootstraps", +)(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const instances = yield* pool.list; + const bootstraps: DesktopEnvironmentBootstrap[] = []; + for (const instance of instances) { + const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID; + const config = yield* instance.currentConfig; + const snapshot = yield* instance.snapshot; + if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) { + const fatalPreflight = + Option.isSome(config) && + Option.isSome(config.value.preflightFailure) && + config.value.preflightFailure.value.fatal; + const stoppedPreflight = + Option.isSome(config) && + Option.isSome(config.value.preflightFailure) && + (!snapshot.desiredRunning || !snapshot.restartScheduled); + if (isPrimary || fatalPreflight || stoppedPreflight) continue; bootstraps.push({ id: instance.id, - label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`, - runningDistro, - httpBaseUrl: httpBaseUrl.href, - wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl), - // A backend launched with the desktop secret accepts whichever token the secret derives - // for the current window, so hand out that one rather than the token frozen into its - // launch config. - ...(bootstrap.desktopBootstrapSecret - ? { bootstrapToken: yield* configuration.currentBootstrapToken } - : bootstrap.desktopBootstrapToken - ? { bootstrapToken: bootstrap.desktopBootstrapToken } - : {}), + label: yield* instance.label, + runningDistro: null, + httpBaseUrl: null, + wsBaseUrl: null, }); + continue; } - return bootstraps; - }), + const { bootstrap, httpBaseUrl } = config.value; + const runningDistro = config.value.runningDistro ?? null; + bootstraps.push({ + id: instance.id, + label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`, + runningDistro, + httpBaseUrl: httpBaseUrl.href, + wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl), + // A backend launched with the desktop secret accepts whichever token the secret derives + // for the current window, so hand out that one rather than the token frozen into its + // launch config. + ...(bootstrap.desktopBootstrapSecret + ? { bootstrapToken: yield* configuration.currentBootstrapToken } + : bootstrap.desktopBootstrapToken + ? { bootstrapToken: bootstrap.desktopBootstrapToken } + : {}), + }); + } + return bootstraps; +}); + +export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL, + result: Schema.Array(DesktopEnvironmentBootstrapSchema), + handler: readLocalEnvironmentBootstrapSnapshot, +}); + +export const getLocalEnvironmentBootstrapsAsync = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL, + payload: Schema.Void, + result: Schema.Array(DesktopEnvironmentBootstrapSchema), + handler: readLocalEnvironmentBootstrapSnapshot, }); function extractWslDistroFromEnvironmentId(envId: string): string | null { diff --git a/apps/desktop/src/preload.test.ts b/apps/desktop/src/preload.test.ts index 2c4bcbb91e0c..87b7229f309a 100644 --- a/apps/desktop/src/preload.test.ts +++ b/apps/desktop/src/preload.test.ts @@ -1,4 +1,5 @@ import type { DesktopBridge } from "@t3tools/contracts"; +import { ipcRenderer } from "electron"; import { expect, it, vi } from "vite-plus/test"; import * as IpcChannels from "./ipc/channels.ts"; @@ -48,3 +49,24 @@ it("polling topology reads do not block the renderer on synchronous IPC each tim .toBeLessThanOrEqual(1); expect.soft(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL)).toBeLessThanOrEqual(1); }); + +it("an async topology refresh replaces the bootstraps later reads return", async () => { + vi.stubGlobal("window", { localStorage: { getItem: () => null, setItem: () => {} } }); + await import("./preload.ts"); + const bridge = exposed.get("desktopBridge") as DesktopBridge; + const wsl = { + id: "wsl:Ubuntu", + label: "WSL (Ubuntu)", + runningDistro: "Ubuntu", + httpBaseUrl: "http://127.0.0.1:4000/", + wsBaseUrl: "ws://127.0.0.1:4000/", + }; + vi.mocked(ipcRenderer.invoke).mockResolvedValueOnce([wsl]).mockResolvedValueOnce([]); + sendSync.mockClear(); + + await bridge.refreshLocalEnvironmentBootstraps?.(); + expect(bridge.getLocalEnvironmentBootstraps()).toEqual([wsl]); + await bridge.refreshLocalEnvironmentBootstraps?.(); + expect(bridge.getLocalEnvironmentBootstraps()).toEqual([]); + expect(sendSync).not.toHaveBeenCalled(); +}); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index bffa02d9ca43..2a2e0da346f6 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -74,6 +74,18 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) { return result as Awaited>; } +const readBootstraps = ( + result: unknown, +): ReturnType => + Array.isArray(result) ? result : []; +// sendSync blocks the renderer until the main process answers, so it runs once for the first +// paint; topology polling refreshes this cache over async IPC instead. +let localEnvironmentBootstraps: + | ReturnType + | undefined; +// Changes take effect on relaunch, so renderer reads can reuse the startup value. +let localEnvironmentEnabled: boolean | undefined; + contextBridge.exposeInMainWorld("desktopBridge", { getAppBranding: () => { const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL); @@ -103,17 +115,19 @@ contextBridge.exposeInMainWorld("desktopBridge", { const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL); return typeof result === "string" ? result : null; }, - getLocalEnvironmentBootstraps: () => { - const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL); - if (!Array.isArray(result)) { - return []; - } - return result as ReturnType; - }, + getLocalEnvironmentBootstraps: () => + (localEnvironmentBootstraps ??= readBootstraps( + ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL), + )), + refreshLocalEnvironmentBootstraps: async () => + (localEnvironmentBootstraps = readBootstraps( + await ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL), + )), getLocalEnvironmentBearerToken: () => ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL), getLocalEnvironmentEnabled: () => - ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false, + (localEnvironmentEnabled ??= + ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false), setLocalEnvironmentEnabled: (enabled) => ipcRenderer.invoke(IpcChannels.SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, enabled), getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL), diff --git a/apps/web/src/connection/desktopLocal.test.ts b/apps/web/src/connection/desktopLocal.test.ts index 2086e9185355..ac9ea3b8e6a0 100644 --- a/apps/web/src/connection/desktopLocal.test.ts +++ b/apps/web/src/connection/desktopLocal.test.ts @@ -4,6 +4,36 @@ import { describe, expect, it } from "vite-plus/test"; import { createDesktopSecondaryBootstrapsReader } from "./desktopLocal"; describe("desktop local topology reads", () => { + it("refreshes topology over the async bridge read, keeping the snapshot through failures", async () => { + const secondary: DesktopEnvironmentBootstrap = { + id: "wsl:Ubuntu", + label: "WSL (Ubuntu)", + runningDistro: "Ubuntu", + httpBaseUrl: "http://127.0.0.1:4000", + wsBaseUrl: "ws://127.0.0.1:4000", + }; + let cached: ReadonlyArray = []; + let refresh = async () => [{ ...secondary, id: PRIMARY_LOCAL_ENVIRONMENT_ID }, secondary]; + const reader = createDesktopSecondaryBootstrapsReader(() => ({ + getLocalEnvironmentBootstraps: () => cached, + refreshLocalEnvironmentBootstraps: async () => (cached = await refresh()), + })); + + expect(reader.readSnapshot()).toEqual([]); + const connected = await reader.refresh(); + expect(connected).toEqual({ _tag: "Success", bootstraps: [secondary] }); + expect(reader.readSnapshot()).toEqual([secondary]); + + const cause = new Error("IPC unavailable"); + refresh = () => Promise.reject(cause); + expect(await reader.refresh()).toEqual({ _tag: "Failure", cause }); + expect(reader.readSnapshot()).toEqual([secondary]); + + refresh = async () => []; + expect(await reader.refresh()).toEqual({ _tag: "Success", bootstraps: [] }); + expect(reader.readSnapshot()).toEqual([]); + }); + it("reuses snapshots when polling returns fresh objects for the same topology", () => { const secondary: DesktopEnvironmentBootstrap = { id: "wsl:default", diff --git a/apps/web/src/connection/desktopLocal.ts b/apps/web/src/connection/desktopLocal.ts index 57f9495521c0..520efa374773 100644 --- a/apps/web/src/connection/desktopLocal.ts +++ b/apps/web/src/connection/desktopLocal.ts @@ -47,6 +47,7 @@ export type DesktopSecondaryBootstrapsRead = export interface DesktopSecondaryBootstrapsReader { readonly readResult: () => DesktopSecondaryBootstrapsRead; + readonly refresh: () => Promise; readonly readSnapshot: () => ReadonlyArray; } @@ -55,10 +56,36 @@ export interface DesktopSecondaryBootstrapsReader { * consumers cannot temporarily disagree with the platform's retained registrations. */ export function createDesktopSecondaryBootstrapsReader( - resolveBridge: () => Pick | undefined, + resolveBridge: () => + | Pick + | undefined, ): DesktopSecondaryBootstrapsReader { let snapshot: ReadonlyArray = []; + const updateSnapshot = ( + entries: ReadonlyArray, + ): DesktopSecondaryBootstrapsRead => { + const next = entries.filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID); + if ( + next.length !== snapshot.length || + next.some((entry, index) => { + const previous = snapshot[index]; + return ( + previous === undefined || + entry.id !== previous.id || + entry.label !== previous.label || + entry.runningDistro !== previous.runningDistro || + entry.httpBaseUrl !== previous.httpBaseUrl || + entry.wsBaseUrl !== previous.wsBaseUrl || + entry.bootstrapToken !== previous.bootstrapToken + ); + }) + ) { + snapshot = next; + } + return { _tag: "Success", bootstraps: snapshot }; + }; + const readResult = (): DesktopSecondaryBootstrapsRead => { const bridge = resolveBridge(); if (bridge === undefined) { @@ -66,27 +93,7 @@ export function createDesktopSecondaryBootstrapsReader( return { _tag: "Success", bootstraps: snapshot }; } try { - const next = bridge - .getLocalEnvironmentBootstraps() - .filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID); - if ( - next.length !== snapshot.length || - next.some((entry, index) => { - const previous = snapshot[index]; - return ( - previous === undefined || - entry.id !== previous.id || - entry.label !== previous.label || - entry.runningDistro !== previous.runningDistro || - entry.httpBaseUrl !== previous.httpBaseUrl || - entry.wsBaseUrl !== previous.wsBaseUrl || - entry.bootstrapToken !== previous.bootstrapToken - ); - }) - ) { - snapshot = next; - } - return { _tag: "Success", bootstraps: snapshot }; + return updateSnapshot(bridge.getLocalEnvironmentBootstraps()); } catch (cause) { return { _tag: "Failure", cause }; } @@ -94,6 +101,15 @@ export function createDesktopSecondaryBootstrapsReader( return { readResult, + refresh: async () => { + const bridge = resolveBridge(); + if (bridge?.refreshLocalEnvironmentBootstraps === undefined) return readResult(); + try { + return updateSnapshot(await bridge.refreshLocalEnvironmentBootstraps()); + } catch (cause) { + return { _tag: "Failure", cause }; + } + }, readSnapshot: () => { const result = readResult(); return result._tag === "Success" ? result.bootstraps : snapshot; @@ -105,8 +121,8 @@ const desktopSecondaryBootstrapsReader = createDesktopSecondaryBootstrapsReader( () => window.desktopBridge, ); -export function readDesktopSecondaryBootstrapsResult(): DesktopSecondaryBootstrapsRead { - return desktopSecondaryBootstrapsReader.readResult(); +export function refreshDesktopSecondaryBootstraps(): Promise { + return desktopSecondaryBootstrapsReader.refresh(); } export function readDesktopSecondaryBootstraps(): ReadonlyArray { diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index 7b0490b6e100..9eddb16c9e1f 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -57,7 +57,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry"; import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState"; import { desktopLocalConnectionId, - readDesktopSecondaryBootstrapsResult, + refreshDesktopSecondaryBootstraps, type DesktopSecondaryBootstrapsRead, } from "./desktopLocal"; import * as ConnectionStorage from "./storage"; @@ -643,6 +643,8 @@ const layerPlatformConnectionSource = Layer.effect( const next = new Map(); const registrations: Array = []; + // The async refresh also updates the bridge's cached primary entry, so it runs first. + const topologyRead = yield* Effect.promise(refreshDesktopSecondaryBootstraps); const primaryTopologyRead = readPrimaryEnvironmentTargetResult(); const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead( previous, @@ -682,7 +684,6 @@ const layerPlatformConnectionSource = Layer.effect( } } - const topologyRead = readDesktopSecondaryBootstrapsResult(); for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead( previous, topologyRead, diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index d1f6b349397e..667b17bb37e4 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1047,6 +1047,8 @@ export interface DesktopBridge { */ getSystemLocale?: () => string | null; getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[]; + /** Updates what getLocalEnvironmentBootstraps returns without blocking the renderer. */ + refreshLocalEnvironmentBootstraps?: () => Promise; getLocalEnvironmentEnabled?: () => boolean; setLocalEnvironmentEnabled?: (enabled: boolean) => Promise; getLocalEnvironmentBearerToken: () => Promise; From 60084dbfa3b3e06aeb10b7b243afe990ea5a3d6c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 22 Oct 2026 12:10:21 +0000 Subject: [PATCH 03/14] test(desktop): stub window listeners so the preload test loads on macOS Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preload.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/preload.test.ts b/apps/desktop/src/preload.test.ts index 87b7229f309a..4dbaf7c529da 100644 --- a/apps/desktop/src/preload.test.ts +++ b/apps/desktop/src/preload.test.ts @@ -29,7 +29,10 @@ vi.mock("electron", () => ({ vi.mock("@clerk/electron/preload", () => ({ exposeClerkBridge: vi.fn() })); it("polling topology reads do not block the renderer on synchronous IPC each time", async () => { - vi.stubGlobal("window", { localStorage: { getItem: () => null, setItem: () => {} } }); + vi.stubGlobal("window", { + addEventListener: () => {}, + localStorage: { getItem: () => null, setItem: () => {} }, + }); await import("./preload.ts"); const bridge = exposed.get("desktopBridge") as DesktopBridge; sendSync.mockClear(); @@ -51,7 +54,10 @@ it("polling topology reads do not block the renderer on synchronous IPC each tim }); it("an async topology refresh replaces the bootstraps later reads return", async () => { - vi.stubGlobal("window", { localStorage: { getItem: () => null, setItem: () => {} } }); + vi.stubGlobal("window", { + addEventListener: () => {}, + localStorage: { getItem: () => null, setItem: () => {} }, + }); await import("./preload.ts"); const bridge = exposed.get("desktopBridge") as DesktopBridge; const wsl = { From 51a48ac05cba8e65802d1298c90e39d8dcf5cb98 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 08:24:56 +0000 Subject: [PATCH 04/14] test(client-runtime): reproduce #25823, one shell update rebuilds the quiet list per changed thread Co-Authored-By: Claude Opus 5.5 --- .../src/state/threadShell.test.ts | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 2dcc3233db3a..abd3e995a19d 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -379,4 +379,45 @@ describe("v2 thread shell lists", () => { harness.registry.dispose(); } }); + + it("delivers one quiet shell list per snapshot update that changes several threads", () => { + const harness = makeHarness(); + const snapshot = { + ...v2ShellSnapshot, + threads: ["a", "b", "c", "d"].map((id) => ({ + ...v2ThreadShell, + id: ThreadId.make(id), + title: id, + })), + }; + harness.registry.set(harness.snapshotAtom(environmentId), snapshot); + const delivered: Array> = []; + const unsubscribe = harness.registry.subscribe( + harness.threads.quietThreadShellsAtom, + (list) => delivered.push(list.map((thread) => thread.title).toSorted()), + { immediate: true }, + ); + try { + expect(delivered).toEqual([["a", "b", "c", "d"]]); + delivered.length = 0; + const next = ["a", "b", "c"].reduce( + (current, id, index) => + applyShellStreamEvent(current, { + kind: "thread.updated", + location: "active", + sequence: index + 1, + thread: { + ...current.threads.find((thread) => thread.id === id)!, + title: `${id} renamed`, + }, + }), + snapshot, + ); + harness.registry.set(harness.snapshotAtom(environmentId), next); + expect(delivered).toEqual([["a renamed", "b renamed", "c renamed", "d"]]); + } finally { + unsubscribe(); + harness.registry.dispose(); + } + }); }); From 6fd4cfcb9af7f8b2e4dd8ac29a1846eefc080aeb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 08:31:50 +0000 Subject: [PATCH 05/14] fix(client-runtime): the quiet thread list rebuilds once per shell update The quiet thread shell list read one quiet atom per thread, and each of those read the whole thread index. Every shell frame re-ran all of them and rebuilt the list once per changed thread, which froze the renderer for about a minute when a thread opened with ~13k threads. The list now builds from each enabled environment's threads and pending subagent requests, the same way the other shell lists do. It holds shells through streaming ticks itself, keyed by thread and pruned on every rebuild. Fixes pingdotgg/t3code#25823 Co-Authored-By: Claude Opus 5.5 --- .../src/state/threadShell.test.ts | 2 +- .../client-runtime/src/state/threadShell.ts | 26 ++++++++++++++++--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index abd3e995a19d..ebc508161db8 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -382,7 +382,7 @@ describe("v2 thread shell lists", () => { it("delivers one quiet shell list per snapshot update that changes several threads", () => { const harness = makeHarness(); - const snapshot = { + const snapshot: OrchestrationV2ShellSnapshot = { ...v2ShellSnapshot, threads: ["a", "b", "c", "d"].map((id) => ({ ...v2ThreadShell, diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 8d61ff6ac567..f741e403cb88 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -389,14 +389,32 @@ export function createEnvironmentThreadShellAtoms(input: { }).pipe(Atom.withLabel("environment-thread-shell-list")); // Lists that arrange threads read this, so a running thread's streaming - // ticks reach only what reads its live shell. + // ticks reach only what reads its live shell. It holds shells itself rather + // than reading quietThreadShellAtom per thread, so a shell update rebuilds + // the list once instead of once per changed thread. let previousQuietThreadShells: ReadonlyArray = []; + let previousQuietShellsById = new Map>(); const quietThreadShellsAtom = Atom.make((get) => { const next: EnvironmentThreadShell[] = []; - for (const ref of get(threadRefsAtom)) { - const shell = get(quietThreadShellAtomFamily(threadKey(ref))); - if (shell !== null) next.push(shell); + const byId = new Map>(); + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); + const previousShells = previousQuietShellsById.get(environmentId); + const shells = new Map(); + for (const thread of get(environmentThreadsAtom(environmentId))) { + const current = scopedThread(environmentId, thread, subagentRequests); + const previous = previousShells?.get(thread.id); + const shell = + previous !== undefined && + (previous === current || sameApartFromStreaming(previous, current)) + ? previous + : current; + shells.set(thread.id, shell); + next.push(shell); + } + byId.set(environmentId, shells); } + previousQuietShellsById = byId; if (arrayElementsEqual(previousQuietThreadShells, next)) return previousQuietThreadShells; previousQuietThreadShells = next; return next; From d1c7b1a917aadc0e7766e02a6cbf97d30439bb8f Mon Sep 17 00:00:00 2001 From: Pixel Perfect Date: Sat, 24 Oct 2026 18:37:38 -0700 Subject: [PATCH 06/14] fix(mobile): keep thread lists stable during streaming --- .../src/state/threadShell.test.ts | 88 +++++++++++++++++++ .../client-runtime/src/state/threadShell.ts | 9 +- 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index fda1054064f7..67697421d1cb 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + MessageId, ProjectId, RunId, RuntimeRequestId, @@ -108,6 +109,93 @@ describe("v2 thread shell lists", () => { registry.dispose(); }); + it("does not notify navigation subscribers for streaming-only updates", () => { + const { registry, threads, snapshotAtom } = makeHarness([environmentId, remoteEnvironmentId]); + const runId = RunId.make("navigation-run"); + const running: OrchestrationV2ThreadShell = { + ...v2ThreadShell, + latestRunId: runId, + activeRunId: runId, + status: "running", + itemCount: 1, + visibleItemCount: 1, + }; + const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) => + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + snapshotSequence: sequence, + threads: [thread], + }); + setThread(running, 1); + let notifications = 0; + const dispose = registry.subscribe(threads.navigationThreadShellsAtom, () => notifications++); + try { + const before = registry.get(threads.navigationThreadShellsAtom); + notifications = 0; + for (let index = 1; index <= 100; index++) { + const updatedAt = DateTime.add(v2Now, { seconds: index }); + setThread( + { + ...running, + updatedAt, + itemCount: index + 1, + visibleItemCount: index + 1, + latestVisibleMessage: { + id: MessageId.make("streaming-message"), + role: "assistant", + text: `Chunk ${index}`, + updatedAt, + }, + }, + index + 1, + ); + registry.get(threads.navigationThreadShellsAtom); + } + expect(notifications).toBe(0); + expect(registry.get(threads.navigationThreadShellsAtom)).toBe(before); + expect( + registry.get(threads.threadShellAtom({ environmentId, threadId: running.id }))?.itemCount, + ).toBe(101); + + setThread({ ...running, title: "Renamed" }, 102); + expect(registry.get(threads.navigationThreadShellsAtom)[0]?.title).toBe("Renamed"); + expect(notifications).toBe(1); + expect(registry.get(threads.navigationThreadShellsAtom)[1]).toBe(before[1]); + + setThread({ ...running, itemCount: 0, visibleItemCount: 0 }, 103); + expect(registry.get(threads.navigationThreadShellsAtom)[0]?.itemCount).toBe(0); + setThread(running, 104); + expect(registry.get(threads.navigationThreadShellsAtom)[0]?.itemCount).toBe(1); + const waiting = { ...running, status: "waiting" as const }; + setThread(waiting, 105); + expect(registry.get(threads.navigationThreadShellsAtom)[0]?.source.status).toBe("waiting"); + setThread( + { + ...waiting, + pendingRuntimeRequest: { + id: RuntimeRequestId.make("navigation-approval"), + kind: "command", + createdAt: v2Now, + }, + }, + 106, + ); + expect(registry.get(threads.navigationThreadShellsAtom)[0]?.hasPendingApprovals).toBe(true); + const completed = { ...running, activeRunId: null, status: "completed" as const }; + setThread(completed, 107); + expect(registry.get(threads.navigationThreadShellsAtom)[0]?.source.status).toBe("completed"); + const updatedAt = DateTime.add(v2Now, { seconds: 108 }); + setThread({ ...completed, updatedAt }, 108); + expect(registry.get(threads.navigationThreadShellsAtom)[0]?.updatedAt).toBe( + DateTime.formatIso(updatedAt), + ); + expect(notifications).toBe(7); + } finally { + dispose(); + registry.dispose(); + } + }); + it("keeps a live subagent question inside the parent without flagging its thread", () => { const { registry, threads, snapshotAtom } = makeHarness(); const root = v2ThreadShell; diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 15718da1eca6..59cc808c6ea5 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -559,7 +559,14 @@ export function createEnvironmentThreadShellAtoms(input: { ) { continue; } - next.push(scopedThread(environmentId, thread, subagentRequests)); + const shell = scopedThread(environmentId, thread, subagentRequests); + const previous = previousNavigationShells[next.length]; + // Token ticks must not rebuild navigation; threadShellAtom still supplies the live values. + next.push( + previous !== undefined && previous !== shell && sameApartFromStreaming(previous, shell) + ? previous + : shell, + ); } } if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells; From b1094d0741c1032a1695f18f48d8b92c58b491f2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 07:49:12 +0000 Subject: [PATCH 07/14] test(client-runtime): takeover tests for stable navigation thread shells Replace the PR's single all-in-one navigation test with two focused tests for #24651: navigation keeps its list and row identities through streaming ticks while threadShellAtom follows live values, and changes a list shows (count zero crossing, status, pending request, run stop, stopped thread's timestamp) still rebuild it. Co-Authored-By: Claude Opus 5.5 --- .../src/state/threadShell.test.ts | 129 +++++++++++------- 1 file changed, 77 insertions(+), 52 deletions(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 67697421d1cb..312a24ce9edb 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -109,8 +109,8 @@ describe("v2 thread shell lists", () => { registry.dispose(); }); - it("does not notify navigation subscribers for streaming-only updates", () => { - const { registry, threads, snapshotAtom } = makeHarness([environmentId, remoteEnvironmentId]); + it("keeps navigation and its rows through streaming ticks while the live shell follows", () => { + const { registry, threads, snapshotAtom } = makeHarness(); const runId = RunId.make("navigation-run"); const running: OrchestrationV2ThreadShell = { ...v2ThreadShell, @@ -120,76 +120,101 @@ describe("v2 thread shell lists", () => { itemCount: 1, visibleItemCount: 1, }; - const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) => + const idle = { ...v2ThreadShell, id: ThreadId.make("idle") }; + const setRunning = (thread: OrchestrationV2ThreadShell, sequence: number) => registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, snapshotSequence: sequence, - threads: [thread], + threads: [thread, idle], }); - setThread(running, 1); - let notifications = 0; - const dispose = registry.subscribe(threads.navigationThreadShellsAtom, () => notifications++); + setRunning(running, 1); + const ref = { environmentId, threadId: running.id }; + const dispose = registry.mount(threads.navigationThreadShellsAtom); try { const before = registry.get(threads.navigationThreadShellsAtom); - notifications = 0; - for (let index = 1; index <= 100; index++) { - const updatedAt = DateTime.add(v2Now, { seconds: index }); - setThread( + const [runningRow, idleRow] = before; + for (let tick = 1; tick <= 3; tick++) { + const updatedAt = DateTime.add(v2Now, { seconds: tick }); + setRunning( { ...running, updatedAt, - itemCount: index + 1, - visibleItemCount: index + 1, + itemCount: tick + 1, + visibleItemCount: tick + 1, latestVisibleMessage: { id: MessageId.make("streaming-message"), role: "assistant", - text: `Chunk ${index}`, + text: `Chunk ${tick}`, updatedAt, }, }, - index + 1, + tick + 1, ); - registry.get(threads.navigationThreadShellsAtom); + expect(registry.get(threads.navigationThreadShellsAtom)).toBe(before); } - expect(notifications).toBe(0); - expect(registry.get(threads.navigationThreadShellsAtom)).toBe(before); - expect( - registry.get(threads.threadShellAtom({ environmentId, threadId: running.id }))?.itemCount, - ).toBe(101); + expect(registry.get(threads.threadShellAtom(ref))?.itemCount).toBe(4); + expect(registry.get(threads.threadShellAtom(ref))?.source.latestVisibleMessage?.text).toBe( + "Chunk 3", + ); - setThread({ ...running, title: "Renamed" }, 102); - expect(registry.get(threads.navigationThreadShellsAtom)[0]?.title).toBe("Renamed"); - expect(notifications).toBe(1); - expect(registry.get(threads.navigationThreadShellsAtom)[1]).toBe(before[1]); + setRunning({ ...running, title: "Renamed" }, 5); + const renamed = registry.get(threads.navigationThreadShellsAtom); + expect(renamed).not.toBe(before); + expect(renamed[0]).not.toBe(runningRow); + expect(renamed[0]?.title).toBe("Renamed"); + expect(renamed[1]).toBe(idleRow); + } finally { + dispose(); + registry.dispose(); + } + }); - setThread({ ...running, itemCount: 0, visibleItemCount: 0 }, 103); - expect(registry.get(threads.navigationThreadShellsAtom)[0]?.itemCount).toBe(0); - setThread(running, 104); - expect(registry.get(threads.navigationThreadShellsAtom)[0]?.itemCount).toBe(1); - const waiting = { ...running, status: "waiting" as const }; - setThread(waiting, 105); - expect(registry.get(threads.navigationThreadShellsAtom)[0]?.source.status).toBe("waiting"); - setThread( - { - ...waiting, - pendingRuntimeRequest: { - id: RuntimeRequestId.make("navigation-approval"), - kind: "command", - createdAt: v2Now, - }, + it("rebuilds navigation for running-thread changes a list shows", () => { + const { registry, threads, snapshotAtom } = makeHarness(); + const runId = RunId.make("navigation-run"); + const running: OrchestrationV2ThreadShell = { + ...v2ThreadShell, + latestRunId: runId, + activeRunId: runId, + status: "running", + itemCount: 1, + visibleItemCount: 1, + }; + const completed = { ...running, activeRunId: null, status: "completed" as const }; + const changes: ReadonlyArray = [ + { ...running, itemCount: 0, visibleItemCount: 0 }, + { ...running, status: "waiting" }, + { + ...running, + pendingRuntimeRequest: { + id: RuntimeRequestId.make("navigation-approval"), + kind: "command", + createdAt: v2Now, }, - 106, - ); - expect(registry.get(threads.navigationThreadShellsAtom)[0]?.hasPendingApprovals).toBe(true); - const completed = { ...running, activeRunId: null, status: "completed" as const }; - setThread(completed, 107); - expect(registry.get(threads.navigationThreadShellsAtom)[0]?.source.status).toBe("completed"); - const updatedAt = DateTime.add(v2Now, { seconds: 108 }); - setThread({ ...completed, updatedAt }, 108); - expect(registry.get(threads.navigationThreadShellsAtom)[0]?.updatedAt).toBe( - DateTime.formatIso(updatedAt), - ); - expect(notifications).toBe(7); + }, + completed, + { ...completed, updatedAt: DateTime.add(v2Now, { seconds: 1 }) }, + ]; + const dispose = registry.mount(threads.navigationThreadShellsAtom); + try { + let sequence = 0; + for (const [index, change] of changes.entries()) { + const from = index === changes.length - 1 ? completed : running; + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + snapshotSequence: ++sequence, + threads: [from], + }); + const before = registry.get(threads.navigationThreadShellsAtom); + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + snapshotSequence: ++sequence, + threads: [change], + }); + const after = registry.get(threads.navigationThreadShellsAtom); + expect(after).not.toBe(before); + expect(after[0]?.source).toBe(change); + } } finally { dispose(); registry.dispose(); From 17e450d08e479364c115a298285125abbd88badf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 07:52:17 +0000 Subject: [PATCH 08/14] fix(client-runtime): navigation thread shells reuse the quiet per-thread shells Derive navigationThreadShellsAtom from quietThreadShellsAtom instead of comparing each row against the previous list's row at the same index. Rows are now matched by thread key through the existing quietThreadShellAtom family, so a streaming thread keeps its row when threads are inserted, removed or reordered, and there is one streaming comparison site. Co-Authored-By: Claude Opus 5.5 --- .../client-runtime/src/state/threadShell.ts | 25 ++++--------------- 1 file changed, 5 insertions(+), 20 deletions(-) diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 59cc808c6ea5..f00ca50f39f0 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -548,27 +548,12 @@ export function createEnvironmentThreadShellAtoms(input: { let previousNavigationShells: ReadonlyArray = []; const navigationThreadShellsAtom = Atom.make((get) => { - const next: EnvironmentThreadShell[] = []; const underParent = get(delegatedUnderParentAtom); - for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { - const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); - for (const thread of get(environmentThreadsAtom(environmentId))) { - if ( - thread.archivedAt !== null || - isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent) - ) { - continue; - } - const shell = scopedThread(environmentId, thread, subagentRequests); - const previous = previousNavigationShells[next.length]; - // Token ticks must not rebuild navigation; threadShellAtom still supplies the live values. - next.push( - previous !== undefined && previous !== shell && sameApartFromStreaming(previous, shell) - ? previous - : shell, - ); - } - } + const next = get(quietThreadShellsAtom).filter( + (thread) => + thread.archivedAt === null && + !isShownUnderParent({ environmentId: thread.environmentId, threadId: thread.id }, thread.lineage, underParent), + ); if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells; previousNavigationShells = next; return next; From e8a926ab707397a464ad1951485a6180771d20d0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 07:59:26 +0000 Subject: [PATCH 09/14] fix(client-runtime): keep the contributor's positional navigation reuse Building navigation from quietThreadShellsAtom mounts one per-thread atom for every thread on mobile and measured 6-25x more derivation work per streaming tick than main. The positional reuse costs what main costs, since unchanged sources keep their cached shell and only changed rows are compared. Co-Authored-By: Claude Opus 5.5 --- .../client-runtime/src/state/threadShell.ts | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index f00ca50f39f0..59cc808c6ea5 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -548,12 +548,27 @@ export function createEnvironmentThreadShellAtoms(input: { let previousNavigationShells: ReadonlyArray = []; const navigationThreadShellsAtom = Atom.make((get) => { + const next: EnvironmentThreadShell[] = []; const underParent = get(delegatedUnderParentAtom); - const next = get(quietThreadShellsAtom).filter( - (thread) => - thread.archivedAt === null && - !isShownUnderParent({ environmentId: thread.environmentId, threadId: thread.id }, thread.lineage, underParent), - ); + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); + for (const thread of get(environmentThreadsAtom(environmentId))) { + if ( + thread.archivedAt !== null || + isShownUnderParent({ environmentId, threadId: thread.id }, thread.lineage, underParent) + ) { + continue; + } + const shell = scopedThread(environmentId, thread, subagentRequests); + const previous = previousNavigationShells[next.length]; + // Token ticks must not rebuild navigation; threadShellAtom still supplies the live values. + next.push( + previous !== undefined && previous !== shell && sameApartFromStreaming(previous, shell) + ? previous + : shell, + ); + } + } if (arrayElementsEqual(previousNavigationShells, next)) return previousNavigationShells; previousNavigationShells = next; return next; From ecafd4ecb4e1fca02145c589f80e4587f30bebbb Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Fri, 6 Nov 2026 22:16:31 -0600 Subject: [PATCH 10/14] perf(web): typing no longer re-renders the composer's footer controls Every keystroke in the composer re-rendered the whole footer (model picker, controls menu and their popovers), because the runtime mode options were rebuilt as a new array on each render. Since the managed policy hook was called between deriving the modes and using them, React Compiler could not memoize that derivation. Call useManagedPolicy before the derivation so the compiler caches the mode options on runtime mode, supported modes and policy. Typing 20 characters drops from 542 to 293 component renders, and the render scenario now asserts the footer re-renders only for the first character. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 4 +++- apps/web/test/appScenarios.renders.tsx | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 69022a93fbee..561dc8d2ea43 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -922,13 +922,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : undefined; const resolvedCompactDisabledReason = compactDisabledReason ?? (noProviderAvailable ? "Compacting is unavailable right now" : null); + // Called before the derivation below: a hook between it and its uses stops React Compiler + // from caching the mode options, and the footer then re-renders on every keystroke. + const managedPolicy = useManagedPolicy(environmentId); const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = resolveCompatibleRuntimeMode( runtimeMode, selectedProviderEntry?.snapshot.supportedRuntimeModes, ); // Modes above an administrator's ceiling stay listed, disabled with the reason. - const managedPolicy = useManagedPolicy(environmentId); const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( compatibleRuntimeModes, managedPolicy, diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsx index 0667a9f4950b..4961d78a6734 100644 --- a/apps/web/test/appScenarios.renders.tsx +++ b/apps/web/test/appScenarios.renders.tsx @@ -259,6 +259,8 @@ it("app-type-in-composer", async () => { await userEvent.type(editor, TYPED_TEXT); await expect.element(editor).toHaveTextContent(TYPED_TEXT); }); + // The footer controls re-render for the first character only, not per keystroke. + expect(counted.components.ComposerControlsBar).toBe(1); await report("app-type-in-composer", [counted]); }); From 684c3abde856684d46fccafde5c4bace1f07b813 Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Tue, 10 Nov 2026 15:39:09 +0530 Subject: [PATCH 11/14] perf(web): completed Markdown blocks no longer render twice --- .../components/ChatMarkdown.browser.test.tsx | 24 +++++++++++++++++-- apps/web/src/components/ChatMarkdown.tsx | 10 +++++--- .../src/components/chat/markdownRenderer.ts | 9 ++++++- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 3cc21392cea8..5b610c55efe2 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -219,7 +219,10 @@ it("reuses the parse of a streaming reply's finished blocks when it remounts", a ); { - await using _first = await render(message); + await using first = await render( + , + ); + await first.rerender(message); } await using screen = await render(message); await expect.element(screen.getByText("Still growing")).toBeVisible(); @@ -234,11 +237,28 @@ it("reuses the parse of a remounted message that has stable extra plugins", asyn ); { - await using _first = await render(message); + await using first = await render( + , + ); + await first.rerender(message); } await using screen = await render(message); await expect.element(screen.getByText("Cached text")).toBeVisible(); expect(parsed).toHaveBeenCalledTimes(1); + const changed = vi.fn(); + await screen.rerender( + () => void changed()]} + />, + ); + expect(changed).toHaveBeenCalledTimes(1); }); describe("ChatMarkdown favicon privacy", () => { diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 06960b273a05..c246e334cd69 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -78,6 +78,7 @@ import React, { type MouseEvent as ReactMouseEvent, use, memo, + useEffect, useLayoutEffect, useRef, useState, @@ -1720,9 +1721,12 @@ const MarkdownSource = memo(function MarkdownSource({ components: CHAT_MARKDOWN_COMPONENTS, urlTransform: markdownUrlTransform, }); - return ( - {render(text, shared && cache)} - ); + const element = render(text, false); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Promote the committed element into the shared parse cache when its block finishes. + useEffect(() => { + if (shared && cache) render.remember(text, element); + }, [render, text, element, shared, cache]); + return {element}; }); function ChatMarkdown({ diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.ts index ab4083f2adf4..51ce410ed8e7 100644 --- a/apps/web/src/components/chat/markdownRenderer.ts +++ b/apps/web/src/components/chat/markdownRenderer.ts @@ -82,7 +82,7 @@ export function createMarkdownRenderer({ } }; - return (text: string, cache: boolean): ReactElement => { + const render = (text: string, cache: boolean): ReactElement => { const key = keyPrefix + text; const cached = rendered.get(key); if (cached !== undefined) { @@ -106,4 +106,11 @@ export function createMarkdownRenderer({ if (cache) remember(key, element); return element; }; + + return Object.assign(render, { + remember(text: string, element: ReactElement) { + const key = keyPrefix + text; + if (!rendered.has(key)) remember(key, element); + }, + }); } From 3a4a1c81176603318f685dc3acdc485d5f3c46c3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 01:07:05 +0000 Subject: [PATCH 12/14] test(client-runtime): the quiet thread list still leaves out tag-hidden threads --- .../client-runtime/src/state/threadShell.test.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 824de0582e85..3469a07c29fd 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -22,7 +22,10 @@ const environmentId = EnvironmentId.make("environment-v2"); const remoteEnvironmentId = EnvironmentId.make("remote-environment-v2"); const otherProjectId = ProjectId.make("other-project"); -function makeHarness(environmentIds: ReadonlyArray = [environmentId]) { +function makeHarness( + environmentIds: ReadonlyArray = [environmentId], + hiddenTags: ReadonlyArray | null = null, +) { const snapshotAtom = Atom.family((_environmentId: EnvironmentId) => Atom.make(v2ShellSnapshot), ); @@ -51,7 +54,7 @@ function makeHarness(environmentIds: ReadonlyArray = [environment threads: createEnvironmentThreadShellAtoms({ catalogValueAtom, snapshotAtom, - hiddenThreadTagsAtom: () => Atom.make(null), + hiddenThreadTagsAtom: () => Atom.make(hiddenTags), }), }; } @@ -635,13 +638,14 @@ describe("v2 thread shell lists", () => { }); it("delivers one quiet shell list per snapshot update that changes several threads", () => { - const harness = makeHarness(); + const harness = makeHarness([environmentId], ["private"]); const snapshot: OrchestrationV2ShellSnapshot = { ...v2ShellSnapshot, - threads: ["a", "b", "c", "d"].map((id) => ({ + threads: ["a", "b", "c", "d", "hidden"].map((id) => ({ ...v2ThreadShell, id: ThreadId.make(id), title: id, + tags: id === "hidden" ? ["private"] : [], })), }; harness.registry.set(harness.snapshotAtom(environmentId), snapshot); From 692eb7a7256e7ad6b382fbfcc6d7093fde7966f7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 01:27:24 +0000 Subject: [PATCH 13/14] test(desktop): keep the topology polling regression test loading after main's preload changes AI-assisted; verified with the tests and tools listed above. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preload.test.ts | 33 +++++++++++--------------------- 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/apps/desktop/src/preload.test.ts b/apps/desktop/src/preload.test.ts index 4dbaf7c529da..ef7162d0b3e1 100644 --- a/apps/desktop/src/preload.test.ts +++ b/apps/desktop/src/preload.test.ts @@ -17,9 +17,7 @@ vi.mock("electron", () => ({ }, ipcRenderer: { sendSync, - invoke: vi.fn(async (channel: string) => - channel === IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL ? true : [], - ), + invoke: vi.fn(async () => undefined), on: vi.fn(), removeListener: vi.fn(), }, @@ -28,38 +26,30 @@ vi.mock("electron", () => ({ })); vi.mock("@clerk/electron/preload", () => ({ exposeClerkBridge: vi.fn() })); -it("polling topology reads do not block the renderer on synchronous IPC each time", async () => { +it("topology polling reads the cache and refreshes it without synchronous IPC", async () => { vi.stubGlobal("window", { addEventListener: () => {}, localStorage: { getItem: () => null, setItem: () => {} }, }); + vi.stubGlobal("document", { + addEventListener: () => {}, + fullscreenElement: null, + documentElement: { style: { setProperty: () => {} } }, + }); await import("./preload.ts"); const bridge = exposed.get("desktopBridge") as DesktopBridge; sendSync.mockClear(); - // The renderer's platform poll reads these every few seconds; ipcRenderer.sendSync - // freezes the renderer for as long as the main process takes to answer. + // sendSync freezes the renderer until main answers; only the first read may use it. for (let poll = 0; poll < 5; poll += 1) { bridge.getLocalEnvironmentBootstraps(); - bridge.getLocalEnvironmentEnabled?.(); + bridge.getLocalEnvironmentEnabled(); } - const syncCalls = (channel: string) => sendSync.mock.calls.filter(([called]) => called === channel).length; - // Each read may block once at startup; later polls must not. - expect - .soft(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)) - .toBeLessThanOrEqual(1); - expect.soft(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL)).toBeLessThanOrEqual(1); -}); + expect(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)).toBeLessThanOrEqual(1); + expect(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL)).toBeLessThanOrEqual(1); -it("an async topology refresh replaces the bootstraps later reads return", async () => { - vi.stubGlobal("window", { - addEventListener: () => {}, - localStorage: { getItem: () => null, setItem: () => {} }, - }); - await import("./preload.ts"); - const bridge = exposed.get("desktopBridge") as DesktopBridge; const wsl = { id: "wsl:Ubuntu", label: "WSL (Ubuntu)", @@ -69,7 +59,6 @@ it("an async topology refresh replaces the bootstraps later reads return", async }; vi.mocked(ipcRenderer.invoke).mockResolvedValueOnce([wsl]).mockResolvedValueOnce([]); sendSync.mockClear(); - await bridge.refreshLocalEnvironmentBootstraps?.(); expect(bridge.getLocalEnvironmentBootstraps()).toEqual([wsl]); await bridge.refreshLocalEnvironmentBootstraps?.(); From 43cf7bc14143139d6249f68a952a552c2a13724d Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:58:50 +0100 Subject: [PATCH 14/14] perf(web): batch first-send composer updates Avoid forcing a separate desktop render to dock a draft composer before send. Keep docking with the optimistic message updates; only real mobile view transitions need a synchronous commit and an awaited update. Co-authored-by: GPT 6.1 Sol Co-authored-by: Claude Opus 5.5 Co-authored-by: Grok 4.7 --- .../chat/draftHeroTransition.test.ts | 130 ++++++++++++++++++ .../components/chat/draftHeroTransition.ts | 78 +++++++---- .../src/components/chat/useComposerSend.ts | 18 +-- 3 files changed, 184 insertions(+), 42 deletions(-) create mode 100644 apps/web/src/components/chat/draftHeroTransition.test.ts diff --git a/apps/web/src/components/chat/draftHeroTransition.test.ts b/apps/web/src/components/chat/draftHeroTransition.test.ts new file mode 100644 index 000000000000..7fb99acce9f2 --- /dev/null +++ b/apps/web/src/components/chat/draftHeroTransition.test.ts @@ -0,0 +1,130 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { runMobileComposerTransition } from "./draftHeroTransition"; + +type StartViewTransition = (update: () => void | Promise) => { + finished: Promise; +}; + +function stubEnvironment(input: { + mobile: boolean; + reducedMotion?: boolean; + startViewTransition?: StartViewTransition; +}) { + const styles = new Map(); + const root = { + style: { + setProperty: (name: string, value: string) => styles.set(name, value), + removeProperty: (name: string) => styles.delete(name), + getPropertyValue: (name: string) => styles.get(name) ?? "", + }, + dataset: {} as Record, + }; + vi.stubGlobal("window", { + matchMedia: (query: string) => ({ + matches: query.includes("max-width") ? input.mobile : (input.reducedMotion ?? false), + }), + }); + vi.stubGlobal("document", { + documentElement: root, + ...(input.startViewTransition ? { startViewTransition: input.startViewTransition } : {}), + }); + return root; +} + +/** A view transition that runs its update after the old snapshot, like the browser does. */ +function deferredViewTransition(): StartViewTransition { + return (update) => ({ + finished: Promise.resolve().then(update), + }); +} + +describe("runMobileComposerTransition", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it.each([ + { name: "desktop viewport", mobile: false, active: true }, + { name: "reduced motion", mobile: true, reducedMotion: true, active: true }, + { name: "panel motion off", mobile: true, active: false }, + { name: "no view transition support", mobile: true, active: true, unsupported: true }, + { name: "no document", mobile: false, active: true, missingGlobal: "document" }, + { name: "no window", mobile: false, active: true, missingGlobal: "window" }, + ])( + "applies the update before returning on $name", + ({ unsupported, missingGlobal, active, ...env }) => { + const startViewTransition = vi.fn(deferredViewTransition()); + stubEnvironment({ ...env, ...(unsupported ? {} : { startViewTransition }) }); + if (missingGlobal) vi.stubGlobal(missingGlobal, undefined); + const update = vi.fn(); + + const docking = runMobileComposerTransition(update, { active, durationMs: 200 }); + + expect(docking).toBeUndefined(); + expect(update).toHaveBeenCalledTimes(1); + expect(startViewTransition).not.toHaveBeenCalled(); + }, + ); + + it("applies the update once inside a mobile view transition and resolves after it", async () => { + let finish!: () => void; + const finished = new Promise((resolve) => { + finish = resolve; + }); + const startViewTransition = vi.fn((update: () => void) => { + void Promise.resolve().then(update); + return { finished }; + }); + const root = stubEnvironment({ mobile: true, startViewTransition }); + const update = vi.fn(); + + const docking = runMobileComposerTransition(update, { active: true, durationMs: 200 }); + + expect(update).not.toHaveBeenCalled(); + expect(root.dataset.mobileComposerRouteTransition).toBe("true"); + expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe("200ms"); + await docking; + expect(update).toHaveBeenCalledTimes(1); + expect(root.dataset.mobileComposerRouteTransition).toBe("true"); + finish(); + await finished; + expect(root.dataset.mobileComposerRouteTransition).toBeUndefined(); + expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe(""); + expect(update).toHaveBeenCalledTimes(1); + }); + + it.each([ + { + name: "the transition cannot start", + startViewTransition: (): ReturnType => { + throw new Error("InvalidStateError"); + }, + update: vi.fn(), + }, + { + name: "the update throws", + startViewTransition: deferredViewTransition(), + update: vi.fn(() => { + throw new Error("render failed"); + }), + }, + { + name: "an inline update throws", + mobile: false, + startViewTransition: deferredViewTransition(), + update: vi.fn(() => { + throw new Error("render failed"); + }), + }, + ])( + "still releases the caller once when $name", + async ({ mobile = true, startViewTransition, update }) => { + stubEnvironment({ mobile, startViewTransition }); + + await runMobileComposerTransition(update, { active: true, durationMs: 200 }); + + expect(update).toHaveBeenCalledTimes(1); + }, + ); +}); diff --git a/apps/web/src/components/chat/draftHeroTransition.ts b/apps/web/src/components/chat/draftHeroTransition.ts index 7a53a22b2042..cc0b7a0cd00f 100644 --- a/apps/web/src/components/chat/draftHeroTransition.ts +++ b/apps/web/src/components/chat/draftHeroTransition.ts @@ -1,3 +1,5 @@ +import { flushSync } from "react-dom"; + export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition"; export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)"; export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer"; @@ -35,12 +37,18 @@ export async function waitForDraftHeroTransition(): Promise { ]); } -export async function runMobileComposerTransition( - update: () => void | Promise, +/** + * Applies a composer layout change. On a mobile viewport with motion allowed, `update` runs once + * inside a view transition, committed synchronously so the new snapshot shows it, and the returned + * promise resolves once it has run. Otherwise `update` runs inline with no flush, so its state + * updates batch with the caller's, and nothing is returned. A failing update never blocks the caller. + */ +export function runMobileComposerTransition( + update: () => void, options: { active: boolean; durationMs: number }, -): Promise { +): Promise | undefined { if (typeof document === "undefined" || typeof window === "undefined") { - await update(); + runInlineUpdate(update); return; } @@ -48,46 +56,58 @@ export async function runMobileComposerTransition( const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false; const prefersReducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false; - if ( - !options.active || - !mobileViewport || - prefersReducedMotion || - !transitionDocument.startViewTransition - ) { - await update(); + const startViewTransition = transitionDocument.startViewTransition?.bind(transitionDocument); + if (!options.active || !mobileViewport || prefersReducedMotion || !startViewTransition) { + runInlineUpdate(update); return; } - let updateStarted = false; - const runUpdate = async () => { - if (updateStarted) return; - updateStarted = true; - await update(); - }; + return new Promise((resolveUpdated) => { + let updateStarted = false; + const runUpdate = () => { + if (updateStarted) return; + updateStarted = true; + try { + flushSync(update); + } finally { + resolveUpdated(); + } + }; + void runViewTransition(startViewTransition, runUpdate, options.durationMs); + }); +} + +function runInlineUpdate(update: () => void) { + try { + update(); + } catch {} +} + +async function runViewTransition( + startViewTransition: (update: () => void) => ComposerViewTransition, + runUpdate: () => void, + durationMs: number, +) { + const root = document.documentElement; let transitionFinished: Promise | null = null; - transitionDocument.documentElement.style.setProperty( - MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, - `${String(options.durationMs)}ms`, - ); - transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true"; + root.style.setProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, `${String(durationMs)}ms`); + root.dataset.mobileComposerRouteTransition = "true"; try { - const transition = transitionDocument.startViewTransition(runUpdate); + const transition = startViewTransition(runUpdate); transitionFinished = transition.finished.catch(() => undefined); activeMobileComposerTransition = transitionFinished; try { await transition.finished; } catch { - await runUpdate(); + runInlineUpdate(runUpdate); } } catch { - await runUpdate(); + runInlineUpdate(runUpdate); } finally { if (activeMobileComposerTransition === transitionFinished) { activeMobileComposerTransition = null; } - delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition; - transitionDocument.documentElement.style.removeProperty( - MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, - ); + delete root.dataset.mobileComposerRouteTransition; + root.style.removeProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY); } } diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 7257dee5ced9..1afe53a94470 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -45,7 +45,6 @@ import { } from "@t3tools/client-runtime/environment"; import { createModelSelection } from "@t3tools/shared/model"; import { type SetStateAction, useLayoutEffect, useRef } from "react"; -import { flushSync } from "react-dom"; import { useNavigate } from "@tanstack/react-router"; import { isAtomCommandInterrupted, @@ -905,25 +904,18 @@ export function useComposerSend(input: ComposerSendInput) { shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) && activeThreadKey ) { - let resolveDockStarted: (() => void) | undefined; - const dockStarted = new Promise((resolve) => { - resolveDockStarted = resolve; - }); - const dockTransition = runMobileComposerTransition( + const docking = runMobileComposerTransition( () => { - flushSync(() => { - captureDraftHeroComposerRect(); - setDockedDraftHeroThreadKey(activeThreadKey); - }); - resolveDockStarted?.(); + captureDraftHeroComposerRect(); + setDockedDraftHeroThreadKey(activeThreadKey); }, { active: panelAnimationsActive, durationMs: panelAnimationDurationMs, }, ); - void dockTransition.catch(() => resolveDockStarted?.()); - await dockStarted; + // Awaiting only a real transition keeps an inline dock in the same render as the send. + if (docking) await docking; } const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();