@devries-cameron20 / t3code-1 / commits / 56fd98be52
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(web): batch first-send composer updates (#36166)

Co-authored-by: Grok 4.7 <noreply@x.ai> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 14, 2026 at 07:32 UTC 56fd98be528babf8a8101004c5b10d8ac86411db
3 files changed +174 -42
apps/web/src/components/chat/draftHeroTransition.test.ts new
+124
@@ -0,0 +1,124 @@
1 +import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { runMobileComposerTransition } from "./draftHeroTransition";
4 +
5 +type StartViewTransition = (update: () => void | Promise<void>) => {
6 + finished: Promise<void>;
7 +};
8 +
9 +function stubEnvironment(input: {
10 + mobile: boolean;
11 + reducedMotion?: boolean;
12 + startViewTransition?: StartViewTransition;
13 +}) {
14 + const styles = new Map<string, string>();
15 + const root = {
16 + style: {
17 + setProperty: (name: string, value: string) => styles.set(name, value),
18 + removeProperty: (name: string) => styles.delete(name),
19 + getPropertyValue: (name: string) => styles.get(name) ?? "",
20 + },
21 + dataset: {} as Record<string, string>,
22 + };
23 + vi.stubGlobal("window", {
24 + matchMedia: (query: string) => ({
25 + matches: query.includes("max-width") ? input.mobile : (input.reducedMotion ?? false),
26 + }),
27 + });
28 + vi.stubGlobal("document", {
29 + documentElement: root,
30 + ...(input.startViewTransition ? { startViewTransition: input.startViewTransition } : {}),
31 + });
32 + return root;
33 +}
34 +
35 +/** A view transition that runs its update after the old snapshot, like the browser does. */
36 +function deferredViewTransition(): StartViewTransition {
37 + return (update) => ({
38 + finished: Promise.resolve().then(update),
39 + });
40 +}
41 +
42 +describe("runMobileComposerTransition", () => {
43 + afterEach(() => {
44 + vi.unstubAllGlobals();
45 + });
46 +
47 + it.each([
48 + { name: "desktop viewport", mobile: false, active: true },
49 + { name: "reduced motion", mobile: true, reducedMotion: true, active: true },
50 + { name: "panel motion off", mobile: true, active: false },
51 + { name: "no view transition support", mobile: true, active: true, unsupported: true },
52 + ])("applies the update before returning on $name", ({ unsupported, active, ...env }) => {
53 + const startViewTransition = vi.fn(deferredViewTransition());
54 + stubEnvironment({ ...env, ...(unsupported ? {} : { startViewTransition }) });
55 + const update = vi.fn();
56 +
57 + const docking = runMobileComposerTransition(update, { active, durationMs: 200 });
58 +
59 + expect(docking).toBeUndefined();
60 + expect(update).toHaveBeenCalledTimes(1);
61 + expect(startViewTransition).not.toHaveBeenCalled();
62 + });
63 +
64 + it("applies the update once inside a mobile view transition and resolves after it", async () => {
65 + let finish!: () => void;
66 + const finished = new Promise<void>((resolve) => {
67 + finish = resolve;
68 + });
69 + const startViewTransition = vi.fn((update: () => void) => {
70 + void Promise.resolve().then(update);
71 + return { finished };
72 + });
73 + const root = stubEnvironment({ mobile: true, startViewTransition });
74 + const update = vi.fn();
75 +
76 + const docking = runMobileComposerTransition(update, { active: true, durationMs: 200 });
77 +
78 + expect(update).not.toHaveBeenCalled();
79 + expect(root.dataset.mobileComposerRouteTransition).toBe("true");
80 + expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe("200ms");
81 + await docking;
82 + expect(update).toHaveBeenCalledTimes(1);
83 + expect(root.dataset.mobileComposerRouteTransition).toBe("true");
84 + finish();
85 + await finished;
86 + expect(root.dataset.mobileComposerRouteTransition).toBeUndefined();
87 + expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe("");
88 + expect(update).toHaveBeenCalledTimes(1);
89 + });
90 +
91 + it.each([
92 + {
93 + name: "the transition cannot start",
94 + startViewTransition: (): ReturnType<StartViewTransition> => {
95 + throw new Error("InvalidStateError");
96 + },
97 + update: vi.fn(),
98 + },
99 + {
100 + name: "the update throws",
101 + startViewTransition: deferredViewTransition(),
102 + update: vi.fn(() => {
103 + throw new Error("render failed");
104 + }),
105 + },
106 + {
107 + name: "an inline update throws",
108 + mobile: false,
109 + startViewTransition: deferredViewTransition(),
110 + update: vi.fn(() => {
111 + throw new Error("render failed");
112 + }),
113 + },
114 + ])(
115 + "still releases the caller once when $name",
116 + async ({ mobile = true, startViewTransition, update }) => {
117 + stubEnvironment({ mobile, startViewTransition });
118 +
119 + await runMobileComposerTransition(update, { active: true, durationMs: 200 });
120 +
121 + expect(update).toHaveBeenCalledTimes(1);
122 + },
123 + );
124 +});
apps/web/src/components/chat/draftHeroTransition.ts
+45 -29
@@ -1,3 +1,5 @@
1 +import { flushSync } from "react-dom";
2 +
3 export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition";
4 export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)";
5 export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer";
@@ -35,12 +37,14 @@ export async function waitForDraftHeroTransition(): Promise<void> {
37 ]);
38 }
39
38 -export async function runMobileComposerTransition(
39 - update: () => void | Promise<void>,
40 +// Only a mobile view transition flushes `update` (its new snapshot must show it) and returns a
41 +// promise; otherwise it runs inline so its state batches with the caller's. Errors never block.
42 +export function runMobileComposerTransition(
43 + update: () => void,
44 options: { active: boolean; durationMs: number },
41 -): Promise<void> {
45 +): Promise<void> | undefined {
46 if (typeof document === "undefined" || typeof window === "undefined") {
43 - await update();
47 + runInlineUpdate(update);
48 return;
49 }
50
@@ -48,46 +52,58 @@ export async function runMobileComposerTransition(
52 const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false;
53 const prefersReducedMotion =
54 window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
51 - if (
52 - !options.active ||
53 - !mobileViewport ||
54 - prefersReducedMotion ||
55 - !transitionDocument.startViewTransition
56 - ) {
57 - await update();
55 + const startViewTransition = transitionDocument.startViewTransition?.bind(transitionDocument);
56 + if (!options.active || !mobileViewport || prefersReducedMotion || !startViewTransition) {
57 + runInlineUpdate(update);
58 return;
59 }
60
61 - let updateStarted = false;
62 - const runUpdate = async () => {
63 - if (updateStarted) return;
64 - updateStarted = true;
65 - await update();
66 - };
61 + return new Promise<void>((resolveUpdated) => {
62 + let updateStarted = false;
63 + const runUpdate = () => {
64 + if (updateStarted) return;
65 + updateStarted = true;
66 + try {
67 + flushSync(update);
68 + } finally {
69 + resolveUpdated();
70 + }
71 + };
72 + void runViewTransition(startViewTransition, runUpdate, options.durationMs);
73 + });
74 +}
75 +
76 +function runInlineUpdate(update: () => void) {
77 + try {
78 + update();
79 + } catch {}
80 +}
81 +
82 +async function runViewTransition(
83 + startViewTransition: (update: () => void) => ComposerViewTransition,
84 + runUpdate: () => void,
85 + durationMs: number,
86 +) {
87 + const root = document.documentElement;
88 let transitionFinished: Promise<void> | null = null;
68 - transitionDocument.documentElement.style.setProperty(
69 - MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY,
70 - `${String(options.durationMs)}ms`,
71 - );
72 - transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true";
89 + root.style.setProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, `${String(durationMs)}ms`);
90 + root.dataset.mobileComposerRouteTransition = "true";
91 try {
74 - const transition = transitionDocument.startViewTransition(runUpdate);
92 + const transition = startViewTransition(runUpdate);
93 transitionFinished = transition.finished.catch(() => undefined);
94 activeMobileComposerTransition = transitionFinished;
95 try {
96 await transition.finished;
97 } catch {
80 - await runUpdate();
98 + runInlineUpdate(runUpdate);
99 }
100 } catch {
83 - await runUpdate();
101 + runInlineUpdate(runUpdate);
102 } finally {
103 if (activeMobileComposerTransition === transitionFinished) {
104 activeMobileComposerTransition = null;
105 }
88 - delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition;
89 - transitionDocument.documentElement.style.removeProperty(
90 - MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY,
91 - );
106 + delete root.dataset.mobileComposerRouteTransition;
107 + root.style.removeProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY);
108 }
109 }
apps/web/src/components/chat/useComposerSend.ts
+5 -13
@@ -45,7 +45,6 @@ import {
45 } from "@t3tools/client-runtime/environment";
46 import { createModelSelection } from "@t3tools/shared/model";
47 import { type SetStateAction, useLayoutEffect, useRef } from "react";
48 -import { flushSync } from "react-dom";
48 import { useNavigate } from "@tanstack/react-router";
49 import {
50 isAtomCommandInterrupted,
@@ -905,25 +904,18 @@ export function useComposerSend(input: ComposerSendInput) {
904 shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) &&
905 activeThreadKey
906 ) {
908 - let resolveDockStarted: (() => void) | undefined;
909 - const dockStarted = new Promise<void>((resolve) => {
910 - resolveDockStarted = resolve;
911 - });
912 - const dockTransition = runMobileComposerTransition(
907 + const docking = runMobileComposerTransition(
908 () => {
914 - flushSync(() => {
915 - captureDraftHeroComposerRect();
916 - setDockedDraftHeroThreadKey(activeThreadKey);
917 - });
918 - resolveDockStarted?.();
909 + captureDraftHeroComposerRect();
910 + setDockedDraftHeroThreadKey(activeThreadKey);
911 },
912 {
913 active: panelAnimationsActive,
914 durationMs: panelAnimationDurationMs,
915 },
916 );
925 - void dockTransition.catch(() => resolveDockStarted?.());
926 - await dockStarted;
917 + // Awaiting only a real transition keeps an inline dock in the same render as the send.
918 + if (docking) await docking;
919 }
920
921 const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();