diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 3a1fc63949cc..1db52b0daaa7 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -36,6 +36,7 @@ import { import { getAppBranding, getLocalEnvironmentBootstraps, + getLocalEnvironmentBootstrapsAsync, getLocalEnvironmentBearerToken, installRelayTelemetryEnabled, getSystemLocale, @@ -105,6 +106,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handleSync(getPrimaryPasteEnabled); yield* ipc.handleSync(getWindowFullscreenState); yield* ipc.handleSync(getLocalEnvironmentBootstraps); + yield* ipc.handle(getLocalEnvironmentBootstrapsAsync); yield* ipc.handleSync(getLocalEnvironmentEnabled); yield* ipc.handle(setLocalEnvironmentEnabled); yield* ipc.handle(getHostEnvironmentId); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 53a1138d71a9..2dd7d1e3f2ec 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -135,55 +135,66 @@ 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), - // Use the current window's derived token; the launch config's token may be stale. - ...(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), + // Use the current window's derived token; the launch config's token may be stale. + ...(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 new file mode 100644 index 000000000000..ef7162d0b3e1 --- /dev/null +++ b/apps/desktop/src/preload.test.ts @@ -0,0 +1,67 @@ +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"; + +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 () => undefined), + on: vi.fn(), + removeListener: vi.fn(), + }, + webFrame: { getZoomFactor: () => 1 }, + webUtils: { getPathForFile: () => "" }, +})); +vi.mock("@clerk/electron/preload", () => ({ exposeClerkBridge: vi.fn() })); + +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(); + + // 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(); + } + const syncCalls = (channel: string) => + sendSync.mock.calls.filter(([called]) => called === channel).length; + expect(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)).toBeLessThanOrEqual(1); + expect(syncCalls(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL)).toBeLessThanOrEqual(1); + + 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 1a0187219bab..7f572edd6e0b 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -103,6 +103,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); @@ -146,17 +158,19 @@ contextBridge.exposeInMainWorld("desktopBridge", { ); return Array.isArray(result) ? result.filter((tag) => typeof tag === "string") : []; }, - 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), getHostEnvironmentId: () => ipcRenderer.invoke(IpcChannels.GET_HOST_ENVIRONMENT_ID_CHANNEL), diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index d24b1c9299ac..0595de792a5d 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -254,7 +254,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(); @@ -269,11 +272,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); }); it("highlights a code block's own source when an earlier block of the same length was cached", async () => { diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index b19e815f5a8b..7fd75c16e183 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -80,6 +80,7 @@ import React, { type MouseEvent as ReactMouseEvent, use, memo, + useEffect, useLayoutEffect, useRef, useState, @@ -1801,9 +1802,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/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 8243322bda39..6dad54b902cd 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -910,13 +910,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? providerInstanceEntries.find((entry) => hasProviderSetup(entry.snapshot))?.instanceId : undefined)) : undefined; + // 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/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/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); + }, + }); } 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(); 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 eb46a09ab3ac..e1343a2cee4a 100644 --- a/apps/web/src/connection/desktopLocal.ts +++ b/apps/web/src/connection/desktopLocal.ts @@ -38,15 +38,42 @@ export type DesktopSecondaryBootstrapsRead = export interface DesktopSecondaryBootstrapsReader { readonly readResult: () => DesktopSecondaryBootstrapsRead; + readonly refresh: () => Promise; readonly readSnapshot: () => ReadonlyArray; } /** Empty reads clear the snapshot; failed reads retain platform 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) { @@ -54,27 +81,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 }; } @@ -82,6 +89,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; @@ -93,8 +109,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 dcd50342f1c9..497b8554e949 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"; @@ -640,6 +640,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, @@ -679,7 +681,6 @@ const layerPlatformConnectionSource = Layer.effect( } } - const topologyRead = readDesktopSecondaryBootstrapsResult(); for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead( previous, topologyRead, diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsx index b3dad1041d7f..0232d7d2c750 100644 --- a/apps/web/test/appScenarios.renders.tsx +++ b/apps/web/test/appScenarios.renders.tsx @@ -262,6 +262,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]); }); diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index d18a3e3adae1..5c833c6f437a 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, @@ -22,7 +23,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 +55,7 @@ function makeHarness(environmentIds: ReadonlyArray = [environment threads: createEnvironmentThreadShellAtoms({ catalogValueAtom, snapshotAtom, - hiddenThreadTagsAtom: () => Atom.make(null), + hiddenThreadTagsAtom: () => Atom.make(hiddenTags), }), }; } @@ -112,6 +116,118 @@ describe("v2 thread shell lists", () => { registry.dispose(); }); + 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, + latestRunId: runId, + activeRunId: runId, + status: "running", + itemCount: 1, + visibleItemCount: 1, + }; + const idle = { ...v2ThreadShell, id: ThreadId.make("idle") }; + const setRunning = (thread: OrchestrationV2ThreadShell, sequence: number) => + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + snapshotSequence: sequence, + threads: [thread, idle], + }); + setRunning(running, 1); + const ref = { environmentId, threadId: running.id }; + const dispose = registry.mount(threads.navigationThreadShellsAtom); + try { + const before = registry.get(threads.navigationThreadShellsAtom); + const [runningRow, idleRow] = before; + for (let tick = 1; tick <= 3; tick++) { + const updatedAt = DateTime.add(v2Now, { seconds: tick }); + setRunning( + { + ...running, + updatedAt, + itemCount: tick + 1, + visibleItemCount: tick + 1, + latestVisibleMessage: { + id: MessageId.make("streaming-message"), + role: "assistant", + text: `Chunk ${tick}`, + updatedAt, + }, + }, + tick + 1, + ); + expect(registry.get(threads.navigationThreadShellsAtom)).toBe(before); + } + expect(registry.get(threads.threadShellAtom(ref))?.itemCount).toBe(4); + expect(registry.get(threads.threadShellAtom(ref))?.source.latestVisibleMessage?.text).toBe( + "Chunk 3", + ); + + 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(); + } + }); + + 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, + }, + }, + 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(); + } + }); + it("keeps a live subagent question inside the parent without flagging its thread", () => { const { registry, threads, snapshotAtom } = makeHarness(); const root = v2ThreadShell; @@ -678,4 +794,46 @@ describe("v2 thread shell lists", () => { harness.registry.dispose(); } }); + + it("delivers one quiet shell list per snapshot update that changes several threads", () => { + const harness = makeHarness([environmentId], ["private"]); + const snapshot: OrchestrationV2ShellSnapshot = { + ...v2ShellSnapshot, + 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); + 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(); + } + }); }); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index e93c992f30ae..59b05f6ced43 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -659,16 +659,34 @@ export function createEnvironmentThreadShellAtoms(input: { }).pipe(Atom.withLabel("environment-visible-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[] = []; const hidden = get(hiddenThreadKeysAtom); - for (const ref of get(threadRefsAtom)) { - if (hidden.has(threadKey(ref))) continue; - 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))) { + if (hidden.has(threadKey({ environmentId, threadId: thread.id }))) continue; + 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; @@ -724,7 +742,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; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 9ebaa872c4f6..f05952bb4f1f 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1073,6 +1073,8 @@ export interface DesktopBridge { /** False when the OS turned off middle-click PRIMARY paste (`gtk-enable-primary-paste`). */ getPrimaryPasteEnabled?: () => boolean; getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[]; + /** Updates what getLocalEnvironmentBootstraps returns without blocking the renderer. */ + refreshLocalEnvironmentBootstraps?: () => Promise; getLocalEnvironmentEnabled: () => boolean; setLocalEnvironmentEnabled: (enabled: boolean) => Promise; /** The environment ID recorded in this app's T3 home, such as its own machine's background service. */