Skip to content

Commit 6b474b7

Browse files
perf(web): markdown replies no longer re-render on reconnects and config pushes
ChatMarkdown subscribed to the whole environment presentation, the prepared connection and the server config map, so every reconnect or config push gave its renderer context a new value and re-rendered every markdown element. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2fbd431 commit 6b474b7

6 files changed

Lines changed: 159 additions & 59 deletions

File tree

‎apps/web/src/components/ChatMarkdown.assets.test.tsx‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,25 @@ import { create, type ReactTestRenderer } from "react-test-renderer";
55
import { expect, it, vi } from "vite-plus/test";
66

77
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+
});
927
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
1028
vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => undefined }));
1129
vi.mock("../hooks/useSettings", async (importOriginal) => {
@@ -36,7 +54,7 @@ vi.mock("../state/session", async (importOriginal) => ({
3654
...(await importOriginal<typeof import("../state/session")>()),
3755
readEnvironmentScope: () => false,
3856
useEnvironmentScope: () => false,
39-
usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }),
57+
readPreparedConnection: () => ({ httpBaseUrl: "https://host.test" }),
4058
}));
4159
vi.mock("../state/entities", () => ({
4260
readEnvironmentSupportsServerBrowser: () => false,

‎apps/web/src/components/ChatMarkdown.permissions.test.tsx‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@ const state = vi.hoisted(() => ({
2727
linkedPullRequest: null as ThreadLinkedPullRequest | null,
2828
}));
2929

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+
});
3135
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
3236
vi.mock("../hooks/useFileMetadata", () => ({ useFileMetadata: () => undefined }));
3337
vi.mock("../hooks/useSettings", () => ({
@@ -70,18 +74,23 @@ vi.mock("../state/session", async () => {
7074
},
7175
() => readEnvironmentScope(id, scope),
7276
),
73-
usePreparedConnection: () => ({ _tag: "None" }),
7477
};
7578
});
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+
});
7989
vi.mock("../state/threads", () => ({
8090
threadEnvironment: { updateMetadata: "updateMetadata" },
8191
}));
8292
vi.mock("../state/entities", () => ({
8393
readEnvironmentSupportsServerBrowser: () => false,
84-
useServerConfigs: () => new Map([[threadRef.environmentId, serverConfig]]),
8594
readThreadShell: () => ({ linkedPullRequest: state.linkedPullRequest }),
8695
useProjects: () => [{ id: linkedPullRequest.projectId, environmentId: threadRef.environmentId }],
8796
}));

‎apps/web/src/components/ChatMarkdown.test.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,25 @@ import { Button } from "./ui/button";
1818
import { setMarkdownTaskChecked } from "./files/filePreviewMode";
1919

2020
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+
});
2240
vi.mock("./chat/MermaidDiagram", () => ({
2341
// Real Mermaid needs layout APIs jsdom lacks; a rendered diagram is an SVG.
2442
MermaidDiagram: () => <svg aria-label="Diagram" />,
@@ -59,7 +77,6 @@ vi.mock("../state/session", async (importOriginal) => {
5977
...actual,
6078
useEnvironmentScope: hasScope,
6179
readEnvironmentScope: hasScope,
62-
usePreparedConnection: () => ({ _tag: "Loading" }),
6380
};
6481
});
6582
vi.mock("../state/entities", () => ({

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/m
7676
import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
7777
import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
7878
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";
8081
import React, {
8182
Children,
8283
Suspense,
@@ -184,7 +185,11 @@ import { readThreadShell, useProjects } from "../state/entities";
184185
import { serverEnvironment } from "../state/server";
185186
import { shellEnvironment } from "../state/shell";
186187
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";
188193
import { previewEnvironment } from "../state/preview";
189194
import { useAtomCommand } from "../state/use-atom-command";
190195
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
@@ -2194,6 +2199,8 @@ function areMarkdownFileLinkPropsEqual(
21942199

21952200
const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = [];
21962201

2202+
type MarkdownServerConfigFields = ReturnType<typeof markdownServerConfigFields>;
2203+
21972204
/** The server config fields markdown reads. */
21982205
function markdownServerConfigFields(config: ServerConfig | null) {
21992206
return {
@@ -2208,6 +2215,29 @@ function markdownServerConfigFields(config: ServerConfig | null) {
22082215
};
22092216
}
22102217

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+
22112241
function useChatMarkdownState({
22122242
text,
22132243
cwd,
@@ -2279,7 +2309,6 @@ function useChatMarkdownState({
22792309
const canUseShellActions =
22802310
canOperateHost &&
22812311
canUseMarkdownFileShellActions(environmentId, remoteOpen.state.mode, remoteOpen.isResolved);
2282-
const preparedConnection = usePreparedConnection(environmentId);
22832312
const openMarkdownMedia = (
22842313
source: string,
22852314
resolvedFilePath?: string,
@@ -2291,8 +2320,10 @@ function useChatMarkdownState({
22912320
resolvedFilePath,
22922321
cwd,
22932322
threadRef,
2323+
// Read at click time: a reconnect replaces the prepared connection, and
2324+
// subscribing would hand every rendered markdown element a new context.
22942325
httpBaseUrl:
2295-
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : undefined,
2326+
environmentId === null ? undefined : readPreparedConnection(environmentId)?.httpBaseUrl,
22962327
createAssetUrl,
22972328
onOpenFile: threadRef
22982329
? (path) => useRightPanelStore.getState().openFile(threadRef, path)
@@ -2323,20 +2354,9 @@ function useChatMarkdownState({
23232354
},
23242355
);
23252356
};
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+
);
23402360
const projects = useProjects();
23412361
const [preferredEditor] = usePreferredEditor(availableEditors);
23422362
const preferredEditorMenuLabel = openInEditorMenuLabel(preferredEditor);
@@ -2480,7 +2500,8 @@ function useChatMarkdownState({
24802500
});
24812501
};
24822502
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) {
24842505
return Promise.resolve(
24852506
AsyncResult.failure<void, BrowserPreviewUnavailableError>(
24862507
Cause.fail(
@@ -2495,7 +2516,7 @@ function useChatMarkdownState({
24952516
threadRef,
24962517
filePath: path,
24972518
workspaceRoot: cwd,
2498-
httpBaseUrl: preparedConnection.value.httpBaseUrl,
2519+
httpBaseUrl: preparedConnection.httpBaseUrl,
24992520
createAssetUrl,
25002521
openPreview,
25012522
});

‎apps/web/src/hooks/usePullRequestLinking.ts‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,11 @@ import {
2424
parseChangeRequestUrl,
2525
type ChangeRequestLink,
2626
} 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";
2832
import { threadEnvironment } from "~/state/threads";
2933
import { useAtomCommand } from "~/state/use-atom-command";
3034

@@ -38,12 +42,21 @@ export function canLinkChangeRequest(
3842
return findProjectForChangeRequest(projects, parsed) !== undefined;
3943
}
4044

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+
4157
export function usePullRequestLinking(environmentId: EnvironmentId | null | undefined) {
42-
const configs = useServerConfigs();
4358
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));
4760
const link = useAtomCommand(threadEnvironment.linkPullRequest, { reportFailure: false });
4861
const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: false });
4962
const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });
@@ -79,7 +92,8 @@ export function usePullRequestLinking(environmentId: EnvironmentId | null | unde
7992
throw new Error("The pull request is not available in this environment.");
8093
const legacyProject = findProjectForChangeRequest(environmentProjects, parsed);
8194
const mutation = planThreadPullRequestMutation({
82-
capabilities,
95+
capabilities: appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId)
96+
?.environment.capabilities,
8397
threadId: threadRef.threadId,
8498
reference: { ...parsed, url },
8599
legacyProjectId: legacyProject?.id ?? null,

‎apps/web/src/remoteOpen.ts‎

Lines changed: 44 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ import {
77
} from "@t3tools/contracts";
88
import * as Option from "effect/Option";
99
import * as Schema from "effect/Schema";
10+
import { Atom } from "effect/reactivity";
11+
import { useAtomValue } from "@effect/atom-react";
1012
import { useEffect, useState } from "react";
1113

1214
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
1315
import { isLoopbackHostname } from "~/environments/primary/target";
1416
import { useLocalStorage } from "~/hooks/useLocalStorage";
15-
import { useEnvironmentPresentation } from "~/state/presentation";
17+
import { environmentPresentations } from "~/state/presentation";
1618

1719
export interface RemoteOpenHost {
1820
readonly kind: "ssh-alias" | RemoteOpenTarget["kind"];
@@ -80,29 +82,48 @@ export function resolveRemoteOpenState(input: {
8082
return REMOTE_UNAVAILABLE;
8183
}
8284

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+
83123
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+
);
106127
}
107128

108129
export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {

0 commit comments

Comments
 (0)