The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 05:30 UTC
perf(web): markdown replies no longer re-render on reconnects and config pushes (#20852)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 03:36 UTC
1d00edb23ad6bfade33beba927947d09f1beeca4
6 files changed
+159
-59
apps/web/src/components/ChatMarkdown.assets.test.tsx
+20
-2
@@ -5,7 +5,25 @@ import { create, type ReactTestRenderer } from "react-test-renderer";
5
import { expect, it, vi } from "vite-plus/test";
6
7
const mint = vi.hoisted(() => vi.fn());
8
-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
8
+// Atoms derived from the server config run in a real registry over a missing
9
+// config; every other subscription reads nothing.
10
+vi.mock("@effect/atom-react", async () => {
11
+ const { AtomRegistry } = await import("effect/reactivity");
12
+ const registry = AtomRegistry.make();
13
+ const derived = new Set(["markdown-server-config-fields", "pull-request-link-mode"]);
14
+ return {
15
+ useAtomValue: (atom: { readonly label?: readonly [string, ...unknown[]] }) =>
16
+ derived.has(atom.label?.[0] ?? "") ? registry.get(atom as never) : null,
17
+ };
18
+});
19
+vi.mock("../state/server", async () => {
20
+ const { Atom } = await import("effect/reactivity");
21
+ const noConfig = Atom.make(null);
22
+ return {
23
+ serverEnvironment: { configValueAtom: () => noConfig },
24
+ environmentServerConfigsAtom: Atom.make(new Map()),
25
+ };
26
+});
27
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
28
vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => undefined }));
29
vi.mock("../hooks/useSettings", async (importOriginal) => {
@@ -36,7 +54,7 @@ vi.mock("../state/session", async (importOriginal) => ({
54
...(await importOriginal<typeof import("../state/session")>()),
55
readEnvironmentScope: () => false,
56
useEnvironmentScope: () => false,
39
- usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }),
57
+ readPreparedConnection: () => ({ httpBaseUrl: "https://host.test" }),
58
}));
59
vi.mock("../state/entities", () => ({
60
readEnvironmentSupportsServerBrowser: () => false,
apps/web/src/components/ChatMarkdown.permissions.test.tsx
+15
-6
@@ -27,7 +27,11 @@ const state = vi.hoisted(() => ({
27
linkedPullRequest: null as ThreadLinkedPullRequest | null,
28
}));
29
30
-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => serverConfig }));
30
+vi.mock("@effect/atom-react", async () => {
31
+ const { AtomRegistry } = await import("effect/reactivity");
32
+ const registry = AtomRegistry.make();
33
+ return { useAtomValue: (atom: never) => registry.get(atom) };
34
+});
35
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
36
vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => undefined }));
37
vi.mock("../hooks/useSettings", () => ({
@@ -70,18 +74,23 @@ vi.mock("../state/session", async () => {
74
},
75
() => readEnvironmentScope(id, scope),
76
),
73
- usePreparedConnection: () => ({ _tag: "None" }),
77
};
78
});
76
-vi.mock("../state/server", () => ({
77
- serverEnvironment: { configValueAtom: () => "config" },
78
-}));
79
+vi.mock("../state/server", async () => {
80
+ const { Atom } = await import("effect/reactivity");
81
+ const config = Atom.make(() => serverConfig);
82
+ return {
83
+ serverEnvironment: { configValueAtom: () => config },
84
+ environmentServerConfigsAtom: Atom.make(
85
+ () => new Map([[threadRef.environmentId, serverConfig]]),
86
+ ),
87
+ };
88
+});
89
vi.mock("../state/threads", () => ({
90
threadEnvironment: { updateMetadata: "updateMetadata" },
91
}));
92
vi.mock("../state/entities", () => ({
93
readEnvironmentSupportsServerBrowser: () => false,
84
- useServerConfigs: () => new Map([[threadRef.environmentId, serverConfig]]),
94
readThreadShell: () => ({ linkedPullRequest: state.linkedPullRequest }),
95
useProjects: () => [{ id: linkedPullRequest.projectId, environmentId: threadRef.environmentId }],
96
}));
apps/web/src/components/ChatMarkdown.test.tsx
+19
-2
@@ -18,7 +18,25 @@ import { Button } from "./ui/button";
18
import { setMarkdownTaskChecked } from "./files/filePreviewMode";
19
20
vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => null }));
21
-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
21
+// Atoms derived from the server config run in a real registry over a missing
22
+// config; every other subscription reads nothing.
23
+vi.mock("@effect/atom-react", async () => {
24
+ const { AtomRegistry } = await import("effect/reactivity");
25
+ const registry = AtomRegistry.make();
26
+ const derived = new Set(["markdown-server-config-fields", "pull-request-link-mode"]);
27
+ return {
28
+ useAtomValue: (atom: { readonly label?: readonly [string, ...unknown[]] }) =>
29
+ derived.has(atom.label?.[0] ?? "") ? registry.get(atom as never) : null,
30
+ };
31
+});
32
+vi.mock("../state/server", async () => {
33
+ const { Atom } = await import("effect/reactivity");
34
+ const noConfig = Atom.make(null);
35
+ return {
36
+ serverEnvironment: { configValueAtom: () => noConfig },
37
+ environmentServerConfigsAtom: Atom.make(new Map()),
38
+ };
39
+});
40
vi.mock("./chat/MermaidDiagram", () => ({
41
// Real Mermaid needs layout APIs jsdom lacks; a rendered diagram is an SVG.
42
MermaidDiagram: () => <svg aria-label="Diagram" />,
@@ -59,7 +77,6 @@ vi.mock("../state/session", async (importOriginal) => {
77
...actual,
78
useEnvironmentScope: hasScope,
79
readEnvironmentScope: hasScope,
62
- usePreparedConnection: () => ({ _tag: "Loading" }),
80
};
81
});
82
vi.mock("../state/entities", () => ({
apps/web/src/components/ChatMarkdown.tsx
+41
-20
@@ -76,7 +76,8 @@ import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/m
76
import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
77
import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
78
import * as Cause from "effect/Cause";
79
-import { AsyncResult } from "effect/reactivity";
79
+import * as Option from "effect/Option";
80
+import { AsyncResult, Atom } from "effect/reactivity";
81
import React, {
82
Children,
83
Suspense,
@@ -184,7 +185,11 @@ import { readThreadShell, useProjects } from "../state/entities";
185
import { serverEnvironment } from "../state/server";
186
import { shellEnvironment } from "../state/shell";
187
import { assetEnvironment } from "../state/assets";
187
-import { readEnvironmentScope, usePreparedConnection, useEnvironmentScope } from "../state/session";
188
+import {
189
+ readEnvironmentScope,
190
+ readPreparedConnection,
191
+ useEnvironmentScope,
192
+} from "../state/session";
193
import { previewEnvironment } from "../state/preview";
194
import { useAtomCommand } from "../state/use-atom-command";
195
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
@@ -2194,6 +2199,8 @@ function areMarkdownFileLinkPropsEqual(
2199
2200
const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = [];
2201
2202
+type MarkdownServerConfigFields = ReturnType<typeof markdownServerConfigFields>;
2203
+
2204
/** The server config fields markdown reads. */
2205
function markdownServerConfigFields(config: ServerConfig | null) {
2206
return {
@@ -2208,6 +2215,29 @@ function markdownServerConfigFields(config: ServerConfig | null) {
2215
};
2216
}
2217
2218
+function markdownServerConfigFieldsEqual(
2219
+ previous: MarkdownServerConfigFields,
2220
+ next: MarkdownServerConfigFields,
2221
+): boolean {
2222
+ return (
2223
+ previous.pullRequestsEnabled === next.pullRequestsEnabled &&
2224
+ previous.revealInFileManagerLabel === next.revealInFileManagerLabel &&
2225
+ previous.availableEditors.length === next.availableEditors.length &&
2226
+ previous.availableEditors.every((editor, index) => editor === next.availableEditors[index])
2227
+ );
2228
+}
2229
+
2230
+// The config object changes with every provider status push and snapshot. The
2231
+// atom keeps its previous value while the fields markdown reads are equal, so
2232
+// those pushes don't re-render every visible reply.
2233
+const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId | null) =>
2234
+ Atom.make((get) => {
2235
+ const next = markdownServerConfigFields(get(serverEnvironment.configValueAtom(environmentId)));
2236
+ const previous = Option.getOrNull(get.self<MarkdownServerConfigFields>());
2237
+ return previous !== null && markdownServerConfigFieldsEqual(previous, next) ? previous : next;
2238
+ }).pipe(Atom.withLabel("markdown-server-config-fields")),
2239
+);
2240
+
2241
function useChatMarkdownState({
2242
text,
2243
cwd,
@@ -2279,7 +2309,6 @@ function useChatMarkdownState({
2309
const canUseShellActions =
2310
canOperateHost &&
2311
canUseMarkdownFileShellActions(environmentId, remoteOpen.state.mode, remoteOpen.isResolved);
2282
- const preparedConnection = usePreparedConnection(environmentId);
2312
const openMarkdownMedia = (
2313
source: string,
2314
resolvedFilePath?: string,
@@ -2291,8 +2320,10 @@ function useChatMarkdownState({
2320
resolvedFilePath,
2321
cwd,
2322
threadRef,
2323
+ // Read at click time: a reconnect replaces the prepared connection, and
2324
+ // subscribing would hand every rendered markdown element a new context.
2325
httpBaseUrl:
2295
- preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : undefined,
2326
+ environmentId === null ? undefined : readPreparedConnection(environmentId)?.httpBaseUrl,
2327
createAssetUrl,
2328
onOpenFile: threadRef
2329
? (path) => useRightPanelStore.getState().openFile(threadRef, path)
@@ -2323,20 +2354,9 @@ function useChatMarkdownState({
2354
},
2355
);
2356
};
2326
- // Only the parts of the server config markdown reads. The config object itself
2327
- // changes with every provider status push, which would re-render every
2328
- // visible reply.
2329
- const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
2330
- const nextConfigFields = markdownServerConfigFields(serverConfig);
2331
- const [configFields, setConfigFields] = useState(nextConfigFields);
2332
- if (
2333
- configFields.pullRequestsEnabled !== nextConfigFields.pullRequestsEnabled ||
2334
- configFields.availableEditors !== nextConfigFields.availableEditors ||
2335
- configFields.revealInFileManagerLabel !== nextConfigFields.revealInFileManagerLabel
2336
- ) {
2337
- setConfigFields(nextConfigFields);
2338
- }
2339
- const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel } = configFields;
2357
+ const { pullRequestsEnabled, availableEditors, revealInFileManagerLabel } = useAtomValue(
2358
+ markdownServerConfigFieldsAtom(environmentId),
2359
+ );
2360
const projects = useProjects();
2361
const [preferredEditor] = usePreferredEditor(availableEditors);
2362
const preferredEditorMenuLabel = openInEditorMenuLabel(preferredEditor);
@@ -2480,7 +2500,8 @@ function useChatMarkdownState({
2500
});
2501
};
2502
const openMarkdownFileInPreview = (path: string) => {
2483
- if (!threadRef || !canOperatePreview || preparedConnection._tag === "None") {
2503
+ const preparedConnection = threadRef ? readPreparedConnection(threadRef.environmentId) : null;
2504
+ if (!threadRef || !canOperatePreview || preparedConnection === null) {
2505
return Promise.resolve(
2506
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
2507
Cause.fail(
@@ -2495,7 +2516,7 @@ function useChatMarkdownState({
2516
threadRef,
2517
filePath: path,
2518
workspaceRoot: cwd,
2498
- httpBaseUrl: preparedConnection.value.httpBaseUrl,
2519
+ httpBaseUrl: preparedConnection.httpBaseUrl,
2520
createAssetUrl,
2521
openPreview,
2522
});
apps/web/src/hooks/usePullRequestLinking.ts
+20
-6
@@ -24,7 +24,11 @@ import {
24
parseChangeRequestUrl,
25
type ChangeRequestLink,
26
} from "~/lib/openPullRequestLink";
27
-import { useProjects, useServerConfigs } from "~/state/entities";
27
+import { useAtomValue } from "@effect/atom-react";
28
+import { Atom } from "effect/reactivity";
29
+import { appAtomRegistry } from "~/rpc/atomRegistry";
30
+import { useProjects } from "~/state/entities";
31
+import { environmentServerConfigsAtom } from "~/state/server";
32
import { threadEnvironment } from "~/state/threads";
33
import { useAtomCommand } from "~/state/use-atom-command";
34
@@ -38,12 +42,21 @@ export function canLinkChangeRequest(
42
return findProjectForChangeRequest(projects, parsed) !== undefined;
43
}
44
45
+// A string, so provider status pushes and snapshots that keep the mode don't
46
+// re-render every link renderer.
47
+const linkModeAtom = Atom.family((environmentId: EnvironmentId | null) =>
48
+ Atom.make((get) =>
49
+ threadPullRequestLinkMode(
50
+ environmentId === null
51
+ ? undefined
52
+ : get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities,
53
+ ),
54
+ ).pipe(Atom.withLabel("pull-request-link-mode")),
55
+);
56
+
57
export function usePullRequestLinking(environmentId: EnvironmentId | null | undefined) {
42
- const configs = useServerConfigs();
58
const projects = useProjects();
44
- const capabilities =
45
- environmentId == null ? undefined : configs.get(environmentId)?.environment.capabilities;
46
- const mode = threadPullRequestLinkMode(capabilities);
59
+ const mode = useAtomValue(linkModeAtom(environmentId ?? null));
60
const link = useAtomCommand(threadEnvironment.linkPullRequest, { reportFailure: false });
61
const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: false });
62
const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
@@ -79,7 +92,8 @@ export function usePullRequestLinking(environmentId: EnvironmentId | null | unde
92
throw new Error("The pull request is not available in this environment.");
93
const legacyProject = findProjectForChangeRequest(environmentProjects, parsed);
94
const mutation = planThreadPullRequestMutation({
82
- capabilities,
95
+ capabilities: appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId)
96
+ ?.environment.capabilities,
97
threadId: threadRef.threadId,
98
reference: { ...parsed, url },
99
legacyProjectId: legacyProject?.id ?? null,
apps/web/src/remoteOpen.ts
+44
-23
@@ -7,12 +7,14 @@ import {
7
} from "@t3tools/contracts";
8
import * as Option from "effect/Option";
9
import * as Schema from "effect/Schema";
10
+import { Atom } from "effect/reactivity";
11
+import { useAtomValue } from "@effect/atom-react";
12
import { useEffect, useState } from "react";
13
14
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
15
import { isLoopbackHostname } from "~/environments/primary/target";
16
import { useLocalStorage } from "~/hooks/useLocalStorage";
15
-import { useEnvironmentPresentation } from "~/state/presentation";
17
+import { environmentPresentations } from "~/state/presentation";
18
19
export interface RemoteOpenHost {
20
readonly kind: "ssh-alias" | RemoteOpenTarget["kind"];
@@ -80,29 +82,48 @@ export function resolveRemoteOpenState(input: {
82
return REMOTE_UNAVAILABLE;
83
}
84
85
+function remoteOpenStatesEqual(previous: RemoteOpenState, next: RemoteOpenState): boolean {
86
+ if (previous.mode !== next.mode) return false;
87
+ if (previous.mode !== "remote-links" || next.mode !== "remote-links") return true;
88
+ return previous.host.kind === next.host.kind && previous.host.host === next.host.host;
89
+}
90
+
91
+// The presentation changes with every server config push and reconnect. This
92
+// keeps the previous resolution while it is equal, so subscribers re-render only
93
+// when where files open actually changes.
94
+const remoteOpenResolutionAtom = Atom.family((environmentId: EnvironmentId) =>
95
+ Atom.make((get): RemoteOpenResolution => {
96
+ const presentation = get(environmentPresentations.presentationAtom(environmentId));
97
+ const entry = presentation?.entry ?? null;
98
+ if (entry === null) {
99
+ return UNRESOLVED_REMOTE_OPEN;
100
+ }
101
+ const profile = Option.getOrNull(entry.profile);
102
+ const next: RemoteOpenResolution = {
103
+ state: resolveRemoteOpenState({
104
+ target: entry.target,
105
+ sshAlias:
106
+ profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null,
107
+ remoteOpenTargets: presentation?.serverConfig?.remoteOpenTargets,
108
+ isDesktopRenderer: window.desktopBridge !== undefined,
109
+ }),
110
+ isResolved: true,
111
+ };
112
+ const previous = Option.getOrNull(get.self<RemoteOpenResolution>());
113
+ return previous !== null &&
114
+ previous.isResolved &&
115
+ remoteOpenStatesEqual(previous.state, next.state)
116
+ ? previous
117
+ : next;
118
+ }).pipe(Atom.withLabel(`remote-open-resolution:${environmentId}`)),
119
+);
120
+
121
+const UNRESOLVED_REMOTE_OPEN_ATOM = Atom.make(UNRESOLVED_REMOTE_OPEN);
122
+
123
export function useRemoteOpenResolution(environmentId: EnvironmentId | null): RemoteOpenResolution {
84
- const { presentation } = useEnvironmentPresentation(environmentId);
85
- // The presentation changes with every server config push. Read only the pieces
86
- // used here so the compiler keys the result on them and callers keep a stable
87
- // result across provider updates.
88
- const entry = presentation?.entry ?? null;
89
- const remoteOpenTargets = presentation?.serverConfig?.remoteOpenTargets;
90
-
91
- if (entry === null) {
92
- return UNRESOLVED_REMOTE_OPEN;
93
- }
94
- const profile = Option.getOrNull(entry.profile);
95
- const sshAlias =
96
- profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null;
97
- return {
98
- state: resolveRemoteOpenState({
99
- target: entry.target,
100
- sshAlias,
101
- remoteOpenTargets,
102
- isDesktopRenderer: window.desktopBridge !== undefined,
103
- }),
104
- isResolved: true,
105
- };
124
+ return useAtomValue(
125
+ environmentId === null ? UNRESOLVED_REMOTE_OPEN_ATOM : remoteOpenResolutionAtom(environmentId),
126
+ );
127
}
128
129
export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {